How to display a box in the middle of the browser, the box shows the browser
1. Implemented through 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. Implemented through 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>
Description
W3.org :? If 'margin-top', or 'margin-bottom 'are 'auto', their used value is 0.
2. If the position: absolute; element is set, it becomes a block element and leaves the normal document stream. The rest of the document is rendered as usual, and the elements are not in the original position. 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; the style block element will let the browser wrap a new box for it, therefore, this element fills up its internal space relative to the parent element. The relative parent element can be a body tag or a container with the position: relative; style set. 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 ).
4. After the width and height of the element are set, the browser will prevent the element from filling up all the space, re-calculate according to the requirement of margin: auto;, and wrap a new box. Developer.mozilla.org :? The margin of the [absolutely positioned] element is then positioned inside these offsets.
5. Since the block element is absolutely positioned and is out of the normal Document Stream, the browser will set an equal value for margin-top and margin-bottom before packaging the box. 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
The use of "completely centered" intentionally complies with the standard margin: auto; style rendering rules, so it should play a role in a variety of browsers compatible with the standard.