我有一个
<ul>
容器和一个 UI,允许我动态添加 <li>
元素到其中。当没有 <ul>
元素时,我想对 <li>
应用不同的样式。
<ul class="con">
</ul>
ul.con:not(:has(> li)) {
background-color: #cccccc;
border: 3px solid #000000 !important;
}
我期望当有 0 个
ul
元素时,li
的背景颜色会发生变化。但是,风格没有改变。
当没有
:has()
元素时,如何正确使用 ul
选择器或任何其他选择器来设置 li
元素的样式。注意: :empty
选择器不起作用,因为 ul
的主体中有空格。
我认为这就是您正在寻找的。请注意,如果您从 HTML 中删除 li 标记,则 :not 选择器将作用于代码:
ul:not(:has(li)){
background-color: #cccccc;
border: 1px solid #000000 !important;
}
ul:has(li){
background-color: red;
color: white;
}
div:has(h1){
border: 1px solid black;
}
<html>
<body>
<div>
<h1> Page title </h1>
</div>
<div>
<ul id="list">
<li> Item 1 </li>
</ul>
</div>
<div>
... another content ...
</div>
</body>
</html>