美文网首页
CSS的优先级

CSS的优先级

作者: 生锈的螺丝钉阿门 | 来源:发表于2018-06-12 17:24 被阅读0次
以下优先级依次递增:
1. 类型选择器(type selectors)(例如, h1)和 伪元素(pseudo-elements)(例如, ::before)
2. 类选择器(class selectors) (例如,.example),属性选择器(attributes selectors)(例如, [type="radio"]),伪类(pseudo-classes)(例如, :hover)
3. ID选择器(例如, #example)
通配选择符(universal selector)(*), 关系选择符(combinators) (+, >, ~, ' ')  和 否定伪类(negation pseudo-class)(:not()) 对优先级没有影响。(但是,在 :not() 内部声明的选择器是会影响优先级)。
给元素添加的内联样式 (例如, style="font-weight:bold") 总会覆盖外部样式表的任何样式 ,因此可看作是具有最高的优先级。

例外的!important规则

当在一个样式声明中使用一个!important 规则时,此声明将覆盖任何其他声明。虽然技术上!important与优先级无关,但效果上它直接相关。

Demo:

<style>
  #gender_male,#gender_female{
        background-color:green;
    }
    .gender_male{
        background-color:red;    
    }
  input{
        background-color:blue;
    }
</style>
</head>
<body>
    <input type="radio" id="gender_male" name="male" class="gender_male" checked>
    <label for="gender_male">男</label>
    <input type="radio" id="gender_female" class="gender_female" name="male">
    <label for="gender_female">女</label>
</body>

页面只有id选择器生效。因为其他选择器优先级没有id选择器高,效果被覆盖。


CSS priority

复杂场景

  • 行内样式<div style="xxx"></div> ==> a
  • id选择器 ==> b
  • 类选择器 ==> c
  • 标签选择器、伪元素 ==> d

demo

*{}                  /* a=0 b=0 c=0 d=0 -> 0,0,0,0 */
p{}                  /* a=0 b=0 c=0 d=0 -> 0,0,0,1 */
a:hover{}            /* a=0 b=0 c=0 d=2 -> 0,0,0,2 */
ul li{}              /* a=0 b=0 c=0 d=2 -> 0,0,0,2 */
ul ol+li             /* a=0 b=0 c=0 d=3 -> 0,0,03 */
h1+input[type=hidden]{}    /* a=0 b=0 c=1 d=2 ->0,0,1,1 */
ul ol li.active{}    /* a=0 b=0 c=1 d=3 -> 0,0,1,3 */
#ct .box p{}        /* a=0 b=1 c=1 d=1 -> 0,1,1,1 */
div#header:after    /* a=0 b=1 c=0 d=2 -> 0,1,0,2 */
/* style="xx" /* a=1 b=0 c=0 d=0 -> 1,0,0,0  */

了解更多信息,访问:
CSS priority

相关文章

  • 前端复习第二周

    主要复习CSS,style来引入css,link来外联css文件 优先级标签内css优先级 > hand内部css...

  • CSS基础

    CSS :层叠样式表(Cascading Style Sheets)。 CSS 书写位置及优先级(优先级按顺序排列...

  • 定位css 和xpath

    推荐的定位方式的优先级 优先级最高:ID 优先级其次:name 优先级再次:CSS selector 优先级再次:...

  • 【CSS优先级与!important】

    CSS样式优先级: 1、相同权值情况下,CSS样式的优先级总结来说,就是——就近原则(离被设置元素越近优先级别越高...

  • css的优先级到底是怎么计算的呢?

    浏览器计算css优先级一共有三个阶段 优先级计算的顺序⬇️ CSS规则的重要性和来源 CSS规则的特殊性 CSS规...

  • css选择器优先级以及photoshop快捷键

    css选择器优先级 CSS选择器的优先级:作用的元素一样,样式一样,就会有优先级问题,当优先级相同时,一旦发生重...

  • CSS选择器优先级

    参考文章:优先级- CSS | MDN

  • css-note

    css学习内容 css基础语法 css使用方法 css选择器 css继承与层叠 css优先级 css命名规范 学习...

  • 2018-06-28

    the presentation of that content 呈现的内容 css样式的优先级是在加载css文...

  • 第三天:css选择器的优先级、Adobe photoshop C

    一.css选择器的优先级 css选择器的优先级:作用的元素一样,样式一样,就会有优先级。 1.通配选择器(*):0...

网友评论

      本文标题:CSS的优先级

      本文链接:https://www.haomeiwen.com/subject/mekleftx.html