- : The Generic Section element
- Try it
- Attributes
- Usage notes
- Examples
- Simple usage example
- Before
- After
- Using a section without a heading
- Result
- Technical summary
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Usage notes
- Avoid using multiple elements on one page
- Examples
- All headings
- Example page
- Accessibility concerns
- Navigation
- Nesting
- Labeling section content
- Sectioning content examples
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Как использовать секционные элементы HTML5
- Заключение
: The Generic Section element
The HTML element represents a generic standalone section of a document, which doesn’t have a more specific semantic element to represent it. Sections should always have a heading, with very few exceptions.
Try it
Attributes
This element only includes the global attributes.
Usage notes
As mentioned above, is a generic sectioning element, and should only be used if there isn’t a more specific element to represent it. As an example, a navigation menu should be wrapped in a element, but a list of search results or a map display and its controls don’t have specific elements, and could be put inside a .
Also consider these cases:
- If the contents of the element represent a standalone, atomic unit of content that makes sense syndicated as a standalone piece (e.g. a blog post or blog comment, or a newspaper article), the element would be a better choice.
- If the contents represent useful tangential information that works alongside the main content, but is not directly part of it (like related links, or an author bio), use an .
- If the contents represent the main content area of a document, use .
- If you are only using the element as a styling wrapper, use a instead.
To reiterate, each should be identified, typically by including a heading (h1 — h6 element) as a child of the element, wherever possible. See below for examples of where you might see a without a heading.
Examples
Simple usage example
Before
div> h2>Headingh2> p>Bunch of awesome contentp> div>
Result
After
section> h2>Headingh2> p>Bunch of awesome contentp> section>
Result
Using a section without a heading
Circumstances where you might see used without a heading are typically found in web application/UI sections rather than in traditional document structures. In a document, it doesn’t really make any sense to have a separate section of content without a heading to describe its contents. Such headings are useful for all readers, but particularly useful for users of assistive technologies like screen readers, and they are also good for SEO.
Consider however a secondary navigation mechanism. If the global navigation is already wrapped in a element, you could conceivably wrap a previous/next menu in a :
section> a href="#">Previous articlea> a href="#">Next articlea> section>
Or what about some kind of button bar for controlling your app? This might not necessarily want a heading, but it is still a distinct section of the document:
section> button class="reply">Replybutton> button class="reply-all">Reply to allbutton> button class="fwd">Forwardbutton> button class="del">Deletebutton> section>
Result
Depending on the content, including a heading could also be good for SEO, so it is an option to consider.
Technical summary
Content categories | Flow content, Sectioning content, palpable content. |
---|---|
Permitted content | Flow content. |
Tag omission | None, both the starting and ending tag are mandatory. |
Permitted parents | Any element that accepts flow content. Note that a element must not be a descendant of an element. |
Implicit ARIA role | region if the element has an accessible name, otherwise no corresponding role |
Permitted ARIA roles | alert , alertdialog , application , banner , complementary , contentinfo , dialog , document , feed , log , main , marquee , navigation , none , note , presentation , search , status , tabpanel |
DOM interface | HTMLElement |
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 Jul 7, 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.
The to HTML elements represent six levels of section headings. is the highest section level and is the lowest.
These elements only include the global attributes.
Usage notes
- Heading information can be used by user agents to construct a table of contents for a document automatically.
- Do not use heading elements to resize text. Instead, use the CSSfont-size property.
- Do not skip heading levels: always start from , followed by and so on.
Avoid using multiple elements on one page
While using multiple elements on one page is allowed by the HTML standard (as long as they are not nested), this is not considered a best practice. A page should generally have a single element that describes the content of the page (similar to the document’s element ).
Note: Nesting multiple elements in nested sectioning elements was allowed in older versions of the HTML standard. However, this was never considered a best practice and is now non-conforming. Read more in There Is No Document Outline Algorithm.
Prefer using only one per page and nest headings without skipping levels.
Examples
All headings
The following code shows all the heading levels, in use.
h1>Heading level 1h1> h2>Heading level 2h2> h3>Heading level 3h3> h4>Heading level 4h4> h5>Heading level 5h5> h6>Heading level 6h6>
Example page
The following code shows a few headings with some content under them.
h1>Heading elementsh1> h2>Summaryh2> p>Some text here…p> h2>Examplesh2> h3>Example 1h3> p>Some text here…p> h3>Example 2h3> p>Some text here…p> h2>See alsoh2> p>Some text here…p>
Accessibility concerns
Navigation
A common navigation technique for users of screen reading software is jumping from heading to quickly determine the content of the page. Because of this, it is important to not skip one or more heading levels. Doing so may create confusion, as the person navigating this way may be left wondering where the missing heading is.
Don’t do this:
h1>Heading level 1h1> h3>Heading level 3h3> h4>Heading level 4h4>
Prefer this:
h1>Heading level 1h1> h2>Heading level 2h2> h3>Heading level 3h3>
Nesting
Headings may be nested as subsections to reflect the organization of the content of the page. Most screen readers can also generate an ordered list of all the headings on a page, which can help a person quickly determine the hierarchy of the content:
- h1 Beetles
- h2 Etymology
- h2 Distribution and Diversity
- h2 Evolution
- h3 Late Paleozoic
- h3 Jurassic
- h3 Cretaceous
- h3 Cenozoic
- h3 Head
- h4 Mouthparts
- h4 Prothorax
- h4 Pterothorax
When headings are nested, heading levels may be «skipped» when closing a subsection.
Labeling section content
Another common navigation technique for users of screen reading software is to generate a list of sectioning content and use it to determine the page’s layout.
Sectioning content can be labeled using a combination of the aria-labelledby and id attributes, with the label concisely describing the purpose of the section. This technique is useful for situations where there is more than one sectioning element on the same page.
Sectioning content examples
header> nav aria-labelledby="primary-navigation"> h2 id="primary-navigation">Primary navigationh2> nav> header> footer> nav aria-labelledby="footer-navigation"> h2 id="footer-navigation">Footer navigationh2> nav> footer>
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 May 19, 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.Как использовать секционные элементы HTML5
Один славный малый Matt West c туманного альбиона, промышляющий фрилансом и предпринимательством, предложил нашему вниманию пост: «Как использовать секционные элементы HTML5».
Ниже приводится его перевод.HTML5 предлагает набор секционных элементов, используя которые в своей разметке вы добавляете смысловую или семантическую нагрузку своим страницам, тем самым позволяя компьютерным программам лучше понимать их содержание.
Прочитав этот пост, вы научитесь применять секционные элементы на ваших веб-сайтах. Я постараюсь объяснить, в каких случаях лучше использовать тот или иной элемент и когда лучше прибегнуть к старому доброму.
Давайте начнем.
Элемент main
Элемент должен содержать главный контент вашей вебстраницы. Причем, все содержимое должно быть уникально на странице и не должно отображаться где-либо еще на сайте.
Повторяющийся на нескольких страницах контент (логотип, окно поиска, ссылки в футере и т.д.) не следует помещать внутри элемента .
Ниже приводится пример представления главного содержимого страницы.
Журнал Rocking StoneГитары
Величайшие гитары современности
Gibson SG
.
Fender Telecaster
.
Примечание: Мы использовали атрибут роли ARIA role=”main”, здесь он указывает на важность этого элемента тем программам, которые еще не поддерживают элемент (например, некоторые скринридеры).
Можно использовать только один элементна странице, который нельзя помещать внутри элементов , , , или .
Элемент article
Элемент должен содержать часть самодостаточной информации, которая может быть вырвана из контекста всей страницы без потери смысла. Это могут быть: новость, статья в блоге, комментарии пользователя.
Название статьи
Опубликовано: 13 февраля 2014
.
один в другой. Это будет означать, что вложенные элементы связаны с внешним элементом .
Название статьи
Опубликовано: 13 февраля 2014
.
.
.
Комментарии
Это была интересная статья
Как ты связываешь это с мировым превосходством?
.
Элемент aside
Элемент используется для выделения содержания, непосредственно связанного с окружающим контентом, но которое может рассматриваться и отдельно. Это могут быть боковые сноски (как в книгах), группы элементов , цифры или цитаты.
Компания Google покупает Nest
Опубликовано: 13 января 2014
.
.
, чтобы выделить информацию о компании Google в новостной статье. Эта информация может быть полезна читателю, но не связана напрямую с новостью.
Элемент header
Элемент используется для представления вводной части к статье или веб-странице. Обычно он содержит заглавие или какие-либо метаданные, относящиеся к данному контенту, например, дата публикации статьи или оглавление (внутри элемента ) для более длинного документа.
Элемент будет связан с ближайшим секционным элементом, обычно это прямой родитель в структуре страницы.
Компания Google покупает Nest
Опубликовано: 13 января 2014
содержит заголовок и дату публикации новостной статьи.
Элемент footer
Элемент используется для представления такой информации о разделе, как автор, авторские права, ссылки на связанные веб-страницы.
, элемент связан с ближайшим секционным элементом.
Элемент address
Элемент один из самых неправильно используемых элементов в HTML. Этот элемент предназначен не для разметки почтового адреса, а для представления контактной информации по статье или веб-странице. Это могут быть ссылки на сайт автора или его электронный адрес.
Контакты Matt West, который в свою очередь располагается внутри элемента .
Компания Google покупает Nest
Опубликовано: 13 января 2014
.
.
Заключение
В этом посте вы узнали как использовать секционные элементы HTML5 для разметки веб-страниц. Использование таких элементов имеет ряд преимуществ.
Одно из самых больших – это придание семантического значения определенным областям вашей веб-страницы, позволяющего компьютерным программам (скринридерам) идентифицировать ключевые элементы содержания и навигации.
Примечание: Пока еще не все скринридеры имеют поддержку семантических элементов. Чтобы обезопасить себя, вы можете продолжать использовать роли ARIA. Использование секционных элементов также помогает разработчикам больше задумываться о структуре своих веб-страниц.
Хотя выбор секционного элемента и очевиден, но он порождает важные вопросы о назначении и цели контента, а также, помогает понять, а относится ли вообще содержимое к этой странице?
Это пример того, как веб-стандарты помогают не только улучшить качество разметки, но и качество веб-страницы в целом.