1. 我们先看一下下面的布局效果
2. 实现思路
1) 要是实现自动换行排列,我们首先想到float加margin-right来实现,那我们来实现一下
比如一个box为宽1000px 每个item宽320px margin-right:20px 我们会发现效果如下 会自动换行 因为最右边超出了20px的margin值
-
这时我们可以给item的外层加一个div 设置margin-right:-20px; 使得这个盒子的宽度增加20px;来承载item 代码如下
<body>
<div class="box">
<div class="item-box">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
</body>
<style>
body {
height: 100%;
width: 100%;
background-color: #ccc;
}
.box {
width: 1000px;
background-color: aliceblue;
height: 700px;
overflow: hidden;//***********关键代码*************
}
.item-box{
height: 100%;
margin-right: -20px;//***********关键代码*************
background-color: burlywood;
}
.item {
float: left;
width: 320px;
height: 320px;
margin-bottom: 10px;
margin-right: 20px;
background-color: blueviolet;
}
</style>
效果如下
2) 还有一种解决办法就是 flex布局
实现思路就是 按行排列 可换行 然后主轴的内容为 justify-content: space-between; 然后再使用伪元素在后进行占位 结构不变 下面为代码实现
body {
height: 100%;
width: 100%;
background-color: #ccc;
}
.box {
width: 1000px;
}
.item-box{
height: 100%;
background-color: burlywood;
//*************主要代码**********************
display: flex;
flex-flow: row wrap;
justify-content: space-between;
//*************主要代码**********************
}
//*************主要代码**********************
.item-box::after{
content: "";
width: 320px;
}
//*************主要代码**********************
.item {
width: 320px;
height: 320px;
margin-bottom: 10px;
background-color: blueviolet;
}
效果如下