32. CSS box model

HTML and CSS through English, HTML and CSS Lessons
HTML and CSS tutorial for beginners in English

Hello friends, welcome again to KTL's HTML and CSS tutorial. Today we will study lesson-32.

In our last lesson, we studied about CSS Outline properties.

Today, we will study CSS box model.


CSS box model


Every element displayed in a web page has an imaginary box. Element occupies the space in that box. In other words, box model gives us an idea of how much of space an element will occupy in the web space.

We have already seen how an element is displayed. Element itself has its contents. We can display a border for the element. Padding is the distance from contents of element to the border of that element. Margin is the space for that element which is outside the border. All this constructs a box for that element. See the figure displayed below.


CSS box model in English
Figure 32-1. CSS box model

Thus space required to display an element is calculated as follows:

Actual contents of element + padding + border width + margin

We have already used these properties in our code. Let us write a script in which will demonstrate CSS box model.

Open a new Notepad file. In this file copy all code from lesson-31. We will specify height and width under style of the header. Under #header insert following lines.

height: 10vw;
width: 80vw;

Save this file as "Lesson-32" and "Lesson-32.html". Click on the following figure for PDF file of source code.


Code for CSS box model in English, CSS height in English, CSS width in English
Lesson-32-2. Code for CSS box model

Double click on HTML file and see the output.


CSS box model in English
Figure 32-3. CSS box model

Note that style that we have mentioned for header is displayed in the output. Now let us calculate how much of space is occupied by our header element according to CSS box model.

  border: 0.5vw solid red;
  padding: 0.5vw;
  margin-bottom: 5vw;
  margin-top: 5vw;
  outline: 0.3vw solid green;
  height: 10vw;
  width: 80vw;

height is 10vw+padding(0.5)+border(0.5)+margin-top(5)+margin-bottom(5) = 10+0.5+0.5+5+5 = 21vw.

This is the total height occupied by the element. Similarly,

width (80)+padding(0.5)+border(0.5) = 80+0.5+0.5 = 81vw.

This is the width occupied by the element.

Likewise, we can calculate total space required in web page to display any element.


Important Points


1. Using CSS box model we can easily understand the amount of space required to display an element in the web page.
2. We consider all dimension properties for an element like padding, border width, margin to calculate this.

Lesson-31                                                             Lesson-33