Unveiling the Magic: How css works behind the scene
Imagine a world where websites lacked personality, where every page appeared bland and monotonous. Thankfully, we don't live in that world, thanks to the magic of CSS, the secret ingredient that transforms ordinary web elements into visually stunning works of art.
In this article, we'll take an exciting journey to uncover the secrets of CSS. Whether you're a developer seeking to learn more or simply curious about how css work, we'll reveal the magic happening behind the scenes of every captivating website you visit.
What will be covered in this article ?
🍧 What is css ?
CSS stands for Cascading Style Sheets, used in web development to describe the visual appearance and formatting of a document written in HTML (Hypertext Markup Language).It defines how HTML elements should be presented on a web page, including aspects such as colors, fonts, layout, spacing, and more.
CSS allows developers to separate the content of a webpage from its design, enabling greater control and flexibility in creating visually appealing and user-friendly websites.
Technically, CSS (Cascading Style Sheets) is not considered a programming language in the traditional sense. It is a style sheet language that is used to describe the presentation of a document written in HTML or XML.
While programming languages are used to create algorithms and perform computations, CSS focuses on specifying how elements should be styled and visually rendered on a webpage , even if it has some functions used to calculate or determine the value of a property like calc().
🍧 What happens to css when we load up a webpage ?
When a webpage is loaded, the CSS (Cascading Style Sheets) associated with that page goes through a specific process known as the CSS rendering or rendering pipeline.
Before delving into the topic at hand, let's begin by understanding the initial step in the webpage loading process. When a website is loaded in a browser, the very first action that takes place is called parsing, which involves the loading of the root HTML document.
Parsing, refers to the process of analyzing and interpreting a document's structure or syntax according to a predefined set of rules.
Once the HTML document is parsed, the browser creates a representation of the document known as the Document Object Model (DOM). The DOM represents the entire web page structure, including parent elements, child elements, and sibling relationships. During the parsing process, the browser also identifies the header links that contain the CSS files.
Once the CSS files are loaded, the parsing of CSS takes place, similar to the parsing of HTML files, but with a slight difference. The parsing of CSS files involves two steps and is slightly more complex.
The first step is resolving conflicting CSS declarations through a process called the cascade. It determines which styles take precedence when multiple rules target the same element.
The second step involves processing the final CSS values. For example, converting percentage-based values to pixels.
Once the parsing is complete, the CSS is stored in a tree-like structure called the CSS Object Model (CSSOM). The DOM and CSSOM together form the Render Tree.
In the next phase, known as website rendering, algorithms are employed to calculate the Box Model and determine the layout of each Box for every element in the tree. This helps establish the final layout for the entire page. The Visual Formatting Model is utilized by the browser during this phase.
So finally, after the visual formatting model, the website is finally rendered.
Let's dive into css parsing process
🍧 So what happens when the browser attempt to parse css ?
First we need to know what is css rule. The CSS rule consists of a selector and a declaration block. Inside the declaration block, there are declaration statements in the form of "property: value".
As we mentioned, the CSS parsing process involves resolving conflicts through a process called the cascade. During the cascade process, CSS rules and declarations from different stylesheets are combined, and conflicts between them are resolved. For example, the "font-size" property may appear in multiple stylesheets or even multiple times within the same stylesheet.
Cascading refers to the process of merging multiple CSS files and addressing conflicts that may arise when applying different rules and declarations to the same element. When writing CSS, certain blocks of rules may apply to specific elements while others do not. This occurs because some styles have greater importance or specificity compared to others. During the cascade, styles with higher precedence take effect, ensuring consistent and intended styling across the webpage.
So how cascade process workes?
First we need to know that There are three types of CSS that contribute to the cascade:
The cascade workes by combines all the CSS declarations from different sources. When multiple rules apply to the same element, the cascade considers factors such as importance, selector specificity, and source order to determine which styles take precedence.
It first looks at the importance, checking for the presence of "!important" declarations, with user styles having higher importance than author styles and author styles with !important becomes second. Then, it considers whether the declaration is specified in user or author styles, where author styles take precedence and user styles becomes second. Lastly, it takes into account default browser declarations, allowing for easy overwriting.
After check importance,if two property have the same importance, the cascade examines selector specificity. It checks whether the declaration is inline style, ID-based, class-based, pseudo-classes, attribute-based, or element-based.
ID-based selectors have higher specificity, followed by pseudo-classes, attributes, and classes. Elements and pseudo-elements have the lowest specificity.
Recommended by LinkedIn
If importance and specificity are equal, the cascade resorts to the source order. The last declaration encountered will override previous ones.
It's worth noting that using "!important" should be avoided whenever possible, as it can lead to less maintainable code. It's important to focus on writing maintainable rules by considering correct specificity.
Selectors with one ID have higher specificity than selectors with a thousand classes, so if you need to increase specificity, use IDs.
Similarly, selectors with one class have higher specificity than selectors with a thousand elements. The universal selector, "*", has no specificity.
Lastly, we should to rely on specificity rather than order when using third-party stylesheets. Always place your author stylesheet last to ensure that your rules take precedence.
In simple terms, the more specific your selector is, the higher priority it has in determining which styles should be applied. Let's say you have a <div> element containing both an <a> element and a <span> element. Now, suppose you want to style the <span> element specifically inside the <div>, and at the same time, another selector targets the <span> element inside the <a> element. Additionally, you have another selector that targets the <span> element within the <div> itself.
If you use different selectors like classes or IDs to target these elements, the selector with the highest specificity will take precedence. For example, if you assigned an ID to the <div> and used an ID selector to style the <span>, while also using a class selector to style the <span> within the <a>, the ID selector will win because IDs have a higher specificity than classes.
Let's dive into the next topic, the process of obtaining final CSS values:
First and foremost, it's important to note that all CSS units, other than pixels (px), are ultimately converted to pixels behind the scenes. But how does this conversion occur?
The various stages involved in the process of obtaining the final value for an element are as follows:
To summarize, the specified value is the intended value for an element, whether explicitly declared or inherited. If no value is declared, the browser's default value may become the specified value.
Example:
In some cases, the browser may need to make adjustments to the used value. This adjusted value is known as the actual value. For example, adjustments may be necessary when applying fonts based on available options or when the browser can only use integer values for rendering.
During the rendering process, certain CSS properties may require values to be rounded or converted to integers for precise rendering. For instance, properties like width, height, and positioning often need whole pixel values. If a value such as 50.7% is set for the width of an element, the browser might round it to the nearest whole pixel value for rendering, such as 101 pixels when the parent container's width is 200 pixels.
Note : when we inherit value from property , then we inherit the computed value , if the property is not inherited we use the initial value
Now, let's discuss website rendering and the visual formatting model:
The visual formatting model refers to the algorithm used to calculate boxes and determine the layout of these boxes for each element in the render tree. This process helps establish the final layout of the web page.
In CSS, the visual formatting model defines how user agents take the document tree, process it, and display it for visual media.
The key components of the Visual Formatting Model include:
Understanding the Visual Formatting Model is crucial for web developers and designers as it allows them to have consistent control over the layout and appearance of web pages across different devices and browsers. By utilizing CSS rules effectively, they can create visually appealing and responsive web layouts.
To summarize, the visual formatting model is a process that involves rendering elements present in the render tree, enabling developers to control the visual display of these elements effectively.
Conclusion : CSS is a powerful tool that enhances the visual appearance and formatting of web pages. It separates content from design, allowing developers to create visually stunning and user-friendly websites. The CSS rendering process involves parsing HTML, loading CSS files, resolving conflicts through cascading, and processing final CSS values. The visual formatting model determines how elements are rendered and laid out on the webpage, considering factors like the box model, display types, box positioning, box sizing, box layout, and visual formatting contexts. Understanding CSS and the visual formatting model empowers developers to create captivating and responsive web layouts.
Resources :
Senior Java Software Engineer at _VOIS (Vodafone Intelligent Solutions) | Ex Asset
1yGreat job my friend 👏👏
Frontend Developer @Startup defenders | Next.js | Node.js | Angular+2
1yGreat effort 👏