定位居中1
讓外層div相對定位(得設置寬高),內層div絕對定位,top、left分別設為50%,然后通過設置margin-top、margin-left值為寬度的負數並且是內層div的一半,就可以成功實現垂直水平居中了。如下:
<style>
.one{ position: relative; width: 100%; height: 500px; }
.two{ position: absolute; left: 50%; top:50%; margin-left: -100px; margin-top: -100px; background-color: #a00; width: 200px; height: 200px; }
</style>
<div class="one">
<div class="two"></div>
</div>
定位居中2
與1類似,不過將two的定位稍作修改,不用算什么百分比,margin什么的,原理就是讓two既要往左也要往右,既要往上也要往下。這時候它就不知所措了,只好待在中間。:
.two{ position: absolute; margin: auto; left: 0; right: 0; top: 0; bottom: 0; background-color: #a00; width: 200px; height: 200px; }
這個方法,不僅能在內部寬度不確定時發揮作用,還能兼容各種主流瀏覽器,看上去似乎很完美,但事實上,當我們的需求改為:寬度隨內部文字自適應 ,即寬度未設置時,這種方法就無法滿足需求了,原因是left、right設為0后,inner在寬度未設置時將占滿父元素的寬度。
定位居中3
居中的主要目的是讓里面的div在top和left方向發生50%偏移之后,再往回偏移一定距離,而在css3中新增的屬性,selector{transform:translate();}也可實現這個功能。translate代表着水平、垂直方向上的轉換(位移),其中當括號內的值設為百分比時,將以元素自身寬度為基准,移位相應的寬度,顯然設為-50%就可以實現我們想要的效果。
將里面的div樣式修改如下:
.two{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);background-color: #a00; width: 200px; height: 200px; }
這個方法妥善解決了內層div寬度不確定的問題,不用像第一種方法一樣計算應該向左向上偏移多少了,但由於使用了css3的新屬性,在低版本ie瀏覽器下是不兼容的。
定位居中4
運用flex布局,flex布局是移動端一種很新潮的布局方法,利用flex布局使元素垂直水平居中,缺點依然是令人頭疼的兼容性問題(在ie11-中不起作用),優點是代碼量比前幾種方法相比略少,方便使用。
<style>
.one{
margin:0 auto;
width: 100%;
height: 500px;
display: flex;/*設置外層盒子display為flex*/
justify-content:center;/*設置內層盒子的水平居中*/
align-items:center;/*設置內層盒子的垂直居中*/
}
.two{
display: inline-block;
background-color: #a00;
width: 200px;
height: 200px;
}
</style>
<body>
<div class="one">
<div class="two">我們都是好孩子</div>
</div>
</body>
以上就是使div垂直+水平居中的四種方式,各有利弊。