グリッドレイアウト - 個人サイトのためのCSS3講座

グリッドレイアウトの作成方法と使い方についての説明です。

CSSに「display: grid」を指定した上で、作成するレイアウトに応じて下記の要素を指定します。

grid-template-rows:縦方向の長さを指定します。
grid-template-columns:横方向の長さを指定します。

長さは、「px」や「%」などの単位を付けた数値を半角スペース区切りで記述します。

《例1》

CSS

.grid1 {
display: grid;
grid-template-rows: 30% 40% 30%;
}

.grid1 div {
margin: 4px;
background-color: skyblue;
}

HTML

<div class="grid1">
<div>1</div>
<div>2</div>
<div>3</div>
</div>

《表示結果1》

1
2
3

《例2》

CSS

.grid2 {
display: grid;
grid-template-rows: 30% 40% 30%;
grid-template-columns: 40% 30% 30%;
}

.grid2 div {
margin: 4px;
background-color: skyblue;
}

HTML

<div class="grid2">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
</div>

《表示結果2》

1
2
3
4
5
6
7
8
9
▲ページの先頭へ

画像のみをグリッド状に配置するソースコードです。画像1つにつき1つのグリッドです。

HTML

<div class="item5">
<span><img src="画像のURL" alt=""></span>
<span><img src="画像のURL" alt=""></span>
<span><img src="画像のURL" alt=""></span>
<span><img src="画像のURL" alt=""></span>
<span><img src="画像のURL" alt=""></span>
</div>

CSS(PC)

.item5 {
display: grid;
grid-template-columns: calc( 100% / 3 ) calc( 100% / 3 ) calc( 100% / 3 );
grid-template-rows: 50% 50%;
}

.item5 span {
padding: 15px;
}

CSS(スマホ)

.item5 {
display: grid;
grid-template-columns: 50% 50%;
grid-template-rows: calc( 100% / 3 ) calc( 100% / 3 ) calc( 100% / 3 );
}

.item5 span {
padding: 10px;
}

《表示結果》

▲ページの先頭へ

画像の下にテキストを配置してグリッド化するソースコードです。1列につき、画像とテキストがセットで1つのグリッド、計3つのグリッドです。スマホでは「display: block」を指定し、すべて1列の縦並びにしています。

HTML

<div class="grid3x1">
<div>
<img src="画像のURL" alt="">
<p>テキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト</p>
</div>
<div>
<img src="画像のURL" alt="">
<p>テキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト</p>
</div>
<div>
<img src="画像のURL" alt="">
<p>テキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト</p>
</div>
</div>

CSS(PC)

.grid3x1 {
display: grid;
grid-template-columns: calc( 100% / 3 ) calc( 100% / 3 ) calc( 100% / 3 );
}

.grid3x1 div {
padding: 15px;
}

CSS(スマホ)

.grid3x1 {
display: block;
}

.grid3x1 div {
padding: 15px 10px;
}

《表示結果》

サンプル画像

テキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト

サンプル画像

テキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト

サンプル画像

テキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト

▲ページの先頭へ

>>CSS3講座メニューへ戻る