プログラミング備忘録 foo

画像リンク埋込

目的

  • 背景画像に画像リンクを均等横並びで埋め込みたい。

実行結果

YouTube
インスタグラム

解説

  • 海の背景画像に画像リンクを載せています。
  • 画像リンクは縦横中央揃えです。
  • 画像リンク数を変えても画像サイズが自動で可変します。

HTML

<div class="layout_7_1">
	<div><a href="https://youtube.com/" target="_blank"><img src="../../image/layout/7-1-a.png" alt="YouTube" /></a></div><div><a href="https://www.instagram.com/" target="_blank"><img src="../../image/layout/7-1-b.png" alt="インスタグラム" /></a></div>
</div>
  • 画像リンク数を増やす場合は<div>〜</div>をコピー&ペーストして内容を変えてください。

CSS

.layout_7_1 {
	background-image: url(../../image/layout/7-1.jpg);
	background-size: cover;
	background-repeat: no-repeat;
	display: flex;
	align-items: center;
	justify-content: center;
	aspect-ratio: 2.8444;
	width: 96%;
	padding-top: 0px;
	padding-right: 20px;
	padding-bottom: 0px;
	padding-left: 20px;
	margin-top: 0px;
	margin-right: auto;
	margin-bottom: 0px;
	margin-left: auto;
	box-sizing: border-box;
	gap: 20px;
}

.layout_7_1 > div {
	flex-grow: 1;
	flex-shrink: 1;
	flex-basis: 0;
}

.layout_7_1 > div img {
	display: block;
	width: 100%;
	height: auto;
}

.layout_7_1 > div a {
	display: block;
	width: 100%;
}

.layout_7_1 > div a:hover {
	filter: brightness(1.03);
}
  • 8行目で背景画像の縦横比率を指定しています。W1920×H675なので計算は1920÷675=2.844となり、その値を入れる事で全表示されます。
  • 画像リンクの画像の縦横比率は全て揃えないとズレが生じます。
  • 11行目と13行目と19行目の値を同じにする事で余白が均等になっています。
  • 40行目はopacityにすると背景画像が透過されてしまうのでfilter: brightness(1.03);としています。