【问题标题】:Is there a way to style a webcomponent based on the container it's in?有没有办法根据它所在的容器来设置 Web 组件的样式?
【发布时间】:2018-07-18 06:58:48
【问题描述】:

我正在尝试编写一些 web 组件来响应它们所在容器的主题。即

<div dataset-theme='light'>
  <my-custom-element></my-custom-element>
</div>

<div dataset-theme='dark'>
  <my-custom-element></my-custom-element>
</div>

我想将深色主题中的背景颜色更改为深色。我在 shadow-root 中尝试了如下 CSS:

[dataset-theme='dark']
  :host
    background-color: #333

但它似乎根本没有回应。有没有办法让 web 组件的样式根据它所在的容器而改变?

【问题讨论】:

  • 你试过[dataset-theme='dark'] my-custom-element{background-color: #333}吗?

标签: css html web-component shadow-dom custom-element


【解决方案1】:

:host-context() CSS pseudo-class 将允许您根据其上下文设置自定义元素的样式。

:host-context( [dataset-theme='dark'] ) {
    background-color: #333
}

作为补充,您可以使用:host 在未定义上下文时应用一些默认 CSS 样式。

下面是一个演示:

customElements.define( 'my-custom-element', class extends HTMLElement {
  constructor () {
    super()
    this.attachShadow( { mode: 'open' } )
        .innerHTML = `<style>
            :host-context([dataset-theme="dark"]) { 
              background-color: darkblue ; 
              color: lightgray ;
            }
            :host-context([dataset-theme="light"]) { 
              background-color: lightyellow ;
              color: orange ;
            }
            :host {
              background-color: white ;
              color: black ;
            }
          </style>
          <slot>No</slot> Theme`
  }
} )
<div dataset-theme='light'>
  <my-custom-element>Light</my-custom-element>
</div>

<div dataset-theme='dark'>
  <my-custom-element>Dark</my-custom-element>
</div>

<div>
    <my-custom-element></my-custom-element>
</div>

【讨论】:

    【解决方案2】:

    你可以这样试试

    CSS : 
    
    div[dataset-theme='dark'] my-custom-element{
       background-color : #333;
    }
    

    这可能是工作。

    【讨论】:

      【解决方案3】:

      尝试为此编写简单的 css。因为您可能在某处创建了该组件。因此,它将作为常规的 html 标签发挥作用。

      CSS : 
      
      my-custom-element {
         background-color : red;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-04-22
        • 2016-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-17
        • 2023-02-24
        • 2011-02-28
        • 2021-05-18
        相关资源
        最近更新 更多