前端布局的时候总是会遇到一些需要居中的方案,下面是我平常使用的一些方法,当然还有很多的方法也能居中显示。 1、宽高固定 – 使用绝对定位居中显示 这儿一般是用在固定的大小的box中使用,如果相对定位的box大于屏幕不建议使用。 代码如下:

<div class="box1"> <div></div> </div> <style type="text/css"> .box1{ position:relative; height:500px; width:500px; background: #eee; margin:0 auto; } .box1 div{ height:200px; width:200px; position:absolute; left:50%; top:50%; margin:-100px 0 0 -100px; background: #999; } </style>

2、宽高固定 – 使用固定定位居中显示

固定定位主要是一些弹出层使用比较好,而且在所有的高度的文档中都可以使用。

代码如下:

<div class="box2"> <div></div> </div> <style type="text/css"> .box2{ height:500px; width:500px; position:fixed; left:50%; top:50%; margin:-250px 0 0 -250px; background: #eee;} </style>

3、宽高不固定 – 屏幕中间 – 使用jq来计算

有些时候咱们会遇到高度和宽度不固定的box需要居中的需求,这时候咱们可以使用js来计算box的宽高然后在控制他的margin来居中。

代码如下:

<div class="box3"></div> <style type="text/css"> .box3{ position:fixed; left:50%; top:50%; width:600px; height:600px; background: #eee; padding:20px;} </style> <script type="text/javascript"> $('.box3').css({ 'margin-top':-$('.box3').outerHeight(true)/2+'px',//获取总高/2 'margin-left':-$('.box3').outerWidth(true)/2+'px' //获取总宽/2 }); </script>

4、不固定宽高 – CSS上下左右居中 – IE7及以上

当然使用纯CSS也是可以办得到的,这个有个前提条件最外层的box必须有高度,然后可以使用display: table;来居中,如果你不想兼容低版本浏览器的话可以使用这个方法,当然这个方法亲测可以支持到IE7。

代码如下:

<div class="box4">(www.gendan5.com) <div> <div> <p>不固定宽高 - CSS上下左右居中 - IE7及以上</p> <p>不固定宽高 - CSS上下左右居中 - IE7及以上</p> <p>不固定宽高 - CSS上下左右居中 - IE7及以上</p> <p>不固定宽高 - CSS上下左右居中 - IE7及以上</p> <p>不固定宽高 - CSS上下左右居中 - IE7及以上</p> </div> </div> </div> <style type="text/css"> .box4{ height:500px; width:500px; display: table; border-collapse: collapse; margin:0 auto; } .box4>div{ display:table-cell; vertical-align:middle; text-align:center; } .box4>div>div{ background:#eee; padding:20px; line-height:28px; display:inline-block; } </style>

5、上下左右定位法 – CSS上下左右居中 – IE7及以上

其实这个方法是我偶然发现的,当初还真是被惊到了

代码如下:

<div class="box5"></div> <style type="text/css"> .box5{ position:fixed; top:20%; left:20%; bottom:20%; right:20%; background:#999; } </style>