The CSS Box Model
Talk about design and layout in CSS and the term box model soon comes up.
It describes a box wrapped around every HTML element, made of four parts: content, padding, border, and margin.
- Content — holds the text and images.
- Padding — a transparent area cleared around the content.
- Border — surrounds both padding and content.
- Margin — a transparent area cleared beyond the border.
Thanks to this model, we can put a border around elements and control the space between them.
Example
Each part of the box is visible on this div, which has a width, a green border, padding, and a margin.
<style> block, give a <div> width 300px, a 15px solid green border, 50px padding, and 20px margin. Add a background color so the content area is visible. Put text inside.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
background-color: lightgrey;
}
</style>
</head>
<body>
<h2>Demonstrating the Box Model</h2>
<p>The CSS box model is a box that wraps around every HTML element. It has content, padding, a border, and a margin.</p>
<div>This text is the content of the box. The padding, border, and margin sit around it.</div>
</body>
</html>
Width and Height of an Element
Getting width and height right in all browsers depends on understanding the box model.
Important: The width and height properties only size the content area. Padding and borders come on top, so add them to find the total size.
Total width = width + padding on the left and right + border on the left and right.
Total height = height + padding on the top and bottom + border on the top and bottom.
Note: The box's size ends at the border. A margin is not part of that size, though it does add to the space the box occupies on the page.
Example
Start from a width of 320px with 10px padding and a 5px border: the result is 350px of total width and 80px of total height.
<style> block, give a <div> width 320px, height 50px, padding 10px, a 5px solid gray border, and margin 0. The total width becomes 350px and the total height 80px. Put text inside.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
div {
width: 320px;
height: 50px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
</style>
</head>
<body>
<div>The total width is 350px and the total height is 80px.</div>
</body>
</html>