CSS Selector: Last-child not working

前端 未结 1 1727
时光说笑
时光说笑 2021-01-29 13:27

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

相关标签:
1条回答
  • 2021-01-29 13:56

    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>

    0 讨论(0)
提交回复
热议问题