CSS margin-bottom 语法
在 CSS 中,margin-bottom 属性用于定义元素的下外边距。从下图所示的 CSS 盒子模型中可以看出,margin-bottom 位于 border 的下方。

语法:
margin-bottom: 数值;说明:
margin-bottom 的取值是一个数值,比如像素值(px)、百分比(%)、em、rem 等。
对于 margin-bottom 属性,小伙伴们要清楚以下几点。
- margin-bottom 是 margin 简写属性的组成部分。
- margin-bottom 属性会影响元素与其下方元素之间的距离。
- margin-bottom 属性可以接受负值,这可能导致元素向下移动,与下方元素重叠。
- margin-bottom 百分比值是相对于父元素的宽度进行计算的,即使是垂直方向的外边距。
- 相邻的块级盒子的垂直外边距(margin-top 和 margin-bottom)有时会合并为一个外边距,其大小取其中最大的那个。margin-bottom 参与垂直外边距的重叠计算。
- 对 inline 元素(如 span、strong 等)设置 width 和 height 是无效的,但对它们设置 padding 和 margin 是有效的。
CSS margin-bottom 摘要
| 属于 | CSS 外边距 |
|---|---|
| 使用频率 | 高 |
| 是否继承 | 否 |
| 默认值 | 0 |
| 兼容性 | 查看 |
| 官方文档 | 查看 |
| MDN | 查看 |
CSS margin-bottom 示例
接下来,我们通过几个简单的例子来讲解一下 CSS margin-bottom 属性是如何使用的。
示例 1:margin-bottom 基本用法
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#father {
display: inline-block; /* 转换为inline-block元素 */
border: 1px solid blue;
}
#son {
display: inline-block; /* 转换为inline-block元素 */
padding: 20px;
margin-bottom: 50px;
border: 1px solid red;
background-color: #FFDEAD;
}
.brother {
height:50px;
background-color: skyblue;
}
</style>
</head>
<body>
<div id="father">
<div class="brother"></div>
<div id="son">绿叶网</div>
<div class="brother"></div>
</div>
</body>
</html>页面效果如下图所示。

示例 2:margin-bottom 外边距重叠
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div {
width: 200px;
height: 100px;
}
.box1 {
margin-bottom: 20px; /* 底部外边距 20px */
background-color: hotpink;
}
.box2 {
margin-top: 40px; /* 顶部外边距 40px */
background-color: lightskyblue;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>页面效果如下图所示。

分析:
在这个例子中,box1 的底部外边距为 20px,而 box2 的顶部外边距为 40px。理论上它们之间的距离应该是 20px + 40px = 60px,但由于相邻元素的垂直外边距会重叠,因此实际的外边距为 40px(取较大值)。
示例 3:margin-bottom 使用负值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div {
width: 200px;
height: 100px;
border: 1px solid gray;
}
.box1 {
margin-bottom: -80px;
background-color: hotpink;
}
.box2 {
background-color: lightskyblue;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>页面效果如下图所示。

分析:
在这个例子中,我们给 box2 设置了 margin-top: -80px;,此时 box2 会相当于原位置向上移动了 80px,并覆盖到 box1 的上面。
margin 的派生子属性
margin 是一个复合属性,它有 4 个派生子属性(如下表所示),用于单独设置某个方向的 margin。
| 子属性 | 说明 |
|---|---|
| margin-top | 上外边距 |
| margin-right | 右外边距 |
| margin-bottom | 下外边距 |
| margin-left | 左外边距 |
