2020面试准备1----水平垂直居中的几种方式

(为了方便阅读,我把基础部分css和居中的css分开来写)
一、使用定位
方法1:
top和left分别为50%,再使用margin-left和margin-top设置负的宽高
(这种方法需要知道子盒子的宽高)

<style>
	.father{
	   height: 300px;
	   width: 600px;
	   background:yellow;
	   overflow: hidden;
	}
	.child{
		border: 1px black solid;
		background: white;
		text-align: center;
		width: 100px;
		height: 50px;
		line-height: 50px;
	}
	.father{
		position: relative;
	}
	.child{
		position: absolute;
		top:50%;
		left: 50%;
		margin-left: -50px;
		margin-top: -25px;
	}
		</style>
		<body>
		<div class="father">
			<div class="child">
				水平垂直居中
			</div>
		</div>
	</body>

方法2:
top right bottom left 都设置为0 再使用margin:auto
(这种方法不需要知道子盒子宽高,但是盒子必须要有宽高)

.father{
	position: relative;
}
.child{
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	margin: auto;
}

方法3
top和left分别为50%,再使用transform:translate(-50%,-50%)
(这种方法不需要知道子盒子宽高,子盒子也不必须有宽高,兼容性不好)

.father{
	position: relative;
}
.child{
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%,-50%);
}

二、弹性盒子
设置主轴和交叉轴都居中
(兼容性不好)

.father{
	display: flex;
	justify-content: center;
	align-items: center;
}

三、通过js实现
分别获取父子盒子的宽高,再设置子盒子left和top

<script>
		let fathH = father.offsetHeight,
			fathW = father.offsetWidth,
			childH = child.offsetHeight,
			childW = child.offsetWidth
			father.style.position = "relative"
			child.style.position = "absolute"
			child.style.left = (fathW-childW)/2 + 'px'
			child.style.top = (fathH-childH)/2 + 'px'
	</script>

四、使用display:table-cell
本来是用于文本的垂直居中,可以将div设置为inine

.father{
	display: table-cell;
	text-align: center;
	vertical-align: middle;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值