我已經建立了我的UL的最後一個LI標籤的規則:選擇最後一個孩子,除非它也是第一個孩子
.className li:last-child {
stuff: here;
}
我是否能夠設置在說CSS規則「應用此樣式到最後的LI標籤,除了last-child
也是first-child
「,即在OL中只有一個LI標籤。
我已經建立了我的UL的最後一個LI標籤的規則:選擇最後一個孩子,除非它也是第一個孩子
.className li:last-child {
stuff: here;
}
我是否能夠設置在說CSS規則「應用此樣式到最後的LI標籤,除了last-child
也是first-child
「,即在OL中只有一個LI標籤。
可以連同:not()
使用選擇。
CSS僞類
:not(X)
是一個函數表示法服用簡單的選擇X作爲參數。它匹配不是由參數表示的元素。
li:last-child:not(:first-child) {
color: red;
}
<ul>
<li>item a</li>
<li>item b</li>
<li>item c</li>
</ul>
<ul>
<li>only item</li>
</ul>
有一個:only-child
選擇:
https://css-tricks.com/almanac/selectors/o/only-child/
除了一個:only-of-type
選擇
https://css-tricks.com/almanac/selectors/o/only-of-type/
你可以使用這些覆蓋任何東西:last-child
選擇正在修改。
唯一的事情就是我別如果它只是一個獨生子女,就不得不設置另一種風格。我想說「如果UL中有多個LI,只應用這種風格」。 –
你可以留下你的CSS,因爲它是和補充,覆蓋它的規則,如果它是第一個孩子:
/* What should happen in the last child */
.className li:last-child {
stuff: here;
}
/* If there is only one child the previous one will be overwritten by this one */
.className li:first-child {
/* default values */
}
或者,你可以使用一些更先進:
/* Select the last child if it is not the first child */
li:last-child:not(:first-child) {
stuff: here;
}
我會使用第二個,但這取決於你對CSS的熟悉程度。
更多分析:
:last-child
- 選擇最後一個子:not()
- 如果不是:first-child
- 第一個子接下來的問題是我不得不通過定義第一個孩子來爲LI設置樣式。 –
看看我的編輯。 –
您可以像li:last-child
一種化合物選擇之前預先準備* +
以防止它選擇的第一個孩子:
.className > * + li:last-child {
color: red;
}
<ul class="className">
<li>item a</li>
<li>item b</li>
<li>item c</li>
</ul>
<ul class="className">
<li>only item</li>
</ul>
完全是我以後的事。完善。 –