Pseudo Class Selectors work on Beforehand too

Pseudo class selectors have always been there, we have used them indefinite times to make our states more cooler and interactive. We have always appended them at the end like a:hover but here I am talking about something on beforehand like:

:hover.content { /* your awesome code */ }

and yes this declaration works too. Such css can be really helpful sometimes, It’s great that these rules work too.

Why do we need Pseudo class selector on before hand ?

We generally do not need Pseudo class selectors on before hand but if they work there, it can be really helpful in making css code cleaner and with lesser repetition of rules. Especially in case if we are using Sass or LessCss. It helps in taking more benefits from these pre-processors. Now lets take a css example:

.content .text { opacity: 0.4; }
.content:hover .text { opacity: 1; }

In normal case the Less for this would be:

.content {
    .text {
        opacity: 0.4;
    }
    &:hover {
        .text {
            opacity: 1;
        }
    }
}

But instead of all this, if we just write :hover&, it will save us from all the confusions, redundancy and will result in lesser number of lines of code. Writing this:

.content {
    .text {
        opacity: 0.4;
        :hover& { opacity: 1; }
    }
}

Will generate this and everyone wins !! Because pseudo selectors work on before hand too !!

.content .text { opacity: 0.4; }
:hover.content .text { opacity: 1; }

Limitations and Screw Ups

This technique will not work for tag selectors. Like :hoverspan is pure nonsense. It will only work if the pseudo selector is after the main tag selector like span:hover. So use this technique with intelligence and common sense 🙂

Why does :hover.content works anyway ?

The answer lies in the definition of Pseudo class: A pseudo-class is similar to a css class, but it’s not specified explicitly in the markup. Pseudo classes are dynamic, they’re applied as a result of user interaction with the element.
So basically it is a class, but its not a real class, its a pseudo class. So if .main.content works, :hover.content should work too 😉

Let me know your thoughts on this . . .

Leave a Reply

  • (will not be published)