ThomasB ThomasB - 5 months ago 17
CSS Question

CSS Selector: Last-child not working

I've a lot about my problem over here, but it didn't solve my problem. Hopefully you guys can help me.
Sorry, but I cant provide a link

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:
enter image description here

If I try to select the last-child, it just does nothing.
enter image description here

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

Answer

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>

Comments