css organisation: hyphenate classes and ids, use short and consistent naming conventions
In this post we will see how implementing a consistent naming convention for our CSS classes and ids, using hyphen delimiters, will allow us to easily arrange our CSS into concise modules making our style sheets more organised and can also speed up our page loading and rendering too.
For the remainder of this post I will be referring mainly to CSS classes, though the same principles can and should be applied to IDs as well.
Use hyphens, not camelCase
There is nothing stopping you from using camel case. I’ve always found using camel case for defining CSS classes makes your code look messy and harder to read when skimming through an html page. It is also easier to search for hyphenated CSS classes in JavaScript rather than camel case as we generally uses camel case naming conventions in JavaScript. Consider the following code:
ns.fooBar = $( '.fooBar' );
ns.fooBar.bind( 'click', function() {
ns.fooBar.toggleClass( 'selected' );
} );
Compared to this:
ns.fooBar = $( '.foo-bar' );
ns.fooBar.bind( 'click', function() {
ns.fooBar.toggleClass( 'selected' );
} );
Your eye has a much easier time finding the foo-bar CSS class amongst all the fooBar JavaScript variables. When you have thousands of lines of code to skim through, this can become a valuable time saver. If you want to do a search and replace on .fooBar, it also leaves a greater margin for creating a JavaScript error — as you can see the JavaScript property ns.fooBar is also preceded by a period — whereas search and replacing on .foo-bar would not only be a much quicker search, it almost eliminates the margin for error by excluding all fooBar strings. Hyphens are not valid characters for standard JavaScript variable/ property names, it’s worthwhile having thus clear separation of presentation and behaviour.
However, if that’s not enough to convince you. Using a hyphen also makes it easier to use a CSS class to hold values we want to later retrieve using JavaScript. Consider the following simple example:
<div class="carousel horizontal3easeIn">...</div>
<script type="text/javascript">
var optionsStr = documents.getElementsByClassName( 'carousel' )[0].className.split( ' ' )[1],
carouselOptions = optionsStr.match( /([A-Za-z]+)(d+)(.*)/ ), // regex to extract carousel options
carousel = new Carousel( {
orientation : carouselOptions[0],
itemsPerPage : carouselOptions[1],
animation : carouselOptions[2]
} );
</script>
To get the options to initialise the JavaScript Carousel class we need to create a regex to extract the values from the CSS class, horizontal3easeIn. This means, if we want to add more options or change the order of these options, we would need to keep adjusting the regex as well as the instantiation code. Consider the next example:
<div class="carousel horizontal-3-easein">...</div>
<script type="text/javascript">
var optionsStr = documents.getElementsByClassName( 'carousel' )[0].className.split( ' ' )[1],
carouselOptions = optionsStr.split( '-' ), // simple String.split
carousel = new Carousel( {
orientation : carouselOptions[0],
itemsPerPage : carouselOptions[1],
animation : carouselOptions[2]
} );
</script>
With this example we only need to split the CSS class, horizontal-3-easein, at the hyphen delimeter. There’s nothing complicated and it’s a lot faster than using a regex.
So to keep things simple, consistent and fast we will only use hyphens in our CSS code.
Don’t include the tag name!
The amount of times I’ve seen code like this:
<style type="text/css">
#containerDiv {}
.leftDiv {}
.middleDiv {}
.rightDiv {}
</style>
...
<div id="containerDiv">
<div class="leftDiv" />
<div class="middleDiv" />
<div class="rightDiv" />
</div>
I mean seriously, at what point do you think you’re going to forget any of these are a div tag and if you did why would that matter?
There is really no need for this kind of verbose commentary in HTML/ CSS, leave it out, it’s annoying and looks amateurish. That’s all I have to say about that.
Use classes not tags
These two fantastic articles on Writing Efficient CSS and Simplifying CSS Selectors outline how browsers match a rule and the performance losses and gains from using different types of CSS selectors. They also include links to further research on the subject. In my opinion this is all mandatory reading for anyone who builds web user interfaces using HTML/ CSS.
Adaptability
The one thing I will say is, using CSS classes instead of tags will allow you to change a tag in your HTML document without having to change your style sheet.
The best example I can give is the use of headings. If you are as fanatical about correctly nesting your headings as I am, then consider the following example:
<style type="text/css">
.foo-ct h3 {}
</style>
...
<div class="foo">
<div class="foo-ct">
<h3 class="foo-hd" />
<div class="foo-bd" />
<div class="foo-ft" />
</div>
</div>
If we want to reuse this module in a different section of our page/ site where the <h3> would be an <h4>, we would need to add more styles to our stylesheet to reflect this or our headings could potentially be different sizes and worse, lacking specific styles like backgrounds, borders, colours, etc.
Using the CSS class .foo-hd instead of the tag, allows us to adapt our mark up without having to, also adjust, our style sheets.
Having a system/ Keeping it simple
Having tried to implement this type of naming convention in a few jobs, I’ve seen some developers churn out CSS/ HTML code with some crazily long class names — I’ve seen some class names with over 30 characters. Consider the following (tame) example:
<style type="text/css">
.foo {}
.foo-container {}
.foo-container-header {}
.foo-container-body {}
.foo-container-footer {}
</style>
...
<div class="foo">
<div class="foo-container">
<h3 class="foo-container-header" />
<div class="foo-container-body" />
<div class="foo-container-footer /">
</div>
</div>
Repetition like this seems ridiculous. Why do we need to repeat the word container in each of its childrens’ class names?
The first thing we can do is get rid of the container- in the header, body and footer div tag class names. That’s easy, but why do we need long names like foo-container, foo-header, etc? If we want to be more efficient we can further reduce those names down, as in the following table:
| class name | description |
|---|---|
| ct | container |
| hd | header |
| bd | body |
| ft | footer |
Let’s look at the revised code:
<style type="text/css">
.foo {}
.foo-ct {}
.foo-hd {}
.foo-bd {}
.foo-ft {}
</style>
...
<div class="foo">
<div class="foo-ct">
<h3 class="foo-hd" />
<div class="foo-bd" />
<div class="foo-ft" />
</div>
</div>
Say you’re building a site for an online retailer and they are displaying 100 products on a page using this format. The first example has an extra 4kb of CSS class names in the HTML page for the end user to download!
Having a set of abbreviated class names in a table like the one above — that you can easily print out and stick on a wall visible to all developers, or as a card developers can have on their desks — can greatly reduce the amount of time developers need to spend coming up with their own class names, improve the consistency of your naming conventions and reduce your overall page weight, without the need of a lengthy document.
Conclusion
Having a consistent naming convention for your CSS classes and IDs, using a hyphen delimiter, and assigning style rules to CSS classes, instead of tags, will help to make your CSS easier to read, easier to program, with JavaScript and potentially quicker to render.
Abbreviating commonly used CSS class names can help to reduce your overall page weight. Printing them out, in a table and making them easily accessible to all developers, provides a very simple guideline to follow without the use of lengthy documents.
This is part 2 of a 3 part series.