解决flex布局中justify-content设置成space-between后因数据问题导致最后一行布局错乱

发布时间 2023-04-16 21:39:31作者: xiaoHeMa

在常用的flex布局中,当页面展示商品时,因为数据的不确定,导致justify-content设置成space-between,最后一行布局错乱

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7   <title>Document</title>
 8   <style>
 9     .box{
10       display: flex;
11       flex-direction: row;
12       justify-content: space-between;
13       flex-wrap: wrap;
14       align-content: flex-start;
15       width: 450px;
16       background-color: antiquewhite;
17     }
18     .box div{
19       width: 100px;
20       height: 100px;
21       text-align: center;
22       line-height: 100px;
23       font-size: 30px;
24       color: aliceblue;
25     }
26     .box .div1{
27       background-color: gold;
28     }
29     .div2{
30       background-color: blueviolet;
31     }
32     .div3{
33       background-color: blue;
34     }
35     .div4{
36       background-color: gray;
37     }
38     .div5{ 
39       background-color: green; 
40     }
41     .div6{
42       background-color: red;
43     }
44     .div7{
45       background-color: aquamarine;
46     }
47     .div8{
48       background-color: rebeccapurple;
49     }
50   </style>
51 </head>
52 <body>
53   <div class="box">
54     <div class="div1">1</div>
55     <div class="div2">2</div>
56     <div class="div3">3</div>
57     <div class="div4">4</div>
58     <div class="div5">5</div>
59     <div class="div6">6</div>
60     <div class="div7">7</div>
61     <div class="div8">8</div>
62     <div class="div4">4</div>
63     <div class="div5">5</div>
64     <div class="div6">6</div>
65     <div class="div7">7</div>
66     <div class="div8">8</div>
67     <div class="div4">4</div>
68     <div class="div5">5</div>
69     <div class="div6">6</div>
70     <div class="div7">7</div>
71     <div class="div8">8</div>
72     <div class="div1">1</div>
73 
74   </div>
75 </body>
76 </html>

解决办法就是在小盒子后面添加标签 i 或者span标签,然后不设置高度,宽度和小盒子.box 下的div宽度一样就可以

问题来了设置几个呢,答案是设置该行的n-2个,比如说一行有4个那么写2个就可以了,如果有5个写3个就可以了

原理就是用 i 标签去占据位置,如果还不明白可以给i添加高度和背景色。再查看

然后再减去一个div第二个 i 就会上来