CSS Box Model
The CSS box model is a fundamental concept that defines how the element's dimensions
and spacing are calculated.
The box model treats every HTML element as a rectangular box consisting of content,
padding, border, and margin.
The box model defines the layout of an HTML element in the following way:
The components of the box model are:
content: actual text or image that is displayed in the element
padding: transparent space between the content and the border of an element
border: line that surrounds the padding and content within the element
margin: transparent area added outside the border
The primary purpose of the box model is to explain how the dimensions and spacing of
elements are calculated and how they relate to each other.
Width and Height of an Element with Box Model
The box model is important for understanding how the width and height of an element are
calculated.
The width and height of the element are applied only to the content of the element by
default. Hence, the actual size of the element is calculated by adding
the padding and border along with the specified width and height of the element.
Actual width: border-left + padding-left + width + padding-right + border-
right
Actual height: border-top + padding-top + height + padding-bottom + border-
bottom
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8" />
<metaname="viewport"content="width=device-width, initial-scale=1.0" />
<style>
div {
width: 400px;
height: 80px;
border: 10px solid black;
padding: 15px;
background-color: greenyellow;
/* clips the background color to content only */
background-clip: content-box;
}
</style>
<title>CSS Box Model</title>
</head>
<body>
<div>
The CSS box model is a way of describing the layout of an HTML
element.
</div>
</body>
</html>
Note: The margin property also affects the total space that the box will take up on the page,
but the margin is not included in the actual size of the box. The box's total width and height
stops at the border.
Box-sizing:border-box;