margin-right

Baseline 廣泛可用 *

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

* 此特性的某些部分可能存在不同級別的支援。

margin-right CSS 屬性設定元素右側的外邊距區域。正值使元素遠離其相鄰元素,而負值使元素靠近其相鄰元素。

試一試

margin-right: 1em;
margin-right: 10%;
margin-right: 10px;
margin-right: 0;
<section id="default-example">
  <div id="container">
    <div class="col"></div>
    <div class="col transition-all" id="example-element"></div>
    <div class="col"></div>
  </div>
</section>
#container {
  width: 300px;
  height: 200px;
  display: flex;
  align-content: flex-start;
  justify-content: flex-start;
}

.col {
  width: 33.33%;
  border: solid #5b6dcd 10px;
  background-color: rgb(229 232 252 / 0.6);
  flex-shrink: 0;
}

#example-element {
  border: solid 10px #ffc129;
  background-color: rgb(255 244 219 / 0.6);
}

兩個相鄰盒子的垂直外邊距可能會融合。這稱為外邊距摺疊

語法

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

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

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

margin-right 屬性被指定為關鍵字 auto,或一個 <length>,或一個 <percentage>。它的值可以是正數、零或負數。

<length>

邊距的大小為固定值。

<percentage>

邊距的大小為百分比,相對於包含塊的內聯尺寸(在水平書寫模式下是寬度,由writing-mode定義)。

auto

右外邊距會獲得未使用的水平空間的一部分,這主要取決於所使用的佈局模式。如果 margin-leftmargin-right 的值都為 auto,則計算出的空間會均勻分佈。此表總結了不同的情況

display 的值 float 的值 position 的值 auto 的計算值 Comment
inlineinline-blockinline-table 任意 staticrelative 0 內聯佈局模式
blockinlineinline-blockblocktableinline-tablelist-itemtable-caption 任意 staticrelative 0,除非 margin-leftmargin-right 都設定為 auto。在這種情況下,它被設定為使元素在其父元素中居中的值。 塊佈局模式
blockinlineinline-blockblocktableinline-tablelist-itemtable-caption leftright staticrelative 0 塊佈局模式(浮動元素)
任何 table-*,除了 table-caption 任意 任意 0 內部 table-* 元素沒有外邊距,請改用border-spacing
任何,除了 flexinline-flextable-* 任意 fixedabsolute 0,除非 margin-leftmargin-right 都設定為 auto。在這種情況下,如果固定,它被設定為在可用 width 中使邊框區域居中的值。 絕對定位佈局模式
flexinline-flex 任意 任意 0,除非存在任何正的水平自由空間。在這種情況下,它會均勻地分配給所有水平 auto 外邊距。 彈性盒子佈局模式

正式定義

初始值0
應用於所有元素,除了具有 table-captiontableinline-table 以外的表格display 型別的元素。它也適用於 ::first-letter
繼承性
百分比參照包含塊的寬度
計算值指定的百分比或絕對長度
動畫型別一個長度

正式語法

margin-right = 
<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-right: 5%;
}
.side-box {
  margin-right: 10px;
}
.logo {
  margin-right: -5px;
}

規範

規範
CSS Box Model Module Level 3
# margin-physical

瀏覽器相容性

另見