Table of Contents
CSS简介
使用CSS布局的优点
Home Web Front-end CSS Tutorial CSS selector weight and precedence rules

CSS selector weight and precedence rules

Mar 02, 2017 pm 03:18 PM
css selector Weights

In CSS, the order of defined style rules will be determined based on the specificity of the selector. Rules with more specific selectors take precedence over rules with general selectors. If the specificity of the two rules is the same, then Rules defined later take precedence We often encounter this situation when using CSS to define styles for web page elements: we need to apply general styles to general elements and then override them on more specific elements. So how do we ensure that our newly defined element style can overwrite the original style on the target element?

In CSS, the order of defined style rules is determined based on the specificity of the selector. Rules with more specific selectors take precedence over rules with general selectors. If the specificity of the two rules are the same, then the rule defined later takes precedence.

So, how to calculate the specificity of the selector? The picture below introduces the calculation method of specificity:

CSS selector weight and precedence rules

We divide specificity into 4 levels. Each level represents a type of selector. Each level The value is the number of selectors it represents multiplied by the weight of this level, and finally the values ​​of all levels are added up to get the special value of the selector.

The four levels are defined as follows:

First level: represents inline style, such as: , the weight is 1000.
Second level: represents the ID selector, such as: #content, with a weight of 100.
Third level: Representative classes, pseudo-classes and attribute selectors, such as .content, with a weight of 10.
Fourth level: Represents type selectors and pseudo-element selectors, such as p p, with a weight of 1.

For example, in the above picture, #NAV is the second-class selector, .ACTIVE is the third-class selector, and UL, LI and A are the fourth-class selector. Then the value of the specificity of the entire selector expression is 1*100+1*10+3*1=113

The following are some calculation examples:

CSS selector weight and precedence rules

Note: Universal selectors (*), sub-selectors (>) and adjacent sibling selectors (+) are not in these four levels, so their weights are all 0.
Let’s look at a specific example: If there are the following set of style rules, can you tell what color the two titles in the HTML code are?

#content p#main-content h2{   
    color:red;   
}   

#content #main-content>h2{   
    color:blue
}   
body #content p[id="main-content"] h2{   
    color:green;   
}   

#main-content p.paragraph h2{   
    color:orange;   
}   
#main-content [class="paragraph"] h2{   
    color:yellow;   
}   
p#main-content p.paragraph h2.first{   
    color:pink;   
}
Copy after login

The following is the HTML code:

<p id="content">
    <p id="main-content">
        <h2 id="CSS简介">CSS简介</h2>
        <p>CSS(Cascading Style Sheet,可译为“层叠样式表”或“级联样式表”)是一组格式设置规则,用于控制Web页面的外观。</p>
        <p class="paragraph">
            <h2 id="使用CSS布局的优点">使用CSS布局的优点</h2>
            <p>1、表现和内容相分离 2、提高页面浏览速度 3、易于维护和改版 4、使用CSS布局更符合现在的W3C标准.</p>
        </p>
    </p>
</p>
Copy after login

Have you judged it? The answer is: both titles are red!
Let us calculate the specificity values ​​of each of the six style rules:
The value of the first specificity=2*100+2*1=202
The value of the second specificity =2*100+1=201
The value of the third particularity=1*100+1*10+3*1=113
The value of the fourth particularity=1*100+1*10 +2*1=112
The value of the fifth particularity=1*100+1*10+1*1=111
The value of the sixth particularity=1*100+2*10+3 *1=123
Clearly, the first style rule won the championship of this style selector specificity contest with a high score of 202. Although the following rules may seem more complicated, they are not specific. It’s not about who should write the selector expression longer, the ID selector is the way to go!
Understanding the specificities of selectors is important, especially when fixing bugs, because you need to understand which rules take precedence and why.
If you encounter a CSS rule that doesn't seem to be working, it's likely that a specificity conflict has occurred. Please add the ID of one of its parent elements to your selector to make it more specific. If this solves the problem, there's probably a more specific rule somewhere else in the stylesheet that overrides yours. If this is the case, you may want to review your code, resolve specificity conflicts, and make the code as concise as possible.


For more articles related to the weight and priority rules of CSS selectors, please pay attention to 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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 resize HTML textbox How to resize HTML textbox Feb 20, 2024 am 10:03 AM

Setting the size of HTML text boxes is a very common operation in front-end development. This article explains how to set the size of a text box and provides specific code examples. In HTML, you can use CSS to set the size of a text box. The specific code is as follows: input[type="text&quot

How to adjust a WordPress theme to avoid misaligned display How to adjust a WordPress theme to avoid misaligned display Mar 05, 2024 pm 02:03 PM

How to adjust WordPress themes to avoid misaligned display requires specific code examples. As a powerful CMS system, WordPress is loved by many website developers and webmasters. However, when using WordPress to create a website, you often encounter the problem of theme misalignment, which affects the user experience and page beauty. Therefore, it is very important to properly adjust your WordPress theme to avoid misaligned display. This article will introduce how to adjust the theme through specific code examples.

What does Weibo weight mean? What does Weibo weight mean? Dec 11, 2020 pm 02:36 PM

Weibo weight refers to Weibo's official rating of Weibo accounts, which is mainly reflected in the ranking during searches and comments. The higher the weight, the higher the ranking. Therefore, Weibo weight will also affect the traffic data of Weibo accounts. The weight can be increased through the real-name system, or by becoming a contracted self-media on Weibo.

What exactly does H5 page production mean? What exactly does H5 page production mean? Apr 06, 2025 am 07:18 AM

H5 page production refers to the creation of cross-platform compatible web pages using technologies such as HTML5, CSS3 and JavaScript. Its core lies in the browser's parsing code, rendering structure, style and interactive functions. Common technologies include animation effects, responsive design, and data interaction. To avoid errors, developers should be debugged; performance optimization and best practices include image format optimization, request reduction and code specifications, etc. to improve loading speed and code quality.

What are the elements in the excluded section of css selector What are the elements in the excluded section of css selector Apr 06, 2024 am 02:42 AM

The :not() selector can be used to exclude elements under certain conditions, and its syntax is :not(selector) {style rule}. Examples: :not(p) excludes all non-paragraph elements, li:not(.active) excludes inactive list items, :not(table) excludes non-table elements, div:not([data-role="primary"]) Exclude div elements with non-primary roles.

What is css selector priority What is css selector priority Apr 25, 2024 pm 05:30 PM

CSS selector priority is determined in the following order: Specificity (ID > Class > Type > Wildcard) Source order (Inline > Internal style sheet > External style sheet > User agent style sheet) Declaration order (latest declarations take precedence) Importance (!important forces the priority to increase)

css selectors which are advanced selectors css selectors which are advanced selectors Oct 07, 2023 pm 02:59 PM

Advanced selectors in CSS selectors include descendant selectors, child element selectors, adjacent sibling selectors, universal sibling selectors, attribute selectors, class selectors, ID selectors, pseudo-class selectors and pseudo-element selectors wait. Detailed introduction: 1. The descendant selector uses a space-separated selector to select the descendant elements of an element; 2. The child element selector uses a selector separated by a greater than sign to select the direct child elements of an element; 3. Adjacent sibling selectors use selectors separated by a plus sign to select the first sibling element immediately following an element, and so on.

Get a deep understanding of the weight and precedence of CSS selector wildcards Get a deep understanding of the weight and precedence of CSS selector wildcards Dec 26, 2023 pm 01:36 PM

In-depth understanding of the weight and priority of CSS selector wildcards In CSS style sheets, selectors are an important tool for specifying which HTML elements the style applies to. The selector's priority and weight determine which style is applied when multiple rules apply to an HTML element at the same time. Wildcard selectors are a common selector in CSS. It is represented by the "*" symbol, which means it matches all HTML elements. Wildcard selectors are simple but can be very useful in certain situations. However, the weight and precedence of wildcard selectors also

See all articles