479 views
この記事は最終更新から 502日 が経過しています。
【1】やりたいこと
ブロック要素内のテキストを、領域内の中央に表示したい。
div, section, p等のブロック要素の中に表示するテキストを、領域内の中央に表示したいのだ。
つまり…
上下左右中央に表示したい。
今回は display: grid を使って上下左右中央表示を簡単に実現する方法を記録しておく。
過去記事では、position: absolute を使用する方法を記していたが、適材適所で使い分けたい。
(37) position absoluteの中寄せ
(88) 複数行テキストの中寄せ
【2】やってみる
例1 : 上下左右中央
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Sample#158</title>
<style>
*{
box-sizing: border-box;
}
.center-grid {
display: grid;
place-items: center; /* 水平・垂直ともに中央揃え */
height: 200px; /* 高さを指定 */
border: 1px solid #000; /* 枠線を追加(オプション)*/
background-color: #f08080; /* 背景色を追加(オプション)*/
}
</style>
</head>
<body>
<div class="center-grid">
中央に配置されたテキスト
</div>
</body>
</html>
サンプルコードを以下にアップした。
https://www.dogrow.net/hp/sample/00158

例2 : 上下中央、左端
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Sample#158</title>
<style>
*{
box-sizing: border-box;
}
.center-grid {
display: grid;
justify-items: start; /* 水平方向で左揃え */
align-items: center; /* 垂直方向で中央揃え */
height: 200px; /* 高さを指定 */
border: 1px solid #000; /* 枠線を追加(オプション)*/
background-color: #f08080; /* 背景色を追加(オプション)*/
}
</style>
</head>
<body>
<div class="center-grid">
中央に配置<br>されたテキスト
</div>
</body>
</html>
サンプルコードを以下にアップした。
https://www.dogrow.net/hp/sample/00158/index2.html
上記の例では左端に表示したが、プロパティの値を変えて中央、右端にも表示できる。
justify-items: start 左端
justify-items: center 中央
justify-items: end 右端
例3 : 上下方向の指定
align-itemsプロパティの値を変えて上端、中央、下端に表示できる。
align-items: start 上端
align-items: center 中央
align-items: end 下端
アクセス数(直近7日): ※試験運用中、BOT除外簡易実装済2026-01-24: 0回 2026-01-23: 0回 2026-01-22: 0回 2026-01-21: 1回 2026-01-20: 0回 2026-01-19: 0回 2026-01-18: 0回