Search the site:

Copyright 2010 - 2024 @ DevriX - All rights reserved.

Naming Your Classes and Writing Proper Selectors

Notice* – The suggested method of naming classes, building markup and writing selectors is what I came up with after dealing with many small, medium and large-sized projects, consisting of many custom elements and layouts. Consider the following tips as a style-guide or a suggestion on how to organize your markup in an easy to read, extensible and modifiable manner that is friendly and welcoming to other developers.

[Most of the examples are in emmet syntaxis]

Many different approaches exist about naming your CSS classes. As with any other conventions each one applies to certain type of projects. The ones you might find useful for example, in large to small-scale applications, could be BEM or SMACSS or any other related. What I want to suggest here is the use of a mix that provides both an easy way to understand and a structure your markup and selectors, as well as good readability and easy to follow standards.

Collection of CSS tools

Image from http://octuweb.com/

What I’ve found to be the most useful strategy, in maybe 90% of the sites I build, was looking into the different elements as modules. Each module is part of a bigger one and is capable of holding other modules as a container. Each of them can and should be able to exist on its own while its parent modules can change their appearance. The idea is to build your markup with those modules, so that you can reuse and write a lot less repetitive code.

Here are a few examples that illustrate this.

Let’s say you want to style your blog post. What is a blog post? It’s an .article or an .entry or .post or whatever you want to call it. Basically, it’s one independent module of your site that should be able to exist on its own. Even though, it’s a part of a bigger one called .main-content or just .content. So we have .entry, its child elements being part of the module with its own name, like header or content or featured image, right? Well, here’s the deal: you can use the module name as a prefix to those sub-elements. So the header becomes .entry-header, the content becomes .entry-content and so on.

Now, this is probably the way, you were making your markup before, and it practically follows most of the standards written across the web. But this was an example for one single module, what we want to do now is nest modules; and here is the way to do that.

Nesting Modules

Let’s say you want to add meta information about your post. You can look at that as a different module that could be inserted into something else, not only articles. Maybe images from your gallery or some user information? So, to keep it a part of the .entry module we will add .entry-meta as usual, but also a .meta class to it, in order to indicate it’s a separate module while also being a part of .entry at the same time.

Now all of its inner elements will be prefixed with the .meta class, so that way the author becomes .meta-author, or the date becomes .meta-date and so on. Using this method, you combine the BEM way of showing which element is a child of what and what’s the connection between them, as well as giving full control and extendability to your elements.

It will also force you to think of a proper way to name your classes so that there are no modules that clash. If that happens, you should consider the main difference between them so that you can create a new module.

The advantage here of the BEM way is that you keep your classes shorter and easier to read. Instead of having .container__select-boxes.container__select-boxes–large you get .select-boxes.large. If this module is part of another container and the element is not the core component to its parent, and the block can be elsewhere, then there is no need to have it in the class name. If it is an important part of a component, then it becomes .container-select-boxes.select-boxes.large

Modifiers

Modifiers are classes that you can use to configure your elements. For instance, let’s take a .button element. If we want to make the button red, what BEM says is to name your modifier .button–red or .button–round. All cool, so then your markup would look like this: a.button.button–red . To me that  takes up space and it’s too long to type. Why not just name your modifier .red ? Then you have .button.red.round – way shorter and easy to read.

Here, it’s important not to have global classes with unspecific naming like .red or .big. Always be specific with the global ones, so if you want red text make it .text-red. For the button, it will be part of the .button module, so you can wrap it easily with SASS.

Some developers though, like to put .u- or .m- for utility classes. To me, it’s vague, and you don’t actually know what it is unless read the documentation or take a guess. Besides, anyone can think of his own modifier classes.

See, the guys that build Foundation, for instance, use self-explanatory modifier classes that configure the style of a module. A quick example can be converting some text to uppercase. You just add the class .text-uppercase and you are done. Or even just .uppercase, it’s up to you.

The reason for this is that if you happen to work as a team, or you are providing stylings for a site or app that will be further developed by other people. And you probably won’t be required to write full documentation on the classes and prefixes you have used throughout your application.

Finally, you should aim to provide a clean way of naming and understanding what your elements are, what module they are part of, and the clearance on their modifiers (utility classes) as well as extendability and reusability – both key to an easy maintenance and collaboration on an app, because thanks to that, the chance for something to break will be significantly lower.

Classes

So you have a nice structure, everything is in its own module, things are going good. Well… not yet. In order to be able to easily extend and use your utilities, you must build good organized selectors that apply your styles.

Rule number one: Don’t go deep into the rabbit hole! Way too explicit selectors are bad and you should feel bad for even writing them. A rule of thumb is: Don’t go more than 4 levels deep including your pseudo selectors. Here is a good article on what CSS specificity is. I recommend bookmarking it and reading it later.

Soo… as we’ve got our modules ready, the markup is built, it’s time to style it. Let’s say that you are working on .entry now. You should be using Sass or Less by now (or whatever other preprocessor). My example is with scss since it’s what I like and what I use daily. Here is how I structure my modules:

.entry {
&-header {}
&-title {}
}

What I’m doing is using the & symbol to make sure i am not being too specific with my selectors. By doing that I’m wrapping them both with the .entry and making sure they are only one level deep. The output css of this would be:

.entry {}
.entry-header {}
.entry-title {}
Specificity graph

See more on http://cssstats.com/

Now if you want to write global utility classes, that don’t only apply to certain elements, you can have them anywhere in your scss files, without worrying that you could overwrite anything. Simply adding your modifier as first level (global) anywhere in the code will give it more weight than .entry or .entry-title or any other first level selector.

Think of the modifier as a helper class, examples can be also .clear-both, .text-center, .ul-center, .alignright and so on. Note that the bad way of writing them is .cl .m-tc, .ulc, .al-r, .al-l or any related short versions.

CSS - Do not use !Important

Source: http://www.2n2media.com/

In short, you don’t have to write modifiers in every module, just do it once globally and reuse them with ease. And of course, !important should rarely be used. In  fact, I can think of only two reasons to place !important in your styles and they are:

  • One – showing your buddy what bad code is, and
  • Two – overwriting inline styles applied from plugins to your markup (which are bad, if you write such plugins use class toggling).

Selectors

You see, css selectors are not only used in css files, you need them if you work with jQuery too (or at least you should need them), because I’ve seen people who use .find() .children() chained until they get the element they need.

However, there is no need to do that, you can set all of this with css selectors. Here are a few that I often use:

  • .element > .children – Selects the first level child elements and nothing else. So you can easily have a dropdown menu and focus only on the first <h1> tags.
  • .element * – Not often used, but still comes in handy. Most popular in the box-sizing trick.
  • .element[data=””] , .input[type=”text”] – You can select by element attributes. It’s useful if you are playing with some extra JS functionality.
  • .element:nth-child – Pretty much one of the most often used by me, select what you need and nothing more. You can play with it here to see some practical examples about how it works.
  • input:required – Can come in handy when dealing with forms.

For a more complete list of selectors check the CSS Selector Reference.

Always keep in mind that you should not be too specific with your selectors. They should be as easy as possible to overwrite. Every instance of overwriting some class is a small step to messy stylesheets. Now, I don’t mean that you shouldn’t ever do that; what I mean is that the more you overwrite, the harder it will be to keep track of what is going on. It also increases the number of possibilities for bugs to appear. For instance, I remember the frustration I had when I had to change the look of foundation’s nav menu.

.top-bar-section li:not(.has-form) a:not(.button)

See how it is not all that specific (3 elements) but it has :not twice, which means that if you want to style this element, you have to add one more rule to it when not using extra classes.

Foundation, Bootstrap and any other similar framework are okay for quick templating your site. Their js plugins can be helpful, and I personally use the grid provided by Foundation. However, all the other css they provide gets in the way. It forces you to overwrite and go deeper and deeper, and in the end, you end up with messy, hard to maintain or extended code.

Markup

So the way to deal with bad selectors is to have a proper markup. Have you ever written a heading of a section with just <h1></h1>

and no other classes? And then select it by .parent > h1 or something similar? I have and it was bad.

Bad, because if you make SEO changes or you want better semantics or whatever else, you have to change the element, and the selector. Therefore, my suggestion is to always have class names assigned to your html elements through which you can access them.

That excludes content of course, it’s pointless to write classes on every element unless you include other custom modules (in WordPress terms – shortcodes).

Your markup must be as simple as possible, try to make the least possible wrappers to your elements. For example having:

<div class="wrapper"></div>

This example is something you should seriously try to avoid. As explained, every module should be able to exist on its own. All of its styles should not be tied to any outer class, although it’s perfectly ok to modify the styles of your modules according to the parent element. In the best case scenario your wrapper classes should be modifiers, which you can reuse around any other module. Let’s say you have a very basic .box element:

<div class="box"></div>

On its own it should have all the stylings like paddings, borders, base background color, font settings, box-sizings, shadows, etc. But when being inside of an .article element, this box should be rounded, then inside your .article definition you set the stylings for .box. That way you can easily overwrite the base stylings and still reuse the module as a child of any other element.


<article class="article">
<div class="box"></div>
</article>

Consider the wrapper element as a modifier. This concept is what allows you to reuse all of the elements you write for your templates. Furthermore, it’ll save you time on rewriting, debugging and trying to overwrite other classes.

Summary

Try to keep all your markup and stylesheets modular. Always ask yourself “can I extend this”, “can I reuse this” or “is it understandable”. Proper class naming and a consistent way of building your markup will pay off as the project grows. Having global modifiers in one place serve as a quick documentation on what can be used and changed through HTML.

Moreover, you shouldn’t have to delete/move or edit your selectors and styles in order to overwrite or update site content. Having them packed will help you reuse code in other projects, saving you a time, and allowing you to focus on the architecture of your application instead of battling your own stylesheets.