
CSS要做到水平或垂直置中,依不同的情況使用的方法也不相同。
水平置中
文字、圖片等行內(inline)元素的水平置中
這個最簡單,給容器元素設置text-align:center即可。
HTML:

CSS:
.container {
background-color: #ccc;
width: 300px;
height: 300px;
text-align: center;
margin-bottom: 10px;
}
區塊(block)元素的水平置中
這個第二簡單,將區塊元素設置margin-left:auto, margin-right:auto 就有了。
HTML:
CSS:
.container {
background-color: #ddd;
width: 300px;
height: 300px;
}
.wrap {
width: 150px;
height: 150px;
background-color: #666;
margin-left: auto;
margin-right: auto;
}
垂直置中
垂直置中就要看容器元素的高度了,有不同的做法,而且由於有IE6,IE7這兩個怪東西,還得用上一點hack技巧,真討厭…
容器元素高度不確定的行內元素的垂直置中
這個對容器元素的上下設置相同的padding就可以做到了
HTML:

CSS:
.container {
background-color: #ccc;
width: 300px;
margin-bottom: 10px;
padding-top: 30px;
padding-bottom: 30px;
}
.wrap {
width: 150px;
height: 150px;
background-color: #666;
}
容器元素高度固定的單行文字垂直置中
這個也很簡單,對容器元素設置line-height並且設定跟高度一樣就可以了
HTML:
CSS:
.container {
background-color: #ccc;
width: 300px;
height: 300px;
margin-bottom: 10px;
line-height: 300px;
}
容器元素高度固定的多行文字、圖片、區塊元素的垂直置中
這其實才是本文的重點,很多人搞不定的就是這裡。有人會說用table加上vertical-align:middle就搞定啦,那是你偷懶,好嗎,咱們正統的Web Developer才不用那種偷吃步咧。而且vertical-align只對td,th元素有效,對其他區塊元素就沒用啦,好在現在有一個叫table-cell的東西,我們可以將區塊元素設置成display:tabel-cell就可以讓它變成如同td,th般,這樣就可以套上vertical-align啦,喔喔喔~你看看,這世界多美好~~(灑花)(轉圈)
HTML:

CSS:
.mb10 {
margin-bottom: 10px;
}
.container {
width:300px;
height:300px;
background-color: #ccc;
display: table-cell;
vertical-align: middle;
}
IE6 IE7 Hack
不過當我們把做好的網頁拿到IE6,7下面看,唉呀,怎麼沒有置中啦,吼吼吼~~~萬惡的IE6,為什麼不趕快消失啦~~唉唷,沒有辦法啦,你沒看到客戶都用IE6嗎,IE6不能看那還接得到案子嘛,唉…那只好搬出看家本領了,hack絕招快快拿出來~~!!
為了這個死IE6,我們要在內容元素外面再包一層,然後用只有IE看淂懂的*星號,先對最外層的容器元素設置*position:relative,好讓後面的絕招可以產生作用,然後對這個外層元素設置*position:absolute跟*top:50%,這樣它的左上角原點會下降到容器元素的中心點,最後再對真正裡面的內容元素設置*position:relative和*top:-50%和*left:-50%,讓它往上往左提升本身高度的一半,這樣最後結果就是置中啦~~
HTML:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
CSS:
.mb10 {
margin-bottom: 10px;
}
.container {
width:300px;
height:300px;
background-color: #ccc;
text-align:center;
display: table-cell;
vertical-align: middle;
*position: relative; /* for IE6,7 */
}
.verticalWrap {
*position: absolute; /* for IE6,7 */
*top: 50%; /* for IE6,7 */
}
.vertical {
*position: relative; /* for IE6,7 */
*top: -50%; /* for IE6,7 */
*left: -50%; /* for IE6,7 */
}
在〈[CSS] 如何做出水平&垂直置中〉中有 2 則留言