flex+margin的组合布局技巧,这套方案能极大简化日常前端开发中的常见布局场景。
基础逻辑:在弹性项上设置margin: auto,本质是让 margin "吃掉" 父元素里的剩余空间 ------ 设置单侧margin-left: auto就能把元素挤到右侧,同时设置左右margin: auto就可以让元素在横向居中,纵向同理,仅靠给子元素写一行代码,就能替代传统给父元素加justify-content和align-items的居中写法。
比如实现如1-3分列效果只要将父级元素设置flex, 然后将第二个子元素设置对应的margin-left:auto即可

如果是2-2等分将第二个子元素设置对应的margin-right:auto即可

如果要实现这种1-1-1三等分效果同理则可以设置中间元素的margin:0 auto即可

如果要实现这中里面盒子全部都是等分布局的则需要计算出对应盒子的margin左右两边的距离

--n: 5;
margin: 10px calc((100% - 80px * var(--n)) / var(--n) / 2);
代码如下:
html
<!--
* @Author: zhongyc 274687156@qq.com
* @Date: 2026-10-31 11:30:47
* @LastEditors: zhongyc 274687156@qq.com
* @LastEditTime: 2026-10-31 11:40:42
* @FilePath: /cesiumjs-editor/pip-demo.html
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>flex+margin巧妙使用实现常规布局</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family:
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
'Helvetica Neue', Arial, sans-serif;
}
#app {
display: flex;
flex-wrap: wrap;
align-content:baseline; /*不设置的话下面的盒子会自使用盒子的整体高度往下移动,中间会流出一些空间*/
width: 500px;
height: 500px;
margin: 100px auto;
background: #eee;
}
.box {
flex-shrink: 1;
width: 80px;
height: 80px;
background: red;
border: 1px solid #ccc;
--n: 5;
margin: 10px calc((100% - 80px * var(--n)) / var(--n) / 2);
}
</style>
</head>
<body>
<div id="app">
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
</div>
</body>
</html>
<script>
</script>