1. Technology

The CSS Box Model


What is the CSS Box Model:

The CSS box model describes the boxes that are formed around elements of content in a Web page. Every element in a Web page is in a box or is a box, even if it's an image of a circle. The boxes on Web pages are constrained by rules defined by the box model.

Parts of the CSS Box Model:

The CSS box model is made up of four parts:

  • margin
  • border
  • padding
  • content

The margin is the outermost edge of the box. It is transparent and manifests as space between the element and others on the page. Margins can collapse into one another, so that the bottom margin of one element overlaps with the top margin of the element below it.

The border is the next thing surrounding the box. Borders can be colored or transparent. If the border is set to 0 it effectively disappears and the border edge is the same as the padding edge.

The padding is the space between the content and the border. Padding is the same color as the background color for the box. If the padding is set to 0, the padding border is the same as the content border.

The content is what most people think of as the element. This is the text or image or whatever is displayed inside the box.

You can manipulate the different parts of the box model with CSS properties:

Box Model Issues:

The problem with the CSS box model is that not all Web browsers implment it the same way. In a nutshell, according to the W3C, width and height properties define the width and height of the content of the box. Items like padding, border, and margin surround that width and height.

Some versions of Internet Explorer instead define the width and height as the width and height of the entire element, including padding, and border.

If you want your designs to look the same in all browsers, you have to employ tricks and sometimes hacks to get IE to work correctly.

Block Level Elements:

The other aspect of the box model is how different elements act. Some are considered block-level elements. These are elements that create boxes within the flow of the document. For example, paragraphs, images, and forms are all block-level elements.

Inline Elements:

Inline elements are elements that don't disrupt the flow of the document. They are often called "text-level" elements because they are typically found within text. Some examples of inline elements are span, strong, and abbreviations.

©2014 About.com. All rights reserved.