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

瀏覽器相容性

另見