Over a million developers have joined DZone.

CSS Selector Length: Myth Busting

DZone's Guide to

CSS Selector Length: Myth Busting

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

If I read one more misguided CSS post or article on CSS  selector length I think I'm going to explode. Somehow component-based CSS ideologies managed to brainwash our community and launched a faux best practice that the length of CSS selectors is something your average CSSer should worry about. Well, it is not, nor should it ever be.

While CSS selectors are an important part of the CSS syntax, the length of a selector is largely defined by the HTML structure, not by the skills of the CSSer. Of course people add 'unnecessary' elements to their selectors from time to time (sometimes for clarity, sometimes for future-proofness, sometimes because they're a little too protective of the scope and sometimes out of error). But there is no way you could ever restrict the length of a CSS selector to a specific number (I read some blogs going as low as just 3 of 4 elements). In the end the HTML dictates the length of a CSS selector, the CSSer's job is to write the correct selectors.

If you want to apply a modular approach to your CSS code you need to make sure you know your way around preprocessors. While a modular CSS approach can only be encouraged, massacring your HTML code for it is plain stupid if you could just as well make an abstraction (mixins) of your styling and apply these mixins to the right selectors. That's what preprocessors are for, as they allow you to implement both a modular HTML  and modular css approach.

And unless you're working on a website in the range of the Alexa Top 500, you don't need to worry too much about performance either. It's best to test for yourself of course, but seeing the data on my blog (as someone who doesn't mind writing a selector of 10+ elements if necessary) we're talking actual single-digit milliseconds here, even in "unoptimized" form. Unless you're a true performance zealot that doesn't care about maintainability and correctness, the impact is negligible.

CSS selectors aren't about length, they are about HTML structures and targeting just the right elements.

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}