您现在的位置是:首页 > 技术教程 正文

CSS - 完美解决 flex 布局下,一行显示固定个数(平均分布)并且强制换行,超出后 “靠左“ 对其(详细解决方案,适用于 Web、Vue、React 等任何前端项目)

admin 阅读: 2024-03-28
后台-插件-广告管理-内容页头部广告(手机)

前言

关于 flex 布局下 justify-content: xx,很多朋友都想让其换行后,靠左进行依次排列(默认会平均分布居中)。

本文实现了 纯 CSS (无任何 JS),实现 flex / justify-content 弹性布局下,断行后让元素始终靠左排序,

你可以一键复制示例,然后稍微改改样式就能使用。


如下图所示,该示例是一行显示 3 个(可自定义),宽度变化时保持 “平均分布”,超出部分 “居左” ,

并且,还可以随意设置各元素之间的 “间隙”,具体详见代码。

在这里插入图片描述

示例代码

推荐使用一键复制功能,避免漏选。

随便新建一个 *.html 复制后直接运行,按照需求进行更改调试即可。

<body> <section class="content"> <div class="item">元素div> <div class="item">元素div> <div class="item">元素div> <div class="item">元素div> <div class="item">元素div> <div class="item">元素div> <div class="item">元素div> section> body> <style> .content { width: 100%; display: flex; flex-wrap: wrap; justify-content: flex-start;/* 替代space-between布局方式 */ } .item { flex: 1; height: 120px; background-color: #cacaca; /* 间隙为5px */ margin: 0 5px 5px 0; /* END */ /* 这里的10px = (分布个数3-1)*间隙5px, 可以根据实际的分布个数和间隙区调整 */ width: calc((100% - 10px) / 3); /* END */ /* 加入这两个后每个item的宽度就生效了 */ min-width: calc((100% - 10px) / 3); max-width: calc((100% - 10px) / 3); /* END */ } .item:nth-child(3n) { /* 去除第3n个的margin-right */ margin-right: 0; } style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

具体请看代码注释,多做修改调试达到您想要的效果。

标签:
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

在线投稿:投稿 站长QQ:1888636

后台-插件-广告管理-内容页尾部广告(手机)
关注我们

扫一扫关注我们,了解最新精彩内容

搜索
排行榜