美文网首页
关于垂直居中

关于垂直居中

作者: Hunter_Gu | 来源:发表于2016-12-10 22:12 被阅读11次

    垂直居中,是前端的基本操作,我主要在两种情况下进行简单的实现。分别为:

    • 已知高度(指自身高度)
    • 未知高度
      简单的html代码如下:
      <style>
        div.father{
                height: 300px;
                width: 500px;
                border: 1px solid red;
            }
      </style>
      <div class="father">
            <div class="child">123</div>
      </div>
    

    - 未知高度时

    • 1.通过 display:table-cell 实现(此方法针对 img 在 div 标签中垂直居中很适用)
        div.father{
                display: table-cell;
                vertical-align: middle;/*IE8 及以上*/
            }
    
    • 2.通过transform: translateY(-50%) 实现
        div.father{
                position: relative;
            }
        div.child{
                position: absolute;
                top: 50%;
                transform: translateY(-50%);/* CSS3 */
            }
    

    - 已知高度时

    • 1.通过 margin-top 实现
        div.father{
                position: relative;
            }
        div.child{
                position: absolute;
                top: 50%;
                height: 100px;
                margin-top: -50px;
            }
    
    • 2.最后是一种比较特别的情况,当 .child 中的内容不超过一行时,通过设置 height = line-height 也可实现垂直居中
        div.child{
                height: 300px;
                line-height: 300px;
            }
    

    以上,是简单的总结,兼容性方面也很差,方法还有很多。

    相关文章

      网友评论

          本文标题:关于垂直居中

          本文链接:https://www.haomeiwen.com/subject/jwuumttx.html