CSS Box Model – Explained with Examples
A CSS box model consists of some set of boxes wrapped around an HTML element for styling purposes.
Parts of a CSS Box Model
The four (4) boxes that make up a CSS box model are:
- Margin box
- Border box
- Padding box
- Content box
Here’s an illustration:
The four boxes that make up a box model make it easy to create complex designs with CSS. Let’s discuss these boxes below.
What Is a Content Box?
A content box is the innermost part of a box model. It is where an HTML element’s content appears.
What Is a Padding Box?
A padding box is a transparent space around the content of a box model.
We use padding to separate the box model’s content from its border.
What Is a Border Box?
A border box is a strip of line that typically wraps the padding. But suppose you omit the padding. In that case, the border will wrap the content.
We use the CSS border
property to specify the width, color, and style of an HTML element’s border.
What Is a Margin Box?
A margin box is the transparent outermost edge of a box model.
The main function of a margin box is to separate a box model from other box models.
Example: A <div>
Element’s Box Model Demonstration
The snippet above specified three properties that we have not discussed: background-color
, width
, and height
—so, let’s talk about them below.
What Is a CSS background-color
Property?
A CSS background-color
property defines the color of an HTML element’s background.
What Is a CSS width
Property?
A CSS width
property defines the width of an HTML element.
What Is a CSS height
Property?
A CSS height
property defines the height of an HTML element.
Important Stuff to Know about the width
and height
Properties
By default, the CSS width
and height
properties set the content box’s width and height.
But suppose you want the width
and height
properties to refer to an HTML element’s border—not its content. In that case, set the box-sizing
property’s value to border-box
.
Example: box-sizing
Configured to Make the width
and height
Reference the Border Box
The background
property is a shorthand for the following properties: