0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CSS で要素をちょうど中心に持ってくる

Last updated at Posted at 2021-07-15

はじめに

いつも目測でなんとなくやってしまっていた。
インターン先でコードを読んでいる途中、綺麗に配置する方法を知ったのでまとめた。

今回は codepen を使って説明する。

中心に配置したい要素を用意する

横が 300px, 縦が 150px の長方形を作った。
スクリーンショット 2021-07-15 22.07.23.png

要素の左上端を中心に移動させる

position: absoluteとし、left: 50%かつtop: 50%の位置に移動させた。

このときの 50% というのは、画面幅基準であって要素幅基準ではないことに注意。
スクリーンショット 2021-07-15 22.06.49.png

要素の左上端部分が白い画面の中心にある状態になった。

要素の横幅50%分だけ左に移動させる

transform属性を使い、translate: (-50%)を指定。
画面の中心にあった要素の左上端が、x軸負の向き(左)に 50% 移動した。

このときの 50% は、要素の横幅に対しての 50% である。

スクリーンショット 2021-07-15 22.06.16.png

これで、要素が水平方向の中心に配置された。

要素の縦幅50%分だけ上に移動させる

translate: (-50%, -50%)とし、y軸負の向き(上)に 50% 移動させた。

このときの 50% は、要素の縦幅に対しての 50% である。
スクリーンショット 2021-07-15 22.05.19.png

要素を白い画面の中央に配置することができた。

画面幅を変えてもレイアウトはそのまま。

スクリーンショット 2021-07-15 22.21.17.png

スクリーンショット 2021-07-15 22.22.41.png

おわりに

CSSを書くたびに、勉強し直さなきゃと思っている。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?