我有一個 css 定義如下:
ul:before{
content:'';
//other css definitions
}
我想要的是, :before 偽僅在 UL 有 LI 孩子時才有效,如果 UL 沒有 LI,則使 :before 不可見。
先感謝您。
uj5u.com熱心網友回復:
如果@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>
uj5u.com熱心網友回復:
如果您控制 html 并且可以完全清空ul,則可以使用:empty
ul:not(:empty):before {
content:'';
}
這將適用于
<ul></ul>
<ul><!-- and with comments too --></ul>
但不會,如果里面有任何可見的符號 ul
<ul>
</ul>
<ul> </ul>
另一種方式,在初始階段控制輸出,ul如果它沒有孩子,則添加一個類。你可以在 css 中使用它來關閉: before
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381207.html
上一篇:設定行高并允許斷字
