CSS ・ Flexbox・Grid
place-items
縦横の配置をまとめて指定
align-items と justify-items をまとめて指定する一括指定です。Grid で place-items: center とすると、子要素を上下左右の中央に置けます。
01
サンプルコード
HTML
1<div class="center">
2 <div class="item">上下左右の中央</div>
3</div>
CSS
1.center {
2 display: grid;
3 place-items: center;
4 height: 120px;
5 background: #f5efe6;
6}
7.item {
8 padding: 8px 14px;
9 background: #b68235;
10 color: #fff;
11}
02
実行結果
ブラウザでの表示
03
解説
place-items は align-items(縦方向)と justify-items(横方向)を1行で書けるプロパティです。値を1つだけ書くと、両方に同じ値が使われます。
display: grid と place-items: center の2行だけで、子要素を親の上下左右の中央に配置できます。中央寄せの最も短い書き方として知られています。
値を2つ書くと「縦方向 横方向」の順になります。
04
応用例・注意点
指定できる値
| 値 | 説明 |
|---|---|
center | 上下左右の中央 |
start | 左上に寄せる |
end | 右下に寄せる |
center start | 縦は中央、横は左 |
stretch | セルいっぱいに広げる |
画面の中央にメッセージを置く
ページ全体を grid にして、中身を真ん中に配置します。
HTML
1<main class="page">
2 <p>ページが見つかりませんでした</p>
3</main>
CSS
1.page {
2 min-height: 100vh;
3 display: grid;
4 place-items: center;
5}
注意点
- 01Flexbox では justify-items が効かないため、place-items: center では横方向が中央になりません。Flexbox では justify-content と align-items を使います。
- 02親に高さがないと、縦方向の中央寄せは見た目に変化がありません。