css div居中显示的3种写法

作者:Leinov 来源:cnblogs.com 发布时间:2014-11-04 查看数:20515

很多同学都在问DIV怎么居中,如果是水平居中是很简单的,但是要垂直居中的话,通过vertical-align:middle 并不能实现。本文介绍三种方法,来实现DIV的水平/垂直居中。

1、absolute 绝对定位 这是我们最常用的一种居中定位写法 要求必须确定div的宽高度 目前市面上的浏览器基本上都支持这种写法

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>absolute居中定位</title>
        <style>
          *{margin:0;padding:0}
          .absoluteCenter{ width:600px; height:400px;position:absolute; background: rgb(50,183,97); left:50%; top:50%; margin-left: -300px; margin-top: -200px;  }
        </style>
    </head>
    <body>
        <div class="absoluteCenter">我是absolute居中定位</div>
    </body>
    </html>

2、translate定位 这是css3 transform的属性 通过自身的偏移来定位 而且他有个极大的好处 不需要知道div的宽高度 就像js里的this self一样 可以将宽高度设为百分比 IE browser

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>translate居中定位</title>
        <style>
          *{margin:0;padding:0}
          .translateCenter{ width: 40%; height: 20%; position: absolute; left:50%; top:50%; transform:translate(-50%,-50%); background: #2d2d2d;}
        </style>
    </head>
    <body>
        <div class="translateCenter">我是translate居中定位</div>
    </body>
    </html>

3、margin居中定位 不需要确定div的宽高度 让top,bottom,left,right都为0 再加个margin:auto 神来之笔 IE browser< IE 8不支持

<!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>margin居中定位</title>
        <style>
          *{margin:0;padding:0}
          .marginCenter{ width:200px; height: 200px; position: absolute;left:0; top:0; right:0; bottom: 0; margin: auto; background: #f2056e;}
        </style>
    </head>
    <body>
        <div class="marginCenter">我是margin居中定位</div>
    </body>
    </html>

演示效果:

原文地址:http://www.cnblogs.com/leinov/p/4073794.html