Categories
CSS Web development

Understanding the Box Model in CSS

The CSS box model is used to create the design and layout of websites. It consists of: margins, borders, padding, and the content itself. The CSS box model allows us to add a border around elements, and to define space between elements. The image below illustrates the box model: 

Explanations of the different parts:

Margin Area – This area consists of space between the border and the margin. The margin is transparent. 

Border Area – The border that goes around the padding and content. Its dimensions are given by the heigh and width of the border.  
Padding Area – It includes the element’s padding. The padding is transparent. 
Content Area – The content of the box, where text and images appear. 

Example:

<!DOCTYPE html>
<html>
<head>
<style>
div {
  background-color: pink;
  width: 400px;
  border: 25px solid red;
  padding: 50px;
  margin: 20px;
}
</style>
</head>
<body>

<h2>Example of CSS Box Model</h2>

<p>The CSS box model consists of: borders, padding, margins, and the actual content.</p>

<div>This text is the content of the box. We have added a 50px padding, 20px margin and a 25px red border. Background color is pink. </div>

</body>
</html>

Output:

Width and height in the CSS box model.

In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.

To calculate the full size of an element, you must also add padding, borders, and margins.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
div {
  width: 320px;
  padding: 10px;
  border: 5px solid gray;
  margin: 0;
}
</style>
</head>
<body>

<h2>Calculate the total width:</h2>

<img src="123.gif" width="350" height="263" alt="css bubbles">
<div>The picture above is 350px wide. The total width of this element is also 350px.</div>

</body>
</html>

Output:

Calculation:

320px (width) + 20px (left and right padding) + 10 px (left and right border) + 0 px (left and right margin) = 350 px

Hope it helps, enjoy coding!

Leave a Reply