Table of Contents
Browser rendering
CSSOM tree
Apply Style
Target attribute
Apply rules
CSS Efficiency
Extension
Home Web Front-end CSS Tutorial Introduction to how CSS element selectors work

Introduction to how CSS element selectors work

Nov 11, 2020 pm 05:56 PM
css html javascript front end

Introduction to how CSS element selectors work

Recommended tutorial: CSS video tutorial

In the daily work of front-end engineers, using CSS element selectors is commonplace; no matter Whether you write general CSS or SASS, SCSS, LESS, etc. that need to be compiled, they will eventually be compiled into line-by-line CSS style attributes, which will eventually be parsed and applied by the browser. But have you ever thought about how it would be possible without this?

Browser rendering

Let’s take a look at the browser rendering steps first:

Introduction to how CSS element selectors work

After CSS is loaded by the browser, it will be Parse it into a CSSOM tree, and try to overlay it with the Dom to form a rendering tree, and then perform steps such as calculating position and rendering. From this point of view, the key to applying CSS properties lies in how to convert CSS into a CSSOM tree and how to apply CSSOM to the DOM.

CSSOM tree

When we write down a set of CSS styles, for example:

#id .class h4 + p {
   ...
}
Copy after login

When the browser parses it, you might think that the CSS will be in order from left to Find #id>.class>h4>p on the right, and finally apply it, but actuallyThe order in which browsers parse CSS is from right to leftp>h4>.class>#id .

Very counterintuitive, right? But if performance issues are taken into account, right-to-left parsing will be much stronger than left-to-right.

Suppose there is HTML like this:

<p>
    </p><p>
        </p><p>
            ...
        </p>
        <p>
            </p><p>
                ...
            </p>
            <p>
                ...
            </p>
        
    
    <p>
        </p><p>
            </p><p>
                ...
            </p>
        
    
Copy after login

And here are five CSS style rules:

#p1 .c .d {}
.f .c .d {}
.a .c .e {}
#p1 .f {}
.c .d {}
Copy after login

Let us simulate it. If the CSS is parsed from left to right, it will A CSSOM tree similar to this will be generated:

Introduction to how CSS element selectors work

## through

.d in

Think about it, when applying styles to such a CSSOM tree, you must check all style rules to confirm whether the style rules will affect .d. Only in the end can you determine whether they may affect . There are three style rules for .d:

  • #p1 .c .d
  • .f .c .d
  • .c .d

By analogy, each element on the DOM tree must facilitate all style rules before it can obtain individual Style, this will cause a lot of redundant calculations, which will seriously affect performance.

Conversely, if the previous CSS is parsed from right to left, the CSSOM tree may be as follows:

Introduction to how CSS element selectors work

Same as the previous example, from <p class="d"></p> From the perspective of .d, since the target elements that will be affected by the style rules are all concentrated on the first layer, so There is no need to facilitate the entire CSSOM tree. You even only need to check whether the sub-attribute variables below .d conform to the actual DOM structure, and then retrieve all matching style rules to complete . dApply style rules to the element.

The right-to-left parsing order can gather all shared rule paths together. When the browser performs attribute comparison, it is no longer necessary to facilitate the entire CSSOM tree, greatly reducing invalid comparison calculations. .

You can also think about it in another way: in the structure of HTML, an element can have countless child elements, but it can only have one parent element. Searching from the child to the parent (from bottom to top) is definitely faster.

Apply Style

After parsing the CSSOM tree, can it be combined with the DOM? It would be great if it was really that simple.

In addition to the CSS files defined by developers, there are several places where style rules may be defined to affect the rendering of the screen:

  • HTML inline style settings
  • Browser default value (that is, what CSS reset/normalize will overwrite)
  • Browser user preference settings

The browser is responsible for processing the CSS part. All the previous things and the style rules defined in the CSS file are organized into separate style rule groups (CSS rule sets), which record the style rules, target attributes and other information.

Target attribute

In order to improve subsequent calculation efficiency, the browser's CSS processing kernel will group and store individual rules in the style rule group according to their target attributes; they are divided into the following four groups in total

  • idRules
  • classRules
  • tagNameRules
  • universalRules

In this way, when accessing, it can be based on whether the target element exists This attribute can quickly filter out the styles that may be applied.

Apply rules

The last step is to apply rules. The browser will apply all style rules in the following order and style rule weight:

  • Browser defaults
  • Browser user preferences
  • Developer-defined CSS
  • inline style
  • Add the !important style attribute

You may be curious: Why are inline style and developer-defined CSS processed separately?

We can review the steps of browser rendering. Since inline style exists in the DOM element, it can only be accessed when CSS is applied to the DOM. It is impossible to combine the two in advance. combine.

CSS Efficiency

In fact, the browser has completed the optimization mechanism here; the browser will automatically take style snapshots of elements with consistent status. The consistent status means that the following conditions must be met:

  • The ID is not set
  • tag and class must be completely consistent
  • The style attribute is not set
  • Various sibling selectors cannot be used in style rules (for example: ~, , :first-child, etc.)

Due to the above conditions and the CSS operation process discussed earlier, there are several places you can pay attention to when writing CSS:

  • Since the target attributes of the style rules will be stored in groups, the id selector The efficiency is very high, so it cannot be mixed with other conditions.
  • Don’t write too deep CSS style rules
  • If you can’t use inline style, don’t use it. In addition to being difficult to maintain, because it exists on the DOM tree, it cannot be combined with other styles in advance, so The efficiency will also be greatly reduced

If you can pay attention to these typical small details, CSS efficiency can naturally be greatly improved.

Extension

After getting to know CSS selectors, you will definitely be curious, what about JavaScript element selectors? You can refer to the source code of jQuery for this question. It is parsed from left to right. As for why it is different, there is actually an answer in the article. I will leave it to you to think about and dig out.

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Introduction to how CSS element selectors work. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to use bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

See all articles