Tutorials CSS Images
Ch 18 / 60
Chapter 18 Beginner 7 min read CSS

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.

What you'll learn
The responsive image reset — max-width, height: auto
object-fit — cover, contain, fill, none, scale-down
object-position — control the focal point
filter — grayscale, blur, brightness and more
Image hover effects and smooth transitions
Aspect-ratio, lazy loading and modern image HTML

The 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:

CSS — Responsive image reset (add to every project)
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)
*/
max-width: 100%
The image shrinks to fit its container but never grows beyond its natural size. Unlike width: 100%, this won't force small images to stretch and pixelate.
height: auto
When width changes, height adjusts proportionally — the original aspect ratio is always preserved. Without this, images squash or distort.
display: block
Images are inline by default and sit on a text baseline, creating a 3–4px gap beneath them inside cards and containers. 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:

Code on screen — fill demo
fill (default)
Stretches to fill — distorts aspect ratio.
Code on screen — cover demo
cover ✓ most used
Fills box, may crop edges. No distortion.
Code on screen — contain demo
contain
Whole image visible, may show gaps.
Code on screen — none demo
none
Natural size, no scaling. May overflow.
Code on screen — scale-down demo
scale-down
Smaller of none or contain. Never upscales.
CSS — object-fit
/* 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) */
cover for cards, contain for logos
cover — card thumbnails, hero images, avatars, backgrounds. Fill the space, cropping is fine.
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:

portrait
top left
portrait
top
portrait
top right
portrait
left
portrait
center ✓
portrait
right
portrait
bottom left
portrait
bottom
portrait
bottom right

All 9 cells use the same photo at the same crop size — only object-position differs.

CSS — object-position
.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:

Nature — no filter
none (original)
filter: none
Nature — grayscale
grayscale
grayscale(100%)
Nature — blur
blur
blur(3px)
Nature — dark
brightness dark
brightness(0.4)
Nature — bright
brightness bright
brightness(1.6)
Nature — contrast
contrast
contrast(2)
Nature — sepia
sepia
sepia(100%)
Nature — desaturate
desaturate
saturate(0.2)
Nature — oversaturate
oversaturate
saturate(2.5)
Nature — hue rotate
hue-rotate
hue-rotate(120deg)
Nature — invert
invert
invert(1)
Nature — combined
combined
gray+bright+contrast
CSS — filter
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:

Code — zoom hover
Zoom on hover
overflow:hidden + transform:scale(1.1)
Team working — grayscale hover
Colour reveal
filter:grayscale(100%) → 0% + transition
Developer — overlay hover
View Project
Overlay reveal
pseudo-element opacity:0→1 transition
Tech workspace — brightness hover
Brightness reveal
filter:brightness(.65) → 1.1 on hover
CSS — Hover effects
/* ── 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.

Code editor
Introduction to CSS
5 min · Beginner
Web design
CSS Flexbox Layout
8 min · Intermediate
Responsive design
Responsive Design
10 min · Intermediate
CSS animations
CSS Animations
7 min · Advanced
CSS — Card thumbnail pattern
.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 1
Avatar 2
Avatar 3
Avatar 4
Avatar 5
Stacked 1 Stacked 2 Stacked 3
+5
CSS — Avatar patterns
.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:

Basic responsive
max-width: 100%;
height: auto;
display: block;
Universal reset. Prevents overflow, preserves ratio, removes gap. Add to every project.
Card thumbnail
width: 100%;
aspect-ratio: 16/9;
object-fit: cover;
Uniform cards regardless of source image dimensions.
Hero / banner
width: 100%;
height: 100svh;
object-fit: cover;
object-position: center top;
Full-viewport image. svh handles mobile browser bars.
Avatar circle
width: 48px;
aspect-ratio: 1;
border-radius: 50%;
object-fit: cover;
Perfect circle regardless of original image shape.
Logo
max-width: 160px;
height: auto;
object-fit: contain;
Logo never distorts. Full image always visible.
Video embed
width: 100%;
aspect-ratio: 16/9;
Always 16:9 at any width. Works for iframes and video elements.

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:

HTML — Modern image attributes
<!-- 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>
width & height attributes
Always add the natural pixel dimensions. The browser reserves space before the image loads, eliminating Cumulative Layout Shift (CLS) — a Core Web Vitals metric.
loading="lazy"
Defers loading until the image approaches the viewport. Reduces initial page load data significantly. Use on all below-fold images. Do NOT use on the above-fold hero (LCP) image.
fetchpriority="high"
Tells the browser to fetch this image with high priority. Use on your Largest Contentful Paint (LCP) image — the first visible hero/banner image — to improve LCP scores.
srcset & sizes
Provides multiple file versions at different widths. The browser picks the best one for the screen — saving data on mobile. sizes describes how wide the image renders at different viewports.
<picture> element
Serves AVIF (best compression) → WebP (wide support) → JPEG (universal fallback). Modern formats can be 40–80% smaller than JPEG at the same quality.
Free Resource
CSS3 Cheat Sheet — All Properties & Selectors
Complete reference covering object-fit, filter, responsive image patterns and all CSS3 properties.
Download PDF

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.

Live Editor
✎ Editor
👁 Preview
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React and Node.js with real projects and placement support.
120+
Chapters
40 hrs
Content
10 Real
Projects
4.9 ⭐
Rating
HTML5CSS3JavaScriptReact.jsNode.jsTailwind CSSAI Tools

Quick Check — Chapter 18

Questions & Answers
The three-rule reset is 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.
Both scale the image while preserving its aspect ratio — but they differ in priority:

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.
The 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.
Adding 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.
Multiple Choice Questions
Question 1 of 5
Which object-fit value fills the container and may crop the image?
Question 2 of 5
Why is display: block added to the responsive image reset?
Question 3 of 5
Which CSS filter turns an image black and white?
Question 4 of 5
What does object-position: top do when used with object-fit: cover?
Question 5 of 5
Which HTML attribute defers image loading until it approaches the viewport?
Chapter Summary
  • 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. Use top for 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 use transition.
  • Card pattern: aspect-ratio: 16/9 + object-fit: cover gives 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).
~7 min read
Beginner level
Chapter 18 of 60

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel