Тег BODY

HTML Tag

The HTML tag is used for creating a ‘body’ element. This element represents the main content section of the HTML document.

Generally, most content displayed on a typical web page is contained within the element. Therefore, the element usually contains many other elements (given the amount of content on a typical web page). This usually results in the start tag being closer to the top of the document, with the end tag near the bottom.

The element is categorized as «sectioning root». Most elements contained within the are categorized as «flow content».

HTML documents must have no more than one element.

Syntax

The tag is written as with the document’s content inserted between the start and end tags. Any attributes can be inserted into the start tag (for example, ). Note that there are 12 event handlers that are only available for the element (and the element in HTML 4 and earlier) — these are listed further down this page.

The must be the second element in an element.

Example

This example demonstrates how the element appears within an HTML document. Notice that none of the content outside of the element appear on the page.

Attributes

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

The element accepts the following attributes.

HTML5 introduced the following event handlers that can be used with the element (and the element in HTML 4 and earlier).

Attribute Description
onafterprint afterprint event handler
onbeforeprint beforeprint event handler
onbeforeunload beforeunload event handler
onhashchange hashchange event handler. The hashchange event is fired when navigating to a session history entry whose URL differs from that of the previous one only in the fragment identifier.
onlanguagechange languagechange event handler.
onmessage message event handler.
onmessageerror messageerror event handler.
onoffline offline event handler.
ononline online event handler.
onpagehide pagehide event handler. The pagehide event is fired when traversing from a session history entry.
onpageshow pageshow event handler. The pageshow event is fired when traversing to a session history entry.
onpopstate popstate event handler. The popstate event is fired when navigating to a session history entry that represents a state object.
onrejectionhandled rejectionhandled event handler.
onstorage storage event handler.
onunhandledrejection unhandledrejection event handler.
onunload unload event handler.
Читайте также:  What is constructor function in javascript

These are also listed under the Event Handlers section below, along with all other event handler content attributes that can be used on all HTML elements.

Global Attributes

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

  • accesskey
  • autocapitalize
  • class
  • contenteditable
  • data-*
  • dir
  • draggable
  • hidden
  • id
  • inputmode
  • is
  • itemid
  • itemprop
  • itemref
  • itemscope
  • itemtype
  • lang
  • part
  • slot
  • spellcheck
  • style
  • tabindex
  • title
  • translate

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

Event Handlers

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.

  • onabort
  • onauxclick
  • onafterprint
  • onbeforeprint
  • onbeforeunload
  • onblur
  • oncancel
  • oncanplay
  • oncanplaythrough
  • onchange
  • onclick
  • onclose
  • oncontextmenu
  • oncopy
  • oncuechange
  • oncut
  • ondblclick
  • ondrag
  • ondragend
  • ondragenter
  • ondragexit
  • ondragleave
  • ondragover
  • ondragstart
  • ondrop
  • ondurationchange
  • onemptied
  • onended
  • onerror
  • onfocus
  • onformdata
  • onhashchange
  • oninput
  • oninvalid
  • onkeydown
  • onkeypress
  • onkeyup
  • onlanguagechange
  • onload
  • onloadeddata
  • onloadedmetadata
  • onloadstart
  • onmessage
  • onmessageerror
  • onmousedown
  • onmouseenter
  • onmouseleave
  • onmousemove
  • onmouseout
  • onmouseover
  • onmouseup
  • onoffline
  • ononline
  • onpagehide
  • onpageshow
  • onpaste
  • onpause
  • onplay
  • onplaying
  • onpopstate
  • onprogress
  • onratechange
  • onreset
  • onresize
  • onrejectionhandled
  • onscroll
  • onsecuritypolicyviolation
  • onseeked
  • onseeking
  • onselect
  • onslotchange
  • onstalled
  • onstorage
  • onsubmit
  • onsuspend
  • ontimeupdate
  • ontoggle
  • onunhandledrejection
  • onunload
  • onvolumechange
  • onwaiting
  • onwheel

Most event handler content attributes can be used on all HTML elements, but some event handlers have specific rules around when they can be used and which elements they are applicable to.

Источник

This is a heading

This is a paragraph.

The element contains all the contents of an HTML document, such as headings, paragraphs, images, hyperlinks, tables, lists, etc.

Note: There can only be one element in an HTML document.

Browser Support

Global Attributes

Event Attributes

More Examples

Example

Add a background image to a document (with CSS):

Hello world!

Visit W3Schools.com!

Example

Set the background color of a document (with CSS):

Hello world!

Visit W3Schools.com!

Example

Set the color of text in a document (with CSS):

Hello world!

This is some text.

Visit W3Schools.com!

Example

Set the color of unvisited links in a document (with CSS):

Example

Set the color of active links in a document (with CSS):

Example

Set the color of visited links in a document (with CSS):

Default CSS Settings

Most browsers will display the element with the following default values:

Example

body <
display: block;
margin: 8px;
>

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Читайте также:  Php exception stack trace string

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

All body attributes html

HTML-элемент представляет собой контент (содержимое) документа HTML. В документе может быть только один элемент .

  • Элемент представляет интерфейс HTMLBodyElement .
  • Вы можете получить доступ к элементу через свойство document.body .

Атрибуты

К этому элементу применимы глобальные атрибуты.

Цвет текста гиперссылок, когда они выделены. Этот метод не согласован, вместо него используйте CSS-свойство color (en-US) вместе с псевдоклассом :active .

URI изображения для использования в качестве фона. Этот метод не согласован, вместо него используйте CSS-свойство background .

Цвет фона документа. Этот метод не согласован, вместо него используйте CSS-свойство background-color .

Отступ от нижнего края элемента . Этот метод не согласован, вместо него используйте CSS-свойство margin-bottom .

Отступ от левого края элемента . Этот метод не согласован, вместо него используйте CSS-свойство margin-left .

Цвет текста непосещенных гипертекстовых ссылок. Этот метод не согласован, вместо него используйте CSS-свойство color (en-US) вместе с псевдоклассом :link .

Функция для вызова после того, как пользователь распечатал документ.

Функция для вызова, когда пользователь отправляет документ на печать.

Функция для вызова перед закрытием окна документа или переходом на другую, внешнюю, страницу в этой же вкладке.

Функция для вызова при потери документом фокуса.

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

Функция для вызова, когда документ получает фокус.

Функция для вызова, когда изменяется часть идентификатора фрагмента (начинается с символа ‘#’ ) текущего адреса документа.

Функция для вызова при изменении предпочитаемых языков.

Функция для вызова, когда документ закончил загрузку (страницы загружена).

Функция для вызова, когда документ получил сообщение.

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

Функция для вызова, когда произошло восстановление сетевого соединения.

Функция для вызова, когда пользователь осуществил управление историей сеанса.

Функция для вызова, когда произошло продвижение пользователя вперёд по истории транзакций (например, обновление страницы).

Функция для вызова, когда размер документа был изменён.

Функция для вызова, когда изменяется содержимое хранилища (Web Storage).

Функция для вызова, когда произошло продвижение пользователя назад по истории транзакций (например, переход на предыдущую страницу в активной вкладке).

Функция для вызова, когда пользователь покидает страницу (закрытие вкладки или окна браузера).

Отступ от правого края элемента . Этот метод не согласован, вместо него используйте CSS-свойство margin-right .

Основной цвет текста. Этот метод не согласован, вместо него используйте CSS-свойство color (en-US).

Отступ от верхнего края элемента . Этот метод не согласован, вместо него используйте CSS-свойство margin-top .

Цвет текста посещённой гипертекстовой ссылки. Этот метод не согласован, вместо него используйте CSS-свойство color (en-US) вместе с псевдоклассом :visited .

Пример

html> head> title>Заголовок документаtitle> head> body> p>Это параграфp> body> html> 

Спецификации

Поддержка браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 4 мар. 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.

Источник

All body attributes html

Элемент предназначен для хранения содержания веб-страницы (контента), отображаемого в окне браузера. Информацию, которую следует выводить в документе, следует располагать именно внутри контейнера . К такой информации относится текст, изображения, теги, скрипты JavaScript и т.д.

Тег также применяется для определения цветов ссылок и текста на веб-странице. Подобная практика в HTML 4 осуждается и взамен для указания цветовой схемы рекомендуется использовать стили, применяя их к селектору BODY . Тем не менее, большинство атрибутов до сих пор поддерживается разными браузерами.

Часто тег используется для размещения обработчика событий, например, onload, которое выполняется после того, как документ завершил загрузку в текущее окно или фрейм.

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

Синтаксис

Атрибуты

alink Устанавливает цвет активной ссылки. background Задает фоновый рисунок на веб-странице. bgcolor Цвет фона веб-страницы. bgproperties Определяет, прокручивать фон совместно с текстом или нет. bottommargin Отступ от нижнего края окна браузера до контента. leftmargin Отступ по горизонтали от левого края окна браузера до контента. link Цвет ссылок на веб-странице. rightmargin Отступ от правого края окна браузера до контента. scroll Устанавливает, отображать полосы прокрутки или нет. text Цвет текста в документе. topmargin Отступ от верхнего края окна браузера до контента. vlink Цвет посещенных ссылок.

Также для этого тега доступны универсальные атрибуты и события.

Закрывающий тег

Открывающий и закрывающий теги не обязательны.

    

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat.

Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Результат текущего примера показан на рис. 1. При использовании события onload тега выполняется скрипт, написанный на языке JavaScript, в данном случае он выводит сообщение, что документ загружен.

Всплывающее окно в документе

Рис. 1. Всплывающее окно в документе

Статьи по теме

Источник

Оцените статью