CSS selector for first of class

/ September 26, 2017/ Frontend General

If you have come here looking for something like :first-of-class sorry, it still does not exist. But there is a way to make something similar using a little selector trick.

Let’s see the juicy code:

Ad:

CSS

.my-container > .class-of-the-item {
    background: red;
}
.my-container > .class-of-the-item ~ .class-of-the-item {
     background: none;
}

Ad:

SCSS

.my-container {
    > .class-of-the-item {
        background: red;
        ~ .class-of-the-item {
            background: none;
        }
    }
}

See the Pen 1 of class by Saninn Salas Diaz (@saninn) on CodePen.light

So what is happening here?

First  .my-container > .class-of-the-item  applies the background to all the elements with the .class-of-the-item class, after this, the ~ .class-of-the-item selector says “select the elements that come after and have the class .class-of-the-item“. It remove the before applied background.

Ad:
Spread the love

Leave a Reply

Be the First to Comment!

Notify of
avatar