margin: auto;を使って要素を寄せる
flexboxで要素を一つだけ右寄せにしたい時に使える方法を紹介します。
[jin-fusen1-even text=”要素を右に寄せたい!”]
[jin-yohaku50]
flexboxの使用時に要素を端に寄せてみましょう。
右に寄せたい場合は、寄せたい要素にmargin-left: auto; を追加します。
[jin-fusen2 text=”右のBOXにmargin-left:auto;を追加”]
↑
この要素に「margin-left: auto;」
[jin-yohaku30]
①HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="style.css"> </head> <body> <div class="boxWrap"> <div class="box"></div> <div class="box"></div> <div class="box"></div> </div> </body> </html> |
②CSS
1 2 3 4 5 6 7 8 9 10 11 12 | .boxWrap { display: flex; } .box { background-color: #eee; border: 2px solid #888; width: 100px; height: 100px; } .box:last-child { margin-left: auto; } |
縦並びで寄せる
[jin-yohaku20]
縦並びも同じ要領でmarginを当てていきます。
一番下の要素を寄せたい場合は、その要素にmargin-top: auto; を追加します。
[jin-fusen2 text=”下のBOXにmargin-left:auto;を追加”]
↑
この要素に「margin-top: auto;」
[jin-yohaku30]
①HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="style.css"> </head> <body> <div class="boxWrap"> <div class="box"></div> <div class="box"></div> <div class="box"></div> </div> </body> </html> |
②CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | .boxWrap { display: flex; flex-direction: column; height: 400px; } .box { background-color: #eee; border: 2px solid #888; width: 100px; height: 100px; } .box:last-child { margin-top: auto; } |
[jin-yohaku50]