前言
關(guān)于 flex 布局下 justify-content: xx,很多朋友都想讓其換行后,靠左進(jìn)行依次排列(默認(rèn)會平均分布居中)。
本文實(shí)現(xiàn)了 純 CSS (無任何 JS),實(shí)現(xiàn) flex / justify-content 彈性布局下,斷行后讓元素始終靠左排序,
你可以一鍵復(fù)制示例,然后稍微改改樣式就能使用。
如下圖所示,該示例是一行顯示 3 個(可自定義),寬度變化時保持 “平均分布”,超出部分 “居左” ,
并且,還可以隨意設(shè)置各元素之間的 “間隙”,具體詳見代碼。
示例代碼
推薦使用一鍵復(fù)制功能,避免漏選。
隨便新建一個 *.html
復(fù)制后直接運(yùn)行,按照需求進(jìn)行更改調(diào)試即可。文章來源:http://www.zghlxwxcb.cn/news/detail-437798.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>
<!-- <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 = (分布個數(shù)3-1)*間隙5px, 可以根據(jù)實(shí)際的分布個數(shù)和間隙區(qū)調(diào)整 */
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>
具體請看代碼注釋,多做修改調(diào)試達(dá)到您想要的效果。文章來源地址http://www.zghlxwxcb.cn/news/detail-437798.html
到了這里,關(guān)于CSS - 完美解決 flex 布局下,一行顯示固定個數(shù)(平均分布)并且強(qiáng)制換行,超出后 “靠左“ 對其(詳細(xì)解決方案,適用于 Web、Vue、React 等任何前端項(xiàng)目)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!