CSS@3继承优先级

CSS的继承、优先级、层叠

CSS的继承

有些元素的样式是可以被子元素继承的,大概包括这些,其中橙色的是文本相关的,蓝色的是列表相关的:

  • azimuth
  • border-collapse
  • border-spacing
  • caption-side
  • color
  • cursor
  • direction
  • elevation
  • empty-cells
  • font-family
  • font-size
  • font-style
  • font-variant
  • font-weight
  • font
  • letter-spacing
  • line-height
  • list-style-image
  • list-style-position
  • list-style-type
  • list-style
  • orphans
  • pitch-range
  • pitch
  • quotes
  • richness
  • speak-header
  • speaknumeral
  • speak-punctuation
  • speak
  • speech-rate
  • stress
  • text-align
  • text-indent
  • text-transform
  • visibility
  • voice-family
  • volume
  • white-space
  • widows
  • word-spacing

优先级

经常会遇到的一个问题,如果多次对一个元素声明样式,到底哪次声明才有效呢?这就要考虑到优先级的问题了。一般来说会对每一次样式的声明都计算一次优先级权值,这个权值比较大的,拥有比较高的优先级,也就是说话最有权力,当然这只是比较简单的说法,具体的规则如下:

  1. 每个选择器都有一个权值,权值越大的优先级越高。
  2. 权值相等时,后出现的覆盖先出现的。
  3. 用JS代码指定的样式,相当于增加了一段行内样式。
  4. !important规则的优先级最大(这条规则只适用于支持!important的浏览器,像IE6这样的就不支持)

规则一:关于选择器权值的计算

  • A. 行内样式数 * 1000(行内样式就是写在标签的style属性中的样式)
  • B. id选择器数量 * 100
  • C. 类、伪类选择器和属性选择器数量 * 10
  • D. 标签选择器和伪元素选择器数量 * 1

最终的权值 = A + B + C + D
举个例子:

<html>
<head>
<style type="text/css">
/* #grandparent为ID选择器,权值为100;.parent和.child都是类选择器,权值为10;*/
/* 权值 = 100 + 10 + 10 = 120*/
#grandparent .parent .child{
color: red;
}
/* #grandparent为ID选择器,权值为100;.parent是类选择器,权值为20; p是标签选择器,权值为1*/
/* 权值 = 100 + 10 + 1 = 111*/
#grandparent .parent p{
color: blue;
}
/* #grandparent为ID选择器,权值为100, .child都是类选择器,权值为10;*/
/* 权值 = 100 + 10 = 110*/
#grandparent .child{
color: green;
}
</style>
</head>
<body>
<div id="grandparent">
<div class="parent">
<p class="child">Which color?</p>
</div>
</div>
</body>
</html>

所以最终的效果应该是,which color?呈现出红色。

规则二:关于先后覆盖的一个例子

这个例子很简单,就是当权值一样的时候,后面的样式覆盖前面的样式。举例:

<html>
<head>
<style type="text/css">
#grandparent .child_b{
color: red;
}
#grandparent .child_a{
color: blue;
}
</style>
</head>
<body>
<div id="grandparent">
<div class="parent">
<p class="child_a child_b">Which color?</p>
</div>
</div>
</body>
</html>

当然,最后是呈现出蓝色的。

规则三:使用JavaScript添加脚本的一个例子

<html>
<head>
<style type="text/css">
#parent{
color: red;
}
</style>
</head>

<body>
<div id="parent">
<p id="child">Which color?</p>
</div>
<script type="text/javascript">
var child = document.getElementById("child");
child.style.color = "blue";
</script>
</body>
</html>

最终的结果中,发现child元素多出了一行行内样式:

规则四:使用!important覆盖

<html>
<head>
<style type="text/css">
#parent #child{
color: red;
}
p{
color: yellow !important;
}
</style>
</head>

<body>
<div id="parent">
<p id="child" sytle="color: blue">Which color?</p>
</div>
</body>
</html>

这段代码,即便ID选择器和行内样式权值都很大,然而!important还是最有话语权;这样看来!important是不是有种钦定的感觉……