How Css Works Behind The Scene

·

2 min read

How Css Works Behind The Scene

What happens to the CSS code when we load up a webpage in the browser?

When a webpage gets loaded in the browser, it parses the html code. It means taking the HTML code and then extracting valuable information from it. After it parses the HTML document, all it stores the code in a DOM (Document Object Model). While parsing the code, it loads the CSS from the header links.

parsing.png

Once CSS is loaded it starts parsing in two steps:

  • Resolving the CSS declaration conflicts also known as Cascading.
  • Processing final CSS values.

Let’s learn more about them!!

  1. Cascading

    CSS comes from these different sources:

    • Author CSS: The developer writes it.
    • User CSS: Configurable by the user in the browser.
    • Browser CSS: Some styles are predefined in the browser.

    So when one or more styles are applied to the same element, CSS performs a set of rules called Cascading which evaluates the strength and the style rule, which has the more weight wins!

    But how does the cascade actually resolve these conflicts? For that we have three factors:

    1. Importance:
    2. Specificity
    3. Source Order

Cascade marks the importance of CSS styles based on the source they are coming from in the following order:

  • User declarations marked with !important keyword.
    • Author declarations marked with !important keyword.
  • Author declarations.
  • User declarations.
  • Browser declarations.

    So if you have two rules on the same element and one has an !important keyword on it then this one will win.

importance.JPG

But if both of them have !important keyword

sp1.JPG

then specificity determins the winner here,

for example: here the selector with id will win as it has a higher specificity.

sp2.JPG

If both of these styles have the same specificity then the order will determine the winner. The last declaration will be applied .

o2.JPG

and with this step we are done with cascading.

2.Processing final CSS values

Here we provide the processed values to all the styles. Finally CSS gets parsed and we get CSS object model which combined with Dom object model and forms a render tree. It is formed with a combination of HTML, DOM, and CSS-OM. After the render tree has been formed, the website uses something known as the Visual Formatting model which helps lay the elements on the page to determine the final layout of the page.

Finally, we have our rendered website.

rendered-website.png