Why does the :host selector only work in chrome with platform.js?

后端 未结 1 816
情书的邮戳
情书的邮戳 2021-02-06 12:47

There\'s a lot of talk around and about about how to style web components.

For example, http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-201/ suggests that

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-06 13:17

    Question is a bit old, but putting this answer here in case you didn't figure it out yet.

    Shadom DOM polyfill doesn't attempt style encapsulation or fixing shadom dom related selectors in non-supported browsers.
    This is the reason that other than :host/:content selectors and :host()/:host-context() pseudo-classes not working, you'll see style written inside shadow dom leaking on to the whole page.

    The way you can make :host selectors work(?), is by rewriting css rules and replacing :host with tag name of host element.
    If you have an x-element custom-element then something like this:

    :host {
      opacity: 0.4;
      transition: opacity 420ms ease-in-out;
    }
    :host(:hover) {
      opacity: 1;
    }
    :host(:active) {
      position: relative;
      top: 3px;
      left: 3px;
    }
    /*Convert it to*/
    
    x-element {
      opacity: 0.4;
      transition: opacity 420ms ease-in-out;
    }
    x-element:hover {
      opacity: 1;
    }
    x-element:active {
      position: relative;
      top: 3px;
      left: 3px;
    }

    This is what polymer does for :content selectors i.e. distributed child nodes.

    I agree there is code duplication, but there is no other way I see in which you can make Firefox/IE/Safari understand what :host selectors mean.
    Hope it helps.

    0 讨论(0)
提交回复
热议问题