居中案例

1.水平居中

1.1行内元素

  • text-align:center

1.2块级元素

  • margin:0 auto

1.3多个块级元素

  • 子元素设置为inline-block类型,同时父元素设置属性 text-align: center;
  • display:flex,justify-content:center

2.垂直居中

2.1行内元素

  • 单行行内元素
    • 1.设置padding-top,padding-bottom
    • 2.如无法使用padding属性,令height = line-height
  • 多行行内元素

    • 1.可以将元素转为table样式,再设置vertical-align:middle;

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      .center-table {
      display: table;
      height: 250px;
      background: white;
      width: 240px;
      margin: 20px;
      }
      .center-table p {
      display: table-cell;
      margin: 0;
      background: black;
      color: white;
      padding: 20px;
      border: 10px solid white;
      vertical-align: middle;
      }

      2.使用flex布局( flex布局要求父元素必须显示的设置heights )

      1
      2
      3
      4
      5
      6
      .flex-center-vertically {
      display: flex;
      justify-content: center;
      flex-direction: column;
      height: 400px;
      }

2.2块级元素

  • 已知高度

    1
    2
    3
    4
    5
    6
    7
    8
    9
    .parent{
    position: relative;
    }
    .child{
    height: 120px;
    position: absolute;
    left: 50%;
    margin-left: -60px;
    }
  • 未知高度

    1
    2
    3
    4
    5
    6
    7
    8
    .parent{
    position: relative;
    }
    .child{
    position: absolute;
    left: 50%;
    transform: translateY(-50%);
    }
  • flex布局

    1
    2
    3
    4
    5
    6
    .parent{
    display: flex;
    flex-direction: column;
    justify-content: center;
    <!-- justify-content: space-between; 垂直居中,且两端对齐 -->
    }

3.垂直和水平居中

3.1固定大小元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.parent{
position: relative;
}
.child{
width: 300px;
height: 100px;
padding: 20px;

position: absolute;
top: 50%;
left: 50%;

margin: -70px 0 0 -170px;
}

3.2未知大小元素

1
2
3
4
5
6
7
8
9
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: (-50%,-50%);
}

3.3 使用flex布局

1
2
3
4
5
.parent{
display: flex;
justify-content: center;
align-items: center;
}

参考文章见于 [http://weizhifeng.net/viewports.html] 篇目二下次再看
另一更全面文章 [https://segmentfault.com/a/1190000016389031]