CSS特异性介绍和代码示例

2021年3月27日18:10:23 发表评论 887 次浏览

当一组以上CSS规则应用于同一元素时, 浏览器将不得不决定将哪个特定的CSS规则应用于该元素。浏览器遵循的规则统称为特异性

特异性规则包括:

内联CSS>内部CSS>外部CSS

通过引用外部样式表应用的CSS样式的优先级最低, 并且被内部和内联CSS覆盖。

内部CSS被内联CSS覆盖。

内联CSS具有最高优先级, 并且会覆盖所有其他选择器。

例子:

< html >
  
< head >
     < link rel = "stylesheet" type = "text/css" href = "external.css" >
     < style type = "text/css" >
         h1 {
             background-color: red;
             color: white;
         }
          
         h2 {
             color: blue;
         }
     </ style >
</ head >
  
< body >
     < h1 >
         Internal CSS overrides external CSS
     </ h1 >
     < h2 style = "color: green;" >
         Inline CSS overrides internal CSS
     </ h2 >
</ body >
  
</ html >

" extenal.css"示例1的示例:

h1{
     background-color: lightgreen;
}
h2{
     color: pink;
}

输出如下:

CSS |特异性1

内联内部和外部CSS

特异性层次结构:每个元素选择器在层次结构中都有一个位置。

  1. 内联样式:内联样式具有最高优先级。
  2. 标识符(ID):ID具有第二高的优先级。
  3. 类, 伪类和属性:接下来是类, 伪类和属性。
  4. 元素和伪元素:元素和伪元素具有最低优先级。

示例2:

< html >
  
< head >
     < style type = "text/css" >
         h1 {
             background-color: red;
             color: white;
         }
          
         #second {
             background-color: black;
             color: white;
         }
          
         .third {
             background-color: pink;
             color: blue;
         }
          
         #second1 {
             color: blue;
         }
          
         .third1 {
             color: red;
         }
     </ style >
</ head >
  
< body >
     < h1 id = "second" class = "third" >
         ID has highest priority.
     </ h1 >
     < h1 >
         Element selectors has lowest priority.
     </ h1 >
     < h1 class = "third" >
         Classes have higher priority than element selectors.
     </ h1 >
  
     < h2 style = "color: green;" id = "second1" class = "third1" >
         Inline CSS has highest priority.    </ h2 >
  
</ body >
  
</ html >

输出如下:

特异性层次结构gfg

特异性层次

注意:

  • 当两个或多个选择器具有相同的特异性时, 最后一个(最新)计数。
  • 通用选择器(例如body和继承的选择器)具有最低的特异性。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: