Content box
Style the content box with the box model.
Width and box sizing: width, box-sizing
We don't want post cards to stretch across the whole screen; we use width to limit their size. But when we add padding, the browser adds it on top of the width, making the box bigger than planned.
To prevent this, we set box-sizing: border-box. Then padding and borders are counted inside the width, and the box stays at the size you specified.
Inner and outer spacing: padding, margin
padding is the inner space between the content and the element's edge; margin is the outer space between the element and its neighbors. Both can be set per side or with a shorthand.
For our post card, padding keeps content away from the edge, and margin gives breathing room between cards:
padding: 24px;
margin: 16px auto;The auto value splits the left-right space equally, centering the card horizontally.
Shorthand: four values in one line
Both padding and margin can take all four sides in one declaration. One value applies to all sides, two values apply to top-bottom and left-right, and four values apply in order: top, right, bottom, left.
Writing margin: 16px auto sets top-bottom to 16px and left-right to auto. This is a handy pattern for centering a card horizontally.
Exercise Add the post card rule
Take the file with the body rule from the previous lesson. Below it, add a .post rule with four declarations: width: 640px, padding: 24px, margin: 16px auto, and box-sizing: border-box. End each declaration with a semicolon; don't delete the body rule.
Show example solution
/* Travel Diary stylesheet */
body {
font-family: Georgia, "Times New Roman", serif;
font-size: 18px;
font-weight: 400;
line-height: 1.6;
}
.post {
width: 640px;
padding: 24px;
margin: 16px auto;
box-sizing: border-box;
}
Test yourself
-
Which property sets the width of an element?
- font-size
- color
- width
- padding
Show answer
width — Correct. The width property sets the horizontal size of an element.
-
Complete the padding value
padding: ____;Show answer
padding: 24px; -
Match each property to its sample value
- width
- 640px
- padding
- 24px
- margin
- 16px auto
- box-sizing
- border-box
-
Which margin shorthand centers a card horizontally?
- margin: 0;
- margin: 24px;
- margin: auto 0;
- margin: 16px auto;
Show answer
margin: 16px auto; — Correct. '16px auto' sets top-bottom to 16px and left-right to auto, centering the card.