CSS系列:对齐

水平居中、垂直居中、右对齐。


前言

元素居中是实际前端开发中常用的一种操作。元素居中分为垂直居中和水平居中,为了以后方便重查,本篇文章总结一下一些常见的对齐方式。

样例代码如下,查看时请参考下面的代码。

See the Pen Centering with CSS Part 1 by 李明岳 (@scarboroughcoral) on CodePen.

水平居中

文本水平居中

  • text-align属性

div水平居中

  • 蓝色盒子,将父容器设为text-align:center,div设为display:inline-block,适用于多个div水平居中。
  • 【推荐】黄色盒子,使用margin:auto属性设置(需要设置宽度)
  • 【推荐,常用于响应式开发,注意脱离文档流带来的问题】绿色盒子,父容器position:relative,div设置position:absoluteleft:50%transform:translateX(-50%)
  • 绿色盒子,父容器position:relative,div设置position:absoluteleft:50%margin-left:(-width/2)
  • 【极度推荐,响应式,无需计算margin】粉色盒子,父容器display:flexflex-direction:row(默认),然后justify-content:center(要看主轴的方向)

右对齐

文本右对齐

  • 使用text-align:right

div右对齐

  • 使用position:absoluteright:0实现
  • 【推荐】使用flex布局
  • (十分奇妙)使用margin-left:auto,需要设置宽度
  • 使用float,注意脱离文档流带来的问题(eg:如果高度大于父容器,则需要设置父容器overflow:auto
  • 将父容器设为text-align:right,div设为display:inline-block

垂直居中

垂直居中不太好演示,代码直接在这里写了。

文本垂直居中

  • 《不推荐》使用padding
  • 【推荐】使用heightline-height设置,考虑文本多行
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    .center {
    line-height: 200px;
    height: 200px;
    border: 3px solid green;
    text-align: center;
    }

    /* If the text has multiple lines, add the following: */
    .center p {
    line-height: 1.5;
    display: inline-block;
    vertical-align: middle;
    }

div垂直居中

  • 父容器设置line-heightheight等高,div设置为display:inline-blockvertical-align:middle

    1
    2
    3
    4
    5
    6
    7
    8
    .parent{
    height:200px;
    line-height:200px;
    }
    .child{
    display:inline-block;
    vertical-align:middle;
    }
  • 父容器position:relative,div设置position:absolutetop:50%margin-top:(-height/2)

  • 【推荐,响应式】父容器position:relative,div设置position:absolutetop:50%transform:translateY(-50%)

    1
    2
    3
    4
    5
    6
    7
    8
    .parent{
    position:relative;
    }
    .child{
    position:absolute;
    top:50%;
    transform:translateY(-50%);
    }
  • 【极度推荐,响应式,无需计算margin】使用flex

    1
    2
    3
    4
    5
    6
    7
    8
    .parent{
    display:flex;
    align-items:center;
    }
    .child{
    width:100px;
    height:100px;
    }

总结

大致就是如此,后续发现其他方法继续补充。

Reference