震惊!!!CSS垂直居中竟然有这么多方法~

@TOC

假设HTML如下:

<body>
    <div id="box">
        <div id="content"></div>
    </div>
</body>

1. 兼容性最好的方法 IE7以上

body,html { margin:0; width:100%; height:100%; }

#box {
     width:100%;
     height:100%;
     background:rgba(0,0,0,0.7);
     position:relative;
 }
#content {
    width:50%;
    height:50%;
    background:pink;
    position:absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    margin:auto;
}

2. transform进行元素偏移 IE8以上

body,html { margin:0; width:100%; height:100%; }

#box {
    width:100%;
    height:100%;
    background:rgba(0,0,0,0.7);
    position:relative;
}
#content{
    position:absolute;
    width:50%;
    height:50%;
    background:blue;
    left:50%;
    top:50%;
    transform:translateX(-50%) translateY(-50%);
    -webkit-transform:translateX(-50%) translateY(-50%);
}

3. 弹性盒模型进行布局 IE兼容性差

body,html { margin:0; width:100%; height:100%; }

#box {
    width:100%;
    height:100%;
    background:rgba(0,0,0,0.7);
    display:box;
    box-pack:center;
    box-align:center;
    display:-webkit-flexbox;
    -webkit-box-pack:center;
    -webkit-box-align:center;
}
#content {
    width:50%;
    height:50%;
    background:blue;
}

4. flex布局 不兼容IE9以下

body,html { margin:0; width:100%; height:100%; }

#box {
    width:100%;
    height:100%;
    background:rgba(0,0,0,0.7);
    display:flex;
    display:-webkit-flex;
     justify-content:center;
     align-items:center;
  }
#content {
    position:absolute;
    width:50%;
    height:50%;
    background:blue;
  }
言: 以上就是博主目前用的比较多的方法啦,如果有什么更好的方法,可以多多交流喔
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,816评论 1 92
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,811评论 1 45
  • 一、HTML5 1.1 认识HTML5 HTML5并不仅仅只是作为HTML标记语言的一个最新版本,更重要的是它制定...
    福尔摩鸡阅读 16,129评论 14 51
  • 作者:无悔铭https://segmentfault.com/a/1190000013565024 前端布局非常重...
    YjWorld阅读 314评论 0 2
  • 《我是怎样的一个人》 ——年初一献给小西瓜 文/五音麦笛 我是一个不爱回忆的人 ...
    五音麦笛阅读 396评论 0 4