Facebook Pixel

How CSS Works?

Now we will first understand the CSS structure and then we will look at how CSS works on the DOM model.

Understanding CSS Basics

CSS is a stylesheet language that styles HTML elements by applying visual properties like colors, fonts, margins, and layouts. It works by selecting specific elements in the DOM and defining their appearance using rules.

CSS Rule Structure

A CSS rule consists of three parts:

selector {
    property: value;
}
  • Selector: Targets an HTML element, class, or ID (e.g., h1, .class-name, #id-name).
  • Property: Defines the style attribute to modify (e.g., color, font-size).
  • Value: Specifies the setting for the property (e.g., blue, 24px).

Example:

h1 {
    color: navy;
    font-size: 28px;
}

This rule targets all <h1> elements, setting their text color to navy and font size to 28 pixels.

How CSS Works?

CSS transforms a webpage by interacting with the DOM through a series of steps.

  1. The user types the URL and clicks enter.
  2. The browser makes a fetch request to the server.
  3. HTML is fetched from the server.
  4. HTML is converted into a DOM. In the DOM, each tag is considered a node.
  5. The browser fetches all the related files and assets that are linked to that HTML, such as external CSS, fonts, images, etc.
  6. The browser then parses the CSS and groups it based on the selectors, which can be tags.
  7. Each CSS is attached to its respective node. In this phase, CSS gets attached to its respective node. This is called a render tree.
  8. The render tree is the well-structured, well-arranged DOM node that will appear on the screen.
  9. The well-structured, custom-designed website is presented on the screen. This is called painting.

The video below will help you understand it better. Video: How CSS Works

What is a DOM?

A DOM is like a tree structure representation of all the tags and elements on the page. Each part of a web page, like headings, paragraphs, images, buttons, etc., will be part of the tree.

You can think of it as a blueprint for a web page that web browsers use to understand and display web content.

Consider the below example:

DOM Example

The tags are converted into nodes. Each node establishes a parent-child relationship between each other. To be precise, Document Object Model (DOM) is a sort of API that represents and interacts with HTML documents.

The final result of the above code (the painting):

Website Painting

Some helpful References:

  • I will recommend going through, How HTML Works
  • MDN will be a great source to get some more insights.