CSS的优先顺序是什么? [英] What is the order of precedence for CSS?

查看:35
本文介绍了CSS的优先顺序是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚为什么我的一个 css 类似乎覆盖了另一个(而不是相反)

这里我有两个css类

.smallbox {背景颜色:白色;高度:75px;宽度:150px;字体大小:20px;框阴影:0 0 10px #ccc;字体系列:继承;}.smallbox-paysummary {@extend .smallbox;字体大小:10px;}

在我看来我打电话给

字体(重叠元素)显示为 10px 而不是 20 - 有人可以解释为什么会这样吗?

解决方案

有几个规则(按这个顺序应用):

  1. 内联 css(html 样式属性)覆盖样式标记和 css 文件中的 css 规则
  2. 更具体的选择器优先于不太具体的选择器
  3. 如果两个规则具有相同的特性,则出现在代码后面的规则会覆盖前面的规则.
  4. 带有 !important 的 css 规则始终优先.

在您的情况下,适用规则 3.

单个选择器从高到低的特殊性:

  • ids(例如:#main 选择

    )
  • 类(例如:.myclass)、属性选择器(例如:[href=^https:])和伪类(例如:>:hover)
  • 元素(例如:div)和伪元素(例如:::before)

要比较两个组合选择器的特异性,请比较上述每个特异性组的单个选择器的出现次数.

示例:比较 #nav ul li a:hover#nav ul li.active a::after

  • 计算 id 选择器的数量:每个都有一个 (#nav)
  • 计算类选择器的数量:每个选择器都有一个(:hover.active)
  • 计算元素选择器的数量:第一个有3个(ul li a),第二个有4个(ul li a ::after),因此第二个组合选择器更具体.

一篇关于 css 选择器特异性的好文章.

I'm trying to figure out why one of my css classes seems to override the other (and not the other way around)

Here I have two css classes

.smallbox { 
    background-color: white;
    height: 75px;
    width: 150px;
    font-size:20px;
    box-shadow: 0 0 10px #ccc;
    font-family: inherit;
}

.smallbox-paysummary {
    @extend .smallbox; 
    font-size:10px;
}

and in my view I call

<pre class = "span12 pre-scrollable smallbox-paysummary smallbox "> 

The font (The overlapping element) shows up as 10px instead of 20 - could someone explain why this is the case?

解决方案

There are several rules ( applied in this order ) :

  1. inline css ( html style attribute ) overrides css rules in style tag and css file
  2. a more specific selector takes precedence over a less specific one
  3. rules that appear later in the code override earlier rules if both have the same specificity.
  4. A css rule with !important always takes precedence.

In your case its rule 3 that applies.

Specificity for single selectors from highest to lowest:

  • ids (example: #main selects <div id="main">)
  • classes (ex.: .myclass), attribute selectors (ex.: [href=^https:]) and pseudo-classes (ex.: :hover)
  • elements (ex.: div) and pseudo-elements (ex.: ::before)

To compare the specificity of two combined selectors, compare the number of occurences of single selectors of each of the specificity groups above.

Example: compare #nav ul li a:hover to #nav ul li.active a::after

  • count the number of id selectors: there is one for each (#nav)
  • count the number of class selectors: there is one for each (:hover and .active)
  • count the number of element selectors: there are 3 (ul li a) for the first and 4 for the second (ul li a ::after), thus the second combined selector is more specific.

A good article about css selector specificity.

这篇关于CSS的优先顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆