1. 开局一张图,内容全靠编
若是普通的css添加左右margin,则红色盒子之间的距离会比红色盒子与父元素的距离大两倍。若是只添加左边距,则最右边的红色盒子和父元素贴在一起了。其实这里可以另外给父元素添加内边距,但是这样要确定红色盒子数量和margin的大小
2. flex+js响应式解决等间距布局
解决这个布局的前提是:
- 子元素即红色盒子的宽度是固定的
- 子元素的margin大于15px(这个自己定)
- 父元素的宽度是响应式的变化,所以每行的盒子数、margin也是响应式的
方法:
父元素宽度=子元素 x 个数 + 子元素margin x (个数+1),然后给子元素添加左margin,因此,一行中剩余的空间就是最右边的margin,不用特意设置,直接在父元素用一个flex-wrap换行,第一行中放不下,自然就转到下一行。
//html
<section></section>
//css
section{
width: 100%;
border: 1px #000 solid;
margin: 100px auto;
display: flex;
flex-wrap: wrap;
}
.item{
width: 100px;
height: 100px;
background-color: red;
}
//js
//创建子元素
let con = document.getElementsByTagName('section')[0];
for (var i = 0; i < 20; i++) {
let item = document.createElement('div');
item.className = 'item';
con.appendChild(item);
}
size();
//定义布局方式
function size(){
let conWidth = con.clientWidth,
itemWidth = document.getElementsByClassName('item')[0].clientWidth,
itemNum = Math.floor(conWidth/itemWidth),
itemMargin = (conWidth - itemNum*itemWidth)/(itemNum + 1),
itemList = document.getElementsByClassName('item');
//margin小于15时,每行的盒子数量减1
if (itemMargin < 15) {
itemNum-=1;
itemMargin = (conWidth - itemNum*itemWidth)/(itemNum + 1)
}
[...itemList].forEach(function(i){
i.style.marginLeft = `${itemMargin}px`;
i.style.marginBottom = `${itemMargin}px`;
//console.log(conWidth);
})
}
//页面宽度发生变化时,重新调用,达到响应式的目的
window.onresize = function(){
size();
}
复制代码