关于垂直居中

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

  • 已知高度(指自身高度)
  • 未知高度
    简单的html代码如下:
  
  
123

- 未知高度时

  • 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;
        }

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

你可能感兴趣的:(关于垂直居中)