CSS的样式优先级问题

1.类选择器的优先级问题:

 1 <style>
 2   body {
 3     background-color: black;
 4     font-family: monospace;
 5     color: green;
 6   }
 7   .pink-text {
 8     color: pink;
 9   }
10   .blue-text {
11     color: blue;
12   }
13 </style>
14 <h1 class="blue-text pink-text">Hello World!</h1>

显示结果:

在FreeCamp上的原文解释是这样的:

Note: It doesn't matter which order the classes are listed in the HTML element.

However, the order of the class declarations in the <style> section is what is important. The second declaration will always take precedence over the first. Because .blue-text is declared second, it overrides the attributes of .pink-text

简译过来就是:在HTML元素中这个class的顺序并不决定谁有显示的优先级,真正重要的是在style区域中声明的顺序,后一项声明总是比前一项声明占据更高的优先级,所以这就是为什么结果是蓝色的原因。

觉得这个还是和平常程序员思维逻辑稍不同的地方,记录下来。

2.id选择器的优先级:

 1 <style>
 2   body {
 3     background-color: black;
 4     font-family: monospace;
 5     color: green;
 6   }
 7   #orange-text{
 8     color:orange;
 9   .pink-text {
10     color: pink;
11   }
12   .blue-text {
13     color: blue;
14   }
15   }
16 </style>
17 <h1 id='orange-text' class="pink-text blue-text">Hello World!</h1>

显示效果:

 好了,咋们还是直接看解释:

Note: It doesn't matter whether you declare this CSS above or below pink-text class, since id attribute will always take precedence.

简译:如果class和id都存在的情况下,id属性总是保持优先级;

3.最高优先级

内联样式:

 1 <style>
 2   body {
 3     background-color: black;
 4     font-family: monospace;
 5     color: green;
 6   }
 7   #orange-text {
 8     color: orange;
 9   }
10   .pink-text {
11     color: pink;
12   }
13   .blue-text {
14     color: blue;
15   }
16 </style>
17 <h1 style="color:white" id="orange-text" class="pink-text blue-text">Hello World!</h1>

简单说:内联优先级最高好吧!

4.至高优先级

老弟,没想到还有更高的吧。

 1 <style>
 2   body {
 3     background-color: black;
 4     font-family: monospace;
 5     color: green;
 6   }
 7   #orange-text {
 8     color: orange;
 9   }
10   .pink-text {
11     color: pink !important ;
12   }
13   .blue-text {
14     color: blue;
15   }
16 </style>
17 <h1 id="orange-text" class="pink-text blue-text" style="color: white">Hello World!</h1>

显示效果:

你们要的粉色回来了

注意在.pink-text样式中的 !important

什么作用,以及在什么场景下使用?

参照FreeCodeCamp的解释:

In many situations, you will use CSS libraries. These may accidentally override your own CSS. So when you absolutely need to be sure that an element has specific CSS, you can use !important

简译:在很多情况下你会用别人的CSS库,这些CSS极有可能覆盖你自己写的CSS,那如果你十分确认某个HTML元素的样式,那么直接使用!important指定就完事了。

原文地址:https://www.cnblogs.com/LeeSki/p/12055323.html