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;
}
发布了23 篇原创文章 · 获赞 0 · 访问量 1002

猜你喜欢

转载自blog.csdn.net/yangling_123/article/details/104180356