How to use the body element in HTML

The <body> tag in HTML contains the renderable content of the document. The <body> tag encloses everything visible to the users, which includes paragraphs, headings, links, etc.

Syntax

The following figure describes the syntax of the <body> tag:

Note: There can only be one body element per document.

Attributes

The following table describes the attributes of the <body> tag:

Attribute Description
text sets the color for the displayed text
link sets the color of the text for the unvisited links
alink sets the color of the text for the links when the mouse hovers over them
vlink sets the color of the text for the visited links
bgcolor sets the background color of the element
background sets the background as the image whose URL is provided to the background attribute

Note: The above attributes are obsolete in HTML5 but can be used in style sheets.

Events

The following table describes the events that can be called with the <body> tag:

Event Description
onafterprint calls a function after the user prints a document
onbeforeprint calls a function after the user requests to print a document
onbeforeunload calls a function when the document is about to be closed
onhaschange calls a function when the fragment identifier of the document’s URL changes
onlanguagechange calls a function when the preferred language of the user changes
onmessage calls a function when the document receives a message
onmessageerror calls a function when a message cannot be deserialized
onoffline calls a function when the document loses the network connection
ononline calls a function when the document reestablished the network connection
onpopstate calls a function when a change in the session history of the document occurs
onunload calls a function when the document begins to close

Examples

The following code demonstrates the use of the <body> tag:

  • The <head> tag contains the metadata of the document, which is the document’s title in our example.
  • The <body> tag follows the <head> tag and contains the <h1> and <p> tags.
  • The <h1> tag is used to write headings, and the <p> tag is used to write paragraphs.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved