web123456

HTML <div> Tags

Example

A section in the document will be displayed in green:

<div style="color:#00FF00">
  <h3>This is a header</h3>
  <p>This is a paragraph.</p>
</div>

Browser support

element Chrome IE Firefox Safari Opera
<div> Yes Yes Yes Yes Yes

All mainstream browsers support the <div> tag.

Definition and usage

<div> can define partitions or sections in a document.

The <div> tag can divide a document into separate and different parts. It can be used as a strict organizational tool and does not use any format to associate it with it.

If you tag <div> with id or class, the function of the tag becomes more effective.

usage

<div> is aBlock-level elements. This means that its contents automatically start a new line. In fact, line breaks are the only format manifestation inherent in <div>. Additional styles can be applied via the class or id of <div>.

There is no need to add a class or id to every <div>, although this also has some benefits.

You can apply class or id attributes to the same <div> element, but it is more common to apply only one of them. The main difference between the two is that class is used for group of elements (similar elements, or can be understood as a certain class of elements), while id is used to identify individual and unique elements.

Differences between HTML and XHTML

In HTML 4.01, the "align" attribute of the div element is not favored.

In XHTML 1.0 Strict DTD, the "align" attribute of the div element is not supported.

Tips and comments:

Note: <div> is a block-level element, which means that browsers usually place a newline before and after the div element.

Tip: Use the <div> element to combine block-level elements so that they can be formatted using styles.

Case Study

<body>

 <h1>NEWS WEBSITE</h1>
  <p>some text. some text. some text...</p>
  ...

 <div class="news">
  <h2>News headline 1</h2>
  <p>some text. some text. some text...</p>
  ...
</div>

 <div class="news">
  <h2>News headline 2</h2>
  <p>some text. some text. some text...</p>
  ...
 </div>

 ...
</body>

Example explanation

As you can see, the above HTML simulates the structure of a news website. Each div combines the title and summary of each news, that is, the div adds an extra structure to the document. At the same time, since these divs belong to the same class, you can use class="news" to identify these divs. This not only adds appropriate semantics to the divs, but also facilitates further formatting of the divs with styles, which can be said to kill two birds with one stone.

Optional properties

property value describe
align
  • left
  • right
  • center
  • justify

Not favored. Please use style instead.

Specifies the alignment of contents in the div element.