CSS 继承性(Inheritance)
css继承性在后续盒子模型,动画等样例中都有重要应用。他是很基础的一部分,也是非常容易搞混的一块,所以今天给大家分享一下css继承性中比较容易混的部分。
一、什么是 CSS 继承
CSS 继承:
某些 CSS 属性的值,会从父元素自动传递给后代元素。
例如:
html
<div class="father">
hello
<p>world</p>
</div>
css
.father{
color:red;
}
结果:
text
hello 红
world 红
因为:color是可继承属性。
CSS继承性是"属性"的特性,不是"元素"的特性。
二、继承到底传给谁?
继承作用于后代元素(descendants)
包括:
- 子元素
- 孙元素
- 曾孙元素
- 所有嵌套后代
例如:
html
<div>
<section>
<p>
<span>文字</span>
</p>
</section>
</div>
css
div{
color:red;
}
结果:
text
section 红
p 红
span 红
三、继承是"逐层"发生的
不是 div 一次性传给所有后代
而是 div → section → p → span 一级一级继承。
四、继承属性的分类
CSS 属性分两类:
1. Inherited Properties(可继承属性)
父元素会自动传给后代。
2. Non-inherited Properties(不可继承属性)
不会自动传递。
五、可继承属性
1. 字体相关
css
font-family
font-size
font-weight
font-style(斜体样式)
建议尽量少些font,因为他会把没写的样式会被重置为normal,并且顺序要求也比较复杂。而且还会影响元素间的继承性
2. 文本相关
css
color
text-align
text-indent(段落首行缩进)
3. 行高
css
line-height
4. 列表
css
list-style
5. 光标
css
cursor
6. 可见性
css
visibility
六、不可继承属性
1. 盒模型
css
width
height
margin
padding
border
2. 背景
css
background
background-color
background-image
background-repeat
background-position
background-size
background-attachment
background-origin
background-clip
css
<div class="father">
<p>hello</p>
</div>
.father{
background:red;
}
效果:整个区域都是红的
这不是继承,而是因为子元素背景默认透明,把父元素背景露出来了。
3. 布局
css
display
position
float
clear
overflow
4. Flex/Grid
css
flex
grid
justify-content
align-items
5. 定位
css
top
left
right
bottom
z-index
6. 其他
css
text-decoration
text-shadow
七、最核心规则
一般规律
文字相关属性
通常可继承。
布局/盒模型相关
通常不可继承。
为什么文字类会继承?
因为:网页通常需要统一文字风格
例如:
body{
font-family:Arial;
color:#333;
}
整个页面文字自动统一。
为什么布局类不继承?
例如:width:500px;
如果子元素都自动继承:整个页面所有元素都会500px 布局会彻底混乱。
所以:布局属性通常不继承
八、继承的流程
浏览器计算元素样式时:
第一步
看元素自己有没有指定值。
第二步
如果没有:
判断属性是否可继承。
第三步
如果可继承:
从父元素继承。
否则:
使用默认初始值。
自己设置的永远大于继承的
九、特例
1. a 标签为什么经常不是继承色?
因为浏览器默认样式:
css
a:any-link{
color:blue;
}
覆盖了继承效果。
不是"不继承"。
例如:
css
a{
color:inherit;
}
就会恢复继承。
2. line-height
情况1:固定值
css
line-height:40px;
子元素继承:40px
情况2:无单位数字
css
line-height:2;
继承的是:数字 2
不是像素值。
例如:
css
div{
font-size:20px;
line-height:2;
}
p{
font-size:30px;
}
p 行高:30 × 2 = 60px
3. inherit 继承的是"计算值"
不是源码字符串。
例如:
css
.parent{
width:50%;
}
.child{
width:inherit;
}
child 继承的是:
父元素计算后的值
不是 "50%" 这个文本。