水平居中
- 行内元素: text-align: center
- 块级元素: margin: 0 auto
- position:absolute+left:50%+ transform:translateX(-50%)
- display:flex + justify-content: center
垂直居中
- 设置line-height 等于height
- position:absolute +top:50%+transform:translateY(-50%)
- display:flex + align-items: center
- display:table+display:table-cell + vertical-align: middle;
如下代码所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.main{
height: 100vh;
width: 100vw;
font-size: 20px;
color: #fff;
}
.demo1{
text-align: center;
width: 400px;
height: 200px;
background-color: #526232;
}
.demo2{
text-align: center;
width: 400px;
height: 200px;
background-color: #27ce43;
}
.demo3{
display: flex;
justify-content: center;
width: 400px;
height: 200px;
background-color: #526232;
}
.demo4{
text-align: center;
width: 400px;
height: 200px;
background-color: #27ce43;
position: relative;
}
.text{
height: 100%;
width: 100%;
position: absolute;
left: 50%;
transform: translateX(-50%);
}
.demo5{
height: 200px;
width: 400px;
line-height: 200px;
background-color: #526232;
}
.demo6{
display: flex;
align-items: center;
width: 400px;
height: 200px;
background-color: #27ce43;
}
.demo7{
position: relative;
height: 200px;
width: 400px;
background-color: #526232;
}
.text1{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.demo8{
display: table;
width: 400px;
height: 200px;
background-color: #27ce43;
}
.text3{
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="main">
<div class="demo1">水平居中: text-aligen:ceter</div>
<div class="demo2">水平居中: margin:0 auto</div>
<div class="demo3">水平居中:flex justify-content: center </div>
<div class="demo4">
<div class="text">水平居中:position absolute left transform </div>
</div>
</div>
<div class="main">
<div class="demo5">垂直居中:height=liner-height</div>
<div class="demo6">垂直居中:flex align-item:center</div>
<div class="demo7">
<div class="text1">垂直居中:position absolute top transfrom</div>
</div>
<div class="demo8">
<div class="text3">垂直居中:表格布局</div>
</div>
</div>
</body>
</html>