css中常用的选择器和选择器优先级

蓝咒 提交于 2019-12-05 04:55:51

css常用的选择器:类选择器,id选择器,元素选择器,伪类选择器,伪元素选择器,属性选择器.
选择器的优先级由四个部分组成:0,0,0,0
一个选择器的具体优先级如下规则确定:

  • ID选择器 加 0,1,0,0
  • 类选择器,伪类选择器,属性选择器 加0,0,1,0
  • 元素和伪元素选择器 加0,0,0,1
  • 结合符和通配符对优先级没有贡献

    例子

  • h1{color:red;} /* 优先级为 0,0,0,1 */
  • p em{color:purple;} /* 优先级为 0,0,0,2 */
  • p.bright em.dark{color:maroon;} /* 优先级 0,0,2,2 */
  • id2 {color:blue;} /* 优先级 0,1,0,0 */

一些常用的选择器

类 id 元素选择器

<li class="red">1</li>
<li id="blue">2</li>
<li class="red">3</li>
<li>4</li>
<style>
    .red{color:red;}
    #blue{color:blue;}
    li{color:green;}
    *{font-size:16px;}
</style>

伪类选择器

<a href="https://www.baidu.com">链接</a>
<style>
    a:link{color:blue;}
    a:visited{color:grey;}
    a:hover{color:red;}
    a:active{color:yellow;}
</style>
且
E:focus
E:not()
E:empty
E:checked
E:enabled
E:disabled
E:first-child  同一层排行第一
E:nth-child(n)
E:nth-last-child(n)
E:last-child
E:only-child
E:first-of-type 同一层细分领域第一
E:nth-child(n)
E:nth-last-child(n)
E:last-of-type
E:only-of-type

伪元素选择器

内的
E::first-letter E内的第一个字母
E::first-line E内的第一行
E::before E内的最前面
E::after E内的最后面

属性选择器

^开始 $结尾 *包含
E[att]
E[att="val"]
E[att^="val"]
E[att$="val"]
E[att*="val"]
包含val并用空格分隔
E[att~="val"]
以val开头并用连接符"-"分隔
E[att|="val"]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!