CSS:last-child Selector不起作用

时间:2017-08-02 03:41:43

标签: css select css-selectors

我使用:last-child Selector但它不起作用。 例如:

.last {background:blue;border-bottom:1px solid #cccccc;}

.last:last-child {background:red;border-bottom:0px solid #cccccc;}

jsfiddle example

感谢每一个人的回答。

但我还有另外一个问题。 jsfiddle example 2

.big_box {
  background:#eeeeee;
  height:500px;
}

.last {
  width:90%;
  margin:auto;
background: yellow;
 border-bottom: 1px solid #cccccc;
}
.last:last-child {
    background: red;
     border-bottom: 0px solid #cccccc;
}
<div class="big_box">
  <div class="other">the other paragraph.</div>
  <div class="last">The first paragraph.</div>
  <div class="last">The second paragraph.</div>
  <div class="last">The third paragraph.</div>
  <div class="last">The fourth paragraph.</div>
  <div class="other">the other paragraph.</div>
  <div class="other">the other paragraph.</div>
  <div class="other">the other paragraph.</div>
</div>

3 个答案:

答案 0 :(得分:4)

您需要做的是使用包装元素。使用时请查看。

JSFiddle

<div>
  <div class="last">The first paragraph.</div>
  <div class="last">The second paragraph.</div>
  <div class="last">The third paragraph.</div>
  <div class="last">The fourth paragraph.</div>
</div>

.last {
background: yellow;
 border-bottom: 1px solid #cccccc;
}
.last:last-child {
    background: red;
     border-bottom: 0px solid #cccccc;
}

答案 1 :(得分:3)

第一季答案:(更新您的帖子)

  

<div class="last">The fourth paragraph.</div>是最后一个没有最后一个,因为在Fiddle你的代码就像(使用开发工具):

<body>
  <div class="last">The first paragraph.</div>
  <div class="last">The second paragraph.</div>
  <div class="last">The third paragraph.</div>
  <div class="last">The fourth paragraph.</div>
  <script>...</script>
</body>

所以,最后一个孩子是<script>没有<div class="last">The fourth paragraph.</div>

用于修复我使用:

.last:nth-last-child(2) {
    background: red;
     border-bottom: 0px solid #cccccc;
}

Demo

另外,您可以使用div:last-of-type

Demo

谢谢@Michael_B。

第二季答案:(更新帖子后):

您必须使用.last:nth-child(5) {

Demo

答案 2 :(得分:0)

你应该试试这个

.last{
  background:yellow;
  border-bottom:0px solid #cccccc;
}

.last div:last-child{
  background:red;
  border-bottom:1px solid #cccccc;
}
<div class="last">
  <div>The first paragraph.</div>
  <div>The second paragraph.</div>
  <div>The third paragraph.</div>
  <div>The fourth paragraph.</div>
</div>