CSS Div

CSS Division (div) is a container element and it is used to group related items together. When ever there is a situation that you need to collect various objects into a larger container for scripting or styling purposes, div is the best solution. The use of < div > tag is straightforward.

Syntax

<div>...</div>

example

<div>
  <p>A paragraph inside Div</p>
</div>

CSS divisions to provide greater flexibility and mark out regions of the page. You can use divs by referencing the selector in the opening tag using ID and CLASS (e,g. id=”myContainer” or class=”myContainer”).

The following source code shows how to implement div in an HTML document.

<html>
<head>
  <style type="text/css">
  #box {
    width: 420px;
    height:120;
    border-width: 2px;
    border-style:solid;
    border-color:red;
    background: #CCC;
  }
  </style>
</head>
<body>
  <div id="box">
    <h1>Box Model</h1>
    <p>
      The Box model determines how elements are positioned within the
      browser window. With the Box Model, a developer can control the
      dimensions, margins, padding, and borders of an HTML element.
    </p>
  </div>
</body>
</html>

output

Nesting Div

The div element grouping a generic block of content that should be treated as a logical unit for scripting or styling purposes. A div can contain a number of other divs ( child div ) like HTML Tables . This is called Nesting Div .

The following example shows how to arrange a nesting Div in an HTML page.

<html>
<head>
  <style type="text/css">
    .parent {
      width: 200px;
      height:120;
      border-width: 2px;
      border-style:solid;
      border-color:red;
      padding:10px;
    }
    .child {
      overflow : hidden;
      background: #CCC;
    }
  </style>
</head>
<body>
  <div class="parent">
  <h1> Nesting Div</h1>
  <div class="child">
  <h2>Child Div 1</h2>
  </div>
  <div class="child">
  <h2>Child Div 2</h2>
  </div>
  </div>
</body>
</html>

output

We can use align attribute to Div elements like align=”left”, align=”center”, align=”right” etc. But this align attribute is deprecated in XHTML and doesn`t work consistently in many browsers. So it is better to avoid when you styling the content with Div element.

Like HTML Table, excessive use of Div is alomst bad when you structuring page content. So you should add Div elements very carefully and use only when it is necessary for logical structure or styling.