2019/01/22

Flexを使わず真ん中配置







PCでFlexを使うのはまだ不安ということで、縦の中央配置のやり方メモ。
昔はline-heightや、positionとマイナスmargin、display tableとかでやりましたが、今はこんなやり方があるんですね。




動作サンプル

See the Pen Flexを使わず真ん中配置 by takapen (@takapen) on CodePen.








html

縦位置真ん中

テキストテストテストテストテスト、テストテストテスト。

上下左右中央

テキストテストテストテストテスト、テストテストテスト。




css
section {
  width: 300px;
  height: 300px;
  margin: 20px;
  background: #cc0;
  position: relative;
}
.test01 {
  background: #ccc;
  position: absolute;
  top: 50%;
  width: 100%;
  transform: translate(0, -50%);
}
.test02 {
  background: #ccc;
  position: absolute;
  top: 50%;
  left: 50%;
  width: 150px;
  transform: translate(-50%, -50%);
}