lit:如何将样式应用于嵌套模板



有一个照明元素container-element,它具有嵌套的照明元素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

最好的选择是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>

最新更新