CSS Box Model Concept

CSS Box Model Concept

Divya
DivyaJun 12, 2024

The CSS Box Model is a set of rules that contains multiple properties including borders, margin, padding, and the content itself and is also used to create the design and layout of web pages.

Properties of the Box Model:

Padding

The padding area is the space around the content area and inside the border box. It can be applied to all sides of the box or to the specific, selected sides – top, right, bottom, or left.

Example

It shows how to define all four sides of an element with one value.

p { 
padding: 40px; 
}

Border

The border area surrounds the padding and the content and can be applied to all the sides of the box or to selected sides – top, right, bottom, and/or left.

Example

It shows borders that are 2px in thickness, solid, and red:

div { 
border: 3px solid red; 
}

Margin

The margin area consists of the space between the border and the margin. The margin does not possess its own background colour and is entirely transparent. It shows the background colour of the element, like the body element.

The margin defines the space for all four sides of an element in one declaration.

Example

div { 
  margin: 20px 20px 30px 60px; 
}

Content

The Content area includes content like text, images or other forms of media content. The height and width properties help to modify the box dimensions. 

It can define the width and height of content boxes with other properties. max-width, min-width, max-height, and min-height can set constraints and not a fixed size.

To calculate the

Total element width =
right margin + left margin + right border + left border + right padding + left padding + width.

Total element height =
bottom margin + top margin + bottom border + top border + bottom padding + top padding + height.

Example

we style a <div> element to have a 400 px total width. This is an math to count the total width of a box: 330px (width) + 30px (right + left padding) + 40px (right + left border) + 0px (right + left margin) = 400px.

<div>CSS Box Model</div>

div { 
 width: 500px; 
 padding: 30px; 
 border: 2px solid red; 
 margin: 50px; 
}

Result

Conclusion

CSS Box model can utilise each of the elements in the right scenario and values are being set and calculate the full width or height of an element

Prev Post

JavaScript Basics

Next Post

Understanding The Basics Of Npm Scripts New

Related Articles