css技巧之等间距布局

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();
}
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值