实现水平垂直居中的5种方法

水平垂直居中

<div class="wrapper">
    <div class="inner">
    </div>
</div>

1. 定位 + margin 方法

  • 定位 + margin : auto;
.wrapper{
    position:relative;
    width:300px;
    height:300px;
    border:1px solid black;
}
.inner{
    position:absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
    width:100px;
    height:100px;
    background:orange;
    margin:auto;
}

  • 定位 + 负 margin
.wrapper{
    position:relative;
    width:300px;
    height:300px;
    border:1px solid black;
}
.inner{
    position:absolute;
    top:50%;
    left:50%;
    width:100px;
    height:100px;
    background:orange;
    margin-top:-50px;
    margin-left:-50px;
}
  • 定位 + transform
.wrapper{
    position:relative;
    width:300px;
    height:300px;
    border:1px solid black;
}
.inner{
    position:absolute;
    top:50%;
    left:50%;
    width:100px;
    height:100px;
    background:orange;
    transform:translate(-50%,-50%)
}

2. 父元素 display:table-cell; 方法

.wrapper{
    width:300px;
    height:300px;
    border:1px solid black;
    display:table-cell;
    vertical-align:middle;
}
.inner{
    width:100px;
    height:100px;
    background:orange;
    margin: 0 auto;
}

3. flex 弹性盒子 方法

.wrapper{
    width:300px;
    height:300px;
    border:1px solid black;
    display:flex;
    justify-content:center;
    align-items:center;
}
.inner{
    width:100px;
    height:100px;
    background:orange;
}

4. inline-block + 伪元素 方法

.wrapper{
    width:300px;
    height:300px;
    border:1px solid black;
   text-align:center;
}
.wrapper::after{
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle; 
}
.inner{
    width:100px;
    height:100px;
    background:orange;
    display:inline-block;
    vertical-align:middle;
}

5. calc() + margin 方法

注意:运算符 - 或 + 两侧要加 空格

.wrapper{
    width:300px;
    height:300px;
    border:1px solid black;
}
.inner{
    width:100px;
    height:100px;
    background:orange;
    margin:calc((100% - 100px)/2);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,806评论 1 92
  • 收听音频,戳链接,旧号itclan已暂停使用,欢迎关注微信itclanCoder公众号可收听更多音频 前言 关于网...
    itclanCoder阅读 8,214评论 3 30
  • 1.绝对定位居中技术 我们一直用margin:auto实现水平居中,而一直认为margin:auto不能实现垂直居...
    DecadeHeart阅读 1,621评论 0 3
  • 我没有想到,我会去看二十二。 从一个完全无从看出半点剧透的名字,到略微了解这是一部关于慰安妇的片子,这部电影,于我...
    王秀秀阅读 746评论 0 1
  • 今天心情真的很差,可能最近忙太多东西,每天就是工作上课谈客户开会,有人说我是一个工作狂,我也听到跟我共事的朋友说我...
    何泽坤Ken阅读 371评论 0 0