css实现左右中布局的几种方式以及遇过的问题

1、display 弹性布局
flex布局 父元素display:flex; 左右子元素设置宽度width: 10rem;
中间子元素设置 flex:1 或者 width: calc(100% - 20rem)
<style>
	*{
		margin: 0;
		padding: 0;
	}
	.content{
		display: flex;
	}
	.box1,.box2,.box3{
		height: 6.25rem;
		display: inline-block;
	}
	.box1{
		width: 10rem;
		background-color: #666666;
	}
	.box2{
		text-align: center;
		// 宽度平分也是可以的
		/* width: calc(100% - 20rem); */
		//2.flex:1
		flex:1
	}
	.box3{
		width: 10rem;
		background-color: #888;
	}
</style>	
<body>
	<div class="content">
		<div class="box1">
			box1
		</div>
		<div class="box2">
			box2
		</div>
		<div class="box3">
			box3
		</div>
	</div>
</body>
以上是我尝试过的方式,可以的;
有尝试过,遇到的问题
原因:外层没有用div包裹起来,所以也没有用display:flex
即使.三个div 设置display: inline-block 和 宽度平分 width: calc(100% - 20rem); 也会造成下图的原因
在这里插入图片描述
为什么会这样呢?
首先是我先把他们设置成了行内元素,然而空格和换行都会造成空白的间隙(来源于浏览器的font-size的大小),我写的三个div换行了,所以有问题,解决方式:1.去掉空格跟换行(不建议),2.外层再用div包裹,设置font-size:0(不建议);3. 上面的写法(嘻嘻)
2、浮动布局 float
左浮动, 右浮动, 中间自动填充
.box1{
	width: 10rem;
	height: 6.25rem;
	background-color: #384;
	text-align: center;
	color: #fdf6e3;
	float: left;
}
.box2{
	height: 6.25rem;
	background-color: #922;
}
.box3{
	width: 10rem;
	height: 6.25rem;
	background-color: #555;
	text-align: center;
	color: #fdf6e3;
	float: right;
}
3、绝对定位
position :absolute
.content{
	position: relative;				
}	
.box1,.box2,.box3{
	height: 6.25rem;
	display: inline-block;
	position: absolute;
	text-align: center;
}
.box1{
	left: 0;
	width: 300px;
	background-color: #823384;
}
.box2{
	left: 300px;
	right: 300px;
	background-color: #d29922;
}
.box3{				
	right: 0;
	width: 300px;
	background-color: #0c8ac5;
}
4、表格布局
dispaly : table
.content{
	width: 100%;
	display: table;		
}	
.box1,.box2,.box3{
	display: table-cell;
	height: 6.25rem;
	text-align: center;
}
.box1{
	width: 300px;
	background-color: #823384;
}
.box2{
	background-color: #d29922;
}
.box3{			
	width: 300px;
	background-color: #0c8ac5;
}
5、网格布局
display: grid
.content{
	display: grid;
	width: 100%;
	grid-template-rows: 100px;   //行高
	grid-template-columns: 300px auto 300px;	 // 左边300px 中间自适应 右边300px
}	
.box1{
	background-color: #823384;
}
.box2{
	background-color: #d29922;
}
.box3{			
	background-color: #0c8ac5;
}
			
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值