プログラミング備忘録 foo

上段1枚+下段2枚(帯なし)

目的

  • 上段に1枚、下段に2枚の画像メニューが欲しい。
  • 下段の2枚は均等横並び。

実行結果

サンプル画像①
サンプル画像② サンプル画像③

解説

  • 上段にメインメニュー、下段にサブメニューを置きたい時にオススメです。
  • 親要素の横幅を変えれば全てが自動で可変します(後述のHTML・CSSで解説)。

HTML

<div class="layout_5_1">
	<div><a href="#"><img src="../../image/sample-1-b.jpg" alt="サンプル画像①" /></a></div>
	<div>
		<a href="#"><img src="../../image/sample-2.jpg" alt="サンプル画像②" /></a>
		<a href="#"><img src="../../image/sample-3.jpg" alt="サンプル画像③" /></a>
	</div>
</div>
  • 下段にaタグを3つ置けば3つとも自動で均等横並びになります。

CSS

.layout_5_1 {
	width: 80%;
	margin-top: 0px;
	margin-right: auto;
	margin-bottom: 0px;
	margin-left: auto;
}

.layout_5_1 a {
	display: block;
	width: 100%;
	overflow: hidden;
}

.layout_5_1 a:hover{
	opacity: 0.8;
}

.layout_5_1 img {
	width: 100%;
}

.layout_5_1 div:nth-child(1) {
	margin-top: 0px;
	margin-right: 0px;
	margin-bottom: 10px;
	margin-left: 0px;
}

.layout_5_1 div:nth-child(1) a {
	aspect-ratio: 16/6;
}

.layout_5_1 div:nth-child(2) {
	display: flex;
	gap: 10px;
}

.layout_5_1 div:nth-child(2) a {
	flex-grow: 1;
	flex-shrink: 1;
	flex-basis: 0;
	aspect-ratio: 3/2;
}
  • 全体の横幅を変える場合は2行目の値を変えてください。その他の要素も自動で可変されます。
  • 上段の画像の縦横比を計算し、その値を31行目に入れてください。画像の縦横比と、CSSの縦横比を同じにしないと適切に表示がされません。
  • 下段の画像の縦横比を計算し、その値を43行目に入れてください。画像の縦横比と、CSSの縦横比を同じにしないと適切に表示がされません。また、下段の各画像は縦横比を揃える必要があります。この構文では43行目で3対2に指定しているので、下段に2枚の画像を使う場合は1枚目W300×H200、2枚目W480×H320(どちらも3対2)のように、サイズが異なっていても縦横比が同じならOKです。
.layout_5_1 {
	width: 80%;
	margin-top: 0px;
	margin-right: auto;
	margin-bottom: 0px;
	margin-left: auto;
}

.layout_5_1 a {
	display: block;
	width: 100%;
	overflow: hidden;
}

.layout_5_1 a:hover{
	opacity: 0.8;
}

.layout_5_1 img {
	width: 100%;
}

.layout_5_1 div:nth-child(1) {
	margin-top: 0px;
	margin-right: 0px;
	margin-bottom: 5px;
	margin-left: 0px;
}

.layout_5_1 div:nth-child(1) a {
	aspect-ratio: 16/6;
}

.layout_5_1 div:nth-child(2) {
	display: flex;
	gap: 5px;
}

.layout_5_1 div:nth-child(2) a {
	flex-grow: 1;
	flex-shrink: 1;
	flex-basis: 0;
	aspect-ratio: 3/2;
}
  • スマホ版の解説内容はPC版と同じなので、PC版をご覧ください。