常用的居中方式,主要分兩種:
一、知道要居中元素的寬高:
公用的代碼:
html
<div class="wrap">
<div class="box">CSS實現水平垂直居中的方式</div>
</div>
css
.wrap {
position: relative;
width: 500px;
height: 500px;
border: 1px solid #2AC845;
}
.box {
height: 100px;
width: 300px;
background-color: #00B7EE;
}
1,利用 position: absolute; 和 margin 的負值
.box {
position: absolute;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -50px;
}
2,利用 position: absolute; 和 margin 的auto
.box {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
3,利用 position: absolute; 和 calc
.box {
position: absolute;
left: -moz-calc(50% - 150px);
left: -webkit-calc(50% - 150px);
left: calc(50% - 150px);
top: -moz-calc(50% - 50px);
top: -webkit-calc(50% - 50px);
top: calc(50% - 50px);
}
第三種方法注意calc的兼容
二、不需要知道要居中元素的寬高:
公用的代碼
html
<div class="wrap">
<div class="box">CSS實現水平垂直居中的方式</div>
</div>
css
.wrap {
width: 500px;
height: 500px;
border: 1px solid #2AC845;
}
.box {
background-color: #00B7EE;
}
1,利用 position: absolute; 和 margin 的負值
.box {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-o-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
2,利用 display:table,(內容居中,要居中元素佔滿父級)
.wrap {
display: table;
text-align: center;
}
.box {
display: table-cell;
vertical-align: middle;
}
3,利用 display:table-cell,
.wrap {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {
display: inline-block;
}
4,flex
.wrap {
display: flex;
align-items: center;
justify-content: center;
}