Sorry, you need to enable JavaScript to visit this website.

Style Diet - Keep Your CSS Lighter

Style Diet - Keep Your CSS Lighter
June 29, 2015


Most UI developers focus only on the output of CSS and not on code efficiency. I can perceive your conscious mind thinking about sprites, minified CSS files, and page specific CSS to avoid unused styles. But, did you ever think about CSS Selectors or CSS Rules? These days, even icons and backgrounds can be designed using CSS. So, don’t you think it is important to know how to improve CSS performance?

If we are working on a page with more than a thousand HTML DOM (Document Object Model) and if we don’t take care of the CSS performance, then the page load and performance will be drastically affected. So, it is always better to keep our CSS lighter and efficient. We need to be familiar with a few concepts such as Key Selectors, Matching Rule, and CSS Selectors before understanding about performance tuning.

Key Selector and Rule Matching

Key selector is a selector / element in the right-most part of a CSS rule. The browser looks first for the key selector while reading our CSS selector.

For example: In div > p {..}

                    ‘p’ is the key selector

We read this from left to right. In the above example, ‘div’ contains ‘p’ element, whereas the browser will read it from right to left. Therefore, first, it will look for all ‘p’ tags and then it will filter the ‘p’ tags wrapped in a ‘div’. This has a huge impact on selector performance.

The fewer the rules used for selecting an element, the higher the CSS efficiency.

CSS Selectors

Most of the selectors will be familiar to us, so here is an example:

  • ID, e.g. #header
  • Class, e.g. .promo
  • Type, e.g. div
  • Adjacent sibling, e.g. p + p
  • Child, e.g. li > ul
  • Descendant, e.g. ul a
  • Universal, i.e. *
  • Attribute, e.g. [type="text"]
  • Pseudo-classes/-elements, e.g. a:hover

ID selectors are faster and more efficient than any other type of selectors, as IDs are always unique.

Guidelines for Efficient (fit) CSS

guidelines for efficient

Avoid universal rules and vendor-specific features, unless necessary.


You might ask, is it really necessary to use these rules for CSS selectors? The answer would probably be no. If you are building a one-page website, you need not depend on these rules. But, if you are rebuilding a 1000 page website, which has 1000’s of DOM elements on each page, and where even seconds make a difference in the page speed, then it is better to stick to the rules and keep your CSS lighter for better user experience.