last-child and last-of-type not working in SASS

75,876

Solution 1

Nesting is not a requirement with Sass. Don't feel obligated to do so if there's no need to break up the selectors.

.try-me img:last-of-type {
    position: absolute;
    top: 0; 
    left: 0;
    display: none;
}

If you are applying styles to the image and then specific styles to the last-of-type, then this what it would look like when you nest it:

.try-me img {
    // styles

    &:last-of-type {
        position: absolute;
        top: 0; 
        left: 0;
        display: none;
    }
}

Solution 2

Neither of the above worked for me, so.

last-of-type only plays nice with elements, you can select things with classes all you like but this gets handled by the elements. So say you have the following tree:

<div class="top-level">
    <div class="middle"></div>
    <div class="middle"></div>
    <div class="middle"></div>
    <div class="somethingelse"></div>
</div>

To get to the last div with the class of middle, doesn't work using last-of-type.

My workaround was to simply change the type of element that somethingelse was

Hope it helps someone out, took me a while to figure that out.

Share:
75,876

Related videos on Youtube

Leon Gaban
Author by

Leon Gaban

Investor, Powerlifter, Crypto investor and global citizen You can also find me here: @leongaban | github | panga.ventures

Updated on September 13, 2020

Comments

  • Leon Gaban
    Leon Gaban over 3 years

    How would you write this to be SASS compliant?

    .fader { display: inline-block; }
    .fader img:last-child {
        position: absolute;
        top: 0; 
        left: 0;
        display: none;
    }​
    

    Basically I'm just replicating this example of fading in one image over another (found here.)

    His JFiddle example: http://jsfiddle.net/Xm2Be/3/

    However his example is straight CSS, I'm working on a project in SASS and am not sure about how to correctly translate it.

    My Code

    Note in my example below, the img hover isn't working correctly (both images are showing up and no rollover fadein action happens)

    My CodePen: http://codepen.io/leongaban/pen/xnjso

    I tried

    .try-me img:last-child & .tryme img:last-of-type
    

    But the : throws SASS compile errors, the code below works

    .try-me img last-of-type {
        position: absolute;
        top: 0; 
        left: 0;
        display: none;
    }
    

    However it spits out CSS which doesn't help me:

    .container .home-content .try-me img last-of-type {
        position: absolute;
        top: 0;
        left: 0;
        display: none;
    }
    

    UPDATE: Working Codepen:

    http://codepen.io/leongaban/pen/xnjso

  • Leon Gaban
    Leon Gaban almost 11 years
    Thanks! That worked :D yeah that was my problem, trying to nest everything, should have stepped back and realized that I was trying to nest 2 different selectors. Working Codepen: codepen.io/leongaban/pen/xnjso