Содержит описание для тега . Тег должен быть первым или последним элементом в группе.
Синтаксис
Атрибуты
Закрывающий тег
Купеческий клуб
Памятник Св. Владимиру
Результат данного примера показан на рис. 1.
Html img with caption
Оформляет изображения с подписью.
Время чтения: меньше 5 мин
Обновлено 8 сентября 2022
Кратко
Скопировать ссылку «Кратко» Скопировано
Элемент используется для вёрстки иллюстраций, изображений или другого автономного содержимого, которое может иметь поясняющую подпись в виде тега .
Пример
Скопировать ссылку «Пример» Скопировано
alt="Слон на фоне заката">Слон на фоне закатаfigure>imgsrc="elephant-sunset.jpg"alt="Слон на фоне заката">figcaption>Слон на фоне закатаfigcaption>figure>
Как понять
Скопировать ссылку «Как понять» Скопировано
Обычно тегом верстают изображение, иллюстрацию, кусок кода и тому подобное, на которые будут ссылаться из основного содержимого документа. При этом вместе со всем содержимым (картинкой, подписью) может быть перенесён в другую часть документа без нарушения целостности потока документа.
Получаем данные о текущем URL из свойства location.function LocationExample() console.log(`Protocol: $`);console.log(`Host: $`);console.log(`Path: $`);console.log(`Hash: $`);>figure>figcaption>Получаем данные о текущем URL из свойства code>locationcode>.figcaption>pre> function LocationExample() < console.log(`Protocol: $`); console.log(`Host: $`); console.log(`Path: $`); console.log(`Hash: $`); > pre>figure>
Подсказки
Скопировать ссылку «Подсказки» Скопировано
💡 Если содержимое элемента на странице является автономным (даже в отрыве от основного контента будет иметь смысл) и имеет подпись, то почти наверняка можно верстать его тегом . Самыми яркими примерами такого содержимого могут быть:
картинка либо другое медиасодержимое с подписью;
фрагменты кода с пояснением;
цитата с указанием автора;
отрывок стихотворения с указанием автора и т.п.
💡 Разрешено использовать только один тег внутри .
💡 Элемент , если он есть, обязательно должен быть первым или последним потомком элемента .
Add Captions to Multiple Images Using the and Tags
Add Captions to Multiple Images Using the Tag
Conclusion
This article discusses the different approaches to writing a caption under or above an image or images on a web page using HTML and CSS properties.
Use of the and Tags
HTML has a specific tag used to insert a caption to an image. The represents a caption for a element, which can be placed as the first or last child of the element in HTML.
and are two new elements introduced as tags in HTML5. Here, the tag is best used to display images and graphics, whereas tells the viewers what they are looking at.
The tag also supports the HTML’s Global Attributes and Event Attributes.
In the following example, we are using an element to mark up an image on a web page or a document and an element to define a caption for the image:
Here we can adjust the image’s resolution (height and width) using the style attribute of the tag in HTML.
Here, the resolution of the image is set to its original size.
Because and are new HTML5 tags, old version browsers cannot understand the process of these two tags. So these tags get rendered on the web page as inline tags, which means those tags won’t get an automatic line break for figure captions where they will just be set side-by-side with the images.
So, as a solution, we can use CSS properties to style and as in the following example:
Here, we can edit the and tags as per the necessity by using different properties of CSS and values.
Add Captions on the Top of an Image
Without any CSS guidelines to the contrary, the caption will appear at the figure’s top or bottom depending on whether the element is the first or last element inside the figure.
In this example, we will set the caption of the image at the top of it as follows:
We can use CSS properties to format the captions of the images by adding different styles or colors to the text.
Add Captions to Multiple Images Using the Tag
With the aid of the tag and CSS properties, we can add captions to multiple images at the same time. In the below example, we will add captions to two images, and optionally, we can add a link that directs to another web page or website once clicked on the image.
When using this method, we can add the caption of the images at the top with further implementations.
Conclusion
Different approaches can be used to caption an image or images using HTML together with CSS properties, as mentioned above. Still, some methods, like adding an image or images and their captions in a table format, are not currently appropriate.
New tags such as and in HTML5 have made the task of captioning an image easier.
Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.
Подрисуночная подпись — это текст, который является комментарием к рисунку и его описывает. Такая подпись важна, поскольку она привлекает внимание читателя к иллюстрации и даёт больше информации об изображении. У элемента существует, конечно, атрибут title , который задаёт текст всплывающей подсказки, но чтобы её получить, приходится наводить курсор мыши на каждый рисунок, что довольно неудобно. Более наглядный способ и, соответственно, более предпочтительный заключается в размещении подрисуночной подписи возле самого изображения. Подпись хоть и называется подрисуночной, но может располагаться сверху или сбоку от рисунка, если это продиктовано соображениями вёрстки и дизайна (рис. 1).
Рис. 1. Варианты размещения подрисуночной подписи
Для размещения на веб-странице и рисунка, и подписи к нему удобно воспользоваться элементами и , а через стили задать параметры рисунка, а также расположение текста (пример 1).
Пример 1. Создание подрисуночной подписи
Подпись снизуПодпись сверху
Для изменения положения текста — сверху или снизу изображения, достаточно просто поменять местами элементы и . Для размещения сбоку применяем свойство float к селектору figcaption , но надо помнить, что это свойство воздействует на все нижележащие элементы тоже.