モバイルファーストの画像
CoddyのHTMLジャーニー「Practical Frontend」セクションの一部 — レッスン 9/35。
モバイルファーストの画像とは、まず小さな画面で画像が適切に表示されるようにし、その後、大きなディスプレイ用に強化することを意味します。モバイルでは、大きくて重い画像は読み込みを遅くする可能性があるため、より小さく最適化されたバージョンから始めます。画面が大きくなるにつれて、より高品質な画像に切り替えることができます。
HTMLの picture 要素を使用して、画面幅に基づいて異なる画像サイズを提供しましょう。
<strong><picture></strong>→ 異なる画面向けに複数の画像オプションを保持するラッパー。
<strong><source></strong>→ どの画像を読み込むか (srcset) と、どのような条件で読み込むか (media) を定義します。例: スマートフォン (≤600px) → 小さい画像、タブレット (≤1024px) → 中くらいの画像。
<strong><img></strong>→<source>が一致しない場合のフォールバックで、通常は大きなデスクトップ用画像です。また、altテキストも含まれます。
<picture>
<source srcset="small-image.jpg" media="(max-width: 600px)">
<source srcset="medium-image.jpg" media="(max-width: 1024px)">
<img src="large-image.jpg" alt="Description of image">
</picture>チャレンジ
簡単モバイルとデスクトップの両方の画面で美しく見える月の画像を表示するという目標が与えられています。
あなたのタスク:
<strong><picture></strong>要素を使用して、レスポンシブイメージを設定します。- 768px以上の画面では、大きい方の月の画像を読み込みます:
https://upload.wikimedia.org/wikipedia/commons/e/e1/FullMoon2010.jpg より小さい画面(デフォルトのモバイル)では、小さい方の月の画像を読み込みます:
https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/330px-FullMoon2010.jpg- アクセシビリティのために
alt="Moon in the night sky"を必ず含めてください。
チートシート
モバイルファーストのレスポンシブ画像には、<picture> 要素を使用します:
<picture>→ 複数の画像オプションのラッパー<source>→ 画像 (srcset) と条件 (media) を定義<img>→altテキストを含むフォールバック画像
<picture>
<source srcset="small-image.jpg" media="(max-width: 600px)">
<source srcset="medium-image.jpg" media="(max-width: 1024px)">
<img src="large-image.jpg" alt="Description of image">
</picture>モバイル向けに最適化された小さな画像から始め、読み込みパフォーマンスを向上させるために、より大きなディスプレイ向けに拡張します。
自分で試してみよう
<!DOCTYPE html>
<html>
<head>
<title>Mobile-First Images</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 1rem;
line-height: 1.6;
background: #0a0a23;
color: #f5f5f5;
}
header {
text-align: center;
margin-bottom: 1.5rem;
}
h1 {
font-size: 1.5rem;
color: #ffd369;
}
.content {
max-width: 800px;
margin: 0 auto;
}
img {
max-width: 100%;
height: auto;
border-radius: 8px;
margin: 1rem 0;
}
p {
font-size: 1rem;
}
@media (min-width: 768px) {
h1 {
font-size: 2.25rem;
}
p {
font-size: 1.125rem;
}
}
</style>
</head>
<body>
<header>
<h1>The Moon</h1>
</header>
<main class="content">
<p>
The Moon is Earth's only natural satellite and has fascinated humans for thousands of years.
It influences tides, inspires myths, and continues to be a target for exploration.
</p>
<p>
Mobile-first images ensure the page loads fast on smaller devices while still looking
beautiful on bigger screens.
</p>
</main>
</body>
</html>このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。