CSS解決未知高度垂直置中的問題

來源:互聯網
上載者:User

除特別說明外,本站內容採用創作共用授權署名和非商業用途,請尊重勞動成果。

原文標題:Vertical Centering in CSS

副標題:Yuhu's Definitive Solution with Unknown Height

翻譯:forestgan

儘管有CSS的vertical-align特性,但是並不能有效解決未知高度的垂直置中問題(在一個DIV標籤裡有未知高度的文本或圖片的情況下)。

標準瀏覽器如Mozilla, Opera, Safari等.,可將父級元素顯示方式設定為TABLE(display: table;) ,內部子項目定為table-cell (display: table-cell),通過vertical-align特性使其垂直置中,但非標準瀏覽器是不支援的。

非標準瀏覽器只能在子項目裡設距頂部50%,裡面再套個元素距頂部-50% 來抵消。

CSS
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

以上CSS代碼的優點是沒有hacks,採用了IE不支援的CSS2選取器#value[id]。

CSS2選取器#value[id]相當於選取器#value,但是Internet Explorer不支援這種類型的選取器。同樣地.value[class],相當於.value,這些只有標準瀏覽器能讀懂。

測試:Firefox1.5、Opera9.0、IE6.0、IE5.0通過。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.