使用flex设置垂直和水平居中

2017-01-14  本文已影响0人  shirleyyu001

flex语法:http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html?utm_source=tuicool

基本的垂直水平居中
//css
.center-wrap{
    display:flex;
    align-items: center;
    justify-content: center;
}
//html
<div class="center-wrap">
    <div>this is the box which need be setted</div>
</div>
扩展:

若多个元素需要进行垂直居中,用以下方法可以减少DOM元素的使用:

多个元素相对于父元素垂直居中.png
//css
.box {
        width: 300px;
        height: 300px;
        margin: 0 auto;
        border: 1px solid;
        -webkit-justify-content: center;
        justify-content: center;  /* 此处是关键*/
        -webkit-align-items: center;
        align-items: center;  /* 此处是关键*/
        -webkit-flex-direction: column;
        flex-direction: column;  /* 此处是关键*/
    }
    .title {
        font-size: 14px;
        font-weight: normal;
    }
    .img {
        width: 200px;
        margin: 20px 0;
    }
    .btn {
        width: 100px;
        height: 28px;
        color: #fc6537;
        border-radius: 5px;
        border: 1px solid #fc6537;
        background-color: #fff;
    }

//html
<div class="box">
    <hl class="title">多个元素相对于父元素垂直居中</hl>
    ![](images/flex-direction.jpg)
    <button class="btn">click me</button>
</div>
上一篇 下一篇

猜你喜欢

热点阅读