CSS Basics · Lesson 6 of 11

Width and Centering

Block elements such as <div>, <p> and <main> are as wide as the space they are in. On a big screen that makes lines of text far too long to read comfortably.

Width and max-width

width sets an exact width. The trouble is that a box with width: 700px sticks out of a phone screen that is only 390 pixels wide.

max-width is the better tool. The box is allowed to shrink on small screens, but never grows wider than the limit:

main {
  max-width: 700px;
}

Centering a box

A box that is narrower than the page sits on the left. To center it, set the left and right margins to auto. The browser then shares the leftover space equally between both sides:

main {
  max-width: 700px;
  margin: 0 auto;
}

This two-line pattern is on almost every website you visit. margin: 0 auto means: zero on top and bottom, automatic on the left and right.

text-align: center centers the text inside a box. margin: 0 auto centers the box itself. They are different jobs, and many pages use both.

Sizes in percent

A width can also be a share of the available space: width: 50% is half as wide as the parent element.

Your Task

  1. Limit main to a max-width of 500px.
  2. Center it on the page with automatic left and right margins.
  3. Make the image 100% wide, so it always fills the column and never sticks out.
  • main has a max-width of 500px
  • main is centered with automatic left and right margins
  • The image is as wide as the space inside main