Responsive Design

Responsive design in CSS is a technique for ensuring that websites look and function optimally on various devices, from desktop computers to smartphones. This can be achieved by using flexbox, grid layout, relative CSS unites and CSS media queries.

CSS Media Queries

Css Media queries are conditions that can be applied to different screen sizes, orientations, and resolutions.

Use media queries to apply different styles based on screen size:

@media (max-width: 600px) {
  .container {
    flex-direction: column; /* Stacks items vertically on small screens */
  }
}

CSS Units

Use relative units like em or rem for font sizes and spacing. This allows elements to scale proportionally with the screen size.

Example:

h1 {
  font-size: 2em;
}

There are two main categories of CSS units.

Relative Units

These units are relative to the size of the parent element or the viewport. This makes them responsive and adaptable to different screen sizes. Examples of relative units include:

  • rem: Relative to the root element's font size.
  • em: Relative to the font size of the parent element.
  • vw: Viewport width (1vw = 1% of the viewport width).
  • vh: Viewport height (1vh = 1% of the viewport height).
  • vmin: The smaller of vw and vh.
  • vmax: The larger of vw and vh.

Absolute Units

These units are fixed and do not change based on the size of the parent element or the viewport. Examples of absolute units include:

  • px: Pixels.
  • pt: Points (1pt = 1/72 of an inch).
  • in: Inches.
  • cm: Centimeters.
  • mm: Millimeters.

clamp

clamp(min, preferred, max)

The preferred value often uses a relative uinite like vw, %, em, etc. clamp() ensures the size stay within min and max.

.container {
  width: clamp(300px, 50vw, 800px);
}

In this case, the width of the .container will be 50% of the viewport width, if that falls within the bounds (300px to 800px), other wise it will be 300px or 800px.