盒子水平垂直居中的方法

盒子水平垂直居中的方法

结构代码

	<div class="father" id="father">
			<div class="son" id="son"></div>
		</div>

1、position+margin实现(需要定义自身的width和height)

<style type="text/css">
.father{
	position: relative;
	width: 400px;
	height:400px;
	background: blue;
}
.son{
	position:absolute;
	left: 50%;
	top:50%;
	margin-top: -50px;
	margin-left: -50px;
	width: 100px;
	height: 100px;
	background : pink;
}
</style>

2、position+transifrom(不同定义自身的width和height,自动算出元素width的一半和height的一半)

.father{
	position: relative;
	width: 400px;
	height: 400px;
	background: blue;
}
.son{
	position: absolute;
	left: 50%;
	top:50%;
	transform: translate( -53%, -50%);
	background: pink;
}

3、第三种方法(需要定义自身的width和height,但不用管width和height多少)

.father{
	position: relative;
	width: 400px;
	height: 400px;
	background: blue;
}
.son{
	position: absolute;
	top:0;
	bottom:0;
	left:0;
	right:0;
	height: 100px;
	width: 100px;
	margin: auto;
	background: pink;
}

4、通过flex弹性布局实现(不用定义自身的width和height)

.father{
	display: flex;
	justify-content : center;
	align-items: center;
	width: 400px;
	height: 400px;
	background: blue;
}
.son{
	background: pink;
}

5、通过js实现

		<script type="text/javascript">
			window.onload=function(){
				var fatherWidth=father.offsetWidth;
				var fatherHeight=father.offsetHeight;
				var sonWidth=son.offsetWidth;
				var sonHeight=son.offsetHeight;
				son.style.position="absolute";
				son.style.left=(fatherWidth-sonWidth)/2+"px";
				son.style.top=(fatherHeight-sonHeight)/2+"px";
			}
		</script>

6、第六种实现水平垂值居中的方法

<style type="text/css">
			.father{
				//父元素必须要定义宽度和高度且不能为百分比,子元素要设置为行内快元素
				display: table-cell;
				text-align: center;
				vertical-align: middle;
				width: 400px;
				height: 400px;
				background: blue;
			}
			.son{
				display: inline-block;
				width: 100px;
				height: 100px;
				background: pink;	
			}
</style>

效果
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值