Lesson 12 +10 XP

Height, Width & max-width

Height, Width & Max-width

Set the size of elements with height, width, and their max/min cousins.

width and height

div {
  height: 200px;
  width: 50%;
}
  • px: a fixed size.
  • % of the parent: width: 50% is half the parent's width.
  • auto: the browser figures it out.

How percentages work

width: 50% is relative to the parent element's width. height percentages are trickier (the parent needs a height too).

max-width

"Never grow wider than this."

div {
  max-width: 400px;
}

Content wraps, but the box NEVER goes past 400px.

max-width: prevents the element from being wider than the value, unlike width` max-width lets it shrink-or-grow smaller.

min-width/min-height

"Never shrink smaller than this":

+min-width, min-height.

The classic centering pattern

max-width + margin: auto:

p {
  max-width: 600px;
  margin: auto;
}

Text now stays readable on big screens AND shrinks on phones.

TL;DR

  • width/height: set a size (px or %).
  • max-width: cap the width.
  • min-width/min-height: floor.
  • max-width + margin:auto = a nice readable column.
  • Useful for responsive design.