Home > Software engineering >  'box-shadow' on a custom component with only a shadow root attached applies as if componen
'box-shadow' on a custom component with only a shadow root attached applies as if componen

Time:06-01

I have a custom component that has only the shadow root attached and no child elements inside it. In Chrome dev tools, hover over the custom component shows its actual size on screen with the correct pixel numbers. However, when adding a box-shadow property to this component result in the shadow being applied to the top left corner of the component, as if the component itself is only 0px by 0px.

customElements.define('my-comp', class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({
      mode: 'open'
    })
    const div = document.createElement('div')
    div.setAttribute('style', 'height: 100px; width: 100px; background: lime')
    this.shadowRoot.append(div)
  }
})
<my-comp style="box-shadow: 0px 0px 10px 10px brown"></my-comp>

Is this a known bug and is there a workaround? Or perhaps there's an error somewhere in my code?

CodePudding user response:

Your custom component will have an inline display and you are adding a block element inside it. You are facing the behavior of "block element inside inline element"

Make your element inline-block to avoid dealing with such case

customElements.define('my-comp', class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({
      mode: 'open'
    })
    const div = document.createElement('div')
    div.setAttribute('style', 'height: 100px; width: 100px; background: lime')
    this.shadowRoot.append(div)
  }
})
<my-comp style="box-shadow: 0px 0px 10px 10px brown;display:inline-block"></my-comp>

  • Related