margin-right
尝试一下
margin-right: 1em;
margin-right: 10%;
margin-right: 10px;
margin-right: 0;
#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: rgba(229, 232, 252, 0.6);
flex-shrink: 0;
}
#example-element {
border: solid 10px #ffc129;
background-color: rgba(255, 244, 219, 0.6);
}
两个相邻的盒子的垂直边距可能会合并。这被称为外边距折叠。
语法
css/*
margin-right: 20px; /* 绝对长度 */
margin-right: 1em; /* 相对于文本大小 */
margin-right: 5%; /* 相对于最近的块级容器的宽度 */
/* 关键字值 */
margin-right: auto;
/* 全局值 */
margin-right: inherit;
margin-right: initial;
margin-right: revert;
margin-right: revert-layer;
margin-right: unset;
margin-right 属性可以被指定为关键字 auto、
值
外边距的大小为固定值。
外边距的大小为相对于包含块的行级尺寸(由 writing-mode 定义的水平文字的宽度)的百分比。
auto
右边距接收未使用的水平空间中的一部分(这主要由所使用的布局模式确定)。如果 margin-left 和 margin-right 的值都是 auto,则最后计算的空间是均匀分布的。下表总结了不同的情况:
display 的值
float 的值
position 的值
auto 的计算值
注释
inline、inline-block、inline-table
任意
static 或 relative
0
行级布局模式
block、inline、inline-block、block、table、inline-table、list-item、table-caption
任意
static 或 relative
0,除非将 margin-left 和
margin-right 都设置为 auto。在这种情况下,它被设置为将元素置于其父级元素中心的值。
块级布局模式
block、inline、inline-block、block、table、inline-table、list-item、table-caption
left 或 right
static 或 relative
0
块级布局模式(浮动元素)
table-* 中的任意一个,除了 table-caption
任意
任意
0
内部的 table-* 元素没有外边距,请使用
border-spacing 代替。
任意,除了 flex、inline-flex 或 table-*
任意
fixed 或 absolute
0,除非将 margin-left 和
margin-right 都设置为 auto。在这种情况下,如果 width 固定,它会被设置为将边框区域在可用宽度内居中的值。
绝对定位布局模式
flex、inline-flex
任意
任意
0,除非存在任何正水平可用空间。在这种情况下,它会均匀分配到所有水平的 auto 外边距中。
弹性盒布局模式
形式定义
初始值0适用元素all elements, except elements with table display types other than table-caption, table and inline-table. It also applies to ::first-letter.是否是继承属性否Percentagesrefer to the width of the containing block计算值the percentage as specified or the absolute length动画类型a length
形式语法
margin-right =
来源:CSS Anchor Positioning, CSS Box Model Module Level 4, CSS Values and Units Module Level 4
示例
使用像素和百分比设置右边距
css.content {
margin-right: 5%;
}
.sidebox {
margin-right: 10px;
}
.logo {
margin-right: -5px;
}
规范
Specification
CSS Box Model Module Level 3# margin-physical
浏览器兼容性
Loading…
参见
margin-top、margin-bottom、margin-left,以及 margin 简写
映射的逻辑属性:margin-block-start、margin-block-end、margin-inline-start、margin-inline-end,以及 margin-block 和 margin-inline 简写
Help improve MDN
Was this page helpful to you?
Yes
No
Learn how to contribute
This page was last modified on 2025年7月15日 by MDN contributors.
View this page on GitHub • Report a problem with this content