如何将一个盒子在显示在浏览器的正中间
2016-02-19 14:19
393 查看
1、通过CSS来实现
1)
position:absolute;top:50%;left:50%;margin-left:-101px;margin-top:-101px;
2)
2、通过JS来实现
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;样式渲染的规定,所以应当在与标准兼容的各种浏览器中起作用。
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。2.设置了position:absolute;的元素会变成块元素,并脱离普通文档流。而文档的其余部分照常渲染,元素像是不在原来的位置一样。
3.设置了top:0;left:0;bottom:0;right:0;样式的块元素会让浏览器为它包裹一层新的盒子,因此这个元素会填满它相对父元素的内部空间,这个相对父元素可以是是body标签,或者是一个设置了position:relative;样式的容器。
4.给元素设置了宽高以后,浏览器会阻止元素填满所有的空间,根据margin:auto;的要求,重新计算,并包裹一层新的盒子。
5.既然块元素是绝对定位的,又脱离了普通文档流,因此浏览器在包裹盒子之前会给margin-top和margin-bottom设置一个相等的值。
使用“完全居中”,有意遵照了标准margin:auto;样式渲染的规定,所以应当在与标准兼容的各种浏览器中起作用。
相关文章推荐
- PHP命名空间(Namespace)的使用详解
- 深度学习的应用
- Android中的人机交互技术
- 对《浅谈数位类统计问题》的学习
- LINUX修改主机名
- 跨路由器连通配置
- 深入理解Netfilter和iptables
- rpm yum方式安装的 mysql的头文件位置
- NodeJS中使用swig模板引擎
- Android数据库高手秘籍(三)——使用LitePal升级表
- 字符串左对齐
- 归纳下js面向对象的几种常见写法
- iOS开发之网络编程--4、NSURLSessionDataTask实现文件下载(离线断点续传下载) <进度值显示优化>
- YII2+jquery.Fileupload 文件上传
- tomcat 启动错误集合一
- vc6开发环境由MBCS改成UNICODE
- hibernate查询总结
- 1015. Reversible Primes (20)
- HDU 2448 Mining Station on the Sea(Floyd+最优匹配)
- HMM模型