Real content is unpredictable; constraints instead of fixed sizes keep layouts intact with long words and odd images.
Fixed width and height break as soon as content changes. Constrain instead:
max-width: 100%stops images overflowing their container;min-heightlets a box grow with its content instead of clipping it.width: min(100%, 60rem)picks the smaller of two values, a one-line responsive container.max()picks the larger;clamp(min, preferred, max)combines both.aspect-ratio: 16 / 9gives a box a ratio, with the height computed from the width. Great for video embeds and card images.object-fit: covermakes an<img>fill its box, cropping instead of stretching;object-positionpicks the focal point.
When content is bigger than its box, overflow decides what happens: visible (default, spills out), hidden (clipped), auto (scrollbars only when needed), scroll (always) and clip (like hidden, but doesn't create a scroll container). overflow-x and overflow-y set each axis.
Long unbroken strings like URLs overflow narrow boxes. overflow-wrap: anywhere lets them break. For a single line with an ellipsis, combine white-space: nowrap; overflow: hidden; text-overflow: ellipsis. For several lines, use line-clamp, available today as -webkit-line-clamp together with display: -webkit-box and -webkit-box-orient: vertical.
scrollbar-gutter: stable reserves space for a scrollbar so content doesn't shift when one appears.
Example
img { max-width: 100%; height: auto; } /* never overflow the container */
.container { width: min(100% - 2rem, 70rem); margin-inline: auto; }
.thumb {
width: 100%;
aspect-ratio: 4 / 3;
object-fit: cover; /* crop, don't stretch */
object-position: center top;
}
.title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.excerpt { /* three lines, then ... */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
}
.comment { overflow-wrap: anywhere; } /* break very long URLs */
.panel { max-height: 20rem; overflow-y: auto; }Remember
- Prefer min/max constraints to fixed sizes
- min(), max() and clamp() compute responsive sizes
- aspect-ratio + object-fit: cover for consistent media boxes
- text-overflow: ellipsis needs nowrap and overflow: hidden
Watch out for
- Setting a fixed height on a text container, which clips or overflows when the text grows.