这是我参与「第五届青训营 」伴学笔记创作活动的第 6 天。
在了解了CSS基本原理后,我们进一步学习CSS的继承与布局。
选择器的特异度(Specificity)
<button class="btn">普通按钮</button>
<button class="btn primary">主要按钮</button>
<style>
.btn {
display: inline-block;
padding: .36em .8em;
margin-right: .5em;
line-height: 1.5;
text-align: center;
cursor: pointer;
border-radius: .3em;
border: none;
background: #e6e6e6;
color: #333;
}
.btn.primary {
color: #fff;
background: #218de6;
}
</style>
继承
某些属性会自动继承其父元素的计算值,除非显式指定一个值。
<p>This is a <em>test</em> of <strong>inherit</strong></p>
<style>
body {
font-size: 20px;
}
p {
color: blue;
}
em {
color: red;
}
</style>
显式继承
初始值
- CSS中,每个属性都有一个初始值
- background-color的初始值为transparent
- margin-left的初始值为0
- 可以使用initial关键字显式重置为初始值
- background-color:initial
CSS求值过程
布局(Layout)是什么?
- 确定内容的大小和位置的算法
- 依据元素、容器、兄弟节点和内容等信息来计算
布局相关技术
盒模型
Width
- 指定content box宽度
- 取值为长度、百分数、auto
- auto由浏览器根据其他属性确定
- 百分数相对于容器的content box宽度
height
- 指定content box高度
- 取值为长度、百分数、auto
- auto取值由内容计算得来
- 百分数相对于容器的content box高度
- 容器有指定的高度时,百分数才生效
内边距
padding
- 指定元素四个方向的内边距
- 百分数相对于容器的宽度
border
指定容器边框样式、粗细和颜色
- 三种属性
- border-width
- border-style
- border-color
- 四个方向
- border-top
- border-right
- border-bottom
- border-left
margin
指定元素四个方向的外边距 取值可以是长度、百分数、auto 百分数相对于容器宽度
使用margin:auto水平居中
<div></div>
<style>
div {
width: 200px;
height: 200px;
background: coral;
margin-left: auto;
margin-right: auto;
}
</style>
margin collapse
<div class="a"></div>
<div class="b"></div>
<style>
.a {
background: lightblue;
height: 100px;
margin-bottom: 100px;
}
.b {
background: coral;
height: 100px;
margin-top: 100px;
}
</style>
box-sizing:border-box
overflow
- visible正常显示超出文本框内容
- hidden隐藏超出文本框内容
- scroll内容可在文本框上下左右滚动