CodeBlanks Logo Icon CodeBlanks

Width and height

CSS course · Beginner · Lesson 27/82

Learn width and height properties.

Width and height

width sets the content width of a box, height sets the content height. These two properties measure only the content box; padding, border and margin are added on top.

Values can be pixels (px), percentages (%) or auto. auto asks the browser to distribute space itself; for example, block elements fill the full width by default.

min-width and max-width

Sometimes you want to bound how small or large a box can get. min-width forces a minimum width, max-width forces a maximum width.

For example, set width: 100% with max-width: 600px on a card: on small screens it fills the width, on large screens it never exceeds 600 pixels. This is called a fluid but bounded layout.

Exercise Write a fluid card

Write a block for the .card selector. Make it full width (width: 100%) but never wider than 600 pixels (max-width: 600px).

Show example solution
.card {
  width: 100%;
  max-width: 600px;
}

Test yourself

  1. What does the width property measure?

    • Only the content area
    • Only padding
    • Content, padding and border together
    • The whole box (including margin)
    Show answer

    Only the content area — Correct. width measures only the content area; padding and border are added on top.

  2. Fluid card rule

    .card {
      width: 100%;
      ____: 600px;
    }
    Show answer
    .card {
      width: 100%;
      max-width: 600px;
    }
  3. When is max-width useful?

    • To shrink the card as the window narrows
    • To stop the card from getting too wide on a large screen
    • To change the card's background color
    • To center the card horizontally
    Show answer

    To stop the card from getting too wide on a large screen — Correct. max-width keeps the card from growing without bound on a wide screen.

  4. Match each size property to its role

    width
    Sets the content width
    height
    Sets the content height
    max-width
    Caps the maximum width
    min-width
    Forces the minimum width

All lessons in Beginner