🐼

margin: 0 auto;が効かなかった時の備忘録

に公開

背景

.innerの中の.boxを左右中央に配置したかったができなかった。

    <div class="container">
        <div class="box"></div>
    </div>
.container {
    width: 100%;
    height: 300px;
    margin: 0 auto;
}


.box {
    width: 200px;
    height: 200px;
    background: #43B549;

}

アウトプット

そもそもmargin: 0 auto;とは?

左右に対して自動的に余白を当てる。Y軸に対しては0としているため、余白は当たらない。

今回のダメだった点

.container {
    width: 100%;
    height: 300px;
    margin: 0 auto; ←ここ
}

margin: 0 auto;はアイテムの外側に自動的に余白をつけるものなので、.containerではなく.boxの方につけるのが正解。

.box {
    width: 200px;
    height: 200px;
    background: #43B549;
    margin: 0 auto;←こっちにつけるのが正解!
}

注意点

そもそもmargin: 0 auto;は width もしくは max-width が指定されていないと発動しません。
(width: 100%;もそもそも.boxが親要素の.contaonerの横幅いっぱいになっちゃうので意味ない)

今回の気づき

marginプロパティがどのような効果があるのかをしっかり理解する。
今回の場合、marginは「外側の余白」を指定するためのもの。
そのため、親要素の.containerにmargin: 0 auto;を用いても、子要素である.boxが左右中央寄せになるわけではない。

Discussion