(1)准备一个已知宽高的父元素,子元素嵌套其中,父元素设置为table,绝对定位,子元素设置为table-cell,然后设置子元素 的vertical-align为middle就可以使其垂直居中,text-align为center使其水平居中
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.parent {
display: table;
height: 300px;
width: 300px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -150px;
}
.child {
display: table-cell;
/*该属性定义行内元素的基线相对于该元素所在行的基线的垂直对齐*/
vertical-align: middle;
text-align: center;
color: green;
}
</style>
</head>
<body>
<div class="parent">
<div class='child'>
hello world!
</div>
</div>
</body>
</html>
(2) 添加一个父元素,包含一个空元素和需要水平垂直居中的元素,将子元素的display属性设置为inline-block
<!DOCTYPE html>
<html>
<head>
<title>水平垂直居中对齐</title>
<style>
* {
margin: 0;
padding: 0;
}
.wrap {
position: absolute;
width: 100%;
height: 100%;
background: green;
text-align: center;
}
.vamb {
width: 0;
height: 100%;
display: inline-block;
vertical-align: middle;
}
.test {
display: inline-block;
vertical-align: middle;
background: pink;
padding: 20px;
}
</style>
</head>
<body>
<div class="wrap">
<b class="vamb"></b>
<div class="test">
水平垂直居中了吧
</div>
</div>
</body>
</html>>
(3)使用flex布局
用一个容器 container 将此未知元素嵌套其中,声明container为弹性盒子,justify-content表示主轴的对齐方式,align-items表示另一轴的对齐方式,默认水平轴为主轴,垂直轴为侧轴,所以设置justify-content为center使其水平居中,设置align-items为center使其垂直居中。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.container {
display: flex;
/*水平方向居中*/
justify-content: center;
/*垂直方向居中*/
align-items: center;
/*给父元素设置一个高度值*/
min-height: 98vh;
}
.child {
/*为了好看一点给其设置了宽度,不设置也不影响*/
width: 10rem;
border: .4rem solid black;
margin: 1rem;
font-size: 1.5rem;
text-align: center;
color: #fff;
background: rgba(0, 0, 0, 0.4);
}
</style>
</head>
<body>
<div class="container">
<div class="child">你好</div>
</div>
</body>
</html>