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 to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.


Published at DZone with permission of Niels Matthijs, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}