水平+垂直 居中

方案一

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>水平居中和垂直居中,并且父容器的宽度高度都是未知的,里面的子容器大小也是不一定的</title>
    <style type="text/css">
    .parent{
        background: #bebebe;
        height: 300px;
        width: 700px;

        /* 水平居中*/
        text-align: center;

        /* 垂直居中*/
        display: table-cell;
        vertical-align: middle;
    }

    .child{
        background: #404040;
        height: 50px;
        width: 50px;
        color:white;
        /* 水平居中 */
        display: inline-block;
    }
    </style>
</head>
<body>
<!--

这个方案的优点:
1。兼容性比较高。

-->
<div class="parent">
    <div class="child">DEMO</div>
</div>
</body>
</html>

image

 

方案二

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>水平居中和垂直居中 absolute_transform</title>
    <style type="text/css">
    .parent{
        background: #bebebe;
        height: 400px;
        width: 600px;

        position: relative;
    }
    .child{
        background: #404040;
        height: 50px;
        color: white;

        position: absolute;
        left: 50%;
        top: 50%;

        transform: translate(-50%,-50%);
    }
    </style>
</head>
<body>
<div class="parent">
    <div class="child">DEMO</div>
</div>
</body>
</html>

image

 

 

方案三

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>水平居中和垂直居中flex_justify-content_align-items</title>
    <style type="text/css">
    .parent{
        background: #bebebe;
        height: 400px;
        width: 600px;

        display: flex;
        justify-content: center;
        align-items: center;
    }
    .child{
        background: #404040;
        color: white;


    }
    </style>
</head>
<body>
<div class="parent">
    <div class="child"><H1>DEMO</H1></div>
</div>
</body>
<!--
缺点: 兼容性是个问题。

-->
</html>

image

posted @ 2016-10-31 17:51  刘江龙  阅读(346)  评论(0编辑  收藏  举报