纯css实现简单瀑布流(flex 和 column-count 两种方式)

958 阅读1分钟

方式一:column-count实现

这种实现方式的缺点是:图片是先从上到下排列,再从左到右排列的

	<!DOCTYPE html>
<html>
  <head></head>
  <style>
    .pubuliu {
      column-count: 4;
      list-style: none;
      counter-reset: item;
    }

    .pubuliu li {
      break-inside: avoid;
      margin-bottom: 4px;
    }
    .pubuliu li::before {
      display: block;
      counter-increment:item;
      content: counter(item);
      color:black;
    }
    .h100 {
      height: 100px;
      background:yellow;
    }
    .h200 {
      height: 200px;
      background: red;
    }
    .h300 {
      height: 300px;
      background:violet;
    }
    .h400 {
      height: 400px;
      background:tomato;
    }
  </style>
  <body>
    <ul class="pubuliu">
      <li class="h100"></li>
      <li class="h400"></li>
      <li class="h300"></li>
      <li class="h100"></li>
      <li class="h200"></li>
      <li class="h100"></li>
      <li class="h400"></li>
      <li class="h300"></li>
      <li class="h100"></li>
      <li class="h200"></li>
    </ul>
  </body>
</html>

方式二:flex布局+巧用order属性实现

这种方式可以实现从左到右 缺点:需要预先设定flex容器的高度,保证想要列数,且调整页面大小时会出现一些间距过大的问题

<!DOCTYPE html>
<html>
  <head></head>
  <style>
    .pubuliu {
      display: flex;
      flex-direction: column;
      flex-wrap: wrap;
      height:800px;
      list-style: none;
      counter-reset: item;
    }

    .pubuliu li {
      margin-bottom: 4px;
    }
    .pubuliu li::before {
      display: block;
      counter-increment:item;
      content: counter(item);
      color:black;
    }
    .pubuliu li:nth-child(4n+1) {
      order: 1;
    }
    .pubuliu li:nth-child(4n+2) {
      order: 2;
    }
    .pubuliu li:nth-child(4n+3) {
      order: 3;
    }
    .pubuliu li:nth-child(4n+4) {
      order: 4;
    }
    .h100 {
      height: 100px;
      background:yellow;
    }
    .h200 {
      height: 200px;
      background: red;
    }
    .h300 {
      height: 300px;
      background:violet;
    }
    .h400 {
      height: 400px;
      background:tomato;
    }
  </style>
  <body>
    <ul class="pubuliu">
      <li class="h100"></li>
      <li class="h400"></li>
      <li class="h300"></li>
      <li class="h100"></li>
      <li class="h200"></li>
      <li class="h100"></li>
      <li class="h400"></li>
      <li class="h300"></li>
      <li class="h100"></li>
      <li class="h200"></li>
    </ul>
  </body>
</html>