怎么让块级元素水平和垂直都居中

在我们平时用DIVCSS布局网页的时候,经常碰到就是如何让div块水平和垂直都居中的情况,今天,建站教程网就给大家提供两种方法:

方式一:利用定位及负边距

<!DOCTYPE html>
<html>
    <head>
        <title>让块级元素水平和垂直都居中(方法一)</title>
        <meta charset="utf-8">
        <style>
            .wrapper {
                height: 600px;
                border: 1px solid red;
                position: relative;
            }
            .box {
                width: 120px;
                height: 120px;
                background: gold;
                position: absolute;
                left: 50%;
                top: 50%;
                margin-left: -50px;
                margin-top: -50px;
            }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <div class="box"></div>
        </div>
    </body>
</html>

方式二:利用margin居中的方法

<!DOCTYPE html>
<html>
    <head>
        <title>让块级元素水平和垂直都居中(方法二)</title>
        <meta charset="utf-8">
        <style>
            .wrapper {
                height: 600px;
                border: 1px solid gray;
            }
            .box {
                width: 120px;
                height: 120px;
                background: gold;
                margin: 250px auto 0;
            }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <div class="box"></div>
        </div>
    </body>
</html>

posted @ 2014-04-21 14:59  eaysun  阅读(540)  评论(0编辑  收藏  举报