瀑布流

大约 1 分钟

方式一:column

源码
<template>
  <div class="container">
    <div class="item" v-for="i in 10" :key="i">
      <img :src="'https://picsum.photos/360/' + i + '00?random=' + i" />
    </div>
  </div>
</template>

<style>
.container {
  column-count: 4;
  column-gap: 0;
}
.item {
  position: relative;
  padding: 2px;
  /* 计数器名称 */
  counter-increment: item-counter;
}
.item img {
  width: 100%;
}
.item::before {
  position: absolute;
  left: 2px;
  top: 2px;
  width: 24px;
  height: 24px;
  background-color: #000;
  text-align: center;
  line-height: 24px;
  color: #fff;
  /* 计数器值 */
  content: counter(item-counter);
}
</style>

实现思路

  1. 外层容器指定列数
.container {
  /* 列数 */
  column-count: 4;
  /* 每列的间隔 */
  column-gap: 0;
}
  1. 图片撑满容器
.item img {
  width: 100%;
}

注意

该方式按竖向排序

方式二:flex

源码
<template>
  <div class="container">
    <div class="item" v-for="i in 8" :key="i">
      <img
        :src="'https://picsum.photos/360/4' + (i % 2) * 5 + '0?random=' + i"
      />
    </div>
  </div>
</template>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 500px;
  flex-wrap: wrap;
}
.item {
  width: 25%;
  position: relative;
  padding: 2px;
  /* box-siz */
  /* 计数器名称 */
  counter-increment: item-counter;
}
.item img {
  width: 100%;
}
.item:nth-child(4n + 1) {
  order: 1;
}
.item:nth-child(4n + 2) {
  order: 2;
}
.item:nth-child(4n + 3) {
  order: 3;
}
.item:nth-child(4n) {
  order: 4;
}
.item::before {
  position: absolute;
  left: 2px;
  top: 2px;
  width: 24px;
  height: 24px;
  background-color: #000;
  text-align: center;
  line-height: 24px;
  color: #fff;
  /* 计数器值 */
  content: counter(item-counter);
}
</style>

实现思路

  1. 外层容器指定高度 flex 布局 纵向排列 超出换行
.container {
  display: flex;
  flex-direction: column;
  height: 500px;
  flex-wrap: wrap;
}
  1. 子元素指定宽度
.item {
  width: 25%;
}
  1. 子元素根据列数排序
/* 1,5,9,13... 排到第一列 */
.item:nth-child(4n + 1) {
  order: 1;
}

/* 2,6,10,14.... 排到第二列 */
.item:nth-child(4n + 2) {
  order: 2;
}

/* 3,7,11,15.... 排到第三列 */
.item:nth-child(4n + 3) {
  order: 3;
}

/* 4,8,12,16.... 排到第四列 */
.item:nth-child(4n) {
  order: 4;
}

注意

该方式需要指定容器的高度和计算 order