您的位置:首页 > 其它

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

2016-02-19 14:19 393 查看
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来实现

<scripttype="text/javascript">
varwinW=document.documentElement.clientWidth||document.body.clientWidth;
varwinH=document.documentElement.clientHeight||document.body.clientHeight;
varbox=document.getElementById("box");
varboxTop=document.getElementById("boxTop");
varboxW=box.offsetWidth;
varboxH=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’,theirusedvalueis0.

2.设置了position:absolute;的元素会变成块元素,并脱离普通文档流。而文档的其余部分照常渲染,元素像是不在原来的位置一样。Developer.mozilla.org:?…anelementthatispositionedabsolutelyistakenoutoftheflowandthustakesupnospace

3.设置了top:0;left:0;bottom:0;right:0;样式的块元素会让浏览器为它包裹一层新的盒子,因此这个元素会填满它相对父元素的内部空间,这个相对父元素可以是是body标签,或者是一个设置了position:relative;样式的容器。Developer.mozilla.org:?Forabsolutelypositionedelements,thetop,right,bottom,andleftpropertiesspecifyoffsetsfromtheedgeoftheelement’scontainingblock(whattheelementispositionedrelativeto).

4.给元素设置了宽高以后,浏览器会阻止元素填满所有的空间,根据margin:auto;的要求,重新计算,并包裹一层新的盒子。Developer.mozilla.org:?Themarginofthe[absolutelypositioned]elementisthenpositionedinsidetheseoffsets.

5.既然块元素是绝对定位的,又脱离了普通文档流,因此浏览器在包裹盒子之前会给margin-top和margin-bottom设置一个相等的值。W3.org:?Ifnoneofthethree[top,bottom,height]are‘auto’:Ifboth‘margin-top’and‘margin-bottom’are‘auto’,solvetheequationundertheextraconstraintthatthetwomarginsgetequalvalues.?AKA:centertheblockvertically

使用“完全居中”,有意遵照了标准margin:auto;样式渲染的规定,所以应当在与标准兼容的各种浏览器中起作用。


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: