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来实现
立即学习“前端免费学习笔记(深入)”;
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";
登录后复制
说明
在普通文档流里,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; 样式渲染的规定,所以应当在与标准兼容的各种浏览器中起作用。
登录后复制
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/3111528.html