前言
这种需求很常见,但网上的教程代码都太乱了。
本文实现了 display flex 弹性布局下,设置每行显示的个数,超出自动换行解决方案,
如下图所示,默认情况下是不会 “换行” 的,而设置之后却可以:
解决方案
您可以直接一键复制,写个 *.html 运行一下查看效果。
核心思路就是,“外层” 加入 flex-wrap: wrap
,“内层” 设置宽度让其一行放不下(自动换行)。
<body> <div class="content"> <div class="item">内容</div> <div class="item">内容</div> <div class="item">内容</div> <div class="item">内容</div> </div> </body> <style> /* 外层 */ .content { display: flex; justify-content: space-between; flex-wrap: wrap;/* 只要您把这个属性去掉,就不会自动换行了*/ } /* END */ /* 内层 */ .item { width: 48%; background: #c3c3c3; margin-bottom: 20px; } /* END */ </style>
复制