App


CSS best practices

CSS best practices

Cascading Style Sheets (CSS) are the backbone of web design. Adopting best practices is crucial in developing and supporting huge and complex web aplications that we create today.

1. Using consistent naming conventions

There are three most used naming convections and those are BEM (Block Element Modifier), SMACSS (Scalable and Modular Architecture for CSS) and OOCSS (Object oriented CSS). It is possible to stick with one of them or create an custimized internal project-specific naming convention (e.g. in 2sxc eav-ui project for all our internal CSS styles we use "eav" prefix so it is known that that style doesn't target any internal classes).

2. Undertand CSS specificity rules

If there are two or more CSS rules that point to the same element, the selector with the highest specificity value will be have its style declaration applied to that HTML element.

There are four categories which define the specificity level of a selector:

  1. Inline styles - Example: <h1 style="color: pink;">
  2. IDs - Example: #navbar
  3. Classes, pseudo-classes, attribute selectors - Example: .test, :hover, [href]
  4. Elements and pseudo-elements - Example: h1, ::before

Specificity calculations can be seen in the table on this page

3. Optimize Selectors and Avoid Overqualification

Efficient selectors contribute to better readability and better performance (e.g. instead of div.container, use just .container if it provides the required specificity). Complex selectors are also usually very brittle as doing changes in the HTML often breakes CSS selectors.

4. Minimize the Use of !important:

While the !important declaration can override other styles, its excessive use can lead to a codebase that is very hard to support and manage. Reserve its usage for exceptional cases, and prefer specificity through proper selector structure. Usually needing to use !important points that we didn't use some best practice somewhere else (e.g. targeting internal styles of some CSS bundle or framework).