LoginSignup
0
0

More than 3 years have passed since last update.

要素やテキストの中央配置

Last updated at Posted at 2020-11-26

こんがらがった際にチラ見して最低限思い出せる用の個人メモ。
(随時追加...)

注: センタリングではなく、中央配置についてです。

目次

要素の中央配置

  • 1. positionを使う場合
  • 2. flexを使う場合
  • 3. gridを使う場合
  • 4. table-cellを使う場合

テキストの中央配置

  • 1. flexを使う場合

要素の中央配置

1. positionを使う場合

親要素に以下を追加

position: relative;

子要素に以下を追加

position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);

See the Pen yLaLYrE by non Man (@nonMan21) on CodePen.

小要素に兄弟要素がある場合でも基本的に関係ない。

2. flexを使う場合

親要素に以下を追加

display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
justify-content: center;

See the Pen jOMObXY by non Man (@nonMan21) on CodePen.

小要素に兄弟要素がある場合、兄弟要素のくくりごと中央になる。
(1つ小要素に対して上記のような使い方はあまりしない。flexについては別記事でまとめ中)

3. gridを使う場合

親要素に以下を追加

display: grid;
align-content: center;
justify-items: center;

See the Pen gOwayyr by non Man (@nonMan21) on CodePen.

4. table-cellを使う場合

親要素に以下を追加

display: table-cell;
vertical-align: middle;
text-align:center;

See the Pen eYdYpPj by non Man (@nonMan21) on CodePen.

テキストの中央配置

1. flexを使う場合

対象に以下を追加

display: flex;
justify-content: center;
align-items: center;

See the Pen OJRJVKJ by non Man (@nonMan21) on CodePen.

ランキングとか通知などのコンテンツ実装時、テキストしか入らない場合はこれ入れるだけなのでスムーズ。
親要素関係なくスタイルできるので、他の大きなコンポーネントへの影響を切り離したい小さいパーツなどにも良いかもです。

0
0
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
0