flexboxを使って同じサイズの子要素を横に並べるのに、%(パーセント)で横幅のサイズを指定した時のサイズを計算で求める方法を記述します。
横に3つ並べる場合
最初に余白を作らないで3つ並べる例を以下に表示します。

画像の上に透けている文字列を表示する方法

clamp関数を使ってフォントサイズを可変にする方法

見出しに文字の長さだけ間隔をあけて下線を引く
横幅が同じサイズの要素を3つ並べる場合は、100を3で割った値で以下の設定になります。
width: 33.33%;
calcを使用した場合は、以下の設定になります。
width: calc(100% / 3);
要素を4つ並べることに変える場合は、自分で計算しないで、calcを使うことで3を4に変更するだけになります。
width: calc(100% / 4);
HTML
<div class="block-wrapper">
<div class="block">
<img src="./images/dog01.jpg" />
<h2>画像の上に透けている文字列を表示する方法</h2>
</div>
<div class="block">
<img src="./images/dog02.jpg" />
<h2>clamp関数を使ってフォントサイズを可変にする方法</h2>
</div>
<div class="block">
<img src="./images/dog03.jpg" />
<h2>見出しに文字の長さだけ間隔をあけて下線を引く</h2>
</div>
</div>
CSS
.block-wrapper {
width: 100%;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
}
.block {
box-sizing: border-box;
width: calc(100% / 3);
height: auto;
margin: 0;
padding: 0;
border: 1px solid #aaa;
}
.block img {
width: 100%;
}
.block h2 {
font-size: 24px;
margin: 0;
padding: 4px 16px;
}
@media only screen and (max-width: 480px) {
.block {
width: 100%;
}
}
横に3つと縦に2列並べる場合
今度は要素と要素の間に余白を指定して表示します。
余白を作るのに一般的には margin を使用すると思いますが、flexbox では gap を使用した方が簡単です。
この例では横と縦の間隔が、横が16pxと縦が24pxの設定は以下になります。
gap: 24px 16px;
余白を作ることで要素の長さも変更します。全体の長さから横の余白分のピクセル数を少なくしますので、この例では以下の設定になります。
width: calc((100% / 3) - 16px);

画像の上に透けている文字列を表示する方法

clamp関数を使ってフォントサイズを可変にする方法

見出しに文字の長さだけ間隔をあけて下線を引く

テーブルのセルの結合

中央寄せで文字列を左寄せにする方法

WordPressのタクソノミーのターム一覧を表示する方法
HTML
<div class="block1-wrapper">
<div class="block1">
<img src="https://blog.raizzenet.com/wp-content/uploads/2024/10/dog01.jpg" />
<h2>画像の上に透けている文字列を表示する方法</h2>
</div>
<div class="block1">
<img src="https://blog.raizzenet.com/wp-content/uploads/2024/10/dog02.jpg" />
<h2>clamp関数を使ってフォントサイズを可変にする方法</h2>
</div>
<div class="block1">
<img src="https://blog.raizzenet.com/wp-content/uploads/2024/10/dog03.jpg" />
<h2>見出しに文字の長さだけ間隔をあけて下線を引く</h2>
</div>
<div class="block1">
<img src="https://blog.raizzenet.com/wp-content/uploads/2024/10/dog04.jpg" />
<h2>テーブルのセルの結合</h2>
</div>
<div class="block1">
<img src="https://blog.raizzenet.com/wp-content/uploads/2024/10/dog05.jpg" />
<h2>中央寄せで文字列を左寄せにする方法</h2>
</div>
<div class="block1">
<img src="https://blog.raizzenet.com/wp-content/uploads/2024/10/dog06.jpg" />
<h2>WordPressのタクソノミーのターム一覧を表示する方法</h2>
</div>
</div>
CSS
.block1-wrapper {
width: 100%;
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 24px 16px; /* 縦24px 横16px の余白を作成する */
}
.block1 {
box-sizing: border-box;
width: calc(100% / 3 - 16px); /* 横16px分を減らす */
height: auto;
margin: 0;
padding: 0;
border: 1px solid #aaa;
}
.block1 img {
width: 100%;
}
.block1 h2 {
font-size: 24px;
margin: 0;
padding: 8px;
}
@media only screen and (max-width: 480px) {
.block1 {
width: 100%;
}
}
ちなみに横と縦の間隔が同じ、または横だけ場合の設定は以下になります。
gap: 縦横の間隔;