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

浏览器兼容性

另见