Computer >> Computer tutorials >  >> Programming >> CSS

What is Box Model in CSS?


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 −

What is Box Model in CSS?

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.

Padding 

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

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

Output

This gives the following output −

What is Box Model in CSS?

Example

<!DOCTYPE html>
<html>
<head>
<style>
body * {
   outline: thin dotted;
}
#demo {
   margin: auto;
   width: 120px;
   height: 120px;
   padding: 1em;
   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;
   border-bottom-right-radius: 100px;
   border-bottom-left-radius: 100px;
}
div:nth-child(even) {
   border: inset lightblue;
   padding: 0.5em;
}
</style>
</head>
<body>
<div id="demo">
<div></div>
<div></div>
<div></div>
</div>
</body>
</html>

Output

This gives the following output −

What is Box Model in CSS?