DEV Community

Anamika
Anamika

Posted on

CSS Box Model

All the components depicted in a web page consists of boxes. So, basically all the html elements can be considered as boxes.
In CSS, box model is used for the design and layout of the html elements ,also how each of them are arranged together to form an overall layout.

What is CSS Box Model?

The CSS Box Model is a box that wraps around every html element. It has four layers: margin, border, padding, content.

css box model

What does it comprise of?

  • Content: It is the innermost area which consists of content like text, image or other media, which can be sized using height and width properties.

  • Padding: This area wraps around the content as an additional layer. Its dimensions can be given using padding properties.

  • Border: This is the area around the padding. It wraps the content as well as padding. It can be sized using border properties.

  • Margin: It is the outermost layer, which wraps around every other layer. It is a white space between the box and other elements. It can be adjusted using margin properties.
    example


When we set height and width properties of any element using CSS, it is merely applied to the content area.
So, to know the actual dimensions of the element we
need to consider padding and border also.

Total width of an element is calculated as :

Total Width = ( width + left padding + right padding + left border + right border)

Total height of an element is calculated as:

Total Height = (height + top padding + bottom padding + top border + bottom border)

The Box-sizing Property

This property defines how the margin, padding and borders are added around the box.

box model property

  • Content-Box: It is considered as the default value. It adds the padding, margin and the border outside the box. This means when we specify a width and height to any element, the padding and border are applied over it , so it seems larger.

example

  • Border-Box: It adds the margin, padding, and border inside the box. As a result the padding and border are included inside the height and width of an element, ensuring all the elements are sized in an easy manner.

Discussion (0)