11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

position:absolute;の要素中央寄せ

Last updated at Posted at 2020-12-14

画像の上にテキストボックスの要素を作り、position: absolute; を指定した時、重ねた要素を中央寄せにしたかったのですが、どうやるんだっけ?となってしまったので、忘れないよう自分用にメモしておきます。

イメージ
WS000000.JPG

ちなみにこれは、要素を上に重ねて中央寄せにした後、
top: -〇〇%とマイナスに配置しています。

左右を中央寄せにする場合

CSS
.example {
    position: absolute;
    left: 0;
    right: 0;
    margin: auto;
}

左右のポジションを0にして、marginで中央に寄せている、という感じです。

もしくは、

CSS
.example {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
}

でも可能。
transformプロパティを使用して、表示位置のX軸を-50%分移動させています。

上下を中央寄せにする場合

CSS
.example {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
}

これも、さっきの逆で同じ考え方です。
上下のポジションを0にして、marginで中央に寄せています。

もしくは、

CSS
.example {
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
}

でも可能。
transformプロパティを使用して、表示位置のY軸を-50%分移動させています。

上下左右を中央寄せにする場合

CSS
.example {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

上下左右のポジションを0にして、marginで中央寄せ。

もしくは、

CSS
.example {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

でも可能。
transformプロパティを使用して、表示位置の上下左右-50%分移動させています。

 

まとめ

top、left、right、bottomの指定だとうまくいかないこともあるので、その時はtransformプロパティを使用してみるといいです。
上下左右の中央寄せは結構使うので、このメモが誰かの役に立てばいいな、、笑

参考リンク

position: absolute;を中央寄せする方法
position: absoluteで中央に要素を寄せる最新の方法【css】(上下左右、上下、左右)

11
10
1

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
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?