移动优先图片
本课属于 Coddy HTML 学习旅程的“前端实践”单元。第 9 课,共 35 课。
移动优先图片是指先确保图片在小屏幕上显示良好,然后再针对更大的屏幕进行优化。在移动设备上,体积大、占用空间多的图片会拖慢加载速度,因此我们先使用体积更小、经过优化的版本。屏幕变大后,我们可以换成质量更高的图片
我们来使用 HTML picture 元素,根据屏幕宽度提供不同尺寸的图片。
<picture>→ 用于容纳适配不同屏幕的多个图像选项的容器。
<source>→ 定义要加载哪张图片(srcset),以及在什么条件下加载(media)。例如:手机(≤600px)→ 小尺寸图片;平板电脑(≤1024px)→ 中等尺寸图片。
<img>→ 如果没有匹配的<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>挑战
简单你的目标是显示一张月球图片,让它在手机和桌面屏幕上都显示得很好。
你的任务:
- 使用
<picture>元素来设置响应式图片。 - 对于 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",以便提供无障碍支持。
亲手试试
<!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>这节课包含一个小测验。开始学习即可作答,并记录你的进度。
前端实践中的所有课
自己练习: Web 在线编辑器