The CSS is the computer language that regulates the stylistic formatting of websites and their web pages: like other elements, when not implemented correctly it can become heavy and slow down the performance of our project. Let’s see together the main information on style sheets and what are the interventions that can lighten and optimize the CSS to make the site faster.
What is the CSS
Before dealing with the technical aspects, let’s start with the necessary definitions and with the history of the CSS. The CSS acronym indicates the Cascading Style Sheets, and is the code used to model the layout and the style of the web pages and the whole site.
What is the style language for
According to experts, the CSS is not really a programming language, but rather a style language universally shared by all browsers that allows you to apply a single style to the elements of web documents and instruct browsers or another program-user on the final surrender of the document to be presented to the user.
Through this code we can intervene on every type of element, defining for example the type of font, its size and color, and then again the background images, the placement of graphic elements, the management of columns or other elements on the page. Moreover, through the CSS we can also set the layout of the elements in a responsive way, or adapt the layout according to the different devices of users.
The history of the CSS
The design of the CSS is directly linked to the HTML language, of which it is in some way an ideal complement to the philosophy of separating the content from the presentation. In the W3C’s intentions, in fact, HTML should be seen and used as a structural language, without graphic or style information on the presentation of the document, while instead the CSS has the task of enriching the visual aspect of the page.
Cascading Style Sheets were therefore needed to separate the contents of HTML pages from formatting or layout elements and allow clearer and easier programming, both for programmers and users, while also ensuring the reuse of code and easier maintenance.
The first official version of the CSS (later called CSS 1) was submitted in December 1995; the CSS 2 specification was released in May 1998, followed by CSS 2.1 on 7 June 2011. It was then the turn of the specifications of CSS 3, consisting of separate sections called “modules”, which were published at different time intervals until June 2018. Since the beginning of 2020 a group of the W3C Community is working on the definition of the new version, which will be called CSS 4.
The CSS characteristics
Let us now, in a nutshell, look at the basics of how this language works. The CSS code can be inserted in the web pages through three different ways:
- Insert a link to an external sheet (marked with the .css extension) in the zhead> tag of the HTML page. This solution assumes the creation of a specific file connected through the link tag or the import directive (which also serves to connect several .css files) and ensures maximum reuse of code, because each HTML page you want calls the same external file.
- Use css statements between specific <style> and </style> tags within the <head>. In this case, the instructions apply only to the page where the declarations are present and therefore the reuse is lower.
- In line within the elements, solution that minimizes the reuse of code.
In principle, a CSS style sheet is syntactically structured as a sequence of rules that can possibly be accompanied by comment notes and one or more @-rule directives.
The rules are pairs consisting of a selector and a block of statements, enclosed in curly brackets; the selector serves to identify the elements of the HTML document in which the rule will be applied, while the declaration (separated with a semicolon from the others) consists of a property (a stretch of style to be applied to the item to be modified) and the corresponding value.
Between the various norms to respect we cite two: every declaration must contain only one property, but it is possible to specify more values; moreover, the blank spaces in a rule do not influence the result and often the empty spaces are useful for improving the readability.
How to optimize the site’s CSS
After this general parenthesis, let’s try to see what are the tips to improve the management of the code on our pages and to avoid burdening the performance of the site. We support the web.dev blog guides, who dedicate some lessons to best practices for the CSS.
The first suggestion is by Demian Renzulli, Senior Web Ecosystems Consultant at Google, and is “defer the non-critical CSS”.
Postpone the uncrucial code loading
CSS files are resources that block rendering, Google explains, why they need to be loaded and processed before the browser renders the page; as a result, Web pages that contain unnecessarily large styles take longer to render.
With the deferral technique you can optimize the critical rendering path and improve the First Contentful Paint, an important element to offer a fast user experience.
Reducing the unused CSS
In order for him to explain the method of simplification of the CSS, Renzulli brings the example of a page that requires a CSS file with eight classes, not all are necessary to make the content “visible”: a more careful management will synchronously load only the critical styles, letting others load (such as those applied to paragraphs) in a non-blocking way.
The tool to verify the impact of the code on the speed of the site is Google Lighthouse, which also reports with a hint called Remove Unused CSS the presence on the page of at least 2048 bytes of CSS rules that are not used when rendering the above the fold content. The risk is that the browser has to wait for the loading and processing of all CSS before painting a single pixel on the screen.
Detecting the critical CSS
To optimize the page you still need to know what classes are considered “critical”: Google has developed a tool – the Coverage Tool contained in the Chrome Devtools – which allows you to verify the coverage of the single page and to understand, also visually, what are the critical CSS resources and those that are not.
Critical (indicated in green) are the classes required by the browser to render the visible content (such as the title, subtitle and accordion buttons); non-critical (in red in the tool) are the styles that apply to contents not immediately visible (like paragraphs within accordions).
With this information we can optimize the CSS so that the browser begins to process critical styles immediately after page loading, sending the non-critical CSS back to a later time.
Minimizing the CSS code
The second procedure that we can implement is the minification technique (minify), or the reduction to the maximum of CSS files: sometimes, the code may contain useless characters, such as comments, blank spaces and indentations, and such characters can be safely removed in production, to reduce file size without affecting the way the browser processes styles.
Already in the drafting phase of the code it is possible to avoid burdens that can be removed – such as spaces for re-entry purposes or comments, which are ignored by the browser; styles that you can group or imprecise indications for font and background color – but alternatively there are auto compilation tools and webpack processes for this purpose.
Extracting critical CSS
The third technique presented – by another Googler, developer Milica Mihajlija – is the extraction of critical CSS: as we said before, the browser must download and analyze CSS files before it can show the page, which makes the code a rendering-blocking resource. If files are large or network conditions are poor, CSS file requests can significantly increase the time it takes to render a web page.
With this technique we can extract the CSS for above the fold contents in order to render them to the user as quickly as possible: the insertion of extracted styles in the <head> of the HTML document eliminates the need to make an additional request to recover these styles, and the rest of the code can be loaded asynchronously.
The perks of this operation
Improving rendering times can make a huge difference in the performance perceived by users, especially in poor network conditions; for mobile networks, high latency is a bandwidth-independent problem.
There are many great tools that can automatically determine the critical CSS for a page, a complex process that requires an analysis of the entire DOM to determine the styles applied to each element in the window. The performance impact we can achieve with this technique depends on the type of website: in general, the more CSS has a site, the greater the potential impact of embedded CSS.
Mihajlija also invites you to remember that inserting a large amount of CSS delays the transmission of the rest of the HTML document: if everything has priority, he writes, then nothing has it. Inline insertion also has some downsides because it prevents the browser from caching the CSS to reuse it at subsequent page uploads, so it is better to use it sparingly.
Quickly offering contents
If our site has poor First Contentful Paint (FCP) values and we see the “Eliminate Rendering Block Resources” report in Lighthouse audits, it is a good idea to try the critical CSS technique. To minimize the number of round trips for the first rendering, the goal is to keep the above-the-fold content below 14 KB (compressed).
This value is obviously not random: the new TCP connections cannot immediately use all the available bandwidth between the client and the server and all pass through the slow-start to avoid overloading the connection with more data than they can carry. In this process, the server starts the transfer with a small amount of data and, if it reaches the client in perfect condition, doubles the amount in the next roundtrip. For most servers, 10 packs or about 14 KB is the maximum size that can be transferred in the first roundtrip.
Optimizing CSS background images with media query
Many sites require heavy resources, such as images, which are not optimized for certain screens and send large CSS files that contain styles that some devices will never use, writes Renzulli presenting the latest CSS optimization method suggested by Google.
The use of media queries is a popular technique to provide stylesheets and resources tailored to different displays, reduce the amount of data transferred to users and improve page loading performance. It is, in summary, to learn how to use the code to provide responsive or responsive images without overloading it.
To do this, we can use the @media rule and implement a responsive background – a technique widely supported by all browsers – or use a new CSS feature: image-set(), which has the same purpose but commits fewer lines of code (but it is not yet supported by all browsers).
This way, we can serve custom-made background images for specific size screens and save bytes when the visitor accesses the site on smaller devices, such as mobile phones.