Introduction to how CSS element selectors work

青灯夜游
Release: 2020-11-11 17:56:57
forward
1902 people have browsed it

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!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template