Lesson 3: Box Model Fundamentals
The CSS Box Model is essential for understanding how elements are laid out on a web page. Every HTML element is considered a box, and the box model defines the space an element takes up, including its content, padding, border, and margin.
Components of the Box Model:
- Content: This is where the text or other media inside the element resides.
- Padding: The space between the content and the border. It affects the internal spacing of the element.
- Border: A line that wraps around the padding (if any) and content.
- Margin: The space outside the border. It separates the element from its surrounding elements.
Here’s a diagram to help you visualize:
+-------------------------------+
| Margin |
| +-------------------------+ |
| | Border | |
| | +-------------------+ | |
| | | Padding | | |
| | | +-------------+ | | |
| | | | Content | | | |
| | | +-------------+ | | |
| | +-------------------+ | |
| +-------------------------+ |
+-------------------------------+
CSS Properties of the Box Model
-
Width and Height: You can specify the
width
andheight
of an element's content box.div {
width: 200px;
height: 100px;
} -
Padding: Adds space between the content and the border. You can set padding for each side individually, or use shorthand.
div {
padding: 10px; /* Equal padding on all sides */
padding-top: 20px; /* Different padding for top */
} -
Border: Surrounds the padding (and content if no padding). You can define the border's width, style, and color.
div {
border: 2px solid black;
} -
Margin: Controls the space outside the border, separating the element from others. Like padding, margins can be set individually or with shorthand.
div {
margin: 10px;
margin-left: 20px; /* Different margin for left */
}
Box-Sizing Property
By default, when you set width
and height
, CSS adds padding and border outside of those dimensions. This can make layout calculations tricky.
To simplify layout management, you can use:
div {
box-sizing: border-box;
}
This changes the box model so that padding
and border
are included within the specified width
and height
.
Box Model Example:
div {
width: 300px;
padding: 20px;
border: 5px solid black;
margin: 15px;
}
In this example:
- The content width is 300px.
- The padding adds 20px on all sides, making the content area effectively 340px wide.
- The border adds 5px, making the box 350px wide.
- The margin is 15px, which separates this box from surrounding elements by that amount.
Overflow Property
The overflow
property handles content that exceeds the box’s defined size. Options include:
visible
(default): The overflow content is displayed outside the box.hidden
: The overflow content is clipped.scroll
: Adds scrollbars for overflow content.auto
: Adds scrollbars only when necessary.
div {
width: 200px;
height: 100px;
overflow: scroll;
}