使用浮动实现js控制一般的双行瀑布流

404 阅读1分钟

提出问题

这种不等高的瀑布流的最优实现方案是什么呢?能不能不借助js且做到从左到右的排布呢?

这个案例并没有什么华丽的代码,但是却提供了一种很省事的解决思路

image.png

重点部分

/*单数左浮动,双数右浮动*/
.view-wrap div:nth-of-type(odd){
    float: left;
}
.view-wrap div:nth-of-type(even){
    float: right;
}

优缺点

优点

这种实现方式可以只用一个容器包裹,而且还是先左再右的排布,这样写就不用在js插入元素的时候判断一下再决定插左边还是右边了 在做商城项目的时候优于使用单纯的flex布局,优于分栏布局.因为他并不需要等待一侧排满后再排另一侧

缺点

自由度有点低,当一侧盒子的高度有可能高于另一侧两个盒子的累加高度会出现布局错乱的情况

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            width: 700px;
        }
        .body-wrap div{
            width: 300px;
        }
        /*重点在这里*/
        /*单数左浮动,双数右浮动,一直被诟病难用的浮动在这里居然有奇效!*/
        .body-wrap div:nth-of-type(odd){
            float: left;
        }
        .body-wrap div:nth-of-type(even){
            float: right;
        }
        /*手动做不等高效果*/
        .body-wrap div:nth-of-type(1){
            height: 200px;
            background-color:antiquewhite;
        }
        .body-wrap div:nth-of-type(2){
            height: 300px;
            background-color: aqua;
        }
        .body-wrap div:nth-of-type(3){
            height: 250px;
            background-color: rgb(82, 138, 119);
        }
        .body-wrap div:nth-of-type(4){
            height: 210px;
            background-color: aquamarine;
        }
        .body-wrap div:nth-of-type(5){
            height: 230px;
            background-color: blue;
        }
        .body-wrap div:nth-of-type(6){
            height: 290px;
            background-color: blueviolet;
        }
        .body-wrap div:nth-of-type(7){
            height: 290px;
            background-color: rebeccapurple;
        }
        .body-wrap div:nth-of-type(8){
            height: 230px;
            background-color: red;
        }
        
    </style>
</head>
<body>
    <div class="body-wrap">
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
        <div>6</div>
        <div>7</div>
        <div>8</div>
    </div>
</body>
</html>

效果展示

image.png

意外情况

一侧盒子的高度有可能高于另一侧两个盒子的累加高度不适用此方案