CSS Images Summary

CSS controls how images fit inside a layout without stretching, overflowing, or becoming awkward on different screen sizes.

img {
	max-width: 100%;
	height: auto;
}

The HTML Images lesson explains the image element, source, alternative text, and size attributes. CSS controls how the image appears in the layout.

Large Images Can Overflow

Image files have natural dimensions. If an image is wider than its container, it can spill out and create horizontal scrolling.

The rule max-width: 100% lets the image shrink to fit its container while keeping its natural size when there is enough room.

Height Auto Preserves Proportions

When the image width changes, the height should usually change by the same proportion.

img {
	max-width: 100%;
	height: auto;
}

height: auto lets the browser calculate the correct height, which prevents stretched or squeezed images.

Object Fit Controls Cropping

Sometimes an image needs to fill a box with a set width and height. The object-fit property controls how the image fits inside that box.

.card-image {
	width: 300px;
	height: 180px;
	object-fit: cover;
}

cover fills the box and may crop part of the image. contain keeps the whole image visible and may leave empty space.

Display Block Removes The Inline Gap

Images are inline elements by default. This can leave a small space below an image because the browser aligns it with nearby text.

img {
	display: block;
	max-width: 100%;
	height: auto;
}

display: block removes that text-alignment gap and often makes images easier to place in layouts.

Interactive Demo

width: 250px; max-width: 100%; height: auto;

180px Container

cat

Code Sandbox

AI Tutor