0
0

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 1 year has passed since last update.

【CSS】position:absoluteを使って上下左右中央ぞろえ

Last updated at Posted at 2022-09-29

やりたいこと

画像を表示するモーダルを作成していて、コンテンツを画面の中央に設置したい

経緯

いつも真ん中に置くのに苦労している。
左右中央はいいんだけど、上下中央がすんなりいかない。
こちらのサイトの内容がドンピシャだったので、備忘録に。
https://cotodama.co/position-absolute-center/

実装

周りの要素は省く

html
<div class="modal-content">
    <img src="url">
</div>
css
.modal-content {
    /* 高さ・幅はお好みで */
    height: 50%;
    width: fit-content;

    /* これで真ん中 */
    position: absolute;
    margin: auto;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
}

img {
    /* 画像の高さもお好みだけど、はみださないよう
    親要素より大きくならないようにしておくのがおすすめ */
    max-height: 100%;
}

こんな感じ。
image.png

おまけ

width: fit-content;で子要素の幅に合わせてくれるので、
子要素の画像のサイズになってくれる。
親要素が大きいと、モーダルを閉じる動きがうまくいかなかったので、設定しておきたかった。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?