CSS selector for first of class

/ September 26, 2017/ Frontend General

(Last Updated On: February 12, 2018) If you have come here looking for something like :first-of-class sorry, it does not exist (yet?). 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 and remove the background from all the elements that come after me and have the class .class-of-the-item“.

Ad:


Spread the love
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments