width and height set the size of an element’s content area.
<style>
.box { width: 240px; height: 80px; background: #d0e8f2; border: 2px solid #1a5276; }
</style>
<div class="box">240px by 80px</div>
Block elements and the default
A block element, such as a div or p, is auto wide by default. That means “fill the available width”. If you leave the width alone, it adapts to the screen. Setting a fixed pixel width removes that flexibility.
Height is the opposite: it is auto too, but that means “as tall as the content needs”. Rarely set it. A fixed height is the usual cause of text spilling out of a box when someone zooms in or translates the page.
max-width: a flexible limit
<style>
.article { max-width: 360px; background: #fdf2e9; padding: 12px; }
</style>
<div class="article">
This box gets wider when there is room, but stops at 360px. On a narrow phone
screen it shrinks to fit instead of overflowing. That is exactly what you want
for text.
</div>
max-width is how you keep lines of text a comfortable length (45 to 75 characters is a common target) without breaking on small screens.
The family of sizing properties
| Property | What it does |
|---|---|
width / height | The preferred size |
min-width / min-height | Never smaller than this |
max-width / max-height | Never larger than this |
min-height is much safer than height: the box can grow if the content needs it.
Images that never overflow
img { max-width: 100%; height: auto; } is the classic rule. The image shrinks to fit its container but never stretches past its real size.A fixed height on text boxes
height: 100px on a card works until the text wraps onto a fourth line, and then it spills out. Use min-height unless the box really must be that tall.