css教程网 css教程网365css.cn
公告为您打开互联网世界的窗户关于本站
首页/属性速查/尺寸与溢出

margin

元素外侧的间距,可负值,垂直方向会与相邻元素折叠。

语法
margin: <length-percentage> | auto{1,4}
常用值
16px / 0 auto / -8px / 12px 0
初始值
0
继承
否

运行效果

示例改成别的值试试,差异一眼能看出来
查看代码
HTML
<div class="mg"><i>margin-bottom: 14px</i><i>第二个盒子</i></div>
CSS
.mg { width: 180px; }
.mg i { display: block; padding: 8px 10px; border-radius: 6px; background: #eef2ff; color: #1c3fd6; font: 600 10px/1.4 ui-monospace, monospace; font-style: normal; margin-bottom: 14px; }
.mg i:last-child { margin-bottom: 0; background: #2b57ff; color: #fff; }

使用要点

  • 垂直相邻的 margin 会折叠成较大值;flex / grid 容器内的子项不折叠。
  • 水平居中用 margin-inline: auto,且元素需要有确定宽度。
  • 列表间距优先用 gap,比逐个清 margin 更省事。