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

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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Flex是Flexible Box的缩写,意为"弹性布局",用来为盒状模型提供最大的灵活性。设为Flex布局以后,...
    xiaotao123阅读 5,680评论 0 1
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,594评论 25 709
  • 愿做一只兔子 洗脸梳毛蹦蹦跳跳 蹦蹦跳跳吃饱睡觉
    陌路舊人阅读 2,435评论 0 0