Home Web Front-end CSS Tutorial What is CSS priority

What is CSS priority

Feb 23, 2021 pm 05:29 PM
css3 priority

The so-called CSS priority refers to the order in which CSS styles are parsed in the browser; the browser uses priority to determine which attribute values ​​are most relevant to the element to decide and apply it to the element. . Priority is a weight assigned to a given CSS declaration, determined by the value of each selector type in the matching selector.

What is CSS priority

The operating environment of this tutorial: Windows 7 system, CSS3 version, Dell G3 computer.

1. Priority

The so-called CSS priority refers to the order in which CSS styles are parsed in the browser.

The browser decides which style to apply to the element based on priority, and the priority is only determined by the matching rules of the selector.

Inline》ID selector》Pseudo class=Attribute selector=Class selector》Element selector [p]》Universal selector (*)》Inherited styles

2. Priority calculation:

As mentioned above, the priority is only determined by the selector. How to calculate it?

a. Use a to represent the number of times ID selector appears in the selector

b. Use b to represent class selector , The total number of times the attribute selector and pseudo-class selector appear.

c, use c to represent tag selector, pseudo-element selectorthe total number of occurrences

d, ignore universal selector

e, then calculate the size of a*100 b*10 c, this is the priority.

Weight: Inline style 1000》id selector 100》class selector 10》tag selector 1

Note:

ID selector "such as: #header" , Class selector "such as: .foo", attribute selector "such as: [class]", pseudo-class "such as: :link", tag selector "such as: h1", pseudo-element "such as: :after", select Device「*」

Next, we will analyze the priority in depth from the following points.

1. Priority calculation ignores the distance in the DOM tree

Example explained at the beginning:

<!DOCTYPE html>
<html>
<style type="text/css">
body h1 {
  color: green;
}
html h1 {
  color: purple;
}
</style>
</head>
<body>
<h1>Here is a title!</h1>
</html>
Copy after login

The priorities of body h1 and html h1 are the same .

[Recommended tutorial: CSS video tutorial]

2. Pseudo-class selector, attribute selector and class selector have the same priority

Pseudo class=Attribute selector=Class selector

So the latter one will overwrite the previous one.

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<style type="text/css">
    :focus {
        color: red;
    }
    [class] {
        color: blue;
    }
    .classtest {
        color: green;
    }
</style>
</head>
<body>
<div class="classtest">
    什么颜色文字
</div>
</body>
</html>
Copy after login

As shown below, the image class selector is at the end, so it overwrites the previous style, so the text is green.

As shown below, the attribute selector comes after it and will overwrite the previous class selector style, so the text is blue.

Similarly, focus will only take effect if it is placed later, otherwise it will be overwritten by pseudo-classes and attribute selectors

3. Type-based priority

Priority is calculated based on the type of the selector.

Example: Although the attribute selector selects an ID, it is still calculated based on the type in the priority calculation. Therefore, even if the same element is selected, the ID selector has a higher priority, so * # The style set by foo takes effect.

<!DOCTYPE html>
<html>
<style type="text/css">
* #foo {
  color: green;
}
*[id="foo"] {
  color: purple;
}
</style>
</head>
<body>
<p id="foo">I am a sample text.</p>
</body>
</html>
Copy after login

4. :not pseudo-class does not participate in priority calculation

[:not] Negates pseudo-class in priority calculation will not be regarded as pseudo-classes, but the selectors in :not will be counted as ordinary selectors. This sentence is a bit difficult to understand. In fact, it just ignores :not. Other pseudo-classes (such as :hover) participate in the calculation of CSS priority, but ":not" does not participate in the calculation.

For example:

<!DOCTYPE html>
<html>
<style type="text/css">
div.outer p {
  color:red;
}
div:not(.outer) p {
  color: blue;
}
</style>
</head>
<body>
<div class="outer">
  <p>This is in the outer div.</p>
  <div class="inner">
    <p>This text is in the inner div.</p>
  </div>
</div>
</body>
</html>
Copy after login

In this example, the priority of selector p.outer p and selector p:not(.outer) p are the same, :not is ignored, and .outer in :not(.outer) counts normally.

If the position is changed, the inner element will turn red

    div:not(.outer) p {
        color: blue;
    }
    div.outer p {
        color:red;
    }
Copy after login

##5. The priority calculation will not increase

Don't compare weights simply as decimal numbers.

a=1的规则优先级将永远高于其他a=0的。

比如一个选择器的a>0,b=0即使另外一个选择器的a=0,b=12,c=12那么前者的权重依然更大!!

为证明我做了一个不现实的demo

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<style type="text/css">

#test{ /*a=1*/
    color: blue
}
div.classtest div.classtest div.classtest div.classtest div.classtest div.classtest div.classtest div.classtest div.classtest div.classtest div.classtest div.classtest{ /*b=12*/
color:green;
}

</style>
</head>
<body>
<div  class="classtest">
<div class="classtest">
<div class="classtest">
<div class="classtest">
<div class="classtest">
<div class="classtest">
<div class="classtest">
<div class="classtest">
<div class="classtest">
<div class="classtest">
<div class="classtest">
<div id="test" class="classtest">
什么颜色文章
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Copy after login

可见文本颜色还是蓝色!!

同样有一个带有10个id选择器的规则,优先级也不如内联样式。

总之优先级的计算不是基于十进制升位的,后面的数优先级再高也不能升到前一位。

6、其他

下面再给出一个经典的例子,自己计算一下就明白了。

Examples:

*               /* a=0 b=0 c=0 -> specificity =   0 */
LI              /* a=0 b=0 c=1 -> specificity =   1 */
UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
Copy after login

如果确实有棘手的情况,可以在Firebug中查看优先级。Firebug中按照优先级排序显示规则,将优先级更高的规则显示在最上面,并将被覆盖的规则用删除线划掉。

三、!import

为什么没有把!import放在优先级顺序中,因为官方认为!import和优先级没一点关系。

不建议使用!import

  • Never 绝不要在全站使用!import。

  • Only 只在需要覆盖全站或外部 css(例如引用的 ExtJs 或者 YUI )的特定页面中使用 !important

  • Never 永远不要在你的插件中使用 !important

  • Always 要优先考虑使用样式规则的优先级来解决问题而不是 !important

选择元素时尽量不要多选,不要放宽选择器的范围。因为范围越小,越具有针对性,优先级越高。

1、什么场合使用!import?

使用!import的场合也是有的,但是是在没有别的解决方案的时候。

比如需要覆盖内联样式,因为内联样式的优先级最高,只能用!import去覆盖内联样式。

还有一种情况

<style type="text/css">
#someElement p {
    color: blue;
}

p.awesome {
    color: red;
}
</style>
</head>
<body>
<div id="someElement">
<p class="awesome">some text</p>
</div>
</body>
Copy after login

在外层有 #someElement 的情况下,你怎样能使 awesome<span class="Apple-converted-space"> </span>的段落变成红色呢?这种情况下,如果不使用 !important ,第一条规则永远比第二条的优先级更高。这也是没有别的办法,如果用内联结果只会更糟糕。

2、怎样覆盖已有!import规则

a、再加一条!import的css语句,将其应用到更高优先级的选择器(在原有基础上添加额外的标签、类或者ID选择器)。

几个更高优先级选择器的例子:

table td    {height: 50px !important;}.myTable td {height: 50px !important;}#myTable td {height: 50px !important;}
Copy after login

b、选择器一样,但添加的位置在原有声明后面。因为相同优先级,后边定义的声明覆盖前面的。

相同选择器的例子:

td {height: 30px !important;}td {height: 50px !important;}
Copy after login

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of What is CSS priority. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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 safely set high priority for apps in Windows 11? How to safely set high priority for apps in Windows 11? May 06, 2023 pm 06:28 PM

Windows does a great job of allocating system resources to the processes and programs that need it most by assigning priorities to them. Most applications you install will run perfectly fine at the default "normal" priority level. Sometimes, however, you may need to run a program, such as a game, at a higher level than the default normal level to improve its performance. But this comes at a cost, and it's a deal worth pondering. What happens when you set an app to high priority? Windows has a total of six priority levels for running different processes and programs - low, below normal, normal, above normal, high and real-time. Windows will rank and queue applications based on their priority. The higher the priority, the application

How to achieve wave effect with pure CSS3? (code example) How to achieve wave effect with pure CSS3? (code example) Jun 28, 2022 pm 01:39 PM

How to achieve wave effect with pure CSS3? This article will introduce to you how to use SVG and CSS animation to create wave effects. I hope it will be helpful to you!

Top 8 Ways to Disable Notifications on Windows 11 (and 3 Tips) Top 8 Ways to Disable Notifications on Windows 11 (and 3 Tips) May 05, 2023 pm 12:49 PM

Notifications are a great tool for productivity, but they can sometimes be distracting. Whether you want to disable notifications entirely or for selected apps, this page is what you need. We'll also look at how to automatically disable and enable notifications using FocusAssist. Additionally, if the Settings app doesn't work for you, you can use tools like Command Prompt, Registry Editor, and Group Policy Editor for a geekier way to disable notifications. Check out the following tutorial to learn 7 ways to disable notifications on Windows 11. Why should you disable notifications on Windows 11? Disabling notifications has its various advantages, some of which are listed below. However, keep in mind that disabling notifications for important apps may

How to change priority in Task Manager in Windows 11 How to change priority in Task Manager in Windows 11 May 17, 2023 am 10:26 AM

What is process priority? Computers are not that different from their creators. Although it may appear that they are multitasking, they are actually juggling between tasks spontaneously. But not all processes or programs are equally allocated resources. Important processes, such as those necessary to keep the system running as smoothly as possible, are given high priority, while those that only work peripherally can be assigned a lower priority. This helps the system run smoothly even when it is under a lot of stress. What is priority? Processes have 6 different priorities. These are as follows: Low – This is the lowest priority. A process with "low" priority will not receive the necessary resources until all other tasks are completed. BelowNorma

How to turn productivity mode on or off for an app or process in Windows 11 How to turn productivity mode on or off for an app or process in Windows 11 Apr 14, 2023 pm 09:46 PM

The new Task Manager in Windows 11 22H2 is a boon for power users. It now provides a better UI experience with additional data to keep tabs on your running processes, tasks, services, and hardware components. If you've been using the new Task Manager, you may have noticed the new productivity mode. what is it? Does it help improve the performance of Windows 11 systems? Let’s find out! What is Productivity Mode in Windows 11? Productivity mode is one of the tasks in Task Manager

Use CSS skillfully to realize various strange-shaped buttons (with code) Use CSS skillfully to realize various strange-shaped buttons (with code) Jul 19, 2022 am 11:28 AM

This article will show you how to use CSS to easily realize various weird-shaped buttons that appear frequently. I hope it will be helpful to you!

Detailed explanation of Linux process priority adjustment method Detailed explanation of Linux process priority adjustment method Mar 15, 2024 am 08:39 AM

Detailed explanation of the Linux process priority adjustment method. In the Linux system, the priority of a process determines its execution order and resource allocation in the system. Reasonably adjusting the priority of the process can improve the performance and efficiency of the system. This article will introduce in detail how to adjust the priority of the process in Linux and provide specific code examples. 1. Overview of process priority In the Linux system, each process has a priority associated with it. The priority range is generally -20 to 19, where -20 represents the highest priority and 19 represents

How to customize notification settings on Windows 11 How to customize notification settings on Windows 11 May 02, 2023 pm 03:34 PM

Customizing general notification settings Let’s start with the basics of notification settings. First, if you want to set up notifications on Windows 11, there are two ways to do it. The quickest way is to right-click the date and time portion in the corner of the taskbar and select Notification Settings. Alternatively, you can use the Start menu to open the Settings app and select Notifications in the System section (open by default). Here you'll see an overview of your notification settings. You can disable notifications entirely, or click on the first option, Notifications, to expand the drop-down menu. This menu has some additional options, such as turning off notification sounds. You can also choose whether you want notifications to appear on the lock screen, including specific settings for reminders and incoming calls.

See all articles