Home > Blockchain >  Why do display:flex do not respect shadow root border?
Why do display:flex do not respect shadow root border?

Time:11-25

If you toggle display:flex on a shadow root child it also affects the element outside. (All big browsers behave like this.) Why?

There is a web component with a shadow root:

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

Inside the shadow root there is a div with display:flex:

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

See https://jsfiddle.net/p32rfnbm/1/ for live example.

CodePudding user response:

To be honest, I can't agree to the example as its layout doesn't seem proper to me. The text "I am not." is innerHTML-text of the body element, if I'm not misleaded. If one properly puts this text into an element for its own -- as done with the text "I am in a shadow root!" --, lets say by <p style="display:flex;align-items:center;height:50px;background:lightgreen">And I am not.</p>, you won't see the effect described.

I see the point of the question, but I don't see the relevance. It just reminds us to correctly layout our documents as intended in the specifications, also to avoid presumably implementation-dependend side-effects. If one doesn't use a hammer as intended, stuff may get broken, I suppose.

CodePudding user response:

Yes, there is an effect, but normal behaviour for inline-block elements with fixed height,

<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>

  • Related