div水平垂直居中的实现方式

前提

在面试的时候,面试官可能会问到如何让一个div水平垂直居中呢?接下来我将为大家列举常见的几种方法来实现它。

准备

首先准备一个父盒子和一个子盒子,并给它们添加一下样式,方便我们观察。

HTML代码
<div class="parent">
	<div class="son"></div>
</div>
CSS代码
.parent {
	width: 300px;
	height: 300px;
	border: 1px solid pink;
}

.son {
	width: 100px;
	height: 100px;
	background-color: red;
}

此时的父子盒子排列如下图所示。
在这里插入图片描述
我们想要实现的效果如下图所示。
在这里插入图片描述

实现方式

1、使用定位加margin-left和margin-top
.parent {
	width: 300px;
	height: 300px;
	border: 1px solid pink;
	position: relative;
}

.son {
	width: 100px;
	height: 100px;
	background-color: red;
	position: absolute;
	top: 50%;
	margin-top: -50px;
	left: 50%;
	margin-left: -50px;
}
2、使用定位加transform
.parent {
	width: 300px;
	height: 300px;
	border: 1px solid pink;
	position: relative;
}

.son {
	width: 100px;
	height: 100px;
	background-color: red;
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%,-50%);
}
3、使用定位加margin:auto
.parent {
	width: 300px;
	height: 300px;
	border: 1px solid pink;
	position: relative;
}

.son {
	width: 100px;
	height: 100px;
	background-color: red;
	position: absolute;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	margin: auto;
}
4、使用flex布局+margin:auto
.parent {
	width: 300px;
	height: 300px;
	border: 1px solid pink;
	display: flex;
}

.son {
	width: 100px;
	height: 100px;
	background-color: red;
	margin: auto;
}
5、使用flex布局+justify-content和align-items
.parent {
	width: 300px;
	height: 300px;
	border: 1px solid pink;
	display: flex;
	justify-content: center;
	align-items: center;
}

.son {
	width: 100px;
	height: 100px;
	background-color: red;
}
6、使用grid布局
.parent {
	width: 300px;
	height: 300px;
	border: 1px solid pink;
	display: grid;
}

.son {
	width: 100px;
	height: 100px;
	background-color: red;
	justify-self: center;
	align-self: center;
}

以上就是实现div水平垂直居中的常见方法,希望对您有帮助!

猜你喜欢

转载自blog.csdn.net/qq_40951289/article/details/103568584