CSS盒子居中的几种方法
第一种:用css的position属性
按 Ctrl+C 复制代码
<style type="text/css">
.wrapper{
width:500px;
height:500px;
border:1px solid #bbb;
position:relative; /*给父元素设置相对定位*/
}
.demo{
width:200px;
height:200px;
background:#ff6700;
position:absolute; /*给子元素设置绝对定位*/
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}
</style>
<div class="wrapper">
<div class="demo">text</div>
</div>
第二种:利用css3的新增属性table-cell, vertical-align:middle;
<style type="text/css">
.wrapper{
width: 200px;
height: 200px;
display: table-cell;
vertical-align: middle;
border:1px solid rgb(0, 0, 0);
}
.demo{
width:100px ;
height: 100px;
margin: auto;
background:#ff6700;
}
</style>
<div class="wrapper">
<div class="demo">text</div>
</div>
第三种:利用定位线左上角居中,然后左移子元素宽度的一半,再上移子元素高度的一半。
<style type="text/css">
.wrapper{
width:500px;
height:500px;
border:1px solid #bbb;
position:relative; /*给父元素设置相对定位*/
}
.demo{
width:200px;
height:200px;
background:#ff6700;
position:absolute; /*给子元素设置绝对定位*/
top:50%;
margin-top:-100px;
left:50%;
margin-left:-100px;
}
</style>
<div class="wrapper">
<div class="demo">text</div>
</div>
第四种:弹性布局
<style type="text/css">
.wrapper{
width:500px;
height:500px;
border:1px solid #bbb;
display:flex; /*css3盒模型*/
justify-content: center;
align-items:center;
}
.demo{
width:200px;
height:200px;
background:#ff6700;
}
</style>
<div class="wrapper">
<div class="demo">text</div>
</div>
第五种:利用transform的属性,注意子绝父相定位
缺点:需要支持Html5
<style type="text/css">
.wrapper{
width:500px;
height:500px;
border:1px solid #bbb;
position:relative; /*给父元素设置相对定位*/
}
.demo{
width:200px;
height:200px;
background:#ff6700;
position:absolute; /*给子元素设置绝对定位*/
top:50%;
left:50%;
-ms-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%); /*css3属性*/
}
</style>