CSS 上下中央揃え


縦方向の中央揃え

line-height 一行

line-heightは行間のサイズ。
line-height - font-size/2(上下の行間高さ)
※複数行に対応できない
line-height 行間について


.wrapper01
  .box
    p ほげほげほげ
.wrapper01 {
  width: 400px;
  height: 400px;
  background: #ccc;
  .box {
    width: 200px;
    height: 200px;
    border: 1px solid black;
    p {
      font-size: 10px;
      line-height: 200px;
    }
  }
}

vertical-aline

適用できるのは、インライン要素とテーブルセルです。ブロックレベル要素には適用できない

.wrapper02
  .box
    p
     | ほげほげほげ
     br
     | ほげほげほげ
.wrapper02 {
  width: 400px;
  height: 400px;
  background-color: #ccc;
  .box {
    width: 200px;
    height: 200px;
    border: 1px solid black;
    display: table;
    p {
      font-size: 10px;
      display: table-cell;
      vertical-align: middle;
    }
  }
}

flex

.wrapper03
  .box
    p
     | ほげほげほげ
     br
     | ほげほげほげ

.wrapper03 {
  width: 400px;
  height: 400px;
  background-color: #ccc;
  .box {
    width: 200px;
    height: 200px;
    border: 1px solid black;
    display: flex;
    align-items: center;
    p {
      font-size: 10px;
    }
  }
}

コメント

上下中央揃えは、flexで。flexは素晴らしい。