Why do people use this kind of CSS and HTML to style their pages?
<div class="page">
<div class="page-left-column">
<div class="page-left-column-container-box">
<div class="page-left-column-container-box-element-header-wrapper">
<h2>This is the header!</h2>
</div>
</div>
</div>
</div>
The above markup would be accompanied by CSS rules like this:
.page-left-column-container-box-element-header-wrapper {
color: red;
}
Why not write it like this:
<div class="page">
<div class="left column">
<div class="container-box">
<div class="element header-wrapper">
<h2>This is the header!</h2>
</div>
</div>
</div>
</div>
And then make the CSS rule (perhaps not all of this would be required):
.page .left.column .container-box .element.header-wrapper {
color: red;
}
As far as I can see, the latter is much superior to the first one. It is easier to specify CSS rules without having to copy-paste everything all over the place because you can specify rules like .container-box .element and .column .header-wrapper. In my opinion, this also makes the rules, code and everything more maintainable. The only downside to this is that if you write CSS rules like this: .page .left.column .container-box .element.header-wrapper then the selector will have a dependency to a deep HTML hierarchy. However, the page-left-column-container-box-element-header-wrapper may not have such a hard dependency to the hierarchy but obviously changing the hierarchy would make one want to update the “false” class name, would it not?
The only reason I can imagine for using class names like page-left-column-container-box-element-header-wrapper is that perhaps using slightly more “complex” selectors is computationally expensive and makes the browser slow. Can this be true? Are there other programming-related/technical advantages that I’m just not seeing? Or is it just that rules that use multiple elements, classes and ids are complicated?
Both of those are poor examples of CSS.
CSS like:
is far too specific, meaning it’s re usability is minimal.
CSS like:
Is just too long a word. You could easily shorten the name down to something like:
Which means it could be used elsewhere in code quite easily, and you can easily identify what the element is for, it wraps a header.
CSS Specificity:
Please note, I do not agree fully with some of the content on these links, such as “never” using IDs
Put simply, people use those methods because they don’t know any better half of the time.
Naming conventions is quite a subjective topic however, I personally believe CSS classes & IDs should be under 20 characters always, if not 10. BUT, they should be understandable. For example:
Is poor … whereas:
etc is a nicer way. (This is just an example, I wouldn’t necessarily recommend having classes named like that.)