CSS flex wrap 布局里,没有直接设置间距的参数,默认情况下各元素会紧贴着排列在一起。
一个普通的 flex wrap 布局代码:
.box {
width: 414px;
height: 736px;
margin: 0 auto;
border: 1px solid blue;
}
.flex {
display: flex;
flex-wrap: wrap;
border: 1px solid red;
}
.item {
display: block;
padding: 4px 10px;
color: white;
background-color: #5454dd;
border-radius: 3px;
}
显示效果:
没有设置间距,各元素都挨在一起了。
加上左和上的间距:
.item {
margin: 8px 0 0 8px;
}
元素之间隔开了,但是布局的起点位置也改变了,如果希望保持起点位置不变,还需要对容器加上以下设置:
.flex {
margin: -8px 0 0 -8px;
}
避免外边距合并问题
设置 margin
的时候需要避免外边距合并问题,否则会改变父容器的布局。
解决方法很简单,父容器只要有 border
就可以了,也可以是一个透明的边框:
.box {
border: 0 solid transparent;
}
Demo.html
这篇文章测试的源码, 点击这里运行
<html>
<head>
<style type="text/css">
*,
:after,
:before {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.nav {
width: 414px;
height: 64px;
margin: 0 auto;
border: 0 solid transparent;
}
.box {
width: 414px;
height: 736px;
margin: 0 auto;
border: 1px solid blue;
}
.flex {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
border: 1px solid red;
}
.flex .item {
display: block;
padding: 4px 10px;
color: white;
background-color: #5454dd;
border-radius: 3px;
}
.flex {
margin: -8px 0 0 -8px;
}
.flex .item {
margin: 8px 0 0 8px;
}
</style>
</head>
<div class="nav"></div>
<div class="box">
<div class="flex">
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
<span class="item">item</span>
</div>
</div>
<body>
</body>
</html>