Sizing Elements
Prerequisites: Margins, padding, and borders
width and height
Block elements are as wide as their container by default and as tall as their content. Setting fixed sizes is often a mistake:
- A fixed
widthin pixels breaks on small screens. - A fixed
heightmakes text overflow when it wraps, is translated, or when someone enlarges the font.
Use limits instead:
.content { max-width: 70ch; }
.hero { min-height: 60vh; }
img { max-width: 100%; height: auto; }
.sidebar { width: 100%; max-width: 20rem; }
img { max-width: 100%; height: auto; } is in almost every stylesheet:
images shrink to fit their container, keep their proportions, and never
grow beyond their natural size.
Intrinsic sizes
<style>
.row { width: 300px; }
.fit { width: fit-content; background: #eef; }
.min { width: min-content; background: #efe; }
.max { width: max-content; background: #fee; }
</style>
<div class="row">
<div class="fit">A short label</div>
<div class="min">A short label</div>
<div class="max">A much longer label that would normally wrap in 300px</div>
</div>
<script>
for (const cls of ["fit", "min", "max"]) {
const el = document.querySelector("." + cls);
console.log(cls, el.offsetWidth > 0, el.offsetWidth < 300 ? "narrower than the row" : "wider than the row");
}
</script>
fit true narrower than the row
min true narrower than the row
max true wider than the row
fit-content— as wide as the content needs, but no wider than the space available. Great for tags and buttons.min-content— as narrow as possible: the longest word.max-content— as wide as the content on one line, even if that overflows.
aspect-ratio
.video-frame { width: 100%; aspect-ratio: 16 / 9; }
.avatar { width: 4rem; aspect-ratio: 1; border-radius: 50%; }
The browser works out the height from the width — no padding hacks needed.
Overflow
When content doesn't fit its box, it overflows (visible by default).
overflow: auto adds scrollbars only when needed; hidden clips it.
Level 2 covers scrolling in depth.
Practice
Make a .card that is full width on small screens but never wider than
24rem, and whose image is always a 4:3 rectangle filling the card width.
Show solution
.card {
width: 100%;
max-width: 24rem;
}
.card img {
width: 100%;
aspect-ratio: 4 / 3;
object-fit: cover;
}
object-fit: cover crops the image instead of stretching it (Level 2).