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
153 views
in Technique[技术] by (71.8m points)

html - :last-child not working as expected?

The issue lies within this CSS and HTML. Here is a link to jsFiddle with the sample code.

HTML

<ul>
    <li class"complete">1</li>
    <li class"complete">2</li>
    <li>3</li>
    <li>4</li>
</ul>

CSS

li.complete:last-child {
    background-color:yellow;
}

li.complete:last-of-type {
    background-color:yellow;
}

Shouldn't either of these lines of CSS target the last li element with the "complete" class?

This query in jQuery doesn't target it either:

$("li.complete:last-child");

But this one does:

$("li.complete").last();

li {
  background-color: green;
}
li.complete:first-child {
  background-color: white;
}
li.complete:first-of-type {
  background-color: red;
}
li.complete:last-of-type {
  background-color: blue;
}
li.complete:last-child {
  background-color: yellow;
}
<ul>
  <li class="complete">1</li>
  <li class="complete">2</li>
  <li>3</li>
  <li>4</li>
</ul>
Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

The last-child selector is used to select the last child element of a parent. It cannot be used to select the last child element with a specific class under a given parent element.

The other part of the compound selector (which is attached before the :last-child) specifies extra conditions which the last child element must satisfy in-order for it to be selected. In the below snippet, you would see how the selected elements differ depending on the rest of the compound selector.

.parent :last-child{ /* this will select all elements which are last child of .parent */
  font-weight: bold;
}

.parent div:last-child{ /* this will select the last child of .parent only if it is a div*/
  background: crimson;
}

.parent div.child-2:last-child{ /* this will select the last child of .parent only if it is a div and has the class child-2*/
  color: beige;
}
<div class='parent'>
  <div class='child'>Child</div>
  <div class='child'>Child</div>
  <div class='child'>Child</div>
  <div>Child w/o class</div>
</div>
<div class='parent'>
  <div class='child'>Child</div>
  <div class='child'>Child</div>
  <div class='child'>Child</div>
  <div class='child-2'>Child w/o class</div>
</div>
<div class='parent'>
  <div class='child'>Child</div>
  <div class='child'>Child</div>
  <div class='child'>Child</div>
  <p>Child w/o class</p>
</div>

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

...