Not just aesthetics: a guide to CSS for a fast, high-performing site

Put us to the test
Put us to the test!
Analyze your site
Select the database

CSS or Cascading Style Sheets is the computer language that governs the aesthetics of web pages and governs the stylistic formatting of sites and related web pages. In practice, it is the key tool for web designers who wish to build web pages that are aesthetically pleasing, functional and accessible, while ensuring simplified maintenance and better overall site performance. Like many other elements, however, we must “handle it with care”: if we do not implement these rules properly, in fact, CSS can become cumbersome and slow down the performance of our project. Let’s see together the main information about style sheets and what interventions can lighten and optimize CSS to make the site faster.

What is CSS: a simple definition

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.

More precisely, it is the style language that defines the presentation of a document written in a markup language such as HTML: without it, sites would be little more than pages of rough text and messy images. CSS describes how elements should be displayed on the screen, on paper, in reading aloud or other media, and applies to the presentation of a document written in HTML or XML (including various XML-based languages such as SVG or XHTML).

It is an essential tool for web designers and developers because it allows the content of the page (HTML) to be separated from its presentation (styling and layout).This means that, instead of embedding styles directly within the HTML code, separate styling rules can be defined that determine how page elements should appear.

What is meant by CSS and how style sheets work

According to experts, CSS is not really a programming language, but rather a style language or, better yet, a collection of formatting rules that control the appearance of the content of a Web page. The big news is that this set is universally shared by all browsers, allowing a single style to be applied to elements of Web documents and instructing browsers or another program-user on the final rendering of the document to be presented to the user.

Take care of your site

Find out where and how to take action to get better results and earn more money quickly and easily
Academy
Webinar
Tools
Registrazione

There is another relevant distinguishing feature of CSS: this technology allows content to be decoupled from its presentation design. That is, the HTML code, which forms the structure of a page, is kept separate from the style rules that define its appearance, which can be housed in a separate file, known as an external style sheet, or integrated within the <head> section of the HTML document.

This separation of structure and presentation results in more efficient website management: for example, changing the appearance of a site becomes a centralized operation that does not require repeated interventions on each individual page, but can be conducted by modifying a single set of CSS rules. As a result, HTML code is more streamlined and uncluttered, promoting reduced loading times and an improved user experience, even for those who rely on assistive technologies such as screen readers.

With CSS, then, visual customization reaches unprecedented levels of precision and flexibility. Every aspect of text can be detailed, from choosing fonts and their sizes, to applying styles such as bold or italics, to defining colors for text, background and links. This meticulous control also extends to block elements, such as headers, paragraphs, and <div> containers, which can be formed with margins, borders, specific placements, and colored backgrounds. The manipulation of these elements is critical to structuring the layout of a page, allowing the creation of complex, responsive structures that adapt to different display devices.

CSS and style rules: the main elements and features

Technically, then, CSS is a declarative language that allows web designers and developers to separate page content (such as text and images) from page presentation (such as design, colors, fonts, and layout).

Basically, this language is composed of a set of rules, known as “style rules,” which are interpreted by browsers to apply styles to web document elements.

Each style rule consists of a selector and a declaration block: the selector points to the HTML elements you want to style, while the declaration block contains one or more declarations separated by semicolons, each of which includes a style property and a value assigned to that property. For example, in

h1 {

color: blue;

font-size: 14px;

}

h1 is the selector that refers to the HTML element <h1>, and the statements within the curly brackets define that <h1> elements should be displayed with blue text color (color: blue;) and a font size of 14 pixels (font-size: 14px;).

Let’s look at what are the main elements that make up CSS and the key concepts to know when creating the structure and design of a web page, allowing designers to precisely control how HTML elements are displayed in the browser. Broadly speaking, a CSS style sheet is structured syntactically as a sequence of rules that may possibly be accompanied by comment notes and one or more @-rule directives.

Rules are pairs consisting of a selector and a declaration block, enclosed in curly brackets; the selector is used to identify the elements of the HTML document in which the rule is to be applied, while the declaration (separated with a semicolon from the others) consists of a property (a style trait to be applied to the element to be modified) and the corresponding value.

Among the various rules to be observed, we mention two: each declaration must contain only one property, but more than one value can be specified; moreover, whitespace in a rule does not affect the result, and blanks are often useful to improve readability.

More specifically:

  • Cascading. The term “cascading” in the name itself refers to the way style rules overlap and how priorities are applied. If multiple style rules have the same selector or apply to the same element, the browser must decide which rule “wins” and is applied. This process is determined by several factors, including selector specificity, importance (rules marked with !important), the origin of the style rule (user, developer, or browser style), and the order in which the rules appear in the CSS. The cascading system allows great flexibility and control in defining styles, ensuring that style rules are applied consistently and predictably.
  • Selectors. Selectors are patterns that identify the HTML elements to which style rules are to be applied. They can be simple, such as tag selectors (e.g., for paragraphs), class selectors (e.g., .class-example), ID selectors (e.g., #id-example), or more complex, such as attribute selectors, pseudo-classes, and pseudo-elements.
  • Declarations. A declaration is a single command that assigns a value to a specific CSS property. A declaration always consists of a property and a value, separated by a colon (e.g., color: red;).
  • Properties. Properties are the types of features that can be controlled with CSS, such as color, margin, border, padding, font, background, and so on. Each property has a set of valid values that can be assigned.
  • Values. Values are assigned to properties to define the appearance of HTML elements. They can be sizes (e.g., px, em, %), colors (e.g., #FFFFFF, rgb(255,255,255), black), fonts (e.g., Arial, serif), and many other types of values.
  • Rules or Style Rules. A style rule is a combination of a selector and a block of statements. A rule tells the browser how to display selected elements (e.g., h1 { font-size: 14px; color: blue; }).
  • Statement Blocks. A declaration block is a set of one or more declarations enclosed in curly brackets {}. A declaration block follows a selector and defines how selected elements are to be styled.
  • Style Sheets. A style sheet is a set of style rules, which can be embedded directly in an HTML document, linked as external files, or included as internal styles in a <style> element within the head of the document.
  • Comments. Comments in CSS are used to explain code and are ignored by browsers. They are useful for documentation and to make code more readable. Comments in CSS are enclosed between /*and */ (e.g., /*This is a comment */).

As mentioned, there are essentially three different methods of implementing CSS in a web page or entire website:

  1. Inline Styles. Inline styles are style rules written directly into the styl attribute of an HTML element. These styles have the highest priority in the waterfall because they are applied directly to the element and affect only the specific element to which they are applied. They can be useful for quickly testing styles or for applying styles that must override all other CSS rules, but they are generally avoided because they make the code less readable, harder to maintain, and do not follow the principle of separation of content and presentation; moreover, code reuse is minimal.

<p style=”color: blue; font-size: 14px;”>This is a paragraph with internal styles.</p>

  1. Internal Stylesheets. Internal stylesheets are blocks of CSS code located within a <style>element in the <head> of an HTML document. These styles apply only to the current page (to be precise, to all elements on the page that match the selectors defined in the CSS) and are useful for styles specific to a single page, without affecting other pages, or when you have a small amount of CSS code. They allow CSS to be kept separate from HTML content, while still being part of the same document, but the code reuse is less. Example:

<style>

h1 {

color: red;

}

</style>

  1. External Stylesheets. External stylesheets are separate CSS files that are linked to an HTML document (marked with the .css. extension) via the <link> element or the import directive (which is also used to link multiple .css files together). This method is the most efficient for managing styles on an entire website, as it allows CSS to be maintained in separate files that can be loaded from multiple pages, ensuring consistency and facilitating maintenance. In addition, it is the solution that ensures maximum code reuse, because each desired HTML page calls the same external file. Example:

<link rel=”stylesheet” type=”text/css” href=”style.css”>

What is the difference between CSS and HTML?

We have mentioned HTML, or HyperText Markup Language, several times, which we know is a fundamental language for the Web, so it is useful to understand what role it plays in the creation of pages on our sites and what “relationship” it has with Cascading Style Sheets.

HTML is the markup language that is used to structure and organize the content of a web page; it defines basic elements such as text, images, videos, links and other content. HTML elements are represented by tags such as <p> for paragraphs, <img> for images, and <a> for links. HTML tags not only organize content into a logical hierarchy that is understandable to both users and browsers, but also provide semantic information that describes the type of content on the page.

CSS, as described, on the other hand, is the language that describes the visual presentation of these HTML elements.

We can say that HTML deals with structure, while CSS focuses on aesthetics, defining how the elements should appear on the screen. With CSS, designers can check the layout, colors, fonts, size, margins, borders, background, and other visual aspects that make the page attractive and readable; in addition, CSS can also be used to create animations and adapt the page design to different devices and screen sizes through responsive design.

Thus, the fundamental difference between HTML and CSS is their purpose: HTML is used to create the basic structure of the page, while CSS is used to control the appearance and layout. Without HTML, there would be no structure on which to apply style, and a web page could not exist. Without CSS, the page would exist but would look very basic and less engaging, similar to a plain text document.

The advantages of Cascading Style Sheets

Cascading Style Sheets were thus developed to separate the content of HTML pages from the formatting or layout elements and enable clearer and easier programming for both programmers and users, while also ensuring code reuse and easier maintenance.

Today, CSS is widely considered a powerful and versatile language that serves to improve the aesthetics, consistency, usability, and performance of a website.

First of all, it ensures design consistency across the entire website: by defining a style in a single CSS file, you can ensure that all corresponding elements on different pages maintain the same appearance, without the need to duplicate the style on each page. This not only simplifies site maintenance, but also reduces workload and the potential for inconsistencies.

Another significant benefit of CSS is its ability to improve the accessibility and usability of a website: with these sheets, responsive layouts can be created that adapt to different devices and screen sizes, ensuring that the site is easily navigable on both desktop and mobile devices.

In addition, the use of CSS can positively affect the loading speed of a website: by separating design from content, HTML files can be significantly lighter and, as a result, faster to load.

Finally, CSS is useful for its flexibility and creative control: it allows for complex, visually appealing designs with effects such as animations, shadows, gradients, and more, which can help distinguish a website and capture the user’s attention.

The history of CSS, from the first version to the latest releases

CSS is maintained by the World Wide Web Consortium (W3C) and its specification is implemented by web browsers. Over the years, CSS has been developed in several versions, adding more and more features and capabilities to create complex and responsive web layouts.

Back to its inception, 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.

The first official version of CSS (later called CSS 1) was unveiled in December 1995; the CSS 2 specification was released in May 1998, followed by CSS 2.1 on June 7, 2011. It was then the turn of the CSS 3 specification (or rather the modular specification system), consisting of separate sections called “modules,” which were released at different time intervals until June 2018. Since early 2020, a W3C Community group has reportedly been working on the definition of the new version, which should be called CSS 4: about its actual release, however, there are various doubts, essentially because there seems to be no “technical” need for its emergence, given the almost infinite scalability of CSS 3.

In any case, the history of CSS is a fascinating journey through the evolution of web design and online content presentation. It all began in 1994, when Håkon Wium Lie, a researcher at CERN, proposed the idea of a style language for the web: his goal was to improve the flexibility and accessibility of web documents by allowing users to define how content should be displayed on their browsers. This proposal was enthusiastically received by Bert Bos, another web pioneer, who was working on his own style language called Argo: the two joined forces and the result was the first draft of what would become CSS.

In December 1996, the World Wide Web Consortium (W3C), the international organization that develops open standards to ensure the long-term growth of the Web, published the first official version of CSS, known as CSS 1. This version provided a basic set of style properties that allowed designers to control aspects such as fonts, colors, margins, and more. However, CSS1 had its limitations and did not support some advanced layout features that designers required.

To overcome these limitations, the W3C introduced CSS 2 in 1998, which added new features such as absolute and relative positioning of elements, z-index for controlling the overlapping order of elements, and the ability to create more complex layouts. Despite these improvements, the implementation of CSS 2 in browsers was initially uneven, leading to consistency problems between different browsers.

With the advent of CSS 3, which was introduced in the 2010s and developed in separate modules to facilitate adoption and implementation, CSS took a quantum leap forward: this version introduced a multitude of new properties and concepts, such as media queries for responsive designs, animations, transitions, and transformations, that enabled designers to create dynamic and interactive user experiences. Today, CSS continues to evolve as new properties and features are added, and its implementation has become much more consistent across browsers, thanks to W3C standardization efforts and the work of the developer community.

CSS and SEO: a complex and relevant relationship

In short, CSS is more than just a tool for making a site “pretty” or “nice to look at”: it is a key component that, when used correctly, can significantly improve a website’s visibility in search results, thus contributing to the overall success of a digital strategy.

In fact, the relationship between CSS and SEO is complex and multifaceted, because style sheets affect many of the factors that search engine algorithms use to index and rank websites.

First, CSS contributes to the loading speed of a page, which is a known ranking factor: clean, optimized code can reduce loading times by eliminating redundancies, using compression and minimization techniques, and taking advantage of the browser cache. This not only improves the user experience, but also signals to search engines that the site is well maintained and performing well, aspects that are rewarding in search results.

Academy
Webinar
Tools
Registrazione

Semplifica e migliora il tuo lavoro

Riduci i tempi di analisi e trova subito soluzioni per migliorare il sito

In addition, CSS has a direct impact on site usability and accessibility: responsive design that adapts fluidly to different screen sizes and devices is essential to reach a wider audience and ensure a positive user experience. Again, CSS allows content to be presented in a way that is visually appealing to users, but also easily interpreted by search engines: its proper use can help highlight important information, such as titles and keywords, without resorting to cloaking techniques that can be penalized by search engines.

However, improper use of CSS can have negative effects on SEO, even transcending into Black Hat tactics: for example, if CSS is used to hide content that is only there to influence search engines, this can be considered a deceptive practice and lead to penalties. In addition, excessive use of CSS in-line or embedded directly into HTML pages can increase page size and negatively affect loading speed.

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.

Iscriviti alla newsletter

Try SEOZoom

7 days for FREE

Discover now all the SEOZoom features!
TOP