1.绝对定位+margin:auto+left: 0; right: 0; top: 0; bottom: 0;
css部分
<style type="text/css">
.wrp {
background-color: #b9b9b9;
width: 240px;
height: 160px;
position: relative;
}
.box{
color: #fff;
background-color: #3e8e41;
width: 200px;
height: 120px;
margin: auto;
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
}
</style>
页面布局
<div class="wrp">
<div class="box">
<p>我是大美女</p>
</div>
</div>
效果:
2、绝对定位+margin反向偏移
<style type="text/css">
.wrp {
background-color: #b9b9b9;
width: 240px;
height: 160px;
position: relative;
}
.box{
color: #fff;
background-color: #3e8e41;
width: 200px;
height: 120px;
position: absolute;
top: 50%; left: 50%;
margin-left: -100px; /* (width + padding)/2 */
margin-top: -60px; /* (height + padding)/2 */
}
</style>
布局:
<div class="wrp">
<div class="box">
<p>我是大美女</p>
</div>
</div>
效果:
3.绝对定位+transform反向偏移
<style type="text/css">
.wrp {
background-color: #b9b9b9;
width: 240px;
height: 160px;
position: relative;
}
.box{
color: #fff;
background-color: #3e8e41;
width: 200px;
height: 120px;
position: absolute;
top: 50%; left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
</style>
布局:
<div class="wrp">
<div class="box">
<p>我是大美女</p>
</div>
</div>
效果:
4.display:tabel
css部分:
<style>
/*** .table和.cell都将撑满页面,cell的子元素水平垂直居中 ***/
.table{
display: table;
width: 200px;
height: 200px;
}
.cell {
display: table-cell;
vertical-align: middle;
text-align: center;
border: 1px solid #666;
}
</style>
布局:
<div class="table">
<div class="cell">
<p>我爱你,我爱你</p>
<p>我爱你,我爱你</p>
</div>
</div>
效果:
5、display: flex
<style>
.flex{
display: flex;
width: 200px;
height: 200px;background: #ccc;
justify-content:center;
align-items: center;
}
.box {
background: red;
height: 50px;
width:100px;
color:#fff;
}
</style>
布局:
<div class="flex">
<div class="box">
我是大美女
</div>
</div>
效果:
可能还有其他方式,之后再做补充!