此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
margin
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
* Some parts of this feature may have varying levels of support.
margin 属性为给定元素设置所有四个(上右下左)方向的外边距属性。也就是margin-top、margin-right、margin-bottom 和margin-left 四个外边距属性设置的简写。
In this article
尝试一下
margin: 1em;margin: 5% 0;margin: 10px 50px 20px;margin: 10px 50px 20px 0;margin: 0;<section> <div> <div></div> <div></div> <div></div> </div></section>#container { width: 300px; height: 200px; display: flex; align-content: flex-start; flex-direction: column; justify-content: flex-start;}.row { height: 33.33%; display: inline-block; border: solid #ce7777 10px; background-color: #2b3a55; flex-shrink: 0;}#example-element { border: solid 10px #ffbf00; background-color: #2b3a55;}组成属性
此属性是以下 CSS 属性的简写:
语法
css
/* 应用于所有边 */margin: 1em;margin: -3px;/* 上边下边 | 左边右边 */margin: 5% auto;/* 上边 | 左边右边 | 下边 */margin: 1em auto 2em;/* 上边 | 右边 | 下边 | 左边 */margin: 2px 1em 0 auto;/* 全局值 */margin: inherit;margin: initial;margin: unset;margin 属性接受 1~4 个值。每个值可以是<length>,<percentage>,或auto。取值为负时元素会比原来更接近临近元素。
- 当只指定一个值时,该值会统一应用到全部四个边的外边距上。
- 指定两个值时,第一个值会应用于上边和下边的外边距,第二个值应用于左边和右边。
- 指定三个值时,第一个值应用于上边,第二个值应用于右边和左边,第三个则应用于下边的外边距。
- 指定四个值时,依次(顺时针方向)作为上边,右边,下边,和左边的外边距。
可取值
<length>以固定值为外边距。
<percentage>相对于包含块的宽度,以百分比值为外边距。
auto让浏览器自己选择一个合适的外边距。有时,在一些特殊情况下,该值可以使元素居中。
语法格式
margin =
<'margin-top'>{1,4}
<margin-top> =
<length-percentage>|
auto|
<anchor-size()>
<length-percentage> =
<length>|
<percentage>
<anchor-size()> =
anchor-size([<anchor-name>||<anchor-size>]? ,<length-percentage>?)
<anchor-name> =
<dashed-ident>
<anchor-size> =
width|
height|
block|
inline|
self-block|
self-inline
示例
>简单的例子
HTML
html
<div>此元素会被居中。</div><div>此元素会显示在包含块之外。</div>CSS
css
.center { margin: auto; background: lime; width: 66%;}.outside { margin: 3rem 0 0 -3rem; background: cyan; width: 66%;}更多的例子
css
margin: 5%; /* 所有边:5% 的外边距 */margin: 10px; /* 所有边:10px 的外边距 */margin: 1.6em 20px; /* 上边和下边:1.6em 的外边距 *//* 左边和右边:20px 的外边距 */margin: 10px 3% -1em; /* 上边:10px 的外边距 *//* 左边和右边:3% 的外边距 *//* 下边: -1em 的外边距 */margin: 10px 3px 30px 5px; /* 上边:10px 的外边距 *//* 右边:3px 的外边距 *//* 下边:30px 的外边距 *//* 左边:5px 的外边距 */margin: 2em auto; /* 上边和下边:2em 的外边距 *//* 水平方向居中 */margin: auto; /* 上边和下边:无外边距 *//* 水平方向居中 */贴士
>水平居中
在现代浏览器中实现水平居中,可以使用display: flex;justify-content: center;。
不过,在 IE8-9 这样的不支持弹性盒布局的旧式浏览器中,上述代码并不会生效。此时要实现在父元素中居中,可使用margin: 0 auto;。
外边距重叠
上下元素的下上外边距有时会重叠,实际空出的空间长度变为两外边距中的较长值。查看外边距重叠可找到更多信息。
规范
| Specification |
|---|
| CSS Box Model Module Level 3> # margin> |
| 初始值 | 该简写所对应的每个属性: |
|---|---|
| 适用元素 | all elements, except elements with tabledisplay types other thantable-caption,table andinline-table. It also applies to::first-letter. |
| 是否是继承属性 | 否 |
| Percentages | refer to the width of the containing block |
| 计算值 | 该简写所对应的每个属性:
|
| 动画类型 | alength |