figcaption в HTML


Содержание
Илон Маск рекомендует:  Что такое код setbuf

HTML тег

Тег используется для добавления подписи или пояснений к содержимому тега . Тег включается в тег и размещается в качестве первого или последнего дочернего элемента. Если является первым вложенным элементом, то содержимое будет отображаться вверху изображения.

В элементе допускается применение только одного тега , но при этом в элемент могут быть включены другие теги (тег или ).

Синтаксис

Содержимое элемента пишется между открывающим и закрывающим тегами.

Примеры использования html-тегов figure и figcaption

HTML-теги figure и figcaption появились в стандарте HTML5 для формирования блока с картинкой и описания к ней. Кроме того, эти теги можно применять для оборачивания блоков кода, рекламы, видео или аудио.

Стандартный вид использования этих тегов таков:

На первый взгляд, ничего особенного, и можно было бы обойтись и без этих тегов, воспользовавшись для формирования блока div-ами. Давайте для начала заглянем в код и посмотрим, к каким тегам — блочным или строчным — они относятся. Инспектор свойств ( F12 , или CTRL + SHIFT + I ) показывает нам, что и , — это блочные теги:

Поэтому мы можем несколько изменить форматирование нашего блока, определив дополнительные ccs-правила для тегов и :

После этого получим уже другой вид той же картинки. Стало намного симпатичней, не так ли?

Эффект увеличения картинки при наведении на figure

Давайте усложним код, добавив эффект увеличения изображения при наведении на figure . Используем для этого свойство transform: scale() . Кроме того, спрячем изначально подпись под изображением в теге figcaption , добавив ему свойство opacity: 0 , и увеличим это свойство до 1 при наведении на figure . Для плавности добавим анимацию типа transition. В результате получим такой код:

В коде для тега figure задан атрибут . Это сделано для создания различия в примерах, хотя при наличии у вас единственного тега figure на странице или в случае форматирования всех таких тегов в соответствии с приведенным выше кодом необязательно.

Сам пример с увеличивающейся картинкой и появляющимся описанием выглядит так:

Как вы, должно быть, догадались, это далеко не все, что можно сделать с тегами и , используя различные правила css. Поэтому давайте рассмотрим ряд примеров с Codepen, которые раскрывают возможности этих тегов, используя намного больше свойств CSS.

Пример использования тегов figure и figcaption для форматирования элементов code и pre

Кроме применения этих тегов в качестве обертки для картинок, можно использовать их для:
— блочных цитат
— блоков кода
— аудио
— видео
— рекламных объявлений

Рассмотрим пример, который демонстрирует код на JavaScript (используются теги Пример кода на JavaScript для обработки события клика на кнопку и случайного изменения цвета фона для body

Примеры форматирования изображений с помощью html-тегов figure и figcaption с Codepen

Прежде, чем решить, использовать вам теги figure и figcaption в оформлении страниц, вы можете посмотреть, каким образом они были оформлены в примерах на популярном ресурсе codepen.io. Авторы примеров используют в своем коде не только привычную разметку в html и описание свойств в css , но и различные препроцессоры, такие, как Haml, Pug или SCSS. Если код на вкладках для вас непонятен, перейдите по ссылке Edit on Codepen и выберите в меню справа на нужной вкладке View Compiled HTML (Показать скомпилированный HTML) или View Compiled CSS (Показать скомпилированный CSS).

Пример очень симпатичного оформления профиля актера, автора статьи или пользователя

Описание изображения в виде меток

Очень интересный вариант использования тега figcaption для создания меток показан в примере ниже. Для этого figcaption содержит внутри несколько вложенных div -ов, причем и сам figcaption , и div -ы внутри него имеют абсолютное позиционирование с разными координатами. В зависимости от размера экрана длина выносной линии для меток изменяется с помощью css-переменной —label-length .

Простая фотогалерея с описаниями

В этом примере текст из описания ( ) разбит на 2 строки и выведен поверх фото, размещенного в теге . Просто и приятно.

Пример форматирования галереи изображений

Галерея изображений, основанная на использовании свойств Flexbox-модели для размещения фото в 3 колонки и на использовании тегов и для отображения изображений и описания к ним. Обратите внимание, что внутри figcaption размещены 2 div -a: один для названия изображения, второй — для имени автора этого изображения.

Фотогалерея с данными об авторе, просмотрах и загрузках

Еще один вариант фотогалереи позволяет на больших экранах увидеть в теге только название фото, а при наведении курсора мыши на картинку — данные об авторе , просмотрах и загрузках. На экранах менее 700px все эти данные отображаются сразу. В примере использованы анимации типа transition.

Пример мини-слайдера

В этом примере изображений, размещенных в тегах figure и снабженных figcaption , можно просмотреть при скролле страницы вправо за счет использования grid-контейнера. Здесь использован небольшой JS-код на основе библиотеки RELLAX.

Фотогалерея с перемещением картинок

Пример организации страницы с анимированной прокруткой изображений за счет использования свойства @keyframes и css-трансформации translate3d . В теге размещен заголовок h3 с абсолютным позиционированием и свойством mix-blend-mode: screen .

Фотогалерея на основе Grid

В этой фотогалерее интересно размещение разных по размеру фото по сетке за счет использования модели Grid. Также здесь использован hover-эффект с всплывающим описанием, немного повернутым за счет использования свойства transform: rotate().

See the Pen Figure + Figcaption by Ryan Mulligan (@hexagoncircle) on CodePen.18892

Слайдер на основе тегов figure и figcaption

В этом примере слайдер организован на основе вложенных тегов figure и figcaption , а также анимации с помощью css-свойств @keyframes и animation .

Мини-фотогалерея с эффектом печатания текста

Фото загружается с анимацией небольшого покачивания. При наведении на изображение мы видим, как печатается текст, размещенный в теге figcaption . Для этого используется JavaScript-код на основе jquery.js.

Пример, демонстрирующий изменение контента при наведении на фото

Используем псевдоклассы ::before и ::after для figure, а также абсолютное позиционирование и анимацию типа transition при наведении курсора на блок с фотографией, причем фото загружается не в теге , а с помощью css-свойства background-image для figure.

Пример изображения с выезжающим описанием


При клике на кнопку More описание, размещенное в коде в теге выезжает вверх. В примере использован svg с фильтром и немного JS-кода на основе jQuery.

Описание на обороте изображения

В этом примере для того, чтобы прочитать полное описание фото, необходимо нажать на кнопку Read the back, после чего фото повернется к нам своей «обратной стороной». В коде использованы 3D трансформации и JavaScript.

Описание, появляющееся при наведении курсора мыши на фото

Решение на чистом CSS: мы видим изначально над изображением текст из абзаца, размещенного непосредственно в теге figure , а полное описание из тега figcaption читаем после наведения на фото. Эффект появления основан на абсолютном позиционировании, а также на использовании свойства transform и transition .

Анимированное исчезновение описания картинки

В этом примере внутри тега текст разбит на несколько span -ов, которые визуально размещены вверху и внизу картинки при загрузке страницы за счет абсолютного позиционирования. При наведении курсора мыши они скрываются за счет использования css-свойств animation и @keyframes . В коде использованы переменные css.

Исчезающее описание

Еще один вариант кода, который не показывает, а наоборот, убирает figcaption для изображения. Очень приятный hover-эффект, в котором при наведении курсора мыши на картинку описание как бы прячется под нее. Используется jQuery и TweenMax.

HTML figcaption Tag

Contents

HTML figcaption: Main Tips

  • The HTML element adds a caption or a legend to the content of .
  • The element encloses both the and to represent an image in more semantic terms.
Theory is great, but we recommend digging deeper!
Comprehensive HTML5 Tutorial: Become Advanced HTML5 Specialist

Use of figcaption

The sets an image caption HTML for a element.

To have a HTML image caption below the picture, place the element after the .

Note: the HTML tag supports all global attributes, but has no special ones.

Теги figure и figcaption, демонстративный материал

В галерее селфи каждая маленькая картинка-превьюшка ссылается на отдельную страницу с «фотокарточкой». Эта фотокарточка содержит полноразмерное изображение и его описание. Она достаточно независима, и позже мы сможем вставить её на любую другую страницу блога. Как правильно размечать такие «карточки»?

Для этого отлично подойдёт тег . Этот тег хорош для любого иллюстративного или демонстрационного материала, которым можно дополнить содержание документа. Таким материалом могут быть схемы, графики, примеры кода, таблицы и так далее. При удалении иллюстративного материала основное содержание не должно пострадать, иначе это уже не дополнительный материал и тег не очень подходит для его разметки.

Обычно каждый такой материал сопровождает разъясняющий комментарий или «легенда». Для разметки этого комментария предназначен ещё один тег — &ltfigcaption> , который размещается первым или последним элементом внутри . Например:

Давайте с помощью разметим фото в нашей галерее. Приступим.

Правильный способ использовать элементы figure и figcaption

Элементы figure и figcaption это два семантических элемента, которые часто используют вместе. Если вы не читали спецификацию, то для начала загляните сюда. Если вам пришлось использовать элементы в своем проекте, но вы не представляете как сделать это правильно, то ниже несколько подсказок, как использовать элементы корректно.

Элемент figure обычно используется для изображений:

Элемент figure представляет собой автономный блок контента. Это означает, что если вы передвинете блок в любое место документа, то это не повлияет на смысл.

Так же мы должны помнить, что не каждая картинка представляет собой фигуру.

Несколько изображений внутри figure

Вы можете поместить несколько тегов img в figure, если они связаны в контексте документа.

Другие элементы, используемые с figure

Использование figure для оборачивания картинок — не единственное его назначение.

Вы можете использовать его для:
— блоков кода
— аудио
— видео или
— рекламных объявлений

Пример использования figure для блока с кодом:

Вложение figure в другой тег figure

Вы можете вложит один блок figure в другой, если это имеет смысл.

В примере ниже добавлен атрибут role для улучшения семантики.

Правильно использование figcaption

Элемент figcaption представляет собой заголовок или легенду для figure.

Не каждый тег figure нуждается в figcaption.


Тем не менее при использовании figcaption, идеально если он идет первым или последним тегом внутри блока figure:

Вы можете использовать потоковые элементы в figcaption

Если вам нужно добавить больше смысла к картинке, то можете использовать h1 и p.

У вас есть еще подсказки по использованию элементов figure и figcaption?

HTML figcaption Tag

Contents

HTML figcaption: Main Tips

  • The HTML element adds a caption or a legend to the content of .
  • The element encloses both the and to represent an image in more semantic terms.
Theory is great, but we recommend digging deeper!
Comprehensive HTML5 Tutorial: Become Advanced HTML5 Specialist

Use of figcaption

The sets an image caption HTML for a element.

To have a HTML image caption below the picture, place the element after the .

Note: the HTML tag supports all global attributes, but has no special ones.

HTML Tag

The tag is used to provide a caption when using the tag (the tag is for annotating illustrations, diagrams, photos, code listings, etc).

Syntax

The tag is written as with the caption inserted between the start and end tags.

The tag is used either as the first or last child of its parent tag.

Examples

Basic tag usage

Here, the tag is placed as the first child of the element.

As Last Child of Element

You can also place the at the end of the element (i.e. so that it’s the last child of the element).

Here, we place the element under the image that is the main content of the element.

Poetry/Lyrics

Poems and lyrics could also be marked up with the tag. Notice that the element is inside the element.

Attributes

Attributes can be added to an HTML element to provide more information about how the element should appear or behave.

There are 3 kinds of attributes that you can add to your HTML tags: Element-specific, global, and event handler content attributes.

The element accepts the following attributes.

Element-Specific Attributes

This table shows the attributes that are specific to the tag/element.

Attribute Description
None

Global Attributes

The following attributes are standard across all HTML5 elements. Therefore, you can use these attributes with the tag , as well as with all other HTML tags.

  • accesskey
  • class
  • contenteditable
  • contextmenu
  • dir
  • draggable
  • dropzone
  • hidden
  • id
  • inert
  • itemid
  • itemprop
  • itemref
  • itemscope
  • itemtype
  • lang
  • spellcheck
  • style
  • tabindex
  • title
  • translate

For a full explanation of these attributes, see HTML 5 global attributes.

Event Handler Content Attributes

Event handler content attributes enable you to invoke a script from within your HTML. The script is invoked when a certain «event» occurs. Each event handler content attribute deals with a different event.


Below are the standard HTML5 event handler content attributes.

Again, you can use any of these with the element, as well as any other HTML5 element.

  • onabort
  • oncancel
  • onblur
  • oncanplay
  • oncanplaythrough
  • onchange
  • onclick
  • oncontextmenu
  • ondblclick
  • ondrag
  • ondragend
  • ondragenter
  • ondragexit
  • ondragleave
  • ondragover
  • ondragstart
  • ondrop
  • ondurationchange
  • onemptied
  • onended
  • onerror
  • onfocus
  • onformchange
  • onforminput
  • oninput
  • oninvalid
  • onkeydown
  • onkeypress
  • onkeyup
  • onload
  • onloadeddata
  • onloadedmetadata
  • onloadstart
  • onmousedown
  • onmousemove
  • onmouseout
  • onmouseover
  • onmouseup
  • onmousewheel
  • onpause
  • onplay
  • onplaying
  • onprogress
  • onratechange
  • onreadystatechange
  • onscroll
  • onseeked
  • onseeking
  • onselect
  • onshow
  • onstalled
  • onsubmit
  • onsuspend
  • ontimeupdate
  • onvolumechange
  • onwaiting

For a full explanation of these attributes, see HTML 5 event handler content attributes.

Differences Between HTML 4 & HTML 5

The tag is new in HTML5.

For more detail on the element, see HTML5 Tag. Also check out the links to the official specifications below.

Template

Here’s a template for the tag with all available attributes for the tag (based on HTML5). These are grouped into attribute types, each type separated by a space. In many cases, you will probably only need one or two (if any) attributes. Simply remove the attributes you don’t need.

Note that the element does not actually have any local attributes (i.e. attributes that are specific to the element), but the following global attributes and event handlers are available to the element (and all other HTML elements).

For more information on attributes for this tag, see HTML5 Tag.

Tag Details

For more details about the tag, see HTML5 Tag.

Specifications

Here are the official specifications for the element.

What’s the Difference?

W3C creates «snapshot» specifications that don’t change once defined. So the HTML5 specification won’t change once it becomes an official recommendation. WHATWG on the other hand, develops a «living standard» that is updated on a regular basis. In general, you will probably find that the HTML living standard will be more closely aligned to the current W3C draft than to the HTML5 specification.

HTML .am>

The HTML5 tag is used to provide a caption or legend when using the tag.

The tag is used either as the first or last child of its parent tag.

The basic tag is written like this with the legend/caption nested between the opening and closing tags.

The tag was introduced in HTML 5.

Example

The following example shows the element in action. You can modify the code (on the left) and click «Refresh» to see your changes take effect (on the right).

Attributes

The tag accepts the following attributes. Try adding some to the above example to see how it affects the display/behavior of the element.

Attributes Specific to the Element

Global Attributes

The tag accepts the following global attributes. These attributes are standard across all HTML 5 tags.

Attribute Description
accesskey Specifies a shortcut key that can be used to access this element.

[Any string of characters. This string of characters specifies the key/s the user needs to use in order to access the element.]

class This is a document wide identifier. It is used to refer to a class that is specified in the style sheet. The value should match the name of the class you wish to use.
contenteditable This attribute specifies whether the user can edit the content or not.
  • true
  • false
contextmenu The contextmenu attribute sets a context menu for an element. The value must be the ID of a menu element in the DOM.
dir Specifies the direction of the text.
Value Description
ltr Specifies that the text should read left to right.
rtl The text should read right to left.
auto The text direction should be determined programatically using the contents of the element.
draggable Specifies whether the user is allowed to drag this element or not.
  • true
  • false
  • auto
Value Description
true This value specifies that the element is draggable.
false A false value specifies that the element is not draggable.
auto Uses the default behavior of the user agent/browser. This is the default value.
dropzone The dropzone attribute specifies what should happen when the user «drops» an element (i.e. after dragging it) onto this element.

Must be an unordered set of unique space-separated tokens that are ASCII case-insensitive.

Value Description
copy Results in a copy of the dragged data. Default value.
move Results in the data being moved to the new location.
link Results in a link to the original data.
Any keyword with eight characters or more, beginning with the an ASCII case-insensitive match for the string » string: « Specifies that items with the drag data item kind Plain Unicode string and the drag data item type string set to a value that matches the remainder of the keyword are accepted.
Any keyword with six characters or more, beginning with an ASCII case-insensitive match for the string » file: « Allows you to specify which file types can be processed (i.e. copied, moved or linked) in this dropzone. Example: dropzone=»copy file:image/png file:image/gif file:image/jpeg»

Note that this attribute must not have more than one of the three feedback values (copy, move, and link) specified. If none are specified, the copy value is implied.

hidden Indicates that this particular element is not yet, or is no longer, relevant. The browser/user agent does not display elements that have the hidden attribute present.

This is a boolean attribute. If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute’s canonical name, with no leading or trailing whitespace (i.e. either hidden or h ).


  • [Empty string]
  • hidden
id The id attribute is a document wide identifier, which is used in conjunction with CSS and JavaScript. The value must match the name of the id you wish to use.
itemid The itemid provides a global identifier for an «item». This attribute is optional, however if it is provided, it must have a value that is a valid URL potentially surrounded by spaces.

The itemid attribute can only be present in elements that include both the itemscope and the itemtype attributes, as long as the itemtype attribute specifies a vocabulary that supports global identifiers for items, as defined by that vocabulary’s specification.

itemprop This attribute provides one or more properties to one or more «items».

Although this attribute is optional, if used it must have a value that is an unordered set of unique space-separated tokens that are case-sensitive, representing the names of the name-value pairs that it adds. The attribute’s value must have at least one token. Each token must be one of the following:

  • A valid URL that is an absolute URL, or
  • If the item is a typed item: a «defined property name» allowed in this situation according to the specification that defines the relevant types for the item, or
  • If the item is not a typed item: a string that contains no U+002E FULL STOP characters (.) and no U+003A COLON characters (:).

Also, Specifications that introduce defined property names that are not absolute URLs must ensure all such property names contain no U+002E FULL STOP characters (.), no U+003A COLON characters (:), and no space characters.

itemref This attribute is used in conjunction with the itemscope attribute, the itemref attribute provides a list of additional elements to crawl to find the name-value pairs of the «item». Although the itemref attribute is optional, if specified, it must have a value that is an unordered set of unique space-separated tokens that are case-sensitive, consisting of IDs of elements in the same home subtree. Also, the itemref can only be used on elements that also have the itemscope attribute present.
itemscope HTML5 elements that have the itemscope attribute create a name-value pair called an «item». Elements with an itemscope attribute may also have an itemtype attribute specified, to give the item types of the item.

This is a boolean attribute. If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute’s canonical name, with no leading or trailing whitespace (i.e. either itemscope or itemscope=»itemscope» ).

  • [Empty string]
  • itemscope
itemtype This attribute provides an item type for elements containing the itemscope attribute. The attribute is optional but if it is specified, it must have a value that is an unordered set of unique space-separated tokens that are case-sensitive, each of which is a valid URL that is an absolute URL, and all of which are defined to use the same vocabulary. The attribute’s value must have at least one token.

The itemtype attribute must only be present in elements that include the itemscope attribute.

lang Sets the language code to be used.

[Must be a valid RFC 3066 language code, or an empty string.]

spellcheck Specifies whether the element should have its spelling checked.
Value Description
[Empty string] The element should have its spelling checked.
true The element should have its spelling checked.
false The element should not have its spelling checked.

If this attribute is missing, the element will use the default behavior, possibly based on the parent’s own spellcheck state.

style Specifies inline styles for this element. This allows you to define the styles within the page, and within this tag, as opposed to referring to styles defined elsewhere (such as an external style sheet). Although this can be useful for over-riding external styles, it is usually preferrable to use external styles in conjunction with the class attribute and/or the id attribute.
tabindex Helps determine the tabbing order for this element (for when the user uses the «tab» key on their keyboard to «tab» through the elements on the page in order to select an element).

[Any valid integer. For example, 0, 1, 2, 3, . etc]

title Specifies a title to associate with this particular element. Many browsers will display this when the cursor hovers over the element (similar to a «tool tip»).

[Any text to be displayed as a «tool tip».]

translate Determines whether the element’s attribute values and the values of its Text node children are to be translated when the page is localized, or whether to leave them unchanged.

The translate attribute is an enumerated attribute and may contain the following possible values:

If the translate attribute is provided, but its value is missing or is invalid, the element will inherit its value from its parent element.

Event Handler Content Attributes

The tag also accepts the event handler content attributes listed below.

An event handler content attribute is an attribute for a specific event handler. The name of the content attribute is the same as the name of the event handler.

Event handlers are commonly used to extend the functionality of an HTML element. By using any of the event handler content attributes below, you can tell the browser to run a specific script and when to run it. For example, by using onclick=»» , you tell the browser to run a piece of JavaScript whenever someone clicks on the element. The JavaScript needs to be inserted between the double quotes. This is typically a small piece of JavaScript that simply calls a JavaScript function that has been defined elsewhere.

Here are the event handler content attributes that can be used with the element.

Attribute Description
onabort Invoked when an event has been aborted. For example, the browser stops fetching media data before it is completely downloaded.
onblur User has left the focus of the element.
oncancel cancel event handler.
oncanplay Invoked when the browser/user agent can start playing media, but hasn’t yet, due to buffering. In other words, if playback were to begin now, it wouldn’t play right to the end (due to the current playback rate) — it would need to pause during playback in order to load the rest of the media.
oncanplaythrough The browser/user agent estimates that if playback were to begin now, the media resource could be rendered at the current playback rate all the way to its end without having to stop for further buffering.
onchange User has changed the object, then attempts to leave that field (i.e. clicks elsewhere).
onclick Invoked when the user clicked on the object.
onclose close event handler.
oncontextmenu Invoked when a context menu has been triggered.
oncuechange cuechange event handler.
ondblclick Invoked when the user clicked twice on the object.
ondrag Invoked when an element is being dragged.
ondragend Invoked when an element has stopped being dragged.
ondragenter Invoked when an element has been dragged to a drop target.
ondragexit dragexit event handler.
ondragleave Invoked when an element leaves a valid drop target.
ondragover Invoked when an element is being dragged over a valid drop target.
ondragstart Invoked when a drag operation has started.
ondrop Invoked when an element is being dropped.
ondurationchange Invoked when the length of the media is changed (i.e. the duration attribute has just been updated).
onemptied Invoked when a media resource element suddenly becomes empty (for example, due to a network error).
onended Invoked when the media has reached the end.
onerror Invoked when an error occurs while the element is being loaded. Also handler for script error notifications.
onfocus Invoked when the focus is on the element.
oninput input event handler.
oninvalid invalid event handler.
onkeydown Invoked when a key was pressed over an element.
onkeypress Invoked when a key was pressed over an element then released.
onkeyup Invoked when a key was released over an element.
onload The element has loaded.
onloadeddata Invoked when the browser/user agent can render the media data at the current playback position for the first time.
onloadedmetadata Invoked when the browser/user agent has just determined the duration and dimensions of the media resource.
onloadstart Invoked when the browser/user agent has started loading the media resource.
onmousedown The cursor moved over the object and mouse/pointing device was pressed down.
onmousemove The cursor moved while hovering over an object.
onmouseout The cursor moved off the object
onmouseover The cursor moved over the object (i.e. user hovers the mouse over the object).
onmouseup The mouse/pointing device was released after being pressed down.
onmousewheel Invoked when the mouse wheel is being rotated.
onpause Invoked when the media resource has been paused.
onplay Invoked when the media resource starts playback.
onplaying Playback has begun.
onprogress The browser/user agent is fetching media data the.
onratechange Invoked when the playback rate has changed (i.e. either the defaultPlaybackRate or the playbackRate has just been updated).
onreset reset event handler.
onresize resize event handler.
onscroll scroll event handler. Invoked when the element’s scrollbar is being scrolled.
onseeked Invoked when the seeking IDL attribute changed to false (i.e. the seeking attribute is no longer true)
onseeking Invoked when the seeking IDL attribute changed to true and the seek operation is taking long enough that the user agent has time to fire the event.
onselect Invoked when some or all of the contents of an object is selected. For example, the user selected some text within a text field.
onshow show event handler.
onstalled Invoked when the browser/user agent is trying to fetch media data but the data has stalled (i.e. the data has stopped coming).
onsubmit User submitted a form.
onsuspend The browser/user agent is (intentionally) not currently fetching media data, but has not yet downloaded the entire media resource (i.e. it has suspended the download).
ontimeupdate Invoked when the media’s current playback position changed.
onvolumechange Invoked when either the volume attribute or the muted attribute has changed.
onwaiting The next frame of the media is not yet available (but the browser/user agent expects it to become available).

More Information About the Element

Content Categories None.
Can be used As the first or last child of a element.
Content model Flow content.
End Tag Required? Yes. Any time you use the element, it must have both a start tag and an end tag.
  • Right:
  • Wrong:
DOM Interface HTMLElement

Specifications for the Tag

Here is the element defined in the various specifications:

HTML figcaption Tag

HTML tag represents a caption text corresponding with a element. The figure element hold image, diagram, illustration, code snippet, etc.

HTML tag introduce in HTML5.

Example

Tag Attributes

HTML tag does not support any specific attributes.

Global Attributes

HTML tag support following global attributes.


Attributes Value Description
id unique_name Declared unique id for an element.
class class_name Declared one or more classnames for an element.
style styles CSS inline styles specify an element.
title title Specify extra details of element contain, this will display as a «tooltip» for an elements.

Event Attributes

HTML tag support following event attributes.

HTML5 Doctor

Helping you implement HTML5 today

The figure & figcaption elements

In traditional printed material like books and magazines, an image, chart, or code example would be accompanied by a caption. Before now, we didn’t have a way of semantically marking up this sort of content directly in our HTML , instead resorting to CSS class names. HTML 5 hopes to solve that problem by introducing the and elements. Let’s explore!

The element

The element is intended to be used in conjunction with the element to mark up diagrams, illustrations, photos, and code examples (among other things). The spec says this about :

The figure element represents a unit of content, optionally with a caption, that is self-contained, that is typically referenced as a single unit from the main flow of the document, and that can be moved away from the main flow of the document without affecting the document’s meaning.

The element

The element has been the subject of much debate. The spec initially wanted to repurpose rather than introduce a new element. Other suggestions included , ,

elements. was changed, so we then used a combination of and inside at Jeremy’s suggestion. Most of these suggestions failed since there was no backwards compatibility for styling with CSS .

Regular readers will know that a new element was recently introduced, namely . Who knows if it’ll stick, but for now here’s what the spec says about :

The figcaption element represents a caption or legend for a figure.

The element is optional and can appear before or after the content within the . Only one element may be nested within a , although the element itself may contain multiple other child elements (e.g., or ).

Using and

So we’ve seen what the spec says about these elements. How do we use them? Let’s look at some examples.

Figure with an image

An image within a element without a caption:

Here’s the code for that:

Figure with an image and caption

An image within a element with an explanatory caption:

A cheeky macaque, Lower Kintaganban River, Borneo. Original by Richard Clark

and the code that we used:

A figure with multiple images

Nesting multiple images within one element with a single caption:

Australian Birds. From left to right, Kookburra, Pelican and Rainbow Lorikeet.
Originals by Richard Clark

Figure with a code block

The element may also be used for code examples:

Here’s the code for that:

Differences between and

Having said that, if its position relates to previous and subsequent content, use a more appropriate element — e.g., a

, or possibly even , depending on its content.

Don’t stop there!

No need to constrain your s to images and code examples. Other content suitable for use in includes audio, video, charts (perhaps using or ), poems, or tables of statistics.

It may not always be appropriate to use the element, though. For example, a graphic banner should not be marked up with . Instead, simply use the element.

Summary

As we’ve illustrated in this article, there are a lot of possibilities for the element. Just remember to make sure it’s the most appropriate element for the job. But you already do that for all your markup, right? :)

Category

Richard Clark

This article was written by Richard Clark . Richard is Head of Interactive at KMP Digitata, a digital agency based in Manchester, UK. Co-author of Beginning HTML5 and CSS3: The Web Evolved. He runs a host of websites including this one and its sister site html5gallery. Another side project is Speak the Web, a series of small gig style web conferences. You should follow him on twitter or check out his site.

125 Responses on the article “The figure & figcaption elements”

[…] The figure & figcaption elements | HTML5 Doctor […]


Before I resorted to using a div->image with a div->caption nested inside to express these kind of structures. The figure element will remove the need for the somewhat silly image class. Definite improvement for quotes too.

It does impose some extra difficulties with wysiwyg editors and such, as I would suggest using the figure element for every image that could have a caption (future-proof coding and such!).

I would think, from an accessibility point of view, that for the second example, that you would leave the alt attribute blank because it’s essentially providing the same content as the figcaption – no need for people listening to the page, or browsing without images to get the same piece of content twice.

@John, good point yeah. I’ll try and check the guidelines on that.

For what it’s worth, I disagree with John Faulds. The caption should provide informationaugmenting the photograph. The alt should provide equivalent content to the photograph. For photographs like the second example, appropriate alt text is a description on what one can see in the photograph. They really shouldn’t amount to the same text, and indeed don’t in the actual example given.

Regardless of whether the two in that example are actually the same, I’d still argue that the content of the alt attribute is redundant; the only piece of info contained in the alt that’s not in the caption is that it is in the trees. So if it’s not an issue of accessibility, it is one about good copywriting.

But I also disagree that a caption’s sole purpose is to augment, rather it should describe first and then augment if required. I can think of lots of examples where the caption is simply describing, e.g. a headshot with the person’s name underneath – no augmentation there, and I believe the majority of captions won’t include any augmentation.

Thanks for this awesome post. just hoping every browser starts supporting html5 and people move into them. ;)

[…] The Figure & Figcaption Elements […]

Completely agree with John Faulds. The alt should be filled if the redundancy between figcaption and alt can be avoided. There are plenty of examples where the captions are depicting a figure and where these textual informations are required for readers/viewers, even those with a regular browser (mean, not a screen reader). In those cases, the alt is often redundant with the (fig)caption.

Alohci is right when he/she says that a visual description of the image is to be provided within the alt. This macaque is in a tree. Is he hiding in the leaves ? looking at a female ? eating sandwiches ? Which information must be provided in a alt attribute is a matter of scope, of overall meaning.

I’ve been brought up nice, so don’t like to over-burden a user with “too much accessibility”. So I don’t think that having alt plus a caption that are pretty much the same helps anyone.

It seems to me that the question should be “what’s better for the user?” and the answer is “it depends”, because those pesky blind users will insist on not being an homogenous mass.

So some blind users will be fine to know that figure X is a picture of a monkey, or the CEO of Blammo Corp. Others will want to know whether the monkey is juvenile or mature, and what colour hair the CEO has.

I favour brevity and reducing repeitiion. So, a picture of the CEO of Blammo Corp leveraging a synergy in a news piece *probably* doesn’t need alt text to tell us that he’s 55 years old, with brown hair, a pinstripe suit.

But I might be a horrible fascist, chuckling as I place my foot on the throat of visually-impaired children; I lose track these days.

[…] our article on the and elements for […]

…or at least that’s the impression I’ve got :)

Oli, you’re right. The question remains: does every image need description? In my opinion (and the opinion of some but not all blind friends), the answer is “no”.

I agree. The spec says “The intent is that replacing every image with the text of its alt attribute not change the meaning of the page,” and that’s a good rule of thumb.

Here’s what I’ve got from the spec: if the image has a function, describe this function. If it provides useful information, then make sure that info is also accessible. If the image is purely decoration use alt=»» . If the image is described adequately in (such that adding alt text wouldn’t convey extra info, or would be repetitive), then alt=»» is fine there too. But above all else think about how the page would read with images turned off, and make sure it reads well.

Finally remember there’s no such thing as perfect accessibility, so just do the best you can.

2010-06-16 edited for clarity

Oli, I think that’s just about spot on. And thanks Bruce for your thoughts.

If the image is described adequately in (such that adding alt text wouldn’t convey extra info, or would be repetitive), then alt=”” is fine there too.

My first thought. But apparently, alt=”” carries an implied ARIA role=”presentational” and, if the figure needs a caption it presumably isn’t presentational. So it should have no alt attribute at all, apparently.

Not sure how I feel about that.

@Bruce. The problem with omitting the alt attribute altogether is , as I understand it, that AT will attempt to “repair” the missing alt text, which really isn’t what is wanted if the image is described adequately elsewhere on the page.

I’m not wholly conf >

I noticed in your examples that the figures are preceded by paragraphs that introduce them. For example the line:

Nesting multiple images within one element with a single caption:

is then followed by a element. And yet the spec says that the is to be used for content that can be moved away into an appendix. Does the use of in this context meet that criteria?

@Christian — yes, as presumably the removed figure would be replaced by a link if done automatically. Also notice the word “can” — it is indeed content that could be moved. Ideally we’d be all literary-like and have (see Figure 1-12) and stuff, but hopefully you’ll forgive us for our lack of highfalootin’ ;-)

[…] Figure 和 Figcaption 元素 […]

[…] Figure 和 caption 元素 […]

[…] Figure 和 caption 元素 […]

[…] example check out this article about the new “figure” and “figcaption” […]

[…] Figure 和 caption 元素 […]

[…] Figure 和 caption 元素 […]

[…] The Figure & Figcaption Elements […]

question… I’m working through Bruce and Remy’s book, and I’ve come to this wonderful new structure, however it won’t seem to work. My visual Studio environment is allowing for and giving feedback on the figure tag, but not the figcaption element (which to me is the cool part of the whole thing). Chrome has been rendering all of the other things in the book delightfully, but not this. suggestions?

@Jenny — Check your source in Chrome (View > Developer > View Source) and make sure that figcaption is there. If it is try adding figcaption , or adding figcaption to the handful of HTML5 elements you declare as display: block . However I suspect that Visual Studio is the problem, so try a quick test in Notepad, and if so check for an update for Virtual Studio, or ask when they will add it.

@Jenny, seems odd that you can use some new elements but not others. Personally I don’t use visual studio, but while the intellisense might not work so long as you’re losing Remy’s shiv every browser will ‘understand’ the new elements.


It was a good idea to add the element to the display:block section in my css, and I made sure to add the Sharp Shiv. Now it does show the text of the figcaption, though a bit disappointingly. Upon taking a closer look at the photo that Bruce’s mum snapped, I see that there is some css3 blingery involved. It looks good. Must be nice to be good looking AND talented!

@Jenny — Aah, if you haven’t added display:block yet you really should have:

Also, while Bruce’s mum thanks you for complementing her photography, she apologies for the photo’s subject — sadly her son didn’t inherit her good looks ;)

I expect that it would be nice to be good-looking and talented. Or even to have just one of those two attributes.

Would wrapping the site logo be an appropriate use?

[…] Figure 和 caption 元素 […]

@Shelomo no, for that you should use the hgroup element or simply an image with text replacement. Figures are primarily for images/quotes/code etc that are referenced in the text.

How about avatars in comment, does it need to be in figure?

@Ramil — probably not, as in general just an image would be fine. If you wanted to have the commenter’s name in a then it’d work…

[…] Figure 和 caption 元素 […]

I’m happy using figure in the context of your examples (images, code etc) but would I be pushing it to mark up links to documents where the front cover is the image and the book title is the caption (with one or both as links)? I ask because we have content authors who use tables to achieve a “gallery” of publications and I really want to eliminate this behaviour by incorporating it into a page edit screen. I’m pretty sure using a group of figures is fine (enclosed by perhaps?) and would allow for a flexible CMS template gallery section (with regards to final content).

Cheers and Happy New Year!

Figure is intended to be used for images/quotes/code samples etc that are referenced from a main article but can be moved away in the source.

To answer your question, I wouldn’t really be using it for the page you describe (sounds similar to Amazon if I’ve interpreted correctly) each book could be within an article sure but I would just have a heading & image within that. E.g.

[article]
[a href=”fullpage.html”]
[h2]Book Title[/h2]
[img src=”mybook.png” alt=”Book title”]
[p]Description[/p]
[/a]
[/article]

Basically you’re not really referencing the image within the article so I wouldn’t use figure.

If you’re unsure about which element to choose, try our flowchart.

My specific use case here is author-generated content with a list of closely-related documents for download. Traditionally, the author adds the documents to the “resource gallery” (to use a CMS term) and then links to them in an unordered list (if you’re lucky). Otherwise it’s a paragraph or line breaks per link. If the author has images of the front pages (the document is a pamphlet or report) they’ll create a table to layout the images and links which even if it’s a very simple structure can still cause problems for a screen reader (remembering that authors are not crafting raw HTML).

I was thinking it would be clever to capture what downloads are associated to the content in the page edit screen and then get the template to put those documents into a consistent markup structure with the front page as an image. Happy with using for this but wanted to explore “etc” from your flowchart (got it from @media, thx!) and this article.

[…] Figure 和 caption 元素 […]

[…] The Figure & Figcaption Elements […]

[…] HTML5 ninjas, we know that we’ll hang any picture and a attendant heading within figure and figcaption elements – though what will we hang a whole organisation of outmost links […]

[…] can read more about the and elements and see some examples on HTML Doctor’s […]

[…] &#1089&#1072n read more &#1072b&#959&#965t th&#1077 &#1072nd elements &#1072nd see &#1109&#959m&#1077 examples &#959n HTML Doctor’s […]

[…] can read more about the and elements and see some examples on HTML Doctor’s […]

[…] Well now lets go through our html5 code. As you can see I have used figure tag which has an optional figcaption tag of html5 in my code which is very helpful for sematics. You can check detailed explanation of figure and figcaption on html5doctor. […]

figcaption can’t content with h1

Currently with XHTML 4.x and CSS 2.x In order to have a caption be right justified with an image (like the way your ‘Submit Comment’ button lines up with the right side of the ‘Enter Comment’ box) , the following conditions need to be met:

1. The image&caption or containing box have to have a width property declared in a style sheet or inline.

With the html5 ‘figure’ tag and figcaption tag is there any inherent capability in these tags that would allow image&caption alignment without having to meet criteria 1?

If you have multiple sized images that you want centered in a containing element but want the caption to be right (or left) justified with the varying image sizes will you STILL have to have a width declared?

Or a better question may be:
Is the only inherent value of these new tags their allowance of more semantic mark up?

When I use and inside a column, it messes up the column – it either breaks it up or it reverts back to a column-ness page.

[…] The Figure & Figcaption Elements […]

Would you be creating any semantic faux pas by wrapping in a , or tag?

Sorry…was meant to read:

Would you be creating any semantic faux pas by wrapping figcaption in a ‘p’, ‘span’ or ‘div’ tag?

What if I have list of special offers where each offer has an image, do I need to use figure?

Is there a way to have multiple s with on one row? When ever I put the and around an image, it puts each image on its own line. I’d like to force it all to be in one line.

Any idea if a figcaption can have nested elements? I tried searching google and they claim you’re the authority on the subject!

[figure]
[img]
[figcaption]
[h2]Title[/h2]
[p]Some text.[/p]
[/figure]

and etc.

Could figure and figcaption be correctly used to display a post thumbnail and the title and/or excerpt as the figcaption. For instance a portfolio page whereby an individual item would look something like the following:

Title


Excerpt content here.

I am sure that this will work, but would it be correct semantically? Or is div – img – h2 – p a more appropriate solution?

That’s what I’m wondering, too, Shawn. If other tags are allowed within the figcaption tag…not a lot of info on the web about that guy just yet.

@Shawn — sure, that’s valid (ref my reply to Nathan above), but if the images are your main content I think in this case not using is better. Remember the “can be moved away from the main flow of the document without affecting the document’s meaning” bit in the spec quote at the start of this article.

For me is appropriate if a mobile browser could replace your s with a “See figure 3” etc link (to save on bandwidth), and the page still works.

[…] code is a neat bit of HTML5, using the shim. One bit of interest was the use of the figure and figurecaption tags, which I haven’t seen used in a production environment […]

just to get my head around it: what is the point of having an image inside a figure without giving it a caption.

Thank you for your nice work!

Thank you for the explanation of figure and figcaption!

What if the image gallery is the main content? Will it still be valid to use figure? It seems very logical to do so, but is it (technically speaking) semantically correct?

I love that this code works. However, my issue is; I am placing images in a row and I can not for the life of me figure out how to give each image it’s own caption without misplacing the order of the images. Every time I try to add a caption to the other images in the row, after adding the caption to the first image, the next image will pop below the first:(

Can anyone figure out what I need to do?

Thank You All in advance:)

[…] image is going to be contained within an HTML5 figure element, but wrapped directly by an anchor in order to link it with something (either a lightbox enlarged […]

Thanks for this explanation, nice and easy.

I have a gallery page.
Should I use figure for pictures that link to external pages?

If yes, then which one is more correct:

Thanks in advance

I don’t think it matters. I’d probably use the link inside the figure as I imagine it would be easier to style. Let us know how it goes!

Thanks for reply, bruce. I agree that styling may be easier with the link inside.. Probably you’re right and link should be inside the figure element in such cases.
I just thought and got to conclusion that images in my gallery are the main content, so maybe it’s not correct to use figure at all.. Maybe it should be just:

Oops.. forgot to encode:

@Sergey – You’re probably right that you don’t need figure at all, but note that of your two options using figure, the first (link inside figure) is invalid in HTML5. figcaption (not figcapture) must be the direct child of figure.

@Alohci – that’s right! I didn’t think about it. Thanks!

@alcohi thanks for pointing that out – I’d forgotten that figcaption must be the direct child of figure.

I’m hanging up my stethoscope in shame.

It’s even more fun — “Contexts in which this element can be used: As the first or last child of a figure element”.

Re: Alt vs. figcaption:

Using the “CEO of Blammo Corp” example.

My vote’s for the alt saying something like “Mugshot”; the figcaption should then be “John Doe, CEO of Blammo Corp.”.

The alt should describe what the photo is… Alt !== caption. :D

Many many thank you for the explanation of figure and figcaption!

Jessica, by default your browser is rending the figure tag as a block-level element. To keep your images from dropping to their own line style the figure tag with display: inline-block.

which one is correct?

hoko, it depends. The first one makes one thing a link inside a figure. The second makes the whole figure a link.

so, both are semantic?

Either may be correct but it’s impossible to know which is correct as I don’t know what your content is, or what you want to do

Is it right if I use figcaption outside the figure tag?

vladimir – no. figcaption is to caption a figure, so it can’t be outside the figure.

Ahh I got. I supposed so – it loses the context other way – many thanks

Some of the article pages I’m designing for a project have an embedded photos gallery instead of a single photo – what’s the most semantic way to mark this up?

Thanks for the info. I wonder if fgcaption will survive the test of time.

should pinterest.com’s blocks of images and captions then be in and tags?

@Johan, I think that they shouldn’t, because those units are the main content of the page. However I may be wrong so am also excited to hear opinions of others.

@Sergey – or maybe they could be article tags?


@Johan, agree on article tags

I like the figure and figcaption, if for one reason, it lets me get the description underneath the figure. However, I can not find a way (without using CSS, to get the text to run around the by using or right? Any ideas?

[…] am a big believer in semantic markup, so we will be using the HTML5 figure and figcaption tags for increased context. Even if none of your users are browsing with a screenreader or other assistive device, descriptive […]

Yes, the feature in html5 is great, but it seems that few sites and blogs are using, here in Brazil (where I live), for example, few, if not none, blogs and websites use this feature and think it should use more, I always use this tag on my blogs and projects, trying to make the site more semantic as possible.

I was going to ask about the same question as @Dinis Correia did. Does anybody know the answer?

Well, the clearest example for me is simply thinking about math books and miscellaneous papers: in those, ecuations, theorems, code snippets and graphs, among others, are clearly defined and referenced several times throughout the document.

I am wondering is it proper to put wrapping divs for each of serveral thumbs inside the figure tag (like in the example code below)?

Or is there any more appropriate/simpler way to combine both html5 semantics and good styling of thumbs img elements?

Thank you in advance for any information.

Can there be a header/footer inside the figcaption?

why would you want to do that?

Is it possible to do 3 (or more) images side by side with different captions centered underneath each image and all center on the page?

Yes, just use 3 figure elements, each with a figcaption. Then use CSS to position them as you wish.

Ok thanks, but may I ask how is this any different then just using DIVS and setting the CSS as you said?

What about for use with comments and/or a commenting system? Seems like they could be essential to the content, but position is unrelated.

Hi, one quick question. Inside figure element, is it allowed to do add other element like div?

@Bobby: Generally speaking, “yes”, you can put most elements inside a figure element. But of course, you should do your best to respect the rules regarding what type of content is suitable to be put inside a figure element, as described in the spec:

The figure element represents some flow content, optionally with a caption, that is self-contained (like a complete sentence) and is typically referenced as a single unit from the main flow of the document.

@Andreas, thank you for your reply.

So basically I am building image gallery, each image has its own figure tag and social widget. I was about to put social widget inside figcaption but I’m sure social widget doesn’t belong in figcaption.

Content model:
Either: One figcaption element followed by flow content.
Or: Flow content followed by one figcaption element.
Or: Flow content.

so apparently the figcaption element (if present) has to be the first or the last child of the figure element.

That would make your example invalid.

Anyhow, the spec. doesn’t say anything about UI controls (like your ‘social widgets’). It’s actually a very good question. Personally I feel that the requirement of the content model is a bit too strict (why only first or last?), and I don’t see any major reason not to allow UI controls if appropriate, like in your case.

If you’re lucky, you might actually get a normative response here from Steve Faulkner, W3C HTML5 editor.

@Andreas, ah I see. I can tolerate about the figcaption position. With a little CSS will do the trick. Anyway your respond has enlighten me, Thanks!

Bobby: Just let me add this: the way the spec. is written at the moment, I think you should not add UI controls at all if you want to follow the spec. strictly. After all, as you say, it is semantically dubious to put them in the caption. But it is equally dubious to put them outside the caption, because

The figcaption element represents a caption or legend for the rest of the contents of the figcaption element’s parent figure element, if any.

so then the caption would also describe the UI controls…

Personally, I am vey much into “hypertext documents” as opposed to “hypertext appliactions“, so I kind of like the strict semantics. Still, HTML5 is not only about documents, and even in documents, I can see the benefit of putting UI controls in a figure (show fullscreen, copy to clipboard, etc.), BUT I would prefer these to be features integrated in the browser.

Anyhow, your example shows there might actually be an occasional need to add custom UI controls to a figure. To me, a new element like figcontrols would make sense, but I don’t think that will happen. So the question remains: what should you do? It is a good question, but I don’t think there is a perfect answer according to the current spec.

How to display ‘figure’ elements side by side? without enclosing in any other elements. Please…

So this is nothing to be confused with in HTML. I thought it was alternate way to address images. But now you have made it clear that it has some uses in image gallery setup in a website.

Lets say I want to markup bird pictures each within a figure element, can I also include and audio tag of the bird’s call and If so, where? In the Caption?

I find the concept of an image being ‘essential’ very vague. When is a picture essential?
the more I think about it the more I get confused. Isn’t a picture always essential except when it is a filler or presentational (in which case they should be placed in a css background, not an img).
Example: when writing a blogpost about a home project, placing a picture of the end result, is that an essential picture?
I can guess the picture of a t-shirt on a webshop site is essential, but what about a picture of a usb-cable on the same site? Is it really essential to show a usb cable (most people know what it looks like and is not really essential to know what the product looks like). But if a t-shirt is essential and a usb-cable is not, then using figure seems arbitrary from a design point of view (think about standard product html templates). Then do I need one template for products with essential pictures and one without?
I am getting a headache.

If the content is simply related and not essential, use

I know this is an old post and that much of discussion has passed but I wanted to chime in. John Faulds is wrong in a major way.

To apply his rational to someone with sight the image is not necessary since we have the caption. That is 100% incorrect. The alt attribute and the figure should not have the same content. The alt attribute is almost always poorly written for screen readers providing bad UX. In example #2 it reads “Macaque in the trees.” It should read something like, “A Macaque monkey resting in the trees looking down through the foliage.” It should be very descriptive. It should be the auditory equivalent of the image. Then the caption gives you context by which the image should then be placed. In example two it gives us the location — something neither sighted nor the blind could tell, and the photographer.

Don’t discount the blind just because the example, and just bout 100% of web sites, use alt incorrectly.

Thanks you for the post. I didn’t know that HTML5 had builtin support for this!

[…] classes or ids to give images with img tag their captions. In this tutorial we are going to use HTML5 figure and figcaption elements to give the image its caption and animate it using […]

[sorry, I forgot about the special characters for brackets]

Can someone tell me if the it is appropriate to use multiple tags in an image gallery and if the code below is correct:

So I have a html5 page, there is an article and there is a gallery, is the code above semantically correct?

So I have a html5 page, there is an article and there is a gallery, is the code above semantically correct?

The theme of each section should be identified, typically by including a heading (h1-h6 element) as a child of the section element.

You introduced your figures with text like ‘An image within a element with an explanatory caption:’.

This is my preferred way of introducing pictures, tables and lists, because it demonstrates the basic principle of context before content, so that the reader knows what to look for in the content, rather than being left up to their own predilections.

I think that the table and list elements should allow a p element as an introduction, as can be done with the figure element.

For a picture, the figcaption element presents an opportunity to put something like a quote, for a portrait, or some other aspect of the subject.

Понравилась статья? Поделиться с друзьями:
Кодинг, CSS и SQL