【问题标题】:Why do display:flex do not respect shadow root border?为什么 display:flex 不尊重阴影根边界?
【发布时间】:2022-11-25 19:03:18
【问题描述】:

如果您在影子根子节点上切换 display:flex,它也会影响外部元素。 (所有大型浏览器的行为都是如此。)为什么?

有一个带有影子根的 Web 组件:

<web-comp style="display: inline-block;"></web-comp>

在 shadow root 里面有一个带有 display:flex 的 div:

div.style="display:flex; align-items:center; height:50px;"

完整的例子:

class demo extends HTMLElement {
  connectedCallback() {
    const shadow = this.attachShadow({mode: 'open'});
    
    const div = document.createElement('div');
    div.innerHTML= "I am in a shadow root!"
    div.style="display:flex;align-items:center;height:50px;background:lightblue"
    shadow.appendChild(div);
  }
}
customElements.define('web-comp', demo);
  <h3>flexbox styles do not respect shadow root border</h3>

   <web-comp style="display: inline-block;"></web-comp>
And I am not.

   <button onclick="document.querySelector('web-comp').shadowRoot.querySelector('div').style.alignItems='baseline'">
   Click to change 'align-items' of div in shadow root.
   </button>

【问题讨论】:

  • 你能把你的 JSFiddle 转换成a StackOverflow snippet吗?你的问题将保留在 SO 上,但你的 JSFiddle 可能会在几年后消失

标签: javascript html css custom-element shadow-root


【解决方案1】:

是的,有效果,但对于固定高度的 inline-block 元素来说是正常行为,

<style>
  web-comp {
    display: inline-block;
    background: lightgreen;
    padding: 1em; /* becomes the "margin" above <span> */
  }
  span { background: pink }
</style>
<h3>Click the light green boxes</h3>
<div style="background:green">
  <web-comp></web-comp>
  <span>span</span>
  <span>span</span>
  <span>span</span>
  <web-comp></web-comp>
  <span>span</span>
  <span>span</span>
</div>

<script>
  customElements.define('web-comp', class extends HTMLElement {
    connectedCallback() {
      this.attachShadow({mode:'open'})
          .append(this.div = document.createElement('div'));
      this.div.style = "display:flex;height:60px";
      this.DIValign("center");
      this.onclick = () => {
        if (this.div.style.alignItems == "center") this.DIValign("baseline");
        else this.DIValign("center");
      };
    }
    DIValign(val) {
      this.div.innerHTML = ` align-items: ${this.div.style.alignItems = val}`;
    }
  })
</script>

【讨论】:

  • 你能给我解释一下吗?我不太明白你的例子。
  • 查看绿色边缘。 display-block 和固定的 DIV 高度让您认为 flex 影响了 &lt;span&gt; 元素。它与那些元素是 Web 组件无关。您可以用 DIV 替换 Web 组件。这是标准的 CSS Block 行为
【解决方案2】:

老实说,我不同意这个例子,因为它的布局对我来说似乎不合适。文本“我不是”。是 body 元素的 innerHTML 文本,如果我没有被误导的话。如果将此文本正确地放入其自身的元素中——就像文本“我在阴影根中!”所做的那样。 --,比方说&lt;p style="display:flex;align-items:center;height:50px;background:lightgreen"&gt;And I am not.&lt;/p&gt;,你不会看到描述的效果。

我明白问题的重点,但我不明白相关性。它只是提醒我们按照规范中的预期正确布局我们的文档,同时也是为了避免可能依赖于实现的副作用。我想,如果不按预期使用锤子,东西可能会坏掉。

【讨论】:

  • 如果影子根中的样式发生变化,为什么 body 的样式会发生变化?所有附加到阴影的样式都应该“留在阴影中”。您使用 p 元素的示例无法显示效果,因为是 display:flex。使用不带样式的 <span> ,您可以再次看到效果。
猜你喜欢
  • 2016-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-12
  • 2016-04-22
  • 1970-01-01
相关资源
最近更新 更多