CSS Images
Images are everywhere on the web — and CSS gives you powerful tools to control how they fit, scale, filter and behave responsively. From avoiding layout-breaking overflows to applying grayscale and blur effects without Photoshop, this chapter covers it all.
object-fit — cover, contain,
fill, none, scale-downobject-position — control the
focal pointfilter — grayscale, blur,
brightness and moreThe Responsive Image Reset
By default, <img> elements render at their
natural pixel size and overflow their container if larger. Three simple CSS rules fix this permanently:
img {
max-width: 100%; /* never wider than container */
height: auto; /* preserve aspect ratio */
display: block; /* remove inline baseline gap */
}
/*
max-width: 100% — shrinks on small screens, never overflows
height: auto — scales proportionally, no distortion
display: block — removes the 3–4px gap below inline images
(caused by text baseline alignment)
*/
width: 100%, this won't force small images to stretch
and pixelate.display: block eliminates
this gap.object-fit — Controlling How Images Fill Their Box
object-fit tells the browser how to size the
image content inside a fixed-dimension container. Without it, setting both width and height distorts the image.
Below is the same Unsplash photo in a fixed 100% × 130px box — each card uses a different object-fit value:
/* Apply a fixed size AND object-fit together */
.thumbnail {
width: 300px;
height: 200px;
object-fit: cover; /* fill box, crop edges */
}
.logo {
width: 120px;
height: 60px;
object-fit: contain; /* show whole logo, no distortion */
}
.avatar {
width: 48px;
height: 48px;
border-radius: 50%;
object-fit: cover; /* perfect circle crop */
}
/* All 5 values */
.fill { object-fit: fill; } /* stretch (default) */
.cover { object-fit: cover; } /* fill, may crop */
.contain { object-fit: contain; } /* fit whole image */
.none { object-fit: none; } /* natural size */
.scale-down { object-fit: scale-down; } /* min(none, contain) */
contain — logos, product shots, diagrams. Show every pixel, gaps around the image are acceptable.
object-position — The Focal Point
When object-fit: cover crops an image, object-position controls which part stays visible. It works exactly
like background-position. The same portrait photo cropped 9 different
ways:
All 9 cells use the same
photo at the same crop size — only object-position differs.
.hero-img {
width: 100%;
height: 400px;
object-fit: cover;
object-position: center; /* default */
}
/* Keywords — keep faces in frame */
.portrait { object-position: top; }
.landscape { object-position: center bottom; }
.left-focus{ object-position: left center; }
/* Percentage */
.custom { object-position: 30% 20%; }
/* Pixel offset */
.offset { object-position: 50px 80px; }
CSS filter — Visual Effects
The filter property applies photo-editing effects
entirely in CSS. Below is the same Unsplash nature photo with different filters applied — no image editor
involved:
img { filter: grayscale(100%); } /* 0–100% */
img { filter: blur(4px); }
img { filter: brightness(0.5); } /* 0=black, 1=normal, 2=double */
img { filter: contrast(1.5); }
img { filter: saturate(0); } /* 0=gray, 1=normal */
img { filter: sepia(1); }
img { filter: hue-rotate(180deg); }
img { filter: invert(1); }
img { filter: drop-shadow(2px 4px 6px black); }
/* Chain multiple — space separated */
.stylised {
filter: grayscale(30%) brightness(1.1) contrast(1.2);
}
/* Colour-reveal hover */
.card img { filter: grayscale(100%); transition: filter .4s; }
.card:hover img { filter: grayscale(0%); }
/* backdrop-filter — blur what is BEHIND the element */
.glass {
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
background: rgba(255,255,255,.12);
}
Image Hover Effects
CSS transitions make it easy to animate image states — hover over each card below to see the effect live:
/* ── Zoom on hover ── */
.card { overflow: hidden; }
.card img { transition: transform 0.4s ease; }
.card:hover img { transform: scale(1.08); }
/* ── Colour reveal ── */
.photo { filter: grayscale(100%); transition: filter .5s; }
.photo:hover { filter: grayscale(0%); }
/* ── Overlay reveal (pseudo-element) ── */
.thumb { position: relative; overflow: hidden; }
.thumb::after {
content: '';
position: absolute;
inset: 0;
background: rgba(38,77,228,.7);
opacity: 0;
transition: opacity .3s;
}
.thumb:hover::after { opacity: 1; }
/* ── Brightness ── */
.dim { filter: brightness(.65); transition: filter .3s; }
.dim:hover { filter: brightness(1.1); }
Card Grid — Real-World Pattern
The most common real-world use of object-fit: cover + aspect-ratio — a
uniform card grid where every thumbnail has the same dimensions regardless of the original image size. Hover
to see the zoom effect.
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 20px;
}
.card { overflow: hidden; border-radius: 12px; }
.card-thumbnail {
width: 100%;
aspect-ratio: 16 / 9; /* or use height: 200px */
object-fit: cover;
display: block;
transition: transform .4s ease;
}
.card:hover .card-thumbnail {
transform: scale(1.06);
}
Avatar Patterns
Avatars are one of the most common object-fit: cover use cases. The key is aspect-ratio: 1 combined with border-radius: 50%:
.avatar {
width: 48px;
aspect-ratio: 1; /* square */
border-radius: 50%; /* circle */
object-fit: cover; /* fill without distorting */
display: block;
}
/* With ring outline */
.avatar-ring {
width: 48px;
aspect-ratio: 1;
border-radius: 50%;
object-fit: cover;
border: 3px solid #264de4;
outline: 3px solid rgba(38,77,228,.3);
outline-offset:2px;
}
/* Stacked overlapping avatars */
.avatar-stack img {
width: 36px;
aspect-ratio: 1;
border-radius: 50%;
object-fit: cover;
border: 3px solid white;
margin-left: -12px; /* overlap */
}
.avatar-stack img:first-child { margin-left: 0; }
Responsive Image Patterns
Different use cases need different approaches. Here are the most important patterns used in real projects:
height: auto;
display: block;
aspect-ratio: 16/9;
object-fit: cover;
height: 100svh;
object-fit: cover;
object-position: center top;
svh handles mobile browser bars.
aspect-ratio: 1;
border-radius: 50%;
object-fit: cover;
height: auto;
object-fit: contain;
aspect-ratio: 16/9;
Modern Image HTML — width, height, loading & srcset
CSS alone is not enough — good image performance also requires the right HTML attributes for Core Web Vitals:
<!-- Always include width + height to prevent CLS (layout shift) -->
<img
src="hero.jpg"
alt="Descriptive alt text"
width="1200"
height="600"
loading="lazy" /* defer until near viewport */
decoding="async" /* off-thread decode */
>
<!-- Above-fold LCP image: eager + high priority -->
<img
src="hero.jpg"
alt="Hero"
width="1200"
height="600"
loading="eager"
fetchpriority="high" /* LCP image — load first */
>
<!-- Responsive srcset — different sizes for different screens -->
<img
src="image-800.jpg"
srcset="image-400.jpg 400w, image-800.jpg 800w, image-1200.jpg 1200w"
sizes="(max-width:600px) 100vw, 800px"
alt="Responsive image"
loading="lazy"
>
<!-- picture element — AVIF > WebP > JPEG fallback -->
<picture>
<source srcset="photo.avif" type="image/avif">
<source srcset="photo.webp" type="image/webp">
<img src="photo.jpg" alt="Fallback JPEG">
</picture>
sizes describes how
wide the image renders at different viewports.Try It Yourself
This demo uses live Unsplash photos. Try changing object-fit values, object-position, and
filter to see the difference on real images.
Quick Check — Chapter 18
max-width: 100%; height: auto; display: block;max-width: 100% — prevents the image from overflowing its container on small screens. Unlike
width: 100%, it won't upscale small images and pixelate
them.height: auto — when the width changes due to max-width, the height adjusts proportionally. Without this, a constrained image squashes or distorts.
display: block — images are inline by default and sit on a text baseline, creating a 3–4px gap beneath them inside cards and containers. This gap causes subtle layout issues.
display: block eliminates it.
cover — scales until the container is completely filled. The image may be cropped on the sides or top/bottom. Nothing is left empty. Best for: card thumbnails, hero images, avatars, backgrounds.
contain — scales until the image fits entirely inside the container. The whole image is visible but there may be empty space around it. Best for: logos, product shots, diagrams where every pixel matters.
fill (default) stretches to fill, ignoring aspect ratio — almost
always undesirable.
filter property applies visual effects entirely in CSS.
Functions: grayscale(), blur(),
brightness(), contrast(), saturate(), sepia(), hue-rotate(), invert(), drop-shadow().Combining: space-separate multiple functions. They apply in order:
filter: grayscale(30%) brightness(1.1) contrast(1.2);drop-shadow() differs from box-shadow — it follows the actual transparent outline of the image, not
the rectangular box.backdrop-filter blurs what is behind the element — used for
glassmorphism effects.
object-position controls which part of the image stays visible when
object-fit: cover crops it. It works exactly like background-position.Default:
center — the centre of the image is
preserved.Most useful for:
— Portrait photos:
object-position: top keeps faces in frame even in
a wide, short crop.— Landscape shots:
object-position: center bottom keeps the
horizon.— Any image with an important subject off-centre:
object-position: 30% 20% for fine control.
width and height
attributes prevents Cumulative Layout Shift (CLS) — a Core Web Vitals metric that
measures unexpected page movement.Without declared dimensions, the browser doesn't know how much space to reserve. As each image loads, surrounding content jumps — a poor user experience and lower CLS score.
With declared dimensions, the browser reserves the exact space before loading. Combined with
max-width: 100%; height: auto; in CSS, the image still scales
responsively — the HTML attributes only establish the aspect ratio for space reservation, not the actual
rendered size.
object-fit value fills the container and
may crop the image?display: block added to the responsive
image reset?object-position: top do when used
with object-fit: cover?- Responsive reset:
img { max-width: 100%; height: auto; display: block; }— prevents overflow, preserves ratio, removes baseline gap. object-fit:cover(fill, may crop — use for cards/heroes/avatars),contain(fit whole image — use for logos),fill(stretches — default, rarely wanted).object-position: focal point for cover-cropped images. Usetopfor portraits so faces stay in frame.filter:grayscale(),blur(),brightness(),contrast(),sepia(),saturate(),hue-rotate(),invert(),drop-shadow(). Chain with spaces.- Hover effects: zoom (
transform:scale+overflow:hidden), colour reveal (filter:grayscale→0), overlay (opacity:0→1), brightness. All usetransition. - Card pattern:
aspect-ratio: 16/9 + object-fit: covergives every thumbnail the same dimensions regardless of source image size. - HTML attributes:
width+height(prevent CLS),loading="lazy"(below-fold),fetchpriority="high"(LCP hero image),srcset/sizes(responsive delivery),<picture>(AVIF→WebP→JPEG).
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.