Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

css - Using :last-child with class selector

I want to style the last/second .heading.

<ul>
    <li class="heading">Hello world</li>
    <li>Hello world</li>
    <li>Hello world</li>
    <li class="heading">Hello world</li>
    <li>Hello world</li>
</ul>

Neither

ul li.heading:last-child {
    background: black;
}

nor

ul li.heading:nth-child(2) {
    background: black;
}

works for me. Why, and how can I apply styles to that <li>? It seems pseudo-class selectors doesn't work with class selectors. Which is weird since I could've sworn I'd used it before.

Update: Oops, totally forgot the jsfiddle.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your statement was: "I want to style the last/second .heading."

That would mean that you would have to write your code like this:

<ul>
    <li class="heading">Hello world</li>
    <li class="heading">Hello world</li>
    <li class="heading">Hello world</li>
    <li class="heading">Hello world</li>
    <li class="heading">Hello world</li>
</ul>

And the CSS:

ul li.heading:last-child {
    background: black;
}
ul li.heading:nth-child(2) {
    background: black;
}

Else, with your current html-code, you would write:

ul li.heading:nth-child(4) {
    background: black;
}
ul li.heading:nth-child(1) {
    background: black;
}

I understand your thought, but the lis with the class "heading" isn't the second or last child.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...