Html table caption title

HTML таблицы продвинутые возможности и доступность

Во второй статье этого модуля мы рассматриваем ещё несколько продвинутых возможностей в HTML таблицах — такие как заголовок/описание и группировка строк внутри head, body и footer секциях таблицы, а также доступность таблиц для пользователей с ограниченными возможностями.

Необходимые знания: Базовый HTML (Введение в HTML).
Цель: Изучить более продвинутые возможности HTML таблиц и их доступность.

Добавление заголовка к таблице с помощью

table> caption>Dinosaurs in the Jurassic periodcaption> . table> 

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

Упражнение: Добавление заголовка

Давайте попробуем это, вернёмся к примеру который мы ранее встретили в прошлой статье.

  1. Откройте расписание занятий школьного учителя по языку в конце статьи HTML таблицы основы, или сделайте копию нашего timetable-fixed.html файла.
  2. Добавьте подходящий заголовок к таблице.
  3. Сохраните свой код и откройте его в браузере, чтобы посмотреть как это выглядит.

Примечание: Этот пример можно найти на GitHub по ссылке timetable-caption.html (живой пример).

Добавление структуры с помощью , и

Когда таблицы становятся более сложными по структуре полезно дать им более структурированное определение. Отличный способ сделать это используя (en-US), и (en-US), которые позволяют вам разметить header, footer и body секции таблицы.

Эти элементы не создают дополнительной доступности для пользователей со скринридерами и не приводят к какому-то визуальному улучшению при их использовании. Зато они очень полезны при стилизации и разметке, как точки для добавления CSS к вашей таблице. Вот несколько интересных примеров, в случае длинной таблицы вы можете сделать header и footer таблицы повторяемый на каждой печатной странице, или вы можете сделать body таблицы отображаемое на одной странице и иметь доступ ко всему содержимому контенту прокручивая вверх и вниз.

  • Элементом нужно обернуть часть таблицы которая относится к заголовку — обычно это первая строка содержащая заголовки колонок, но это не обязательно всегда такой случай. Если вы используете / (en-US) элемент, тогда заголовок должен находиться ниже его.
  • Элементом нужно обернуть ту часть, которая относится к footer таблицы — например, это может быть последняя строка в которой отражаются суммы по столбцам таблицы. Вы можете включить сюда footer таблицы, как и следовало ожидать, или чуть ниже заголовка таблицы (браузер всё равно отобразит его внизу таблицы).
  • Элементом необходимо обернуть остальную часть содержимого таблицы которая не находится в header или footer таблицы. Этот блок располагают ниже заголовка таблицы или иногда footer таблицы, зависит от того какую структуру вы решите использовать (читать выше по тексту).

Примечание: всегда включён в каждой таблице, неявно если не укажете его в коде. Проверьте это, открыв один из предыдущих примеров в котором не используется и посмотрите HTML код в browser developer tools — вы увидите, что браузер добавил этот тег самостоятельно. Вы могли бы задаться вопросом почему мы должны волноваться о его включении, но вы должны, потому что это даёт больше контроля над структурой таблицы и стилем.

Упражнение: Добавление структуры таблицы

Давайте используем эти новые элементы.

  1. В первую очередь, сделайте копию spending-record.html и minimal-table.css в новой папке.
  2. Попробуйте открыть это в браузере — вы увидите, что все выглядит классно, но могло бы быть лучше. Строка «SUM» которая содержит потраченные суммы кажется находится не в том месте и некоторые детали отсутствуют в коде.
  3. Поместите очевидную строку заголовка внутрь элемента, строку «SUM» внутрь элемента и оставшийся контент внутрь элемента.
  4. Сохраните, перезагрузите и вы увидите, что добавление элемента привело к тому, что строка «SUM» опустилась к нижней части таблицы.
  5. Далее, добавьте атрибут colspan , чтобы ячейка «SUM» занимала первые четыре столбца, таким образом числовое значение «Cost» появится в последнем столбце.
  6. Давайте добавим несколько простых дополнительных стилей к таблице, чтобы дать вам представление насколько эти элементы полезны при использовании CSS. Внутри в вашего HTML документа вы увидите пустой элемент . Внутри этого элемента добавьте следующие строки CSS кода:
tbody  font-size: 90%; font-style: italic; > tfoot  font-weight: bold; > 

Примечание: Мы не ожидаем что сейчас вы полностью поймёте CSS. Вы узнаете больше когда пройдёте наши CSS курсы (например, Вступление в CSS это хорошее место для начала; у нас также есть статья конкретно о стилизации таблиц).

Ваша готовая таблица должна выглядеть примерно так:

DOCTYPE html> html> head> meta charset="utf-8"> title>My spending recordtitle> style> html  font-family: sans-serif; > table  border-collapse: collapse; border: 2px solid rgb(200,200,200); letter-spacing: 1px; font-size: 0.8rem; > td, th  border: 1px solid rgb(190,190,190); padding: 10px 20px; > th  background-color: rgb(235,235,235); > td  text-align: center; > tr:nth-child(even) td  background-color: rgb(250,250,250); > tr:nth-child(odd) td  background-color: rgb(245,245,245); > caption  padding: 10px; > tbody  font-size: 90%; font-style: italic; > tfoot  font-weight: bold; > style> head> body> table> caption>How I chose to spend my moneycaption> thead> tr> th>Purchaseth> th>Locationth> th>Dateth> th>Evaluationth> th>Cost (€)th> tr> thead> tfoot> tr> td colspan="4">SUMtd> td>118td> tr> tfoot> tbody> tr> td>Haircuttd> td>Hairdressertd> td>12/09td> td>Great ideatd> td>30td> tr> tr> td>Lasagnatd> td>Restauranttd> td>12/09td> td>Regretstd> td>18td> tr> tr> td>Shoestd> td>Shoeshoptd> td>13/09td> td>Big regretstd> td>65td> tr> tr> td>Toothpastetd> td>Supermarkettd> td>13/09td> td>Goodtd> td>5td> tr> tbody> table> body> html> 

Примечание: Этот пример можно также найти на GitHub по ссылке spending-record-finished.html (живой пример).

Источник

: The Table Caption element

The HTML element specifies the caption (or title) of a table.

Try it

Attributes

This element includes the global attributes.

Deprecated attributes

The following attributes are deprecated and should not be used. They are documented below for reference when updating existing code and for historical interest only.

This enumerated attribute indicates how the caption must be aligned with respect to the table. It may have one of the following values:

The caption is displayed to the left of the table.

The caption is displayed above the table.

The caption is displayed to the right of the table.

The caption is displayed below the table.

Warning: Do not use this attribute, as it has been deprecated. The element should be styled using the CSS properties caption-side and text-align .

Usage notes

If used, the element must be the first child of its parent element.

A background-color on the table will not include the caption. Add a background-color to the element as well if you want the same color to be behind both.

Example

This simple example presents a table that includes a caption.

table> caption> Example Caption caption> tr> th>Loginth> th>Emailth> tr> tr> td>user1td> td>user1@sample.comtd> tr> tr> td>user2td> td>user2@sample.comtd> tr> table> 
caption  caption-side: top; > table  border-collapse: collapse; border-spacing: 0px; > table, th, td  border: 1px solid black; > 

Technical summary

Content categories None.
Permitted content Flow content.
Tag omission The end tag can be omitted if the element is not immediately followed by ASCII whitespace or a comment.
Permitted parents A element, as its first descendant.
Implicit ARIA role caption
Permitted ARIA roles No role permitted
DOM interface HTMLTableCaptionElement

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 13, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

caption HTML Table Tag

Table captions are usually just plain text, but we can also add images and other tags, if necessay, as demonstrated below.

   src="/images/demo-icon.png" alt="demo"> Price List   Model 3 $42,900   Model Y $54,990    

Caption Styles

By default, a table caption will be aligned to the center, above the table, outside the borders. We can use the text-align and caption-side CSS properties to overwrite the default placement.

Aligning the caption text to the right

 class="demo">  style="text-align:right"> January  Name Salary   John $500   

Displaying the caption at the bottom of the table

 class="demo">  style="caption-side:bottom"> Transferred  Name Salary   Jade $900   

Table Captions Generator

The online interactive table generator and styler below doens’t have the option to add captions. Please add them manually to your code.

Источник

HTML Tag

By default, a table caption is center-aligned above a table. But it is possible to use the text-align and caption-side properties to align and place the caption.

Syntax

The

tag comes in pairs. The content is written between the opening ( ) and closing (

) tags.

Example of the HTML tag:

html> html> head> title>Title of the document title> head> body> table width="400" border="1"> caption>Evaluation paper caption> thead> tr> th>Student th> th>1st exam th> th>2nd exam th> tr> thead> tbody> tr> td>John Johnson td> td>75 td> td>65 td> tr> tr> td>Mary Nicolson td> td>55 td> td>80 td> tr> tr> td>Max Thomson td> td>60 td> td>47 td> tr> tbody> table> body> html>

Result

Evaluation paper

Student 1st exam 2nd exam
John Johnson 75 65
Mary Nicolson 55 80
Max Thomson 60 47

Example of the HTML tag with the CSS caption-side property:

html> html> head> title>Title of the document title> style> caption < background: #1c87c9; color: #fff; caption-side: bottom; > table, th, td < border: 1px solid #1c87c9; padding: 3px; > td < background-color: #cccccc; color: #666666; > style> head> body> h2>Caption-side property example h2> p>Here the caption-side is set to "bottom": p> table> caption>Some title here caption> tr> td>Some text td> td>Some text td> tr> table> body> html>

Attributes

Attribute Value Description
align Aligns the header horizontally.
Not used in HTML5.
right the header is placed on top and aligned to the right.
left the header is placed on top and aligned to the left.
top the header is placed on top and aligned to the center.
bottom the header is placed below and aligned to the center.

How to style tag?

Common properties to alter the visual weight/emphasis/size of text in tag:

  • CSS font-style property sets the style of the font. normal | italic | oblique | initial | inherit.
  • CSS font-family property specifies a prioritized list of one or more font family names and/or generic family names for the selected element.
  • CSS font-size property sets the size of the font.
  • CSS font-weight property defines whether the font should be bold or thick.
  • CSS text-transform property controls text case and capitalization.
  • CSS text-decoration property specifies the decoration added to text, and is a shorthand property for text-decoration-line, text-decoration-color, text-decoration-style.

Coloring text in tag:

  • CSS color property describes the color of the text content and text decorations.
  • CSS background-color property sets the background color of an element.

Text layout styles for tag:

  • CSS text-indent property specifies the indentation of the first line in a text block.
  • CSS text-overflow property specifies how overflowed content that is not displayed should be signalled to the user.
  • CSS white-space property specifies how white-space inside an element is handled.
  • CSS word-break property specifies where the lines should be broken.

Other properties worth looking at for tag:

  • CSS text-shadow property adds shadow to text.
  • CSS text-align-last property sets the alignment of the last line of the text.
  • CSS line-height property specifies the height of a line.
  • CSS letter-spacing property defines the spaces between letters/characters in a text.
  • CSS word-spacing property sets the spacing between words.

Источник

Читайте также:  Фоновое изображение с помощью HTML
Оцените статью