Jim Jim - 2 months ago 12
Sass (Sass) Question

CSS last-child selects all?

I've been trying to figure out why my code below doesn't work as expected.
Basically I want the ups

img
to have
width: 60px
and fedex
img
to have
width: 100px
.

My mark up is:

<div class="delivery-services">
<span>Delivery Services</span>
<br>
<a href="#"><img src="img/fedex.png" alt="fedex" /></a>
<a href="#"><img src="img/ups.png" alt="ups" /></a>
</div>


SCSS is:

.delivery-services {

&:nth-child(3) img {
width: 100px;
}

&:last-child img {
width: 60px;
}
}


But it appears that both img are affected by
last-child
!

Answer

Here is how a browser processes your selector .delivery-services:last-child img:

  1. Find the element with the class .delivery-services and make sure it's the last child. It finds <div class="delivery-services"> and it's indeed a last child. If you changed your HTML a bit like this:

    <div class="delivery-services">
        <span>Delivery Services</span>
        <br>
        <a href="#"><img src="img/fedex.png" alt="fedex" /></a>
        <a href="#"><img src="img/ups.png" alt="ups" /></a>
    </div>
    <div>I am last child now</div>`
    

    You would see that your selector doesn't match any img element.

  2. Find all img elements inside the element found on first step

That's why the style width: 60px; is applied to all img elements.

I would also advise you to use classes on those images. nth-child selector is a good fit for recurring patters, like, for example, every 3rd row has to have green background.

Here is the fix to your problem if you need to use nth-child selector:

.delivery-services {

  :nth-child(3) img  {
    width: 100px;
  }

  :last-child img {
    width: 60px;
  }
}