Sub topic 1
Every Element Is a Box
Prerequisites
You should know basic HTML structure, CSS selectors and declarations, and common length units such as px, em, rem, and %.
Every element is a box
CSS lays out each HTML element as a rectangular box. The box has four layers:
- Content: the text, image, or child elements.
- Padding: space between the content and border.
- Border: the visible edge around the box.
- Margin: space outside the border, which separates the box from other boxes.
This chapter focuses on the first three layers. Together, they determine the box's rendered size.
The content area: width and height
By default, width and height apply only to the content area. This default is called content-box sizing.
.card {
width: 300px;
height: 120px;
padding: 20px;
border: 5px solid #333;
}The content is 300 pixels wide and 120 pixels high. The padding and border are added outside those dimensions:
- Total width:
300 + 20 + 20 + 5 + 5 = 350px - Total height:
120 + 20 + 20 + 5 + 5 = 170px
The two padding values represent the left and right, or top and bottom, sides.
Padding: space inside the border
Padding creates internal space. It pushes content away from the border and increases the box's size under content-box sizing.
.card {
padding: 12px 24px;
}This sets 12 pixels of padding on the top and bottom, and 24 pixels on the left and right. Padding cannot be negative.
Border: the edge of the box
A border surrounds the padding and content. Set its width, style, and color together:
.card {
border: 2px solid #333;
}The border contributes to the rendered dimensions. A border style such as solid is required for the border to appear.
Exercise
A box has width: 200px, padding: 10px, and a border: 2px solid. What is its total width under content-box sizing?
Show answer
224px: 200 + 10 + 10 + 2 + 2.