方案一:距离上边界50%,div沿Y轴平移自身高度的一半
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
效果截图:
x
示例代码:后面只展示关键代码
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>css123</title>
<style>
body {
background: #2ae0bb;
}
.box {
width: 500px;
height: 500px;
background: #008800;
}
.text {
width: 300px;
height: 200px;
background: #e0e0e0;
position: relative;
left: 50%;
transform:translateX(-50%)
}
.text span{
position: absolute;
left: 50%;
background: #18aa8c;
transform:translateX(-50%)
}
</style>
</head>
<body>
<div class="box">
<div class="text">
<span>这是一个居中元素块。</span>
</div>
</div>
<div class="pool">
<div class="text-dec">
<span>Look!I'm here.while just you know.</span>
</div>
</div>
</body>
</html>
方案二:设置div的展示模式为flex盒子,然后设置子元素水平与垂直居中
flex详细解析请转移至:https://www.cnblogs.com/hellocd/p/10443237.html
display: flex;
display: -webkit-flex;
align-items:center;/*垂直居中*/
justify-content:center;/*水平居中*/
效果截图:DIV水平居中
![](https://i-blog.csdnimg.cn/blog_migrate/ed700c2851a1f07cd7774fc14c10c81f.png)
方案三:margin:auto;本方案演示相对整个窗口水平垂直居中,针对父控件只会水平居中
margin:auto详情请参考:https://www.php.cn/css-tutorial-412560.html
position: absolute;
top: 0;
left: 0;
right: 0;
bottom:0;
margin: auto;
效果截图:整个窗口水平垂直居中
方案四:父窗口设置tabel,子窗口设置table-cell;
.box {
width: 500px;
height: 500px;
background: greenyellow;
display: table;
}
.text {
width: 100px;
height: 100px;
font-size: 20px;
background: blueviolet;
display: table-cell;
vertical-align: middle;
}
效果截图:父窗口垂直居中