おはこんばんにちは!ノボルです。
CSSの勉強してるんだけど、「position: absolute;」を使って要素を中央寄せすることってできるの?
もちろんできるよ!サクッと説明するね。
そこで今回は、「position: absolute;」を使って要素を中央寄せする方法について解説します!

左右を中央寄せする方法
See the Pen gObzdEM by monkey d ruffy (@ruffy126) on CodePen.
1 2 3 4 5 6 7 8 |
img{ position: absolute; left: 0; right: 0; margin: auto; } |
左右のpositionを0にして「margin: auto;」で左右を中央寄せできます。
上下を中央寄せする方法
See the Pen NWPMLJg by monkey d ruffy (@ruffy126) on CodePen.
1 2 3 4 5 6 7 8 |
img{ position: absolute; top: 0; bottom: 0; margin: auto; } |
今度は、上下のpositionを0にして「margin: auto;」で上下を中央寄せできます。
上下左右ともに中央寄せする方法
See the Pen povVOYa by monkey d ruffy (@ruffy126) on CodePen.
1 2 3 4 5 6 7 8 9 10 |
img{ position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; } |
最後は、ド真ん中に配置する方法です。上下左右のpositionを0にして「margin: auto;」で上下左右ともに中央寄せすることができます。
ちなみ、上の方法だとどうしても上手くいかないことがあります。その場合は、下記のtransformプロパティを使ったやり方を試してみてください。
See the Pen bGNMmGr by monkey d ruffy (@ruffy126) on CodePen.
1 2 3 4 5 6 7 8 9 10 |
img{ position: absolute; top: 50%; left: 50%; transform: translateY(-50%) translateX(-50%); -webkit- transform: translateY(-50%) translateX(-50%); margin: auto; } |
最後に
今回の記事では、「position: absolute;」を使って要素を中央寄せする方法について解説しました。
CSSを使っていると中央寄せする機会が多いので、いろんな方法に慣れておきましょう!
最後まで読んで頂き、ありがとうございました(o^^o)




コメント