CSS margin-bottom 属性


CSS margin-bottom 属性

在CSS中,margin-bottom属性用于定义元素下方的外边距,可以控制元素与下方元素之间的距离,也可以影响父元素的尺寸。

语法格式

margin-bottom: length|percentage|auto|initial|inherit;
描述
length 指定长度单位的数值,例如:px、em、rem等
percentage 相对于包含块元素的百分比值
auto 自动计算外边距
initial 设置属性为它的默认值
inherit 从父元素继承属性

属性值

length

length代表具体的长度值,是一个数字后面跟着长度单位(e.g. px)。

margin-bottom: 10px;

在上述声明中,margin-bottom被设置为10像素。

percentage

percentage代表相对于包含块元素(包含当前元素的最近父元素)的百分比值。

margin-bottom: 20%;

在上述声明中,margin-bottom被设置为包含块元素高度的20%。

auto

auto关键字可用于自动计算外边距,通常是用于内联元素水平居中。

margin: 0 auto;

在上述声明中,margin-bottom会自动计算以实现元素在包含块中水平居中。

initial

initial关键字指定该属性使用它的默认值。

margin-bottom: initial;

在上述声明中,margin-bottom被设置为默认值。

inherit

inherit关键字从父元素继承margin-bottom属性。

margin-bottom: inherit;

在上述声明中,margin-bottom被设置为从父元素继承该属性的值。

如何使用

单个元素

<div class="container">
  <h1>Title</h1>
  <p>Content</p>
</div>
.container {
    margin-bottom: 20px;
}

在上述例子中,.container元素的下方会有一个20像素的外边距。

多个元素

<div class="container">
  <h1>Title</h1>
  <p>Content</p>
</div>
<div class="container">
  <h1>Title</h1>
  <p>Content</p>
</div>
.container {
   margin-bottom: 20px;
}

在上述例子中,每个.container元素的下方都会有一个20像素的外边距,它们互相之间没有重叠。

影响父元素大小

<div class="container">
  <h1>Title</h1>
  <p>Content</p>
  <div class="box"></div>
</div>
.container {
   margin-bottom: 20px;
}
.box {
   height: 100px;
}

在上述例子中,.container元素的下方会有一个20像素的外边距,但其高度并不会将下方的.box元素包含在内。因此,.container元素的高度是h1p和外边距的总和,如图所示:

image-20210928193852361.png

总结

通过使用margin-bottom属性,我们可以控制元素下方的外边距,影响元素与下方元素的距离,也会影响父元素的尺寸,帮助我们更好地构建网页布局。