paint-brush
Best Practice in CSS: Organisation and Naming Conventionsby@daniel-sipe
17,088 reads
17,088 reads

Best Practice in CSS: Organisation and Naming Conventions

by Daniel SipeJuly 30th, 2020
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

Best Practice in CSS: Organisation and Naming Conventions. I've been writing code for over three years and asked myself about the good practices and how I could make my code more readable, understandable, easy to maintain and to be handled by other developers. Without some writing rules, one can find himself with a complicated code to read and difficult to debug. We spend more time reading our code rather than writing it because we always look for the element that we can modify, improve or just to remember ourself how this or that element works.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Best Practice in CSS: Organisation and Naming Conventions
Daniel Sipe HackerNoon profile picture

I've been writing code for over three years. I have always asked myself about the good practices and how I could make my code more readable, understandable, easy to maintain and to be handled by other developers.

We spend more time reading our code rather than writing it because we always look for the element that we can modify, improve or just to remember ourself how this or that element works. So, it’s important to write a good code in others words a clean, consistent, an extensible and correct code.

Writing a code is not as easy as it appears. Without some writing rules, one can find himself with a complicated code to read and difficult to debug. Therfore, difficult to maintain and to evolve with the harmful effects on the performance of the software hence the importance of optimizing our code in other words, a code permeating good practices. So what are good practices in CSS?

Use stickler

Stickler is a powerful tool which allows a developer to respect the standards of coding established before the realisation of a project by himself or by his work team. Before writing a line code, most often developers establish coding standards that they will follow in order to realise the project on which they want to work. This tool intervenes on several aspects especially the improvements of the code indentation, the correction of syntax errors and the identification of places where there is a duplication of the code.

Stickler is used by a wide community and it’s quite flexible in his configuration.

Segment the CSS in multiple files

Cutting out his CSS code into many files each corresponding to a module, a view, or a page of your application is very recommended. The choice of cutting is free depending on what appears for you most pertinent.

The cutting of the code into files enables to navigate easily when we have to extend, modify or create new declarations.

Examples:

homepage.css
header.css
footer.css
archive.css

The merits of splitting the CSS in multiple files and to increase appears mainly when someone uses a preprocessor CSS (Sass or Less)

Understanding the specificity

The specificity determines what CSS rule is to apply by the navigator. The is a hierarchy, not necessarily intuitive in the order of application CSS rules.

It’s important to keep in your mind that all selector has to be declared with the less of specificity as possible. This facilitates reusability of the selector and reduces the dependency to another selector.

Prefer :

.myclass {...}

rather than:

body.page .main .sidebar article > .myclass {...}

In most cases, this will prevent you from having to deal with CSS-specific conflicts.

Be DRY

Don't repeat yourself (DRY, or sometimes do not repeat yourself) is a principle of software development aimed at reducing repetition of codes or software patterns.

The DRY principle is simple to understand "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system".

Example :

.texte-erreur {
 font-size: 15px;
 background-color: #ccc;
 border-color: red;
 color: red;
}
 
.bloc-erreur {
 width: 250px;
 height: 250px;
 background-color: #000;
 font-size: 17px;
 border-color: red;
 color: red;
}

We observe that two classes share their properties border-color and color. We can consider they always find themself together for a certain number of classes. Then we can create a mixin and the follow classes :

mixin erreur-base() {
 border-color: red;
 color: red;
}
 
.texte-erreur {
 font-size: 15px;
 background-color: #ccc;
 @include erreur-base();
}
 
.bloc-erreur {
 width: 250px;
 height: 250px;
 background-color: #000;
 font-size: 17px;
 @include erreur-base();
}

We just gained readability and refactored our code to avoid repetition.

Naming convention

Naming things is never easy and the nomenclature of classes and id attributes in CSS is no exception. The problem with bad naming is that it is then difficult to find yourself in its code, so it’s important to find a particular convention to organize yourself well.

During my researches on this subject, I have identified two popular naming conventions notably the OOCSS and BEM.

OOCSS

Object-oriented programming (OOP) is a programming paradigm that focuses on creating reusable objects and establishing relationships between them, as opposed to procedural programming that organizes the code into procedures (routines, subroutines, or functions).

Object oriented CSS was proposed by web developer Nicole Sullivan in 2008.

It’s neither a preprocessor nor even a new language, but rather a code philosophy.

OOCSS PRINCIPLES:

  1. The separation of “structure” from “skin
  2. The separation of “container” from “content

CONTENT - SKIN :

  1. Define the repeating “visual” patterns as reusable “skins
  2. Define the repeating “invisible” patterns as reusable “structures“ 
/* structure */
.btn {
  display: inline-block;
  font-weight: 400;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  border: 1px solid transparent;
  padding: 0.375rem 0.75rem;
  font-size: 1rem;
  line-height: 1.5;
  border-radius: 0.25rem;
  transition: color 0.15s; 
}
/*SKIN*/
.btn-success {
  color: #fff;
  background-color: #28a745;
  border-color: #28a745;
}

.btn-danger {
  color: #fff;
  background-color: #dc3545;
  border-color: #dc3545;
}

.btn-warning {
  color: #212529;
  background-color: #ffc107;
  border-color: #ffc107;
}

CONTAINER - CONTENT

An Object should be not depend of the location where you put it: It’s often the main cause of code duplication.

    .announcecategory > div:nth(3) {
      color: red;
      /*...*/
      /*BAD! div:nth(3) styles are location dependent*/
    }
    
    .announcecategory {
      display: inline-block;
      /*...*/
      /*we can reuse this category style wherever*/
    }


Limitations and disadvantages of OOCSS:

  1. Utility classes tie your markup to presentation.
  2. OOCSS doesn’t give rules of the clear and firm building, and the past time to factorize the appearance can very often exceed the gain of the reuse. That could increase considerably the time of realisation projects.

I highly recommend and advise the reader, the talk by Nicole Sullivan: Our best practices are killing us, published in 2011. It has allowed to several integrators to better understand OOCSS and to start using this naming concept.

The reader wishing to deepen will then read the wiki of the framework OOCSS.

If you've ever worked with the bootstrap, you probably noticed by reading this section that the bootstrap team uses this approach heavily.

it exists other good practices of naming.

BEM

BEM is the acronym of Block, Element, Modifier and all the methodology of the naming hold on in these three words. The force of the concept? What makes up a page or a web application can always be stored in an arborescence of blocks, Elements and modifiers.

A block is an independent entity which must be able to be moved without affecting its appearance or its functioning.

An element is a part of block. The context of an element is that of the block. This can be a header, a footer, a container (articles, sections ...), a menu or even a button. As it appears clearly, a block can also contain other blocks. An interface can include several instances of the same block. 

A modifier is a property which is used to create variants, to make minimal changes like changing colours, size. There exists modifiers of blocks and the element modifiers.

The methodology BEM has three essential rules:

  1. The blocks and elements have to each other have a unique name, which will be used as a CSS class
  2. The CSS selectors don't have to use the HTML elements (not of footer div)
  3. Cascades in CSS selectors should be avoided ( not of .foo > .bar)

Naming convention:

Bloc:

  • bloc-name

Element:

  • bloc-name__element-name

Modifier :

  • bloc-name--modifier-name
  • bloc-name__element-name--modifier-name

The official website takes care to specify that only the concepts count, the syntax remaining free.

Advantages of BEM:

  • Performance: The performance concern more particularly the web application. The nomenclature of BEM allows to have the majority of CSS classes at the first level. Browsers organize CSS classes in a table of the global hash, but it would be too expensive to create subtables for descendants at the level of each HTML element. Also, in CSS, only the first level of selection is high-performance.  CSS cascade, when there are many of them, this creates fluidity problems, especially on the animated pages of Web applications.
  • Lisibility: Class names are logical and intuitive, and every member of the team knows what that element does on the website. BEM gives everyone on a project a declarative syntax they can share. So, they’re on the same page.

Limits and disadvantages of BEM:

  • Verbose: The nomenclature of BEM is a little bit verbose. Indeed, we remark that as soon as we have modifiers to implement, we find ourself very fastly with a long and complex class attribute.

Important to know:
The naming convention is open, someone can mix the two conventions listed previously depending on needs of the project or even in creating if someone can do better than the conventions of existing name

Conclusion:

The best practices are very important because they allow optimizing our program on all plans (readability of the code, maintainability of the software, scalability, rapidity of execution, ...).