標籤: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. transform中translate位移的百分比值是相對於自身大小的,和第一個方法思路類似。
CSS垂直置中方法整理