Performance seen from CSS

Openweb.eu.org > Articles  > Performance seen from CSS

Abstract

You cannot escape it : performance has become a vital and probably one of the most critical requirements of modern websites.

CSS production has to take this into account.

Article

(Note: this article was previously published in French a few weeks before this translation –if you have any feedback on the translation made by Nicolas Hoffmann and John Elbing, please let us know.)

A great part of performance optimization for a website is the front-end optimization. Some major themes allow to contribute strongly to the performance effort from a CSS point of view.

Reducing the weight of stylesheets

The first idea is to reduce the file size of your CSS. The advice that we saw in “Basic CSS principles” and in (in French) «Introduction à la performance web» still apply:

  • Always go from the general to the specific;
  • Avoid using unnecessary styles (for example, putting a display: block is useless on a floating element);
  • Correctly use inheritance;
  • Use compact notations;
  • Factor out as much as possible the properties common to multiple items;
  • Avoid unnecessary units, eg border: 0 does not need unit.

Then, when your CSS is ready, think about minifying it, this drastically reduces the weight as well. Naturally, you have wonderfully commented your style sheet? smile

Do not forget to activate GZIP or DEFLATE compression to further reduce the weight of your style sheets, even if it is, in theory, more the server’s responsibility.

Other important point: your CSS must be sent and received as soon as possible. It is important to understand that your critical path for rendering a page very often passes by CSS, sometimes it is even CSS itself that is the critical path.

This implies to combine as much as possible your CSS files in a single one, so you will save requests. Ideally, serve them from the same domain as the page, it will avoid a costly DNS request. In extreme cases of performance quest, it is even recommended to put the CSS directly embedded in the page (or at least the part critical for accelerating the page display speed sensation). That is to say how this part is critical.

Reduce requests

CSS development can also can also help saving HTTP requests, either by reducing their number or by removing them.

CSS sprites

CSS sprites allow to group multiple images into a single one. We have published here an article that explains the technique (in French): Les sprites CSS.

In general, this technique should be reserved for images of the same nature and/or the same function (for obvious reasons of maintainability).

Various tools facilitate their creation and maintenance, pre-processors like Sass have functions that generate them automatically. This can be useful if the site must use many sprites.

Once again, effective factorization can help greatly reduce the weight of the CSS. For example, suppose you have 64 images of 16 by 16 pixels which are combined into a CSS sprite, instead of having 64 times this kind of code:

.icon-16-pdf,
.icon-16-doc,
.icon-16-wav,
/* etc. */
.icon-16-zip {
  display: inline-block;
  width: 16px;
  height: 16px;
  // etc.
}

It is possible to make a much more efficient and lightweight factorization through some selectors, for example:

[class*=icon-16] {
  display: inline-block;
  width: 16px;
  height: 16px;
  // etc.
}

This will save you a lot of dispensable statements. This selector will automatically target all classes whose attribute class contains icon-16.

On repeat view

Of course, a properly caching of static elements (CSS, images, JavaScript are the main ones) optimizes the performance of integration in a second consultation. However, these good practices are the responsibility of the cache management, and thus a server problem.

We have written about it in previous articles, so we will not go back on it. You can read (in French) «Les performances web, pour aller plus loin».

Embed content in the CSS

The other solution to improve performance is to limit HTTP requests. Indeed, an HTTP request can have a much higher cost performance than the directly embedded content in a style sheet, especially in mobile situations where latency or simply poor connectivity can significantly slow the download of a resource.

We have already discussed the possibility of data-URI in (in French) «Les performances web, pour aller plus loin». It is particularly suitable for small images. In general, the resulting code is a little bit heavier than the original image as a file, but the economy of a HTTP request remains generally preferable.

It is also possible to embed other types of content in stylesheets, web fonts or SVG for example. It really depends on the use cases on which the decision will be made. For example, a web font embedded in the CSS will really increase its weight.

Other tips

Hardware acceleration

The display and the calculation of CSS properties consumes generally very little CPU resources, however, the calculation of CSS animations or transitions can be more complicated for some less powerful devices, and saccades and other delays may occur. However, it is possible to delegate some of these calculations to graphics processors that are specialized in this kind of calculations. This is called “hardware acceleration” and this can be triggered by using certain properties such as:

transform: translateZ(0);
/* with all necessary prefixes! */

The gain in fluidity is sometimes visible immediately. Other benefits are also possible, such as font smoothing, acceleration of CSS filters, etc.

For more on this topic, you can read the following (in French) article: Hardware acceleration serving your animations CSS.

Pure CSS?

Sometimes the simplest solutions are the best: if the desired design can be created entirely with CSS (or almost), do not hesitate for a second and go for it! Avoiding the use of images will earn you valuable queries, but also CSS properties are the most efficient: few lines of CSS properties will always be faster and more flexible to use than images.

To say that this is one more reason to involve the front-end developer early in the process of creating websites, there is only one step… that I happily cross! This is a substantial saving in time to export images for the graphic designer and immense flexibility offered to the front-end developer (especially on responsive sites), which it would be a shame not to use.

Another point: the integration approach chosen by the front-end developer can also affect performance: Typically, if (s)he chooses mobile-first integration, it will surely render faster on small screens, and the surplus styles for larger displays will be absorbed by the more powerful browsers of “classic” desktops.

What about efficient selectors?

We have mentionned it too here in (in French) «Introduction à la performance web»: having short and qualifying selectors is also an optimization point. A lot of articles like “Writing efficient selectors” tell us to pay attention to our selectors.

First reminder: an efficient selector can be defined as a selector that reduces the amount of analysis the browser engine needs to apply styles.

Example: #header ul li a.header-link is a too long selector: it is uselessly over-specifying styles. Whereas .header-link will be enough to target these links. Moreother, surcharge in a media-query will be shorter (and simpler) to do with a short selector.

Second reminder : a qualifying selector is a selector that allows the browser to target very efficiently the elements to which styles apply. This “error” is often committed by simple ignorance of how browsers evaluate styles.

As example: .header a seems to be a good selector : short and specific. The developer will say while writing it: the browser is going to take all a in .header. However, this does not happen like that at all for the browser!

The browser is going to evaluate this CSS selector from right to left, in other words, it is going to target all links a in the entire page, and then look at those that are in .header. If we imagine that there are many links on the page, this selector becomes inefficiently qualifying: the browser is testing many elements with few chosen. A direct targeting by .header-link might avoid work for the browser.

To take an analogy, it is like making a SELECT * in a SQL query: this is to be avoided, better select only needed fields. If you are not familiar with the back-end, here’s a humorous analogy: this means taking all supermarket products in your cart and buy only the ones you want. Not very efficient! smile

However, these articles have been written a few years ago, and these statements should be moderated: on modern browsers and on descent computers, efficiency of selectors should be put in perspective, as some articles are showing [1]. This would be micro-optimization. Other articles are telling to pay attention to poor selectors and are advising to simplify them [2], such as the universal selector. To sum up, the issue is not completely resolved.

Anyway, I think that having efficient and qualifying selectors is a part of qualitative work that must be done for CSS, and for several reasons:

  • this work is induced by other factors as CSS should not be too dependant on the HTML structure, that we talked about in “Basic CSS principles”;
  • short selectors will be easier to surcharge, CSS of responsive websites will be lighter;
  • qualifying selectors will have less risk of being too broad or too specific: edge effects on complex CSS will be limited;
  • even if it’s on the order of micro-optimization for modern browsers, why not do it? Older browsers or smaller devices will appreciate it, and it does not cost anything more to do.

Conclusion

Surely this question of performance is not trivial. As already specified in the performance articles here on OpenWeb, it is mainly good practices and good habits to take early and throughout the design of websites.

The front-end developer is particularly important on this issue. Even if optimizing often oversteps his/her role by soliciting the back end, (s)he certainly has a place in the work on web performance when (s)he produces CSS.

References, supplements

In French

In English

Note

This article is part of the series “Great modern CSS conception principles”.

Notes

About this article

  • Openweb.eu.org
  • Cet article existe aussi en français : Les performances vues des CSS
  • Profil : Expert
  • Technologie : CSS
  • Thème : Industrialisation, Méthodes, Qualité
  • Author:
  • Published on:
  • Updated on: 29 October 2015

Comment on this article

Who are you?

To show your avatar with your message, register it first on gravatar.com (free et painless) and don’t forget to indicate your Email addresse here.

Enter your comment here
  • This form accepts SPIP shortcuts [->urls] {{bold}} {italics} <quotes> <code> and HTML code <q> <del> <ins>. To create paragraphs, just leave empty lines.

Follow the comments: RSS 2.0 | Atom