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:

CSS

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

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.

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
*
*