一、水平垂直居中的通用方法
- flex布局
设置父元素的display属性为flex,并设置主轴(justify-content)和交叉轴(align-items)上的对齐方式为center即可。
<html>
<head>
<style>
.father {
width: 200px;
height: 200px;
background-color: indianred;
display: flex;
justify-content: center;
align-items: center;
}
.son {
width: 50px;
height: 50px;
background-color: whitesmoke;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
注:flex布局学习指路:Flex布局教程:语法篇.
- 绝对定位+transform属性
①父元素的position属性设置为相对定位(relative),子元素设置为绝对定位(absolute)
②使子元素距离top50%(相对于父元素),距离left50%(相对于父元素)
③利用transform属性定义子元素的2D转换,分别在x轴和y轴上各平移-50%(相对于子元素本身)
<html>
<head>
<style>
.father {
width: 200px;
height: 200px;
background-color: indianred;
position: relative;
}
.son {
width: 50px;
height: 50px;
background-color: whitesmoke;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
二、水平居中
- 文字的水平居中(单行&多行)
只需要设置文字所在容器的text-align属性为center即可。
<html>
<head>
<style>
.con {
text-align: center;
}
</style>
</head>
<body>
<div class="con">
文字水平居中
</div>
</body>
</html>
- 容器的水平居中
设置子容器(即要居中的容器)的外边距margin属性为0 auto即可。
注意:该方法只适用于已知容器宽度的场景。若子容器没有设置width或者设置了width为100%,则将不起作用。此时可以采用flex布局实现水平居中。
<html>
<head>
<style>
.father {
background-color: indianred;
}
.son {
background-color: whitesmoke;
width: 50px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="father">
<div class="son">容器的水平居中</div>
</div>
</body>
</html>
三、垂直居中
- 单行文字垂直居中
设置文字所在容器的height等于line-height即可。
<html>
<head>
<style>
.con {
height: 100px;
line-height: 100px;
background-color: yellowgreen;
}
</style>
</head>
<body>
<div class="con">
单行文字垂直居中
</div>
</body>
</html>
- 多行文字垂直居中
设置文字所在容器的内边距padding即可,例:30px 0
注:此方法同样适用于单行文字的垂直居中。
<html>
<head>
<style>
.con {
background-color: indianred;
padding: 30px 0;
}
</style>
</head>
<body>
<div class="con">
多行文字垂直居中多行文字垂直居中多行文字垂直居中
多行文字垂直居中多行文字垂直居中多行文字垂直居中
多行文字垂直居中多行文字垂直居中多行文字垂直居中
</div>
</body>
</html>
- 容器的垂直居中
通用方法去掉水平居中即可,略。