skip to Main Content
.d1 {
  display: flex;
  justify-content: space-between;
}

.d1>div {
  display: flex;
  flex-direction: column-reverse;
  justify-content: flex-end;
}

.d1>div>span:last-child {
  color: green;
  font-size: 30px;
}

.d1>div>span:nth-child(2n) {
  color: red;
}

.d1>div>span:nth-child(2n+1) {
  color: blue;
}
<div class="d1">
  <div>
    <span>2</span>
    <span>+3</span>
    <span>5</span>
    <span>+6</span>
    <span>11</span>
  </div>
  <div>
    <span>7</span>
  </div>
</div>

In the above example, I am trying to implement an addition for two different columns that is executed with javascript code. The row is from bottom to the top. The last number to be shown must be higher font-size and with green color. This font-size works for both columns but not the color. I add the color: green inside the span:last-child but that does not seem to work… How could I fix this? Thanks

2

Answers


  1. To fix this, you can update your CSS code to force the color change on the last element as follows:

    .d1>div>span:last-child {
      color: green !important;
      font-size: 30px;
    }
    

    (Caution: Using !important would override any other styles applied to the element, it is generally considered bad practice to use it unless absolutely necessary)

    Login or Signup to reply.
  2. It’s a specificity problem:

    When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element. (MDN)

    Your last-child styles are overridden by the odd and even elements styles. To solve this, you can move the last-child styles after the odd and even ones:

    .d1>div>span:nth-child(even) {
      color: red;
    }
    
    .d1>div>span:nth-child(odd) {
      color: blue;
    }
    
    .d1>div>span:last-child {
      color: green;
      font-size: 30px;
    }
    

    You can also use the odd and even keywords to make the code more readable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search