14 - CSS The Box Model

The box model in CSS is a tool which we use to layout our web page into invisible number of individual boxes.

During our web design phase, we must not only take into account the size of content of the web page but also the borders, padding and margins.

To create a balanced layout for a web page we need to plan everything well in advance by arranging everything in terms of boxes.

The figure below illustrates the box model for you,

The definition for the terms we just used,

  • Content: The content of the box it could be images, text etc.
  • Padding: This is the amount of invisible area around the content.
  • Border: A border that surrounds the content and padding
  • Margin: The area to be left around the border. The margin is transparent.

The <div> tag in Box model

We have learnt and used <div> tag many times in our examples.

This tag is the basic building block when we layout a web page’s design.

Everything height, width, padding and margins are specified for <div> and </div> tags only either by using class or id.

By mentioning the style information for <div> tag we are asking the browser to reserve the space specified whatsoever.

The actual content will be enclosed within <div> and </div> tags.

An Example would clear the air,

<html>
 <head>
  <style type="text/css">
   div {
     width: 320px;
     padding: 10px;
     border: 5px solid gray;
     margin: 0;
   }
  </style>
 </head>
 <body>
  <img src="Apple.jpg" width=350 height=125>
  <div> The width of this box is same as the image above(350 pixels)</div>
 </body>
</html>

The output of the above program would be,

Calculating Overall dimensions

How to calculate the total width of the box,

When designing we have to estimate the total width a div element consumes,

The total width of the element would follow the following formula,

  • Total element width= defined width + left padding + right padding + left border + right border + left margin + right margin.

How to calculate the total height of the box,

When designing we have to estimate the total height a div element consumes,

The total height of the element would follow the following formula

  • Total element height = defined height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

.Pixels Vs. Percentages

We can use either pixels or percentages to specify the dimensions of an element.

When we specify width as percentages, say width: 50% means we are instructing the browser to span the element exactly 50% wide of the space available.

Usage of pixels is highly recommended as it makes flexible use of the space available when compared to percentages.

The next chapters take you more closer to the box model of CSS.

Like us on Facebook