margin-block

Baseline 廣泛可用 *

此特性已得到良好支援,可在多種裝置和瀏覽器版本上使用。自 2021 年 4 月起,所有瀏覽器均已支援此特性。

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

margin-block 是一個 CSS 簡寫屬性,它定義了一個元素的邏輯塊起始和結束外邊距,這些外邊距會根據元素的書寫模式、方向性和文字方向對映到物理外邊距。

試一試

margin-block: 10px 20px;
writing-mode: horizontal-tb;
margin-block: 20px 40px;
writing-mode: vertical-rl;
margin-block: 5% 20%;
writing-mode: horizontal-tb;
margin-block: 1rem auto;
writing-mode: vertical-lr;
<section id="default-example">
  <div id="container">
    <div class="row">One</div>
    <div class="row transition-all" id="example-element">Two</div>
    <div class="row">Three</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;
  color: white;
  flex-shrink: 0;
}

#example-element {
  border: solid 10px #ffbf00;
  background-color: #2b3a55;
}

構成屬性

此屬性是以下 CSS 屬性的簡寫:

語法

css
/* <length> values */
margin-block: 10px 20px; /* An absolute length */
margin-block: 1em 2em; /* relative to the text size */
margin-block: 5% 2%; /* relative to the nearest block container's width */
margin-block: 10px; /* sets both start and end values */
margin-block: anchor-size(inline);
margin-block: calc(anchor-size(width) / 4) 1em;

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

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

此屬性對應於 margin-topmargin-bottom,或者 margin-rightmargin-left 屬性,具體取決於為 writing-modedirectiontext-orientation 定義的值。

margin-block 屬性可以使用一個或兩個值來指定。

  • 當指定一個值時,它會將相同的邊距應用於起始和結束
  • 當指定兩個值時,第一個邊距應用於起始,第二個邊距應用於結束

margin-block 屬性接受與 margin 屬性相同的值。

正式定義

初始值作為簡寫中的每個屬性
應用於margin 相同
繼承性
百分比取決於佈局模型
計算值作為簡寫中的每個屬性
  • margin-block-start: 如果指定為長度,則為相應的絕對長度;如果指定為百分比,則為指定值;否則為 auto
  • margin-block-end: 如果指定為長度,則為相應的絕對長度;如果指定為百分比,則為指定值;否則為 auto
動畫型別一個長度

正式語法

margin-block = 
<'margin-top'>{1,2}

<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

css
div {
  background-color: yellow;
  width: 120px;
  height: auto;
  border: 1px solid green;
}

p {
  margin: 0;
  margin-block: 20px 40px;
  background-color: tan;
}

.verticalExample {
  writing-mode: vertical-rl;
}

HTML

html
<div>
  <p>Example text</p>
</div>
<div class="verticalExample">
  <p>Example text</p>
</div>

結果

規範

規範
CSS 邏輯屬性和值第 1 級
# propdef-margin-block

瀏覽器相容性

另見