1、通過CSS來實現
1)
position: absolute; top:50%; left:50%; margin-left:-101px; margin-top:-101px;
2)
position:absolute; left:0; top:0; right:0; bottom:0; margin:auto;
2、通過JS來實現
<script type="text/javascript">
var winW = document.documentElement.clientWidth || document.body.clientWidth;
var winH = document.documentElement.clientHeight || document.body.clientHeight;
var box = document.getElementById("box");
var boxTop = document.getElementById("boxTop");
var boxW = box.offsetWidth;
var boxH = box.offsetHeight;
box.style.position = "absolute";
box.style.left = (winW - boxW) / 2 + "px";
box.style.top = (winH - boxH) / 2 + "px";
</script>
說明
- 在普通文檔流里,margin: auto; 的意思是設置元素的margin-top和margin-bottom為0。
W3.org:?If ‘margin-top’, or ‘margin-bottom’ are ‘auto’, their used value is 0.
2. 設置了position: absolute; 的元素會變成塊元素,並脫離普通文檔流。而文檔的其余部分照常渲染,元素像是不在原來的位置一樣。 Developer.mozilla.org:?…an element that is positioned absolutely is taken out of the flow and thus takes up no space
3. 設置了top: 0; left: 0; bottom: 0; right: 0; 樣式的塊元素會讓瀏覽器為它包裹一層新的盒子,因此這個元素會填滿它相對父元素的內部空間,這個相對父元素可以是是body標簽,或者是一個設置了position: relative; 樣式的容器。 Developer.mozilla.org:?For absolutely positioned elements, the top, right, bottom, and left properties specify offsets from the edge of the element’s containing block (what the element is positioned relative to).
4. 給元素設置了寬高以后,瀏覽器會阻止元素填滿所有的空間,根據margin: auto; 的要求,重新計算,並包裹一層新的盒子。 Developer.mozilla.org:?The margin of the [absolutely positioned] element is then positioned inside these offsets.
5. 既然塊元素是絕對定位的,又脫離了普通文檔流,因此瀏覽器在包裹盒子之前會給margin-top和margin-bottom設置一個相等的值。 W3.org:?If none of the three [top, bottom, height] are ‘auto’: If both ‘margin-top’ and ‘margin-bottom’ are ‘auto’, solve the equation under the extra constraint that the two margins get equal values.?AKA: center the block vertically
使用“完全居中”,有意遵照了標准margin: auto; 樣式渲染的規定,所以應當在與標准兼容的各種瀏覽器中起作用。