There is an old wisdom in computer engineering that software should be divided into independent components. This is called a separation of concern principle. This principle should be practiced when you write website’s front-end: HTML, CSS, JavaScript. Bellow is a list of rules I try to follow to achieve separation of concern in CSS.

CSS in separate file from HTML

HTML, CSS and JavaScript should NOT be mixed. They should be located in separate files. If you believe that you want to send them together for better performance, you still should write them separately. Then, write a script that combines different source files. Finally, measure how much your performance improved.

There are few exceptions to this rule. For example, you are writing a blog article. You want a specific text to be of a specific color. That color would be defined as inline CSS.

Divide Page into Independent Elements

Take your webpage and divide it into independent elements. Each element should have separate class name and CSS definition. Each element should be simple, but it can be composed of sub-element. However, sub-element should be independent of the parent. Also, have a convention for naming your independent elements. I like to use “-block” suffix.

Consider the following example:

<div class="aside-area-block">
  <div class="aside-area-block-content">
    <div class="news-banner-block">...</div>
    <div class="recommendations-banner-block">...</div>
  </div>
  <div class="aside-area-block-footer">...</div>
</div>

Here, you have three independent elements:

  • aside-area-block
  • news-banner-block
  • recommendations-banner-block

Each one should be styled as if there was no relationship between them.

Define Common Style Separately

Have a separate set of classes for definitive common style between elements. One convention is to have “is-” prefix for boolean properties. For example:

  • is-disabled
  • is-active
Use “-look” suffix to define  common style between different elements. For example, you could have a class “important-banner-look” that draws a red box around this element.

Let’s say you have two elements of the same type, “news-banner-block”. You want to have two versions of it: wide and narrow. Then use “-version” suffix to create two variants of the same element, ex: class=”news-banner-block narrow-version”

Finally, buttons and titles are recurring elements on most websites. They repeat over and over in different areas, and they often follow the same style. If you design has 2 styles of buttons and 3 styles of titles, have that in CSS two. Create appropriate class with “-button” and “-title” suffixes.