Search the site:

Copyright 2010 - 2017 @ 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 as well as 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 easy way to understand and a structure for 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 have 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 a 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 its 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 can illustrate what all of this is about.

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, but 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 this .entry, all of whose child elements being part of this module and have their own name, like header or content or featured image, right? Well, here’s the deal: you just 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 all good, this is probably the way you were making your markup until now 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.

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 the images of your gallery or brief information about your users? 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 its 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 is 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 for naming your classes so that there are no modules that clash. If that happens, you should think of what is the main difference between them for you to have new module created.

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 being part of another container and the element is not core component to its parent and additionally the block can be used in other places, then there is really no need to have it in the class name. If it is important to be a part of a component, then it becomes .container-select-boxes.select-boxes.large

Modifiers

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

Here it’s important to say that having global classes with unspecific naming like .red or .big is bad. 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- or whatever it is for having utility classes. To me it’s unreadable and you can say what it is only by reading the documentation or guessing, since anyone can think of his own modifier classes.

See, the guys that build Foundation for example 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 can be up to you. There is no room for confusion here.

The reason in all of 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, you won’t be required to write full documentation on the classes and prefixes you have used throughout your application.

Finally, with all of this you will aim for providing clean way of naming and understanding what your elements are, what module are they a part of and clearance on their modifiers (utility classes) as well as extendability and reusability – both key to easy to maintain and easy to collaborate on app, because thanks to that the chance to break something else will be way 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 writing them. A rule of thumb is: don’t go more than 4 levels deep including your pseudo selectors. There is a good article on what CSS specificity is, so you can bookmark it and read it later.

Soo… as we got our modules ready, the markup is built, and it’s time for styling it. Let’s say that you will be working on .entry now. Well, if you don’t live in the past, you should be using Sass or Less by now (or whatever other preprocessor is there). My example will be with scss since it’s what i like and 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 am both having them all wrapped with the .entry and having them 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, not worrying that you could overwrite anything. Simply adding your modifier as first level (global) anywhere in the code will have 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. I guess you can tell what they are just from reading here without having me explain, right? 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 once globally and reuse them with ease. And of course no !important will have to be used. Well, I can think of 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 be needing them), because i have seen people who go using .find() .children() chained until they get the element they need.

But there is no need in that, you can set all of this with just css selectors. Here are a few of the most often used by me:

  • .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 so often used, but still comes in handy. Most famous in the box-sizing trick
  • .element[data=””] , .input[type=”text”] – you can select by element attributes. Something really 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. It must be as easy as possible to overwrite them. Every instance of overwriting some class is a small step to messy stylesheets. Now, i don’t mean that you should never do that, what i mean is that the more you overwrite, the harder it will get to keep in track what is going on and increases the number of possibilities for bugs to come up and bite you. One quick example i can give is the frustration i got 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 ok for quick templating your site, i see how their js plugins can be helpful, and i personally use the grid provided by Foundation, but all the other css they provide is standing in your way. It forces you to always overwrite and go deeper and deeper, and with that you end up with messy, hard to maintain or extend code.

Markup

So the way to deal with bad selectors is to have a proper markup. Have you ever written for example 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 have to make some SEO changes or you want better semantics or whatever the reason you have to change the element, you will also have to change 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 there unless you are including 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. So for example 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 or whatever this box should look like. 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 and will definitely save you a lot of 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 get bigger and bigger. Having your global modifiers in one place will serve as a quick documentation on what can be used and changed through your HTML only.

In a perfect world you should not be having the need to delete/move or edit your selectors and styles in order to overwrite or update the content of the site. Having them all packed will help you to reuse the code in other projects, saving you a huge amount of time, allowing you to focus on the architecture of your application instead of battling your own stylesheets.

Leave a Reply

Your email address will not be published. Required fields are marked *

Find us at:
Google Plus
LinkedIn
Contacts