本文使用的HTML结构如下所示:
<div class="container">
<div class="item"></div>
</div>
所有方法仅仅是css样式不同
1.高度已知
-
方法一:绝对定位+margin:auto;
<style>
.container {
width: 200px;
height: 400px;
background: red;
position: relative;
}
.item {
width: 50px;
height: 50px;
background: white;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
以下所有代码都是在此基础上改的。
-
方法二:绝对定位+margin负值
.item { width: 50px; height: 50px; background: white; position: absolute; left: 50%; top: 50%; margin-left: -25px; margin-top: -25px; }
-
方法三:绝对定位+transform(transform相对于自身的宽高来计算)
.item { width: 50px; height: 50px; background-color: white; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);
}
-
方法四:使用弹性盒模型
.container { display: -webkit-flex; display: flex; -webkit-justify-content: center; justify-content: center; -webkit-align-content: center; align-items: center; width: 200px; height: 400px; background: red; } .item { width: 50px; height: 50px; background-color: white; }
2.不定高的垂直居中
-
方法一:绝对定位+transform
.container { position: relative; width: 200px; height: 400px; background: red; } .item { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); background: white; } </style> <div class="container"> <div class="item">adbf</div> </div>
-
方法二:伸缩布局
.container { display: -webkit-flex; display: flex; -webkit-justify-content: center; justify-content: center; -webkit-align-content: center; align-items: center; width: 200px; height: 400px; background: red; } .item { width: 50px; height: 50px; background-color: white; }
-
方法三:模仿表格,使用display:table-cell
.container { width: 200px; height: 400px; display: table-cell; vertical-align: middle; background: red; } .item { display: block; width: 100px; background: white; margin: auto; } </style> <div class="container"> <div class="item">高度不固定的垂直居中</div> </div>