css总结

223 阅读4分钟

选择器类型

  • 通配选择符 (*)

  • 关系选择符

    + 相邻兄弟选择器     
     > 子选择器  
     ~ 通用兄弟选择器  
     ' ' 后代选择器  
     :not() 否定伪类 
    

伪类和伪选择器

  • 伪类
    :link :visited :hover :active 对 <a> 标签推荐使用这个顺序

link: 链接平常的状态
visited: 链接被访问过之后 hover: 鼠标放到链接上的时候 active: 链接被按下的时候

:first-child :last-child :nth-child() :nth-last-child() :only-child
:not()
:focus

  • 伪选择器
    ::before
    ::after
    ::first-line
    ::first-letter
    ::selection

优先级

浏览器从右到左进行查找的好处是为了尽早过滤掉一些无关的样式规则和元素。

权重值:

STYLE:1000
#ID:100
.CLASS 10
ELEMENT 1

ID 选择器 (#demo) > 伪类选择器 (:hover) > 类选择器 (.class1) 和 属性选择器 (a[title] img[title*=hello]) 两者优先级相同,声明在后面的会覆盖前面的 > 伪元素 (::before ::after) > 元素选择器(h1 p div) > 关系选择器 > 通配符选择器

内联 style=""> 内联样式表 <style> >外链样式 >浏览器缺省
  • !important优先级最高,高于内联样式
  • 同类型 最后面生效的是样式表中最后定义的,而不是class属性中写的顺序
.class3 {color: blue}   

.class1 {color: green;}     

.class2 {color: red;}   

<span class="class1 class2 class3"> 我是红色,class2生效</span>

  • 无视dom中的距离 都是标签选择器 标签选择器的形式,跟dom的距离无关,取最后面定义的样式
body h1 {   
  color: green;  
}  

div h1 {   
  color: red;  
}  

html h1 {   
  color: purple;  
}   

<div>   
  <h1>Here is a title!,color is purple</h1>  
</div>

  • :not()

:not 否定伪类在优先级计算中不会被看作是伪类,而是当作普通选择器来处理。

伪元素是无法被其他选择器选中,所以他的样式是伪类样式,否则继承使用伪类的元素。

div.outer p {   
  color:orange;  
}  

div:not(.outer) p {   
  color: lime;  
}   

<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>

  • 如果内联样式真的添加了 !important,则可以用 js 来消除(js 无法消除 class、ID 选择器的 !important)。
  <body>
    <div id="box" class="box1" style="color: red !important">
      hello div
    </div>
    <script>
      document.querySelector("#box").style.color = "blue";
    </script>
  </body>
得到blue

css编写原则:

- 一定要优化考虑使用样式规则的优先级来解决问题而不是 !important
- 只有在需要覆盖全站或外部 CSS 的特定页面中使用 !important
- 永远不要在你的插件中使用 !important,别人将很难更改样式
- 永远不要在全站范围的 CSS 代码中使用 !important

怎么覆盖!important

1)在important元素前面,加上元素、类、id ,也就是用更高级的覆盖;
 table td { height: 50px !important; }
.myTable td { height: 50px !important; }
#myTable td { height: 50px !important; }

2)使用相同的选择器,但是写在原来的之后
td { height: 50px !important; }

3)写新的选择器,不使用!important
p.awesome {
  color: red;
}
  • 优先级是基于选择器的形式进行计算的
  <head>
    <style>
      *#foo {
        color: green;
      }

      *[id="foo"] {
        color: purple;
      }
    </style>
  </head>
  <body>
    <div id="foo">
      hello div
    </div>
  </body>

得到green,
管选择器 *[id="foo"] 选择了一个ID,但是它还是作为一个属性选择器来计算自身的优先级

总结:

  • 样式表的元素选择器选择越精确,则其中的样式优先级越高
  • 对于相同类型选择器制定的样式,在样式表文件中,后面声明的比前面声明的优先级越高
  • !important会覆盖前面所有的声明,包括内联样式
  • 类选择器 和 属性选择器优先级形同
  • 伪元素是无法被其他选择器选中
  • !important > 内联样式 style > ID 选择器 > 伪类选择器 (:hover) > 属性选择器 = class 选择器 > 伪元素 (::before ::after) > 元素(类型)选择器 > 关系选择器 > 通配符选择器
  • 优先级是基于选择器的形式进行计算的

BFC

请看我的BFC总结:juejin.cn/post/685041…

flex

请看我的flex总结:juejin.cn/post/685041…

vertical-align

请看我的vertical-align总结: juejin.cn/post/685041…

参考链接

developer.mozilla.org/zh-CN/docs/…