CSS Selector: Last-child not working

2020-05-10 17:44发布

问题:

In the following example the first-child selector works, the last-child doesn't. Please see attached screenshots.

The Problem: My class "gotit" colors the bar green, the class "go4" colors it grey. The last gotit should be red. Sounds simple, huh?

So now dig in: If I try to select the first-child, it works like a charm:

If I try to select the last-child, it just does nothing.

Anyone here with a hint whats wrong? Thank you in advance!

回答1:

Make sure .gotit is actually the last child of .parent. Like below.

.inner {
  min-width: 50px;
  min-height: 20px;
  background-color: gray;
  float: left;
  margin: 2px;
}
.inner:last-child {
  background-color: red;
}
<div class="outer">
  <div class="inner"></div>
  <div class="inner"></div>
  <div class="inner"></div>
</div>

If it isn't, using :last-child with .gotit won't work. See below.

.inner,
.inner-other {
  min-width: 50px;
  min-height: 20px;
  background-color: gray;
  float: left;
  margin: 2px;
}
.inner:last-child {
  background-color: red;
}
<div class="outer">
  <div class="inner"></div>
  <div class="inner"></div>
  <div class="inner"></div>
  <div class="inner-other"></div>
  <div class="inner-other"></div>
  <div class="inner-other"></div>
</div>

I'm guessing your markup looks like the above markup. Try regrouping your elements to help ensure that :last-child or :last-of-type will work. Something like below.

.inner div,
.inner-other div {
  min-width: 50px;
  min-height: 20px;
  background-color: gray;
  float: left;
  margin: 2px;
}
.inner div:last-child {
  background-color: red;
}
<div class="outer">
  <div class="inner">
    <div></div>
    <div></div>
    <div></div>
  </div>
  <div class="inner-other">
    <div></div>
    <div></div>
    <div></div>
  </div>
</div>