在前端开发中,常常会碰到布局须要左右居中,上下居中的状况,在现代浏览器中实现居中仍是挺方便的,本文只考虑在高版本现代浏览器中的状况,不考虑IE.css
这是经常使用的水平居中图片,按钮,文字等行内元素的方法,但不能上下居中html
<style lang="css"> .parent { width: 100%; height: 800px; background: green; } .sub { width: 200px; height: 200px; background: red; text-align: center; } </style> <body> <div class="parent"> <div class="sub"> abcedd </div> </div> </body>
实现效果:前端
此方法也只能实现水平居中,具体用法为:margin:0 auto
.sub { width: 200px; height: 200px; background: red; margin: 0 auto; }
实现效果:css3
.sub { width: 200px; height: 200px; background: #ccc; margin: 0 auto; line-height: 200px; text-align: center; }
若是使用表格居中的话,用表格属性 td(也可能会用到 th)元素的 align="center" 以及 valign="middle" 就能够实现左右上下居中了浏览器
对于不是表格的元素,可使用display:table-cell模拟表格,实现居中的目的。这种状况下,父级容器要指定宽度,用百分比的话达不到左右居中的目的布局
<style lang="css"> .parent { width: 800px; height: 800px; display: table-cell; vertical-align: middle; } .sub { width: 200px; height: 200px; margin: 0 auto; background: #ccc; } </style> <body> <div class="parent"> <div class="sub"> </div> </div> </body>
<style lang="css"> .parent { width: 800px; height: 800px; position: relative; } .sub { width: 200px; height: 200px; background: #ccc; position: absolute; top: 0; left: 0; bottom: 0; right: 0; margin: auto; } </style>
<div class="parent"> <div class="sub"> </div> </div>
要注意的是。margin:auto必不可少,这是其一,还有一种spa
<style lang="css"> .parent { width: 100%; height: 800px; position: relative; } .sub { width: 200px; height: 200px; background: #ccc; position: absolute; left: 50%; top: 50%; margin-left: -100px; margin-top: -100px; } </style> <body> <div class="parent"> <div class="sub"> </div> </div> </body>
这些都是经常使用的居中方式,在css3中,还可使用弹性布局来居中元素,下篇文章在详细说明。code