:last-child pseudo-class mixed with attribute sele

2019-01-20 09:40发布

问题:

I'm trying to select the first and last child of an element with a specific data- attribute.

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;
}

回答1:

I'm trying to select the first and last child of an element with a specific data- attribute.

Bottom line is, there's no way to do that in CSS.

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.