【问题标题】:lit: how to apply style to nested template?点燃:如何将样式应用于嵌套模板?
【发布时间】:2022-01-12 18:22:15
【问题描述】:

有一个 lit 元素 container-element 具有嵌套的 lit 元素 gmail-item

如何将样式应用于嵌套元素,以使最后一个 gmail-item 具有 border-none

目前,li:last-of-type 的样式不会传播到包含 li 的嵌套发光元素。

      @container-element
  
      li:last-of-type {
        border-bottom: none;
      }

      <gmail-item></gmail-item>
      <gmail-item></gmail-item>
      <gmail-item></gmail-item>
      <gmail-item></gmail-item>
      <gmail-item></gmail-item>
@gmail-item

li {
 border-bottom: 1px solid black;
}


<li>I am gmail item</li>

编辑:

尝试了以下方法。

      <style>
        gmail-item::slotted(li) {
          border: 1px solid orange;
        }
        gmail-item li {
          border: 1px solid orange;
        }
        li {
          border: 1px solid orange;
        }
      </style>
      <gmail-item></gmail-item>
           ........

但不幸的是,它们都没有将样式应用于gmail-item 内部的li

我也尝试添加createRendeRoot,但这删除了gmail-item 中的所有样式。

@gmail-item

createRenderRoot() {
return this;
}

还尝试设置li border-bottom to inherit

【问题讨论】:

  • @Danny'365CSI'Engelman 我已经尝试了提供的解决方案,但不幸的是,li 元素没有应用任何样式。
  • CSS 被封装在 Web 组件中,这意味着您的内部元素不会“看到”任何外部 CSS,并且您在 shadow DOM 中的 CSS 不会影响组件外部的任何内容。 没有任何东西流出,没有任何东西渗入(继承的属性除外,例如自定义属性又名“CSS 变量”)。

标签: html web-component lit-element lit-html lit


【解决方案1】:

你最好的选择是 css 变量。它是一个标准,而且是有范围的。

.container-1 {
  --my-status: grey;
}

.container-2 > gmail-item:first-child {
  --my-status: orange;
}
<script type="module">
import {
  LitElement,
  html,
  css
} from "https://unpkg.com/lit-element/lit-element.js?module";

class MyContainer extends LitElement {
  static get styles() {
    return css`
      .wrapper {
        min-height: 100px;
        min-width: 50%;
        margin: 5em;
        padding: 10px;
        background-color: lightblue;
      }
    `;
  }

  render() {
    return html`
      <div class="wrapper">
        <slot></slot>
      </div>
    `;
  }
}

class GmailItem extends LitElement {
  static get styles() {
    return css`
      .status {
        margin: 1em;
        border: 2px solid white;
        background-color: var(--my-status, red);
      }
    `;
  }

  render() {
    return html`
      <div class="status">STATUS</div>
    `;
  }
}

customElements.define("my-container", MyContainer);
customElements.define("gmail-item", GmailItem);
</script>

<my-container class="container-1">
  <gmail-item></gmail-item>
  <gmail-item></gmail-item>
</my-container>

<my-container class="container-2">
    <gmail-item></gmail-item>
    <gmail-item style="--my-status: magenta"></gmail-item>
</my-container>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-25
    • 2011-06-21
    • 2020-04-17
    • 2014-12-06
    • 1970-01-01
    • 2012-09-29
    • 2011-10-28
    相关资源
    最近更新 更多