如何将一个盒子在显示在浏览器的正中间

时间:2021-03-01 19:31:58

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>



说明

  1. 在普通文档流里,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; 样式渲染的规定,所以应当在与标准兼容的各种浏览器中起作用。