火曜日, 5月 06, 2025

HTMLとCSSの様々な表現 22 
指定画像を16分割し隙間を空けて表示

指定画像を16分割し隙間を空けて表示します。画像は正方形であればサイズは強制的に400px四方になります。正方形でない場合は強制的にデフォルメされます。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>画像グリッド分割(隙間あり)</title>
<style>
body {
background: darkgray;
display: flex;
justify-content: center;
align-items: center;
}
.grid {
display: grid;
/* セルサイズを調整
正方形の元画像を 400×400px に設定し、
各セルは 96×96px に設定(ギャップが4pxなので) */
grid-template-columns: repeat(4, 96px);
grid-template-rows: repeat(4, 96px);
/* セル間の隙間
gap: 4px を使うことで、セル間に自動的に隙間が入る */
gap: 4px;
width: 400px;
height: 400px;
background: darkgray; /* 隙間の背景 */
}

.cell {
width: 96px;
height: 96px;
/* ↓画像を指定 */
background-image: url("links/image.jpg");
background-size: 400px 400px;
background-repeat: no-repeat;
}

/* 各セルの位置を手動で設定(4×4=16個)
background-position を使って元画像の該当部分だけを表示 */
.cell:nth-child(1) { background-position: 0px 0px; }
.cell:nth-child(2) { background-position: -100px 0px; }
.cell:nth-child(3) { background-position: -200px 0px; }
.cell:nth-child(4) { background-position: -300px 0px; }

.cell:nth-child(5) { background-position: 0px -100px; }
.cell:nth-child(6) { background-position: -100px -100px; }
.cell:nth-child(7) { background-position: -200px -100px; }
.cell:nth-child(8) { background-position: -300px -100px; }

.cell:nth-child(9) { background-position: 0px -200px; }
.cell:nth-child(10) { background-position: -100px -200px; }
.cell:nth-child(11) { background-position: -200px -200px; }
.cell:nth-child(12) { background-position: -300px -200px; }

.cell:nth-child(13) { background-position: 0px -300px; }
.cell:nth-child(14) { background-position: -100px -300px; }
.cell:nth-child(15) { background-position: -200px -300px; }
.cell:nth-child(16) { background-position: -300px -300px; }
</style>
</head>
<body>
<div class="grid">
<!-- 16個のセル -->
<div class="cell"></div><div class="cell"></div>
<div class="cell"></div><div class="cell"></div>
<div class="cell"></div><div class="cell"></div>
<div class="cell"></div><div class="cell"></div>
<div class="cell"></div><div class="cell"></div>
<div class="cell"></div><div class="cell"></div>
<div class="cell"></div><div class="cell"></div>
<div class="cell"></div><div class="cell"></div>
</div>
</body>
</html>

元画像は800×800pxです。

実行後はこんな感じです。背景色とグリッド線の色を合わせます。