本記事では、position:absoluteを使って中央寄せする方法について解説しています。
HTML/CSSの学習におすすめ書籍
1冊ですべて身につくHTML&CSSとWebデザイン入門講座

メリット
- HTMLとCSSの基本が体系的に学べる
- Webデザインの基本が学べる
- 1つのWebサイトを作りながら学べる


Amazon Kindle Unlimitedに登録すると、月額980円で読み放題だからオススメだよ!



初回30日間は無料だから、まだ登録したことのない人はぜひ試してみてね!
全プログラマー必見!
変数名/関数名にもう悩まない!
変数名/関数名にもう悩まない!
リーダブルコード


メリット
- 美しいコードが書けるが自然と書けるようになる
- 他の開発者が理解しやすいコードになる
著:Dustin Boswell, 著:Trevor Foucher, 解説:須藤 功平, 翻訳:角 征典
¥2,640 (2023/07/23 02:48時点 | Amazon調べ)


目次
position:absoluteで中央寄せする手順



先輩!position:absoluteで中央寄せする方法を教えてください!



了解!3つの手順に分けて解説するね!
サンプルコード
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="parent">
<p class="children">SAMPLE</p>
</div>
</body>
</html>
.parent {
background-color: brown;
width: 200px;
height: 200px;
}
.children {
color: white;
}


手順1:親要素にposition:relative、子要素にposition:absoluteを指定



まず始めに起点となる親要素にposition:relativeを指定し、中央寄せしたい子要素にposition:absoluteを指定するよ!
.parent {
background-color: brown;
width: 200px;
height: 200px;
/* 追加 */
position: relative;
}
.children {
color: white;
/* 追加 */
position: absolute;
}



この状態で、下準備は完了です!次から子要素を動かして中央寄せしていきます!
手順2:中央寄せ①



position:absoluteを指定した子要素に中央寄せする記述を追加します!
.parent {
background-color: brown;
width: 200px;
height: 200px;
position: relative;
}
.children {
color: white;
position: absolute;
/* 追加 */
top: 50%;
left: 50%;
}





中央よりも少し右下にずれていませんか?



いい所に気が付いたね!ここでの中央寄せは、子要素の左上(画像の黒丸)を起点に中央寄せしているから、まだ完璧な中央寄せになっていないんだ!
手順3:中央寄せ②



最後に子要素本体を左に50%・上に50%移動する記述を追加します!
.parent {
background-color: brown;
width: 200px;
height: 200px;
position: relative;
}
.children {
color: white;
position: absolute;
top: 50%;
left: 50%;
/* 追加 */
transform: translate(-50%, -50%);
}





綺麗に子要素が中央に配置されましたね!