問題描述
我正在嘗試選擇具有特定 data-
屬性的元素的第一個和最后一個子元素.
I'm trying to select the first and last child of an element with a specific data-
attribute.
:first-child
選擇器工作正常,但 :last-child
不工作.我真的不知道是什么原因造成的.我檢查了錯別字.
The :first-child
selector works fine, but :last-child
isn't working. I seriously don't know what can cause this. I have checked for typos.
CSS
.element[data-type='element']:first-child {
padding-left: 0;
background-color:red !important
}
.element[data-type='element']:last-child {
padding-right: 0;
border-right:0;
background-color:red !important;
}
推薦答案
我正在嘗試選擇具有特定
data-
屬性的元素的第一個和最后一個子元素.
I'm trying to select the first and last child of an element with a specific
data-
attribute.
底線是,在 CSS 中沒有辦法做到這一點.
Bottom line is, there's no way to do that in CSS.
last-child
(和 last-of-type
)意思是,last child"和last child of type",它們確實是 不是的意思是最后一個孩子匹配整個選擇器,包括一個屬性選擇器".在您的情況下,第三個 div
實際上可能不是父元素中的最后一個子元素(或不是最后一個 div
);除非您顯示整個 HTML,包括父元素及其所有子元素,否則無法判斷.
last-child
(and last-of-type
) mean, well, "last child", and "last child of type", they do not mean "last child matching the entire selector including an attribute selector". In your case, it is likely that the third div
is not actually the last child (or not the last div
) within the parent element; it's impossible to tell unless you show the entire HTML including the parent element and all its children.
這篇關于:last-child 偽類與屬性選擇器混合不起作用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!