CSS:Disable :当 UL 没有 LI 时伪造之前 sub-elements

CSS:Disable :before pseudo when UL without LI sub-elements

我有一个 css 定义如下:

ul:before{
    content:'';
    //other css definitions 
}

我想要的是,:before pseudo 仅在 UL 有 LI 时有效 children,如果 UL 没有 LI,则使 :before 不可见。

提前致谢。

如果你控制html并且可以完全空ul,你可以使用:empty

ul:not(:empty):before {
 content:'';
}

ul:before {
 content:'';
}

ul:empty:before {
 content:none;
 display:none;
}

这适用于

<ul></ul>
<ul><!-- and with comments too --></ul>

但不会,如果里面有任何可见符号 ul

<ul>
</ul>
<ul> </ul>

另一种方式,在初始阶段控制输出,如果没有子节点,则在ul中添加一个class。您可以在 css 中使用它来关闭 : before

如果@MrSwed 提供的解决方案(使用 :empty)由于布局原因对您不起作用,您可以在第一个 li 上使用伪元素。

这完全取决于您想要实现的目标。

更新:如果至少有一个LI,则要求UL有背景图片。此代码段将背景图像放在第一个 LI 的 before 伪元素上,但它的大小和位置与 UL 相关,因此看起来像是整个 UL 的背景。

ul {
  position: relative;
  color: white;
  /* just so it shows for this demo */
}

li:first-child::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  display: inline-block;
  z-index: -1;
  background-image: url(https://picsum.photos/id/1015/200/300);
  background-size: cover;
  background-position: center center;
  width: 100%;
  height: 100%;
  top: 0 left: 0
}
<h2>Empty ul</h2>
<ul></ul>
<h2>ul with a couple of lis</h2>
<ul>
  <li>first li</li>
  <li>second li</li>
</ul>