URLをコピーしました!
スキルアップを始める!

【Flexbox】要素を上下左右の中央に配置する方法(CSS)

CSS(シー・エス・エス)
\ワードプレスのスキルアップはこちら!/ WordPress入門読本

CSSで「画面の上下左右中央に要素を配置したい」と思った時にも、Flexboxが便利です。簡単にできますのでお試しください。

四角形を準備する

まずは、四角形を準備します。ひとまず、以下のような感じにして四角形を準備します。

    <style>
        .box {
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>

        <div class="box"></div>

とりあえずの四角形が配置できました。

コンテナを準備する

次に、四角形を中央に配置するためのコンテナを準備します。背面に画面いっぱいに広がる青背景を準備します。

    <style>
        .container {
            width: 100%;
            height: 100%;
            position: fixed;
            left: 0;
            top: 0;
            background: blue;
        }

        .box {
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>

    <div class="container">
        <div class="box"></div>
    </div>
</body>

</html>

表示されました!

display: flex;を指定する

赤色の四角形を中央に配置してみます。まずは、display: flex;を指定します。

    <style>
        .container {
            width: 100%;
            height: 100%;
            position: fixed;
            left: 0;
            top: 0;
            background: blue;
            display: flex;
        }

        .box {
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>

    <div class="container">
        <div class="box"></div>
    </div>

要素がflexboxの状態になりました。

align-items: center;(上下中央)

上下左右中央に揃えていきます。上下中央に揃えるためには「align-items: center;」を指定します。

[rml_read_more]

align-items: center;

justify-content: center;(左右中央)

左右中央に揃えるためは「justify-content: center;」を指定します。

justify-content: center;

上下左右の中央揃えにする

つまり、上記の両方を設定することで「上下左右の中央揃えにする」が可能となります。

    <style>
        .container {
            width: 100%;
            height: 100%;
            position: fixed;
            left: 0;
            top: 0;
            background: blue;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .box {
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>

    <div class="container">
        <div class="box"></div>
    </div>

上下左右の中央に配置されました!

まとめ

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

この3行を入れてあげれば、中の子要素を上下左右の中央揃えにすることができます。

ご参考ください。

Kindle Unlimited 会員は無料で購読できます
購読はこちら
Kindle Unlimited 会員は無料で購読できます
購読はこちら