张登友,张登友的博客,张登友的网站——
水平和垂直居中的几种方法
行内元素
水平居中
给父容器设置:
text-align: center;
垂直居中
让文字的行高 等于 盒子的高度,可以让单行文本垂直居中。比如:
.father {
height: 20px;
line-height: 20px;
}
块级元素
水平居中
对它自身应用 margin: auto
或者 margin: 0 auto
。
.box{
margin: 0 auto;
}
垂直居中
方式一:绝对定位+margin(不推荐)
缺点:要求指定子元素的宽高,才能写出 margin-top
和 margin-left
的属性值。
- 设置子元素为绝对定位,
- 设置
top: 50%
和left: 50%
- 上边距减去自身高的一半,左边距减去自身宽的一半
.father {
height: 500px;
background: pink;
position: relative;
}
.son {
width: 300px;
height: 200px;
background: red;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -150px;
}
方式二:绝对定位+translate(推荐)
优点:无需指定子元素的宽高
- 设置子元素为绝对定位
- 设置
top: 50%
和left: 50%
- 设置
transform: translate(-50%,-50%);
.father {
height: 500px;
background: pink;
position: relative;
}
.son {
width: 300px;
height: 200px;
background: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
方式三:flex布局
缺点:会导致父容器里的所有子元素们都垂直居中了
- 将父容器设置为
Flex 布局
, - 设置
justify-content: center;
即可水平居中, - 设置
align-items: center;
即可垂直居中
.father {
height: 500px;
background: pink;
display: flex;
justify-content: center;
align-items: center;
}
.son {
width: 300px;
height: 200px;
background: red;
}
方式四:flex布局+margin:auto(推荐)
给父容器设置
display: flex
给指定元素设置
margin: auto
注意,当我们给父容器使用 Flex 布局 时,子元素的margin: auto
不仅能让其在水平方向上居中,垂直方向上也是居中的。
.father {
height: 500px;
background: pink;
display: flex;
}
.son {
width: 300px;
height: 200px;
background-color: red;
margin: auto;
}
标准示例
红包幕帘/弹窗很标准
的写法(参考某位JD大佬的代码)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
/* 整个弹窗组件 */
.component_popup {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 100;
}
/* 遮罩背景 */
.popup_mask {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.7);
}
/* 弹窗区域(内容 + close):严格居中 */
.popup_content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* 弹窗的内容部分 */
.content_box {
width: 15.45rem;
height: 19.32rem;
background: url(图片地址) no-repeat;
background-size: 15.45rem 19.32rem;
}
/* 弹窗的close图标 */
.content_close {
width: 1.25em;
height: 1.25em;
background: url(图片地址) no-repeat;
background-size: 1.25rem 1.25rem;
margin: 0 auto;
margin-top: 0.5rem;
}
</style>
</head>
<body>
<div class="content">默认文档流中的页面主体</div>
<div class="component_popup">
<div class="popup_mask"></div>
<div class="popup_content">
<div class="content_box"></div>
<div class="content_close"></div>
</div>
</div>
</body>
</html>