垂直居中的总结

无需固定高度的方式

用如下的方式,能够适应任何高度的div实现居中。css

方式1:使用jquery.popup.js插件html

本人封装了一个名为jquery.popup.js的插件,主要是为了弹窗实现居中显示问题,还不错的,简单易用。特征:jquery

  1. 无需固定高度
  2. 有多种效果选择
  3. 须要jQuery的支持,js的调用
  4. 支持IE6+

插件放在本git上: http://git.oschina.net/luozt007/FrontEnds 路径为:FrondEnds/data/proj-backup/netease/kobe-fis-init/resources/jquery.popup/css3

方式2:translate50%git

设置left:50%; top:50%; transform:translate(-50%,-50%);,特征:web

  1. 须要css3支持
  2. 无需固定高度
  3. 纯css,简单,复用
  4. 支持IE9+

方式3:table-cell浏览器

利用表格table,而在table-cell里面设置vertical-align:center,特征:布局

  1. 无需固定高度
  2. 支持IE6+
  3. 纯css
  4. 这时table,table-cell不能用浮动

具体作法:学习

<style>
.box{vertical-align: middle;}
.target{margin: 0 auto;}
</style>

<table>
    <tr>
        <td class="box">
            <div class="target"></div>
        </td>
    </tr>
</table>

方式4:flexflex

利用flex布局的justify-content: center; align-items: center;来实现

##须要固定高度

方式1:负margin

设置top:50%; left:50%; margin-left:width/-2; margin-top:height/-2;。这种方式没什么好说,你们都理解,特征:

  1. 纯css
  2. 支持IE6+

方式2:上下左右都为0

利用top\right\bottom\left都为0,特征:

  1. 不支持IE7及如下
  2. 纯css

添加如下样式可实现自动居中:

.target{height:300px;}
.abs-center{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

##总结

兼容写法推荐

高度不固定:推荐使用jquery.popup.js插件的方式 高度固定:推荐使用负margin的方式

现代浏览器首选技术的写法推荐

高度不固定:推荐translate的方式 高度固定:translate方式


更多阅读:

相关文章
相关标签/搜索