๐ŸŽ“ A1Learner
๐Ÿ”

CSS Responsive Design

Responsive design makes one page work at many widths. It combines fluid widths, a max-width ceiling, shrinking images and media queries into one habit.

A fluid box, narrow screen

The box takes 90 percent of the page width. This render is 500 pixels wide, and the box follows it.

.box {
  width: 90%;
  max-width: 600px;
}

The same box, wide screen

The same code renders again at 1024 pixels wide. Ninety percent would pass 600 pixels, so the ceiling holds the box at 600.

.box {
  width: 90%;
  max-width: 600px;
}

An image that shrinks

The image asks for 400 pixels of width. max-width caps it at the width of its container.

.pic {
  width: 400px;
  max-width: 100%;
  height: auto;
}

The same image, narrow screen

The same code renders again at 300 pixels wide. The image shrinks to fit the page instead of spilling past its edge.

.pic {
  width: 400px;
  max-width: 100%;
  height: auto;
}

Example

.box {
  width: 90%;
  max-width: 600px;
}
.pic {
  max-width: 100%;
  height: auto;
}
ul {
  display: flex;
  gap: 12px;
}
@media (max-width: 600px) {
  ul {
    flex-direction: column;
  }
}

Key points

  • A fluid width in percent grows and shrinks with its container
  • max-width puts a ceiling on a fluid width
  • An image with max-width 100% never grows wider than its container
  • height auto keeps an image's proportions while it shrinks
  • Designing for narrow screens first is called mobile-first

In this example, the box is fluid with a ceiling of 600 pixels. The image can shrink but never outgrow its container. The list is a flex row with a gap. This render is 500 pixels wide, so the media query matches and the list stacks into a column.

Note

Test a responsive page by resizing the window, not by checking a list of devices.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does max-width do on a fluid box?