Skip to main content

CSS Box Model

By SamK
0
0 recommends
Topic(s)

In CSS, the "box model" refers to the concept used for design and layout. 

Most of the web pages consist of content boxes presented in various layouts.

The CSS box model is a box that encapsulates every HTML element, consisting of the following components:

  • Content
  • Padding
  • Border
  • Margin

Here's an example:

div {
  width: 250px;    
  height: 100px;      
  padding: 15px; 
  border: 15px solid black; 
  margin: 15px;
}

CSS Box Model Demo

Explanation

  • Content: The grey area, where your text or other elements are displayed, defined by width and height.
  • Padding: The green area, which shows space between the content and the border.
  • Border: The black area, which is around the padding and content.
  • Margin: The yellow area, which shows space outside the border.

Width and Height of an Element

To accurately set the width and height of an element, you need to consider the entire box model, which includes content, padding, border, and margin.

In the above example, the div element will have:

  • A total width of 310px (250px content width + 15px left padding + 15px left border + 15px right padding + 15px right border)
  • A total height of 160px (100px content height + 15px top padding + 15px top border + 15px bottom padding + 15px bottom border)
  • And a 15px margin around the above dimensions.  

In the above example, if you want to ensure that the width remains 250px regardless of the padding, you can use the box-sizing property. It also ensures that these dimensions are correctly applied in all browsers.

Note: When you set the width and height properties of an element with CSS, you are only setting the dimensions of the content area. To determine the total width and height of an element, you must also include the padding and borders.

Please check below options for the links to our previous or next tutorial.

Questions & Answers