Do you find CSS simple and hard at the same time? If so, you’re not alone. Understanding the inner workings of CSS is key to unlocking its full potential. In this post, I’ll share the theoretical concepts of ‘How CSS actually works behind the scenes’ that have helped me to grasp CSS better.
How CSS works?
Background
While HTML is responsible for the structure and content of a webpage, and JavaScript is responsible for its interactivity and behavior, CSS is responsible for its presentation and styling. It is one of the three pillars of Frontend Development. Though often neglected, A deeper understanding of CSS is crucial for writing well-structured and efficient CSS.
So, let’s start:
- Whenever a user requests a webpage, it downloads the initial HTML page and parses it (ie. decodes it line by line) to construct the Document Object Model (DOM). DOM stores the entire decoded HTML and describes the entire web document in a tree-like structure. During the parsing, the browser comes across CSS links or embedded style elements in the HTML head, which it downloads and starts parsing it as well.
How CSS works?
2. CSS Parsing Phase The parsing of CSS is a bit more complex. In this phase, the browser reads the CSS code line by line and applies a set of rules to determine how each CSS rule should be applied to the HTML elements in the document.
It usually involves the following steps:
2.1. Cascade (Resolving conflicting CSS declarations)
The “cascade” refers to the process of combining different stylesheets and determining which styles should be applied to an HTML element when there are multiple style rules that could potentially affect it.
Well, that was easy but how does a CSS know which style to apply when more than one style is applied**?
**It takes the following thing into consideration to resolve the conflict:
2.1.1. Importance: First of all the cascade starts by giving them different importance based on where they are declared ie. their source. The origin can be either Author, User, or Agent that is.
- Author declarations: These are the styles declared by the author of the webpage.
- User declarations: These are the styles applied by the user of the webpage, such as custom styles applied through browser extensions or modifications made by the user in the browser settings.
- User-agent declarations: These are the default styles that come with the browser.
It follows the following priority order:
- User Declaration marked with !important keyword
- Author (ie. programmer) declaration marked with !important keyword
- Normal Author declaration
- Normal User declaration
- Default Browser Declaration
Hence, the CSS declaration marked with ‘!important’ keyword has the highest priority.
2.1.2. Specificity: Sometimes there might be conflicting declarations of the same importance from the author’s stylesheet, in such scenarios, the cascade calculates and compares the specificity of the declaration selector.
Specificity is calculated based on the CSS selectors which are used to target elements.
Here’s the list, from highest to lowest specificity:
- Inline CSS
- IDs
- Classes, Pseudo Classes, Attribute
- Elements, Pseudo elements
Order of specificity
Notes:
i. inline CSS has the highest priority over styles in external stylesheets.
ii. a selector containing 1 ID is more specific than 1000 classes
How specificity is calculated? If you are interested in knowing how CSS specificity is calculated, Check out this Medium Article by Eleftheria Batsou where she has done an amazing job explaining it.
2.1.3. Source order: What happens when two styles have the same specificity?
If it is still not resolved, the last declaration in the code will override all other declarations and it will be applied.
So, whenever you are including an external stylesheet in your HTML file make sure to place them below your own defined stylesheet.
So now you know why CSS is called Cascading Style Sheet. 🥳
2.2 Processing final CSS values (converting all CSS relative units to px) Since we are talking about the CSS parsing phase, after cascading then comes value processing. It determines how the CSS styles are applied to the HTML elements and ultimately how the webpage appears to the user.
How CSS values are processed?
The browser can only understand pixel (px), so percentages and all the relative units like em, rem, vh & vw are converted ultimately converted into px in the end.
The value processing phase involves several steps, including:
- Resolving inheritances: The browser determines whether a CSS property value should be propagated from a parent element to the child or set to its default value.
- Calculating values: The browser calculates the final value of a property based on its declared value, any inherited values, and any contextual values.
- Handling units: The browser converts values to the appropriate units, such as pixels or percentages, based on the context in which they are used.
- Handling invalid values: The browser may ignore or replace invalid values with default values to ensure that the layout of the webpage is not disrupted.
- Applying styles: The browser applies the computed values to the appropriate elements in the DOM tree, resulting in the final layout of the webpage.
If you are interested in understanding ‘how CSS values are converted to ‘px and the difference between all the CSS units’ and want to have more control over the units you use for your CSS properties, check out this article on How CSS units are processed?
3. After this is resolved, the final CSS is also stored in a tree-like structure called the CSS Object Model (CSSOM).
4. Browser combines both DOM and CSSOM to form a Render Tree and renders a website using an algorithm called Visual Formatting Model which is responsible for creating the visual layout of a webpage.
How CSS renders a website? CSS Visual Formatting Model is the algorithm that calculates the boxes and determines the layout for these boxes, for each element in a render tree, in order to determine the final layout of the page. his model describes how elements are laid out and how their visual properties, such as size, color, and positioning, are determined.
It consists of:
- Box Model: The box model describes how each HTML element is treated as a rectangular box, with properties such as width, height, padding, border, and margin. These properties affect the size and positioning of the element on the page.
- Layout Algorithm: The layout algorithm determines how these boxes are arranged on the page, taking into account factors such as the element’s display property, position property, and float property. This algorithm also considers the document flow and the order in which elements appear in the HTML code.
Together, the box model and layout algorithm determines how HTML elements are displayed on a webpage, including their size, position, and visual properties.
If you’re interested in knowing how Visual Formatting Model does all that, be on the lookout for my next article where I’ll explain it in detail.
Finally, the painting of the final visual representation of the page on the screen begins where the browser draws each element and applies the computed styles to create the final visual output.