在CSS中,則要吐槽一下,利用margin:0 auto;可以達到水平方向的居中,但是margin: auto 0則無法達到垂直方向的居中。
這里主要還是由于沒有對父控件即控件本身進行正確的定位。直接看代碼, 首先對父控件需要使用相對布局,之后對子控件需要使用絕對布局,并且利用top,和bottom屬性,結(jié)合margin: auto 0;,則可以達到效果。
.container-vertical { position: relative; width: 100%; height: 200px; background: deepskyblue; margin-bottom: 20px;} .container-vertical-item { position: absolute; width: 130px; height: 80px; text-align: center; background: yellow; line-height: 80px; top: 0; bottom: 0; margin: auto 0;}
垂直方向上居中.png
水平垂直方向居中
有了5.2的經(jīng)驗,我們可以嘗試設(shè)置子控件的left和right,top,bottom屬性都為0,并且margin: auto;四個方向上都是自動外邊距。則可以達到這樣的效果。其中需要注意的子控件需要必須是display: block; 屬性。
看代碼
.container-horization-vertical { position: relative; width: 100%; height: 200px; background: deepskyblue; margin-bottom: 20px;} .container-horization-vertical-item { position: absolute; width: 150px; height: 80px; background: yellow; line-height: 80px; text-align: center; top: 0; left: 0; bottom: 0; right: 0; margin: auto;}
小結(jié): 這種方案在解決一些不算復(fù)雜的頁面布局時還是很不錯的,可以適配任何界面以及幾乎所有的瀏覽器。但對于十分復(fù)雜的頁面可能會需要其他的解決方案,但是從這個思路出發(fā)也可以得到啟示
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
|
新聞熱點
疑難解答