样式的继承
定义:父元素设置了某属性,子元素也会有该属性
下面是会被继承的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, speechrate,
stress, text-align, text-indent, texttransform,
visibility, voice-family, volume, whitespace,
widows, word-spacing
文本相关属性:
font-family, font-size, font-style,
font-variant, font-weight, font, letter-spacing,
line-height, text-align, text-indent, texttransform,word-spacing
列表相关属性:
list-style-image, list-style-position,
list-style-type, list-style
样式的覆盖
规则:
- 根据引入方式确定优先级
优先级由高到低依次为:“内联属性”——>“写在 style标签里”——>“外部链接” - 后写的覆盖先写的(同一级别)
即就是在文件上代码行号更靠下的优先级更高 - 加有“
!important
”的样式,优先级最高
即无论哪一种情况,只要在样式上加了important
,那么该样式的优先级最高。加了important
的代码如下:
p {
color: white !important;
}
- 选择器优先级
在选择器不同的情况下,给每种选择器制定一个权值,计算命中一个元素的所有选择器的总权值,值高者获胜
元素选择器: 1
类选择起器: 10
ID选择器: 100
内联选择器: 1000
样式继承与覆盖示例
- 样式继承不是一个默认行为,实际上而是看某一个属性的默认值是否是
inherit
。
所谓的浏览器默认样式。a
标签的color
浏览器默认样式不是inherit
。代码如下所示:
.abstract{
color:grey;
}
.abstract a{
color:inherit;
text-decoration:none;
border:thin black solid;
}
.different {
color: red ;
}
.different a{
text-decoration: none ;
border:thin black solid;
}
执行效果如下图:
- 前面讲到外部文件引用
css
的优先级比style
标签里的低。但是id
选择器的优先级是比元素选择器要高的。所以当元素选择器和id
选择器都命中同样的元素的时候,id
选择器的样式会覆盖元素选择器的样式。 代码如下:
h1{
color:red;
}
#change{
color:blue;
}
执行效果如下:
- 我们知道内联样式的优先级是最高的,那么当元素已经被内联样式设置的时候。我们通过
!important
来覆盖。代码如下:
<body>
<h1 id="change" style="color: grey">
HelloWord,你看到的是已经经历过三次变换的文字。
</h1>
</body>
h1{
color: red;
}
#change{
color:black !important
}
执行效果如下:
- 若给一种元素设置了普适的效果,如何通过更精确的选择器将其覆盖掉,代码如下:
a{
color:black;
}
a.hehe{
color:white;
background:grey;
}
当一个元素有两个class
的时候,到底哪个class
会影响元素呢, 代码如下:
a.hehe1{
color:black;
}
a.hehe2{
color:white;
background:grey;
}
文件上代码行号更靠下的优先级更高,即后写的覆盖先写的。
- 让
span
继承abstract
的border
属性。代码如下:
.abstract{
color:white;
background:grey;
border:medium black solid;
}
span{
border:inherit
}
如上所示,将span
的 border
属性设为“inherit
”,span
就会继承父元素的样式。