-
Notifications
You must be signed in to change notification settings - Fork 8.1k
/
index.md
352 lines (253 loc) · 33.2 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
---
title: Изображения в HTML
slug: Learn/HTML/Multimedia_and_embedding/Images_in_HTML
---
{{LearnSidebar}}{{NextMenu("Learn/HTML/Multimedia_and_embedding/Video_and_audio_content", "Learn/HTML/Multimedia_and_embedding")}}
В начале Web был просто текстом, что было довольно скучно. К счастью, это продолжалось не долго - до появления возможности вставлять изображения (и другие, более интересные, типы контента) в веб-страницы. Существуют и другие типы мультимедиа, однако логичнее начать со скромного {{htmlelement("img")}} элемента, используемого для вставки простого изображения в веб-страницу. В этой статье мы рассмотрим, как использовать элемент, начиная с основ, снабжать примечаниями, используя {{htmlelement("figure")}}, и разберём, как это относится к фоновым изображениям {{glossary("CSS")}}.
| Необходимы: | Базовые знания компьютера, [установленное базовое ПО](/ru/docs/Learn/Getting_started_with_the_web/Installing_basic_software), базовые знания по [работе с файлами](/ru/docs/Learn/Getting_started_with_the_web/Dealing_with_files), знания основ HTML (как описано в статье [Начало работы с HTML](/ru/docs/Learn/HTML/Introduction_to_HTML/Getting_started)). |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Цель: | Узнать, как встраивать изображения в HTML, как добавлять к ним описания и как изображения HTML связаны с фоновыми изображениями CSS. |
## Как разместить картинку на странице?
Чтобы разместить изображение на странице, нужно использовать тег {{htmlelement("img")}}. Это пустой элемент (имеется ввиду, что не содержит текста и закрывающего тега), который требует минимум один атрибут для использования — `src` (произносится _эс-ар-си_, иногда говорят его полное название, _source_). Атрибут `src` содержит путь к изображению, которое вы хотите встроить в страницу, и может быть относительным или абсолютным URL, точно так же, как значения атрибута `href` для элемента {{htmlelement("a")}}.
> [!NOTE]
> Перед тем как продолжить, вам стоит вспомнить про [типы адресов URL](/ru/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks#%d0%90%d0%b1%d1%81%d0%be%d0%bb%d1%8e%d1%82%d0%bd%d1%8b%d0%b5_%d0%b8_%d0%be%d1%82%d0%bd%d0%be%d1%81%d0%b8%d1%82%d0%b5%d0%bb%d1%8c%d0%bd%d1%8b%d0%b5_url-%d0%b0%d0%b4%d1%80%d0%b5%d1%81%d0%b0), чтобы обновить в памяти про относительные и абсолютные адреса.
Например, если ваше изображение называется `dinosaur.jpg`, и оно находится в той же директории что и ваша HTML страница, вы можете встроить это изображение как:
```html
<img src="dinosaur.jpg" />
```
Если изображение было в поддиректории `images` , находящаяся внутри той же директории, что и HTML страница (что рекомендует Google для индексации и целей SEO), тогда вы можете встроить его так:
```html
<img src="images/dinosaur.jpg" />
```
И так далее.
> [!NOTE]
> Поисковые системы также читают имена изображений и считают их для оптимизации поискового запроса. Поэтому присваивайте вашим изображениям смысловые имена: `dinosaur.jpg` лучше, чем `img835.png`.
Вы можете встроить изображение используя абсолютный URL, например:
```html
<img src="https://www.example.com/images/dinosaur.jpg" />
```
Но это бессмысленно, так как он просто заставляет браузер делать больше работы, запрашивая каждый раз IP-адрес от DNS-сервера. Вы почти всегда будете держать свои изображения для сайта на том же сервере, что и ваш HTML.
> **Предупреждение:** **Внимание:** Большинство изображений защищены. Не отображайте изображения на вашем сайте пока:
>
> - вы не будете владеть изображением
> - у вас не будет письменного разрешения владельца изображения, или
> - пока у вас не будет достаточно доказательств что изображение находится в открытом доступе.
>
> Нарушение авторских прав является незаконным. Кроме того, никогда не указывайте в своём атрибуте `src` ссылку на изображение, размещённое на чужом сайте. Это называется "хотлинкинг" (с англ. 'hotlinking' - 'горячая ссылка'). Запомните, кража пропускной способности чужого сайта незаконна. Это также замедляет вашу страницу и не позволяет вам контролировать, будет ли изображение удалено или заменено чем-то неприятным.
Наш код выше даст нам следующий результат:
![A basic image of a dinosaur, embedded in a browser, with Images in HTML written above it](basic-image.png)
> [!NOTE]
> Такие элементы как {{htmlelement("img")}} и {{htmlelement("video")}} иногда называются замещаемыми элементами. Это потому что содержание элемента и размер, определяет внешний ресурс (как изображение или видео файл), а не содержание самого элемента. Вы можете узнать о них больше в [Замещаемых элементах](/ru/docs/Web/CSS/Replaced_element).
> [!NOTE]
> Вы можете найти готовый пример этого раздела, [размещённый на Github](https://mdn.github.io/learning-area/html/multimedia-and-embedding/images-in-html/index.html) (смотрите также [исходный код](https://github.com/mdn/learning-area/blob/master/html/multimedia-and-embedding/images-in-html/index.html)).
### Альтернативный текст
Следующий атрибут, который мы рассмотрим — `alt`. Его значением должно быть текстовое описание изображения для использования в ситуациях, когда изображение не может быть просмотрено / отображено или отрисовка занимает много времени из-за медленного интернет-соединения. Чтобы продемонстрировать использование атрибута `alt` на практике, внесём изменения в код из предыдущего примера:
```
<img src="images/dinosaur.jpg"
alt="Голова и туловище скелета динозавра;
у него большая голова с длинными острыми зубами">
```
Самый простой способ увидеть атрибут `alt` в действии — это сделать намеренную ошибку в имени файла. Например, если бы мы написали имя изображения как `dinosooooor.jpg`, браузер не смог бы его отобразить, и на экране появился бы текст из атрибута `alt`:
![The Images in HTML title, but this time the dinosaur image is not displayed, and alt text is in its place.](alt-text.png)Итак, в каких случаях текст из атрибута `alt` может быть нам полезен? Приведём несколько примеров:
- Пользователь с нарушением зрения использует [устройство чтения с экрана](https://en.wikipedia.org/wiki/Screen_reader), которое может читать вслух описание элементов веб-страницы. На самом деле, наличие текста в атрибуте `alt` для описания изображения может быть полезно для большинства пользователей.
- В случае, если была допущена ошибка в имени файла или пути к нему (как было описано выше).
- Браузер не поддерживает формат данного изображения. Некоторые люди до сих пор используют текстовые браузеры, такие как [Lynx](https://en.wikipedia.org/wiki/Lynx_%28web_browser%29), которые вместо изображений отображают текст из атрибута `alt`.
- Если вы хотите добавить возможность найти ваше изображение с помощью поисковых систем. Например, поисковые системы могут искать совпадения поисковых запросов с текстом атрибута `alt`.
- Если пользователи отключили отображение изображений на странице для уменьшения объёма передаваемых данных и для сокрытия элементов, отвлекающих внимание. Это обычная практика для пользователей мобильных телефонов, а также в странах с маленькой пропускной способностью интернет-каналов и с высокой стоимостью интернет-трафика.
Что именно вы должны писать в атрибут `alt`? В первую очередь, это зависит от того, _зачем_ изображение вообще находится на странице. Другими словами, что вы потеряете, если ваше изображение не появится:
- **Декорация.** Вы должны использовать [Фоновые изображения CSS](#фоновые_изображения_css) для декоративных изображений, но если вы должны использовать HTML, добавьте пустой alt = "". Если изображение служит просто украшением и не является частью содержимого, добавьте пустой `alt=""`. Например, программа чтения с экрана не тратит время на чтение содержимого, которое не является важным для пользователя.
- **Контент.** Если ваше изображение содержит важную информацию, передайте ту же информацию через краткий `alt`. Или даже лучше, в _главном_ тексте, который все увидят. Не используйте `alt` , если можете обойтись без него. Насколько неудобно было бы для пользователя, если бы _параграфы_ были написаны дважды в _главном контенте_? Если изображение адекватно описано в основном тексте, можете просто использовать `alt=""`.
- **Ссылка.** Если вы помещаете изображение в {{htmlelement("a")}}, для того, чтобы сделать из него ссылку, вы всё ещё должны [использовать чёткие формулировки описания ссылок](/ru/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks#%d0%98%d1%81%d0%bf%d0%be%d0%bb%d1%8c%d0%b7%d1%83%d0%b9%d1%82%d0%b5_%d1%87%d1%91%d1%82%d0%ba%d0%b8%d0%b5_%d1%84%d0%be%d1%80%d0%bc%d1%83%d0%bb%d0%b8%d1%80%d0%be%d0%b2%d0%ba%d0%b8_%d0%be%d0%bf%d0%b8%d1%81%d0%b0%d0%bd%d0%b8%d1%8f_%d1%81%d1%81%d1%8b%d0%bb%d0%be%d0%ba). В таком случае, вы сможете использовать элемент `<a>` или атрибут `alt` . Старайтесь выбрать лучший вариант.
- **Текст.** Не пишите текст в изображениях. Если вашему заголовку понадобится тень, то лучше используйте для этого [CSS](/ru/docs/Web/CSS/text-shadow) вместо добавления текста в изображение. Однако, если _действительно этого не избежать_, то вам следует дополнить текст в атрибуте `alt`.
По существу, главная идея здесь это предоставить нечто полезное, для случая когда изображения не видны. Это гарантирует что все пользователи не упустят ничего из содержимого страницы. Попробуйте отключить изображения в своём браузере и посмотрите как всё выглядит. Вы вскоре выясните насколько полезным является альтернативный текст, если изображения не видны.
> [!NOTE]
> Более подробную информацию, смотрите здесь: [Альтернативный текст](/ru/docs/Learn/Accessibility/HTML#%d0%90%d0%bb%d1%8c%d1%82%d0%b5%d1%80%d0%bd%d0%b0%d1%82%d0%b8%d0%b2%d0%bd%d1%8b%d0%b9_%d1%82%d0%b5%d0%ba%d1%81%d1%82).
### Ширина и высота
Вы можете использовать атрибуты `width` и `height`, чтобы указать ширину и высоту вашего изображения. Ширину и высоту вашего изображение можете найти различными способами. Например, на Mac можно использовать <kbd>Cmd</kbd> + <kbd>I</kbd> чтобы получить информацию по изображению. Повторяя наш пример, мы можем сделать так:
```html
<img
src="images/dinosaur.jpg"
alt="The head and torso of a dinosaur skeleton;
it has a large head with long sharp teeth"
width="400"
height="341" />
```
Это не приводит к большой разнице в отображении при нормальных обстоятельствах. Но если изображение не будет показано, например, когда пользователь только что перешёл на страницу, а оно ещё не успело загрузится, вы укажите браузеру оставить место для отрисовки изображения:
![The Images in HTML title, with dinosaur alt text, displayed inside a large box that results from width and height settings](alt-text-with-width-height.png)
Это хорошая практика, в результате страница загрузится быстрее и более гладко.
Однако, вы не должны изменять размеры ваших изображений используя HTML атрибуты. Если вы установите размер изображения слишком большим, то в конечном итоге вы столкнётесь с изображениями, которые выглядят зернистыми, размытыми или слишком маленькими, и потратите трафик для загрузки изображения, которое не будет соответствовать нуждам пользователя. Конечное изображение может также выглядеть искажённым, если вы не сохраните правильное [соотношение сторон](<https://en.wikipedia.org/wiki/Aspect_ratio_(image)>). Рекомендуется использовать графический редактор для подгонки изображения к нужному размеру, перед вставкой его на вашу веб-страницу.
> [!NOTE]
> Если вам действительно нужно изменить размер изображения, вы должны использовать вместо этого [CSS](/ru/docs/Learn/CSS).
### Заголовок изображения
Как и для [ссылок](/ru/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks), вы также можете добавить атрибут `title` для изображений, чтобы при необходимости предоставить дополнительную информацию. В нашем примере мы могли бы сделать это так:
```html
<img
src="images/dinosaur.jpg"
alt="The head and torso of a dinosaur skeleton;
it has a large head with long sharp teeth"
width="400"
height="341"
title="A T-Rex on display in the Manchester University Museum" />
```
Это даёт нам всплывающую подсказку при наведении курсора мыши, также как и в ссылках:
![The dinosaur image, with a tooltip title on top of it that reads A T-Rex on display at the Manchester University Museum ](image-with-title.png)
Однако это не рекомендуется - `title` имеет ряд проблем с доступностью, в основном из-за того, что поддержка программ чтения с экрана очень непредсказуема, и большинство браузеров не будут отображать её, если вы не наведёте курсор мыши (например, нет доступа для пользователей клавиатуры). Зачастую лучше включить такого рода вспомогательную информацию в основной текст статьи, чем прикреплять её к изображению. Однако, она полезна в некоторых обстоятельствах; например, в галереях изображений, когда у вас нет места для их заголовков.
### Активное обучение: встраивание изображения
Наступила очередь немного поиграть! Этот раздел активного обучения поможет вам выполнить простое упражнение по встраиванию. Вы будете обеспечены простым {{htmlelement("img")}} тэгом; мы хотели бы чтобы вы встроили изображение расположенное по следующей ссылке:
<https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg>
Ранее мы говорили никогда не используйте горячие ссылки на изображения с других серверов, данный случай только для целей обучения, итак мы позволим вам пренебречь этим один разок.
Мы также хотели бы, чтобы вы:
- Добавили любой альтернативный текст, и проверили как это работает внеся ошибку в ссылку на изображение.
- Установите правильные значения `width` и `height` (подсказка: это 200px по ширине и 171px по высоте), после поэкспериментируйте с другими значениями, чтобы увидеть какой будет эффект.
- Установите `title` для изображения.
Если вы сделаете ошибку, вы всегда можете очистить код, используя кнопку _Reset_. Если вы реально не будете понимать как сделать, нажмите кнопку _Show solution_, чтобы увидеть ответ:
```html hidden
<h2>Input</h2>
<textarea id="code" class="input"><img></textarea>
<h2>Output</h2>
<div class="output"></div>
<div class="controls">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```css hidden
body {
font-family: "Open Sans Light", Helvetica, Arial, sans-serif;
}
.input,
.output {
width: 90%;
height: 10em;
padding: 10px;
border: 1px solid #0095dd;
overflow: auto;
}
button {
padding: 10px 10px 10px 0;
}
```
```js hidden
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var code = textarea.value;
var output = document.querySelector(".output");
var solution = document.getElementById("solution");
function drawOutput() {
output.innerHTML = textarea.value;
}
reset.addEventListener("click", function () {
textarea.value = code;
drawOutput();
});
solution.addEventListener("click", function () {
textarea.value =
'<img src="https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg"\n alt="The head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"\n width="200"\n height="171"\n title="A T-Rex on display in the Manchester University Museum">';
drawOutput();
});
textarea.addEventListener("input", drawOutput);
window.addEventListener("load", drawOutput);
```
{{ EmbedLiveSample('Playable_code', 700, 500) }}
## Придание изображению структуры и установка заголовка
Начиная разговор о заголовках, есть множество путей как вы можете добавить заголовок к своему изображению. Для примера, нет ничего, что может вас остановить сделать это таким образом:
```html
<div class="figure">
<img
src="images/dinosaur.jpg"
alt="The head and torso of a dinosaur skeleton;
it has a large head with long sharp teeth"
width="400"
height="341" />
<p>A T-Rex on display in the Manchester University Museum.</p>
</div>
```
Это нормально. Это содержит всё что вам нужно, и красиво стилизуется с помощью CSS. Но, есть проблема: здесь нет ничего, что семантически связывает изображение с его заголовком, и это может вызвать сложности для читателей. Например, когда у вас есть 50 изображений и заголовков, какой заголовок идёт вместе с каким изображением?
Лучшим решением будет использование элементов HTML5 {{htmlelement("figure")}} и {{htmlelement("figcaption")}}. Они были созданы исключительно для этой цели: предоставить семантический контейнер для рисунков и чётко связать рисунок с заголовком. Наш пример выше мог бы быть переписан так:
```
<figure>
<img src="images/dinosaur.jpg"
alt="The head and torso of a dinosaur skeleton;
it has a large head with long sharp teeth"
width="400"
height="341">
<figcaption>A T-Rex on display in the Manchester University Museum.</figcaption>
</figure>
```
Элемент {{htmlelement("figcaption")}} говорит браузерам и вспомогательной технологии, что заголовок описывает содержимое элемента {{htmlelement("figure")}}.
> [!NOTE]
> С точки зрения доступности, заголовки и [`alt`](/ru/docs/Web/HTML/Element/img#alt) имеют различные предназначения. Заголовки помогают даже тем, кто имеет возможность просматривать изображение, тогда как [`alt`](/ru/docs/Web/HTML/Element/img#alt) обеспечивает замену функциональности отсутствующего изображения. Таким образом, заголовки и `alt` не подразумевают под собой одни и те же вещи, потому что оба используются браузером при отсутствии изображения. Попробуйте отключить изображения в своём браузере, чтобы увидеть как это выглядит.
Тег \<figure> не является изображением. Он представляет собой независимый структурный элемент, который:
- Передаёт смысл компактным, интуитивно понятным способом.
- Может использоваться в различных местах страницы.
- Предоставляет ценную информацию, поддерживающую основной текст.
Тег \<figure> может быть несколькими изображениями, куском кода, аудио, видео, уравнением, таблицей, либо чем-то другим.
### Активное изучение: создание \<figure>
В этом разделе активного изучения мы хотели бы, чтобы вы взяли текст из предыдущего раздела активного изучения и преобразовали его в \<figure>:
- Оберните его в {{htmlelement("figure")}} элемент.
- Скопируйте текст из атрибута `title`, удалите атрибут `title`, и вбейте текст в элемент {{htmlelement("figcaption")}}.
В случае допущения ошибки, вы всегда можете набрать код повторно, нажав кнопку _Reset_. Если вы застряли, нажмите кнопку _Show solution_, чтобы увидеть ответ:
```html hidden
<h2>Input</h2>
<textarea id="code" class="input"></textarea>
<h2>Output</h2>
<div class="output"></div>
<div class="controls">
<input id="reset" type="button" value="Reset" />
<input id="solution" type="button" value="Show solution" />
</div>
```
```css hidden
body {
font-family: "Open Sans Light", Helvetica, Arial, sans-serif;
}
.input,
.output {
width: 90%;
height: 10em;
padding: 10px;
border: 1px solid #0095dd;
overflow: auto;
}
button {
padding: 10px 10px 10px 0;
}
```
```js hidden
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var code = textarea.value;
var output = document.querySelector(".output");
var solution = document.getElementById("solution");
function drawOutput() {
output.innerHTML = textarea.value;
}
reset.addEventListener("click", function () {
textarea.value = code;
drawOutput();
});
solution.addEventListener("click", function () {
textarea.value =
'<figure>\n <img src="https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg"\n alt="The head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"\n width="200"\n height="171">\n <figcaption>A T-Rex on display in the Manchester University Museum</figcaption>\n</figure>';
drawOutput();
});
textarea.addEventListener("input", drawOutput);
window.addEventListener("load", drawOutput);
```
{{ EmbedLiveSample('Playable_code_2', 700, 500) }}
## Фоновые изображения CSS
Вы можете использовать CSS для встраивания изображений в веб-страницы (или JavaScript, но это совсем другая история). Параметры CSS {{cssxref("background-image")}} и другие `background-*` применяются для контроля размещения фонового изображения. К примеру, чтобы залить фон каждого параграфа страницы, необходимо сделать следующее:
```css
p {
background-image: url("images/dinosaur.jpg");
}
```
Получившееся в конечном итоге изображение можно легко позиционировать и контролировать, в отличие от его HTML аналога. Так зачем же возиться с HTML изображениями? Как указано выше, фоновые изображения CSS предназначены только для украшения. Если вы просто хотите добавить что-то красивое на свою страницу, чтобы улучшить визуальные эффекты, это нормально. Тем не менее, такого рода изображения не имеют семантического смысла вообще. Они не могут иметь каких-то текстовых эквивалентов, видимых посетителю, они невидимы для программ чтения с экрана. Вот где блистают HTML-изображения!
Итог: если изображение имеет важность, в контексте содержимого вашей страницы, вам следует использовать HTML изображения. Если же картинка является банальной декорацией, используйте фоновые изображения CSS.
> [!NOTE]
> Вы можете узнать больше о [фоновых изображениях CSS](/ru/docs/Learn/CSS/Building_blocks/Backgrounds_and_borders) в нашей теме о [CSS](/ru/docs/Learn/CSS).
## Проверьте свои навыки!
Вы дошли до конца этой статьи, но можете ли вы вспомнить самую важную информацию? Вы можете найти дополнительные тесты, чтобы убедиться, что вы усвоили эту информацию, прежде чем двигаться дальше. Смотрите [Проверьте знания по изображениям в HTML](/ru/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML/Test_your_skills:_HTML_images).
## Резюме
На этом пока все. Мы подробно рассмотрели изображения и их заголовки. В следующей статье мы рассмотрим, как использовать HTML для встраивания видео и аудио на веб-страницы.
{{NextMenu("Learn/HTML/Multimedia_and_embedding/Video_and_audio_content", "Learn/HTML/Multimedia_and_embedding")}}