子元素个数不定的垂直居中布局

平时需要‘子元素个数不定的垂直居中’的场景应该不少见吧,像下面这样的效果:

 

 

 直接上代码:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>demo</title>
    <style type="text/css">

        /* table-cell方案,完美兼容ie8,考虑ie8的同学可以用 */
        .article{    
            width:600px;
            height:400px;
            border:1px orange solid;
            display: table-cell;;         /*最外面层display:table-cell*/
            vertical-align: middle;
        }

       .child{
            vertical-align: middle;
            width: 80%; 
            height: 50px; 
            margin: 10px auto;
            background: pink;
        }


        /* flex方案,但是不兼容ie8,移动端放心使用(还是要自己看) */
        .flex-article {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            width:600px;
            height:400px;
            border:1px orange solid;
        }

        .flex-child {
            width: 80%;
            height: 50px;
            margin: 10px 0;
            background: pink;
        }
    </style>
</head>
<body>

方案一:
<div class="article">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
</div>

方案二:
<div class="flex-article">
    <div class="flex-child">1</div>
    <div class="flex-child">2</div>
    <div class="flex-child">3</div>
    <div class="flex-child">4</div>
</div>

</body>
</html>

 

posted @ 2017-09-15 17:36  小黑的胡子  阅读(323)  评论(0编辑  收藏  举报