CSS解決未知高度垂直居中
更新時(shí)間:2006年09月05日 00:00:00 作者:
盡管有CSS的vertical-align特性,但是并不能有效解決未知高度的垂直居中問題(在一個(gè)DIV標(biāo)簽里有未知高度的文本或圖片的情況下)。
標(biāo)準(zhǔn)瀏覽器如Mozilla, Opera, Safari等.,可將父級(jí)元素顯示方式設(shè)定為TABLE(display: table;) ,內(nèi)部子元素定為table-cell (display: table-cell),通過vertical-align特性使其垂直居中,但非標(biāo)準(zhǔn)瀏覽器是不支持的。
非標(biāo)準(zhǔn)瀏覽器只能在子元素里設(shè)距頂部50%,里面再套個(gè)元素距頂部-50% 來抵消。
body {padding: 0; margin: 0;}
body,html{height: 100%;}
#outer {height: 100%; overflow: hidden; position: relative;width: 100%; background:ivory;}
#outer[id] {display: table; position: static;}
#middle {position: absolute; top: 50%;} /* for explorer only*/
#middle[id] {display: table-cell; vertical-align: middle; position: static;}
#inner {position: relative; top: -50%;width: 400px;margin: 0 auto;} /* for explorer only */
div.greenBorder {border: 1px solid green; background-color: ivory;}
xhtml
<div id="outer">
<div id="middle">
<div id="inner" class="greenBorder">
</div>
</div>
</div>
以上CSS代碼的優(yōu)點(diǎn)是沒有hacks,采用了IE不支持的CSS2選擇器#value[id]。
CSS2選擇器#value[id]相當(dāng)于選擇器#value,但是Internet Explorer不支持這種類型的選擇器。同樣地.value[class],相當(dāng)于.value,這些只有標(biāo)準(zhǔn)瀏覽器能讀懂。
測(cè)試:Firefox1.5、Opera9.0、IE6.0、IE5.0通過。
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
標(biāo)準(zhǔn)瀏覽器如Mozilla, Opera, Safari等.,可將父級(jí)元素顯示方式設(shè)定為TABLE(display: table;) ,內(nèi)部子元素定為table-cell (display: table-cell),通過vertical-align特性使其垂直居中,但非標(biāo)準(zhǔn)瀏覽器是不支持的。
非標(biāo)準(zhǔn)瀏覽器只能在子元素里設(shè)距頂部50%,里面再套個(gè)元素距頂部-50% 來抵消。
復(fù)制代碼 代碼如下:
body {padding: 0; margin: 0;}
body,html{height: 100%;}
#outer {height: 100%; overflow: hidden; position: relative;width: 100%; background:ivory;}
#outer[id] {display: table; position: static;}
#middle {position: absolute; top: 50%;} /* for explorer only*/
#middle[id] {display: table-cell; vertical-align: middle; position: static;}
#inner {position: relative; top: -50%;width: 400px;margin: 0 auto;} /* for explorer only */
div.greenBorder {border: 1px solid green; background-color: ivory;}
xhtml
復(fù)制代碼 代碼如下:
<div id="outer">
<div id="middle">
<div id="inner" class="greenBorder">
</div>
</div>
</div>
以上CSS代碼的優(yōu)點(diǎn)是沒有hacks,采用了IE不支持的CSS2選擇器#value[id]。
CSS2選擇器#value[id]相當(dāng)于選擇器#value,但是Internet Explorer不支持這種類型的選擇器。同樣地.value[class],相當(dāng)于.value,這些只有標(biāo)準(zhǔn)瀏覽器能讀懂。
測(cè)試:Firefox1.5、Opera9.0、IE6.0、IE5.0通過。
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
相關(guān)文章
top、clientTop、scrollTop、offsetTop
top、clientTop、scrollTop、offsetTop...2006-08-08CSS重新定義項(xiàng)目符號(hào)和編號(hào)技巧
CSS重新定義項(xiàng)目符號(hào)和編號(hào)技巧...2006-09-09