margin-top

Baseline 广泛可用 *

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

* 此特性的某些部分可能存在不同级别的支持。

margin-top CSS 属性用于设置元素顶部的外边距区域。正值会使其远离相邻元素,而负值会使其更靠近相邻元素。

试一试

margin-top: 1em;
margin-top: 10%;
margin-top: 10px;
margin-top: 0;
<section id="default-example">
  <div id="container">
    <div class="row"></div>
    <div class="row transition-all" id="example-element"></div>
    <div class="row"></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;
}

此属性对非替换的行内元素(如 <span><code>)没有影响。

语法

css
/* <length> values */
margin-top: 10px; /* An absolute length */
margin-top: 1em; /* relative to the text size */
margin-top: 5%; /* relative to the nearest block container's width */
margin-top: anchor-size(height);
margin-top: calc(anchor-size(--my-anchor self-inline, 25px) / 4);

/* Keyword values */
margin-top: auto;

/* Global values */
margin-top: inherit;
margin-top: initial;
margin-top: revert;
margin-top: revert-layer;
margin-top: unset;

margin-top 属性可以指定为关键字 auto,或 <length>,或 <percentage>。其值可以是正数、零或负数。

<length>

边距的大小为固定值。

<percentage>

边距的大小为百分比,相对于包含块的内联尺寸(在水平书写模式下是宽度,由writing-mode定义)。

auto

浏览器会选择一个合适的值来使用。请参阅 margin

正式定义

初始值0
应用于所有元素,除了具有 table-captiontableinline-table 以外的表格display 类型的元素。它也适用于 ::first-letter
继承性
百分比参照包含块的宽度
计算值指定的百分比或绝对长度
动画类型一个长度

正式语法

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

示例

设置正负上外边距

css
.content {
  margin-top: 5%;
}
.side-box {
  margin-top: 10px;
}
.logo {
  margin-top: -5px;
}
#footer {
  margin-top: 1em;
}

规范

规范
CSS Box Model Module Level 3
# margin-physical

浏览器兼容性

另见