CSS继承
CSS继承是一种机制,允许子元素自动继承父元素的某些样式属性,从而减少重复代码。
以下是一些常见的具有继承性的CSS属性:
color
: 文字颜色
font-family
: 字体族名称
font-size
: 字体大小
font-weight
: 字体粗细
line-height
:行高
text-align
: 文本对齐方式
text-indent
: 文本块首行缩进
margin
: 外边距
padding
: 内边距
以下是一些不具有继承属性的CSS属性:
border
:边框样式
width
:宽度
height
:高度
background
:背景样式
position
:定位方式
需要注意的是,并非所有属性都具有继承性,即使在上述示例中,继承性也可能受到其他因素影响。另外,有时可以使用inherit
关键字来显式地指定子元素继承父元素的样式。
以下是一个实例,演示CSS的继承效果:
html
<!DOCTYPE html>
<html>
<head>
<title>CSS继承示例</title>
<style>
body {
font-family: Arial, sans-serif;
font-size: 16px;
color: blue;
text-align: center;
}
h1 {
font-weight: bold;
color: red; /* 覆盖继承的蓝色 */
}
p {
line-height: 1.5; /* 继承body的font-family/font-size/color/text-align */
}
.container {
margin: 20px;
padding: 10px;
background-color: lightgray;
}
</style>
</head>
<body>
<div class="container">
<h1>Title</h1>
<p>This is a paragraph of text.</p>
</div>
</body>
</html>