Google analytics script

Latest jQuery CDN with code tiggling.

Wednesday 14 November 2018

Any CSS class selector can have ID specificity

This will be a very short blog post. It's actually a life-saving hack that allows you to define a CSS class selector that has an ID specificity. You will know where it comes handy when you'll face such problem.

We were having a situation of our Angular app running inside a container and outer styles were interfering with our app styles. We already prefix all of our selectors by the container's CSS class name, but sometimes that's just not enough. And since scoped CSS isn't a thing any more, and we didn't want to refactor our app to have an ID container as there may be multiple instances of the same app in different containers (ID must be unique even though browsers are very loose when it comes to this), we wanted to raise our selectors' specificity anyway.

The highest specificity is the one of the element ID. But our container element only had a CSS class. We could prefix our selectors by multiple container's CSS class names, but we still wanted to have an ID selector specificity to stay on the safe side.

// multiple CSS classes sometimes help, but not always
.app.app.app.app.app p {
    ...
}

So something occurred to me and I started up the specificity calculator and tested what it returns for the selector I had in mind. This is what I entered:

// let's make a CSS class selector with an ID specificity
.app:not(#nonexisting) {
    ...
}
To my great surprise, the specificity calculator actually gave me an ID specificity! But calculator itself may not be correct so I tried it in the browser and it also worked.

So there you have it. Using the same trick you can always write a selector that will have the desired specificity. Just put the correct selector within the :not() pseudo class and voila... Specificity raised.

1 comment:

This is a fully moderated comments section. All spam comments are marked as spam without exception. Don't even try.

Note: only a member of this blog may post a comment.