HTML Div

The HTML div element is a block-level container used to group and structure sections of a web page. When combined with CSS, it helps create layouts and organize content effectively.

On this page

HTML Div Element

The <div> element is used as a container for other HTML elements.

The div Element

The <div> element is a block-level element by default.

This means it takes up the full available width and starts on a new line, with line breaks before and after.

<p>Lorem Ipsum <div>I am a div</div> dolor sit amet.</p>

The <div> element has no required attributes, but style, class, and id are commonly used.

div as a Container

The <div> element is often used to group sections of a web page.

<div>   <h2>London</h2>   <p>London is the capital city of England.</p>   <p>London has over 9 million inhabitants.</p> </div>

Center Align a div Element

If a <div> element has a fixed width, it can be centered using margin: auto.

<style> div {   width: 300px;   margin: auto; } </style>

Multiple div Elements

You can use multiple <div> elements on the same page.

<div>   <h2>London</h2>   <p>London is the capital city of England.</p>   <p>London has over 9 million inhabitants.</p> </div>  <div>   <h2>Oslo</h2>   <p>Oslo is the capital city of Norway.</p>   <p>Oslo has over 700,000 inhabitants.</p> </div>  <div>   <h2>Rome</h2>   <p>Rome is the capital city of Italy.</p>   <p>Rome has over 4 million inhabitants.</p> </div>

Aligning div Elements Side by Side

There are several CSS methods to align <div> elements next to each other.

Using Float

The float property allows elements to be positioned horizontally.

<style> .mycontainer {   width: 100%;   overflow: auto; } .mycontainer div {   width: 33%;   float: left; } </style>

Using Inline-block

Changing the display value to inline-block removes line breaks and places elements side by side.

<style> div {   width: 30%;   display: inline-block; } </style>

Using Flexbox

Flexbox makes it easier to build flexible and responsive layouts.

<style> .mycontainer {   display: flex; } .mycontainer > div {   width: 33%; } </style>

Using Grid

CSS Grid provides a grid-based layout system with rows and columns.

<style> .grid-container {   display: grid;   grid-template-columns: 33% 33% 33%; } </style>

Exercise

Consider the following code:

<div style="width:200px; margin:auto">   <h2>London</h2> </div>

How will the div element be aligned?

Left aligned Center aligned Right aligned

HTML Tags

Tag Description
<div> Defines a section in a document (block-level)

HTML Div Examples (8)