Responsive Design
fluid layouts, object-fit, aspect-ratio
Skills taught: css.responsive, css.object-fit, css.aspect-ratio
The viewport meta tag
<!-- Required in <head> for responsive sites -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- Without this, mobile browsers zoom out to fit desktop width -->
Fluid images and media
/* Make all images responsive by default */
img, video, svg {
max-width: 100%; /* never wider than the container */
height: auto; /* maintain aspect ratio */
display: block; /* remove inline baseline gap */
}
/* object-fit — how image fills its container */
.card-image {
width: 100%;
height: 200px; /* fixed container height */
object-fit: cover; /* fill the box, crop if needed */
object-position: center top; /* crop from top */
}
/* object-fit values:
cover — fill box, crop to maintain ratio (most common)
contain — fit inside box, may letterbox
fill — stretch to fill (distorts)
none — natural size, may overflow */
aspect-ratio — consistent proportions
/* Enforce consistent proportions */
.video-wrapper {
width: 100%;
aspect-ratio: 16 / 9; /* widescreen video */
}
.avatar {
width: 48px;
aspect-ratio: 1; /* perfect square */
border-radius: 50%; /* circle */
object-fit: cover;
}
.card-image {
width: 100%;
aspect-ratio: 4 / 3; /* photo card */
object-fit: cover;
}
Fluid layout without media queries
/* Auto-responsive card grid — NO media queries needed */
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 24px;
}
/* Fluid container with comfortable max-width */
.container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
padding: 0 clamp(1rem, 5vw, 4rem); /* fluid side padding */
}
Tip: repeat(auto-fill, minmax(280px, 1fr)) + object-fit: cover + aspect-ratio on images gives you a fully responsive image grid with zero media queries.
Frequently Asked Questions
What is the difference between max-width: 100% and width: 100%?
width: 100% forces the element to always be exactly its container's width. max-width: 100% allows the element to be smaller but prevents it from exceeding the container — ideal for images that should never overflow but shouldn't be forced full-width.
What are container queries?
Container queries (@container) let you apply styles based on a parent element's width rather than the viewport. A card component can change layout based on its container — so it works correctly in a sidebar (narrow) or in main content (wide).