What happens to the CSS code when we load up a webpage in the browser?
Process that happens behind the scenes:
- The browser starts to load the HTML file.
- It takes the loaded HTML file and parses it, which means it decodes the code line by line, – From this process, the browser builds the so called Document Object Model (DOM).
DOM basically describes the entire web document like a family tree, with parent, children and sibling elements. So this document object model is where the entire decoded HTML code is stored.
As the browser parses the HTML file, it also finds the stylesheet included in the HTML head. Therefore, it starts to load it as well.
Just like the HTML, CSS is also parsed, but the parsing of the CSS is much more complex.
During the CSS parsing phase, there are two main steps.
- First: Conflicting CSS declarations are resolved through a process known as the cascade.
- Second: Process final CSS values.
Such as converting a margin defined in percentage unit to pixel. Imagine we define a left margin as 50%, but that 50% on a smart phone is different from a 50% in a large screen. That’s why this percentage and other relative units can only be calculated on an user device in the parsing phase.
After all of this is done, the final CSS is also stored in a tree-like structure called CSS Object Model (CSSOM), similar to the DOM.
Now that we have HTML as well as CSS parsed and stored, these together form the so-called Render tree.
With that, we finally have everything needed to render the page.
In order to actually render the page, the browser uses something called the visual formatting model.
This algorithm calculates and uses a bunch of stuff that we already know, such as the box model, floats, and positioning.
After the visual formatting model has done its work, the webiste is finally rendered on the screen, and the process is fininshed.
Browser -> load HTML -> Parse HTML -> Document Object Model (DOM)
When parsing HTML -> Find CSS -> Load CSS -> Parse CSS (resolve conflicting CSS declarations (cascade) and process final CSS values) -> CSS Object Model (CSSOM)
DOM & CSSOM together form the Render three -> Website rendering: the visual formatting model -> Final rendered website