What is Box Model in CSS?

CSSWeb DevelopmentFront End Technology

Every element in an HTML document is rendered as a rectangular box by the browser. The width, height, padding and margin determine the space allocated in an around the element. The following diagram illustrates the box model concept −

Source: w3.org

Content

This includes the actual data in the form of text, image or other media content. The width and height properties modify the dimensions of this box.

The space between the outer edge of the content and its border refers to padding. This box can be resized by the padding property. Edge-specific properties like padding-left, padding-bottom, etc. help in achieving custom spacing.

Border

The distance between the outer edge of the padding and the inner edge of the margin defines the border of an element. By default, its width is set to 0. The border property is used to define an element’s border. Individual edges can also be styled.

Margin

The space between an element’s box and its surrounding elements’ box is defined as margin. This is analogous to the page margin which is defined as the space between the edge of a page and its content. It is transparent in color, simulating properties of padding, except that it clears area outside the element’s border. Like padding, the individual edges can be defined to have a custom margin.

Example

Live Demo

<!DOCTYPE html>
<html>
<style>
body * {
outline: solid;
}
#demo {
margin: auto;
width: 50%;
border: 1px outset;
display: flex;
box-shadow: inset 0 0 15px mediumvioletred;
box-sizing: border-box;
}
#demo div {
box-shadow: inset 0 0 9px orange;
}
</style>
<body>
<div id="demo">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</body>
</html>

Output

This gives the following output −

Example

Live Demo

<!DOCTYPE html>
<html>
<style>
body * {
outline: thin dotted;
}
#demo {
margin: auto;
width: 120px;
height: 120px;
border: 1px outset;
display: flex;
box-shadow: inset 0 0 15px indianred;
}
#demo div {
width: 40px;
height: 40px;
}
div:nth-child(odd) {
border: inset lightgreen;
}
div:nth-child(even) {
border: inset lightblue;
}
</style>
<body>
<div id="demo">
<div></div>
<div></div>
<div></div>
</div>
</body>
</html>

Output

This gives the following output −

Published on 08-Jan-2020 07:26:40