jquery時代大多使用插件實現瀑布流布局,但現在我們可以直接使用存粹的css來實現。從css3開始出現了column-count與column-gap后,我們便可直接使用此屬性來進行布局,其中column-count代表列數,column-gap代表列之間的距離。值得注意的是,當使用column-count時,容器中不只一個元素時,列末尾容器中一部分元素可能會斷裂至另一列中,為防止此種情況發生可以使用break-inside: avoid,避免容器斷裂成兩部分。
各大瀏覽器支持程度:
實例
步驟
1、給容器屬性column-count與column-gap。
2、給容器中項目屬性break-inside: avoid。
實現代碼
html代碼
<div class="wrapper">
<div class="task-container">
<!--遍歷任務列表-->
<div v-for="(item, index) in taskData" :key="index" class="tasks">
<div class="task-div">
<!--任務標簽-->
<span
:style="{
backgroundColor:
tagColorList[Math.floor(Math.random() * tagColorList.length)],
}"
v-for="tag in item.tag"
:key="tag"
>{{ tag }}
</span>
<img
v-if="item.img"
:src="taskImgLis[Math.floor(Math.random() * taskImgLis.length)]"
/>
<h1>{{ item.tit }}</h1>
<p>{{ item.con }}</p>
<a href="#">Detalies</a>
</div>
</div>
</div>
</div>
css代碼
<style scoped lang='scss'>
.wrapper {
margin: 5px auto;
width: 98%;
height: 99%;
overflow: auto;
.task-container {
margin: 10px auto;
width: 99%;
column-count: 4; /*表示分割的列數 */
column-gap: 0px;/*表示列之間的間隔*/
.tasks {
break-inside: avoid; /*防止元素內部斷裂成第二列*/
margin: 0px 20px 30px 20px;
background-color: #eff6ff;
border-radius: 10px;
padding: 10px;
.task-div {
span {
margin: 10px 10px 10px 0px;
padding: 3px 5px;
background-color: #ffe5d3;
border-radius: 5px;
}
img {
margin: 10px auto;
width: 100%;
border-radius: 10px;
}
p {
color: #aaa;
margin: 0px 0px 10px 0px;
}
a {
padding: 10px 0px 0px 0px;
text-decoration: none;
color: #4c33e6;
}
}
}
}
}
.wrapper::-webkit-scrollbar {
/*滾動條整體*/
width: 5px;
height: 5px;
}
.wrapper::-webkit-scrollbar-track {
/*滑軌*/
background-color: #ccc;
border-radius: 30px;
}
.wrapper::-webkit-scrollbar-thumb {
/*滑塊*/
background-color: rgba(0, 0, 0, 0.6);
border-radius: 30px;
cursor: pointer;
}
</style>