margin-top CSS 属性用于设置元素的顶部外边距外边距区域。正值使它离相邻元素更远,而负值使它更靠近相邻元素。
CSS Demo: margin-top
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。
语法
/* <length> 值 */
margin-top: 10px; /* 绝对长度 */
margin-top: 1em; /* 相对与文本的大小 */
margin-top: 5%; /* 相对于最近的块容器的宽度 */
/* 关键字值 */
margin-top: auto;
/* 全局关键字值 */
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。
形式语法
示例
将上边距设置为正值和负值
.content {
margin-top: 5%;
}
.sidebox {
margin-top: 10px;
}
.logo {
margin-top: -5px;
}
#footer {
margin-top: 1em;
}
规范
浏览器兼容性
参见
- margin-right、margin-bottom、margin-left,以及 margin 简写属性
- 映射的逻辑属性:margin-block-start、margin-block-end、margin-inline-start、margin-inline-end,以及 margin-block 和 margin-inline 简写属性
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
