CSS垂直置中方法整理

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

CSS定位中常常用到垂直置中,比如覆蓋層上的彈框。

相容性比較好的方法:

<!DOCTYPE html PUBliC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><style type="text/css">#box{ width:200px; height:100px; text-align:center; position: absolute;  left: 50%; top: 50%; margin-top: -50px;    /* 高度的一半 */ margin-left: -100px;    /* 寬度的一半 */ background-color:#ffff99;}</style></head><body><div id="box">Hello World!</div></body></html>

這個方法只適用於已知寬高的塊,因為要設定負邊距來修正。
如果是未知尺寸的塊,可以使用以下方法:

<!DOCTYPE html PUBliC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><style type="text/css">#box{ width:200px; height:100px; text-align:center; position: absolute;  left: 0; top: 0; right:0; bottom:0; margin:auto; background-color:#ffff99;}</style></head><body><div id="box">Hello World!</div></body></html>

原因是,絕對位置的布局取決於三個因素,一個是元素的位置,一個是元素的尺寸,一個是元素的margin值。沒有設定尺寸和 margin 的元素會自適應剩餘空間,位置固定則分配尺寸,尺寸固定邊會分配 margin,都是自適應的。

IE7- 的渲染方式不同,渲染規則也不一樣,他不會讓定位元素去自適應。

 

現在有了CSS3,就又有新招數了:

<!DOCTYPE html PUBliC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><style type="text/css">#box{ width:200px; height:100px; text-align:center; position: absolute;  left: 50%; top: 50%; transform: translate(-50%, -50%);  background-color:#ffff99;}</style></head><body><div id="box">Hello World!</div></body></html>

就是使用transform代替margin. transformtranslate位移的百分比值是相對於自身大小的,和第一個方法思路類似。

 

CSS垂直置中方法整理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.