问题描述
我有一个Web组件,它的模板看起来像这样...
I have a web component that has a template which looks like this...
<template>
<div class="jrg-app-header">
<slot name="jrg-app-header-1"></slot>
<slot name="jrg-app-header-2"></slot>
<slot name="jrg-app-header-3"></slot>
</div>
</template>
我基本上是在尝试将最后一个广告位的内容设置为样式为 flex:1;
.是否有CSS查询可以做到这一点?我尝试了一些清单
I am basically trying to set the contents of the last slot to have flex:1;
in style. Is there a CSS query that will do this? I tried something list
::slotted(*):last-child{
flex:1;
}
但是它没有用.如何设置最后一个插槽对象的样式?
But it did not work. How do I style the last slotted object?
推荐答案
有关:: slotted的详细答案,请参见:
For long answer on ::slotted see: ::slotted CSS selector for nested children in shadowDOM slot
从文档中: https://developer.mozilla.org/en-US/docs/Web/CSS/:: slotted
伪选择器放在方括号内: :: slotted(*:last-child)
The pseudo selector goes inside the brackets: ::slotted(*:last-child)
注意::slotted(...)
使用 简单 选择器( https://vegibit.com/css-selectors-tutorial/)
customElements.define('my-table', class extends HTMLElement {
constructor() {
let template = document.cloneNode(document.querySelector('#t1').content, true);
super()
.attachShadow({ mode: 'open' })
.append(template);
}
})
<template id="t1">
<style>
:host {
display: flex;
padding:1em;
}
::slotted(*:first-child) {
background: green;
}
::slotted(*:last-child) {
background: yellow;
flex:1;
}
::slotted(*:first-of-type) {
border: 2px solid red;
}
::slotted(*:last-of-type) {
border: 2px dashed red;
}
</style>
<slot name="column"></slot>
</template>
<my-table>
<div slot="column">Alpha</div><div slot="column">Bravo</div><div slot="column">Charlie</div>
</my-table>
<my-table>
<div slot="column">Delta</div><div slot="column">Echo</div>
</my-table>
JSFiddle游乐场: https://jsfiddle.net/CustomElementsExamples/whtjen3k/
JSFiddle playground: https://jsfiddle.net/CustomElementsExamples/whtjen3k/
可通过StackOverflow搜索找到更多与SLOT相关的答案:
More SLOT related answers can be found with StackOverflow Search: Custom Elements SLOTs
这篇关于如何设置Web组件中最后一个插入的元素的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!