Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 139 ยท Backgrounds and Effects

Styling Images

Style images with CSS - responsive images, rounded and circular photos, thumbnails, hover overlays, captions, grid galleries, sprites and an image lightbox with dialog.

Images are the first thing visitors notice on most pages, and a few lines of CSS decide whether they look polished or broken. In Sizing Images you learned how to fit an image into a box with object-fit and aspect-ratio. This lesson builds on that and covers the everyday patterns: making images responsive, rounding them into circles, framing thumbnails, placing captions and overlays on top, laying out a gallery and opening a full-size view.

You will also meet one historical technique, image sprites, so you can recognize it in older code, along with the modern tools that replaced it.

A responsive baseline

An <img> is displayed at its natural size by default. A 1200-pixel photo in a 360-pixel phone screen overflows the page. One small rule fixes that for every image on the site:

CSS
img {
  max-width: 100%;  /* never wider than its container */
  height: auto;     /* keep the proportions when the width shrinks */
  display: block;   /* no mysterious gap underneath */
}
  • max-width: 100% lets the image shrink but never stretches it beyond its natural size.
  • height: auto matters when the HTML has width and height attributes (which it should, so the browser can reserve space). Without it, the height attribute would stay fixed and the image would squash.
  • display: block removes a small gap under the image. Images are inline by default, so they sit on the text baseline, and the space below it, reserved for letters like "g" and "y", shows up as a few pixels of empty space.
The gap under inline images

vertical-align: middle (or top) also removes the gap if you need the image to stay inline, for example an icon inside a line of text. The HTML side of responsive images, serving different files to different screens with srcset and <picture>, is covered in Responsive Images.

Rounded corners, circles and thumbnails

border-radius works on images just like on boxes. A small radius softens a photo; 50% turns a square image into a circle. For avatars, the image is rarely a perfect square, so combine three properties:

CSS
.avatar {
  width: 96px;
  aspect-ratio: 1;      /* force a square box */
  object-fit: cover;    /* crop the image to fill it */
  border-radius: 50%;   /* then round it into a circle */
}

If you skip aspect-ratio and object-fit, a rectangular photo becomes an oval instead of a circle.

A thumbnail is a small preview, often framed with padding and a border so it stands out from the page. Padding on an <img> sits between the picture and its border, so you get a frame without any extra element.

Rounded, circular and framed images

The avatar uses a neat double ring: a white border followed by a box-shadow with zero blur and a 2px spread, which draws a second, colored ring outside the border. You saw that trick in Box Shadows.

Captions and overlays on images

Placing text on top of an image is a job for positioning: make the container position: relative, then place the caption with position: absolute. A <figure> with a <figcaption> is the natural markup, because it ties the caption to the image for assistive technology too.

Text over a photo is hard to read when the photo is busy or bright. The fix is a scrim: a dark gradient behind the text that fades out towards the middle of the image.

CSS
.photo { position: relative; }
.photo figcaption {
  position: absolute;
  inset: auto 0 0 0;   /* stick to the bottom edge */
  padding: 24px 12px 10px;
  color: white;
  background: linear-gradient(transparent, rgb(0 0 0 / 0.7));
}

A hover overlay hides extra information until the pointer is over the image. Make it reachable for keyboard users too: if the card contains a link or button, show the overlay on :focus-within as well as :hover. Touch screens have no hover, so never put essential information only in a hover overlay.

Captions and hover overlays

Hover over the second image, or press Tab until the link is focused: the overlay fades in either way. Opacity is explained in detail in Opacity and Visibility.

CSS Grid makes a responsive gallery almost effortless. repeat(auto-fill, minmax(140px, 1fr)) creates as many columns as fit, and aspect-ratio with object-fit: cover makes every tile the same shape, whatever the original image proportions.

A gentle zoom on hover adds life. Put overflow: hidden on the tile so the enlarged image is clipped by its frame, and wrap the effect in a prefers-reduced-motion query so people who turned off animations don't get it.

A responsive grid gallery

The first tile spans two columns and gets a wider ratio, so the rows still line up. If the preview is too narrow for two columns, span 2 adds an extra column; a container query or a media query can switch the wide tile off on small screens. You will learn those in Responsive Web Design.

A lightbox with <dialog>

A lightbox shows a full-size version of an image over a dimmed page. The HTML <dialog> element does most of the hard work: showModal() puts it in the top layer, makes the page behind it inert, traps keyboard focus inside and closes on Esc. CSS only needs to style the dialog and its ::backdrop.

Use real <button> elements for the thumbnails, so they are focusable and work with the keyboard.

An image lightbox with dialog

Because the dialog has padding: 0, a click on the backdrop reports the <dialog> itself as its target, while clicks on the image or caption report those elements, so the small listener at the end can tell them apart. When the dialog closes, the browser returns focus to the thumbnail button that opened it.

Image sprites (and what replaced them)

Years ago, every image file meant a separate, slow HTTP request. To save requests, developers packed many small icons into one image, a sprite sheet, and showed one icon at a time by moving the background:

CSS
.icon {
  width: 32px;
  height: 32px;
  background: url("/img/icons.png") no-repeat;
}
.icon-home { background-position: 0 0; }
.icon-star { background-position: -32px 0; }  /* shift the sheet left */

Each icon is a 32 ร— 32 window onto the sheet; a negative background-position slides the right icon into view.

A CSS sprite sheet

The icons are decorative here because the text next to them carries the meaning. Sprites still work, but they have real drawbacks: one color per icon, fiddly positions to maintain, blurry scaling for bitmap sheets, and no way for assistive technology to know what an icon means. Modern alternatives are better in almost every case:

  • Separate files. HTTP/2 and HTTP/3 send many small files over one connection, so the original reason for sprites has mostly disappeared.
  • Inline SVG. Sharp at any size, styleable with CSS, and fill="currentColor" makes the icon match the text color. See SVG.
  • An SVG <symbol> sprite with <use href="#icon-star">: the modern take on a sprite, with one file and many icons, each still recolorable.
  • mask-image to tint one icon file in any color, as shown in Clip Paths and Masks.

Pixel-art scaling with image-rendering

When the browser shows a bitmap image larger than its real size, it has to invent the pixels in between. By default it smooths them, blending neighboring colors. That's right for photos, but it ruins images whose whole point is their hard pixels: pixel-art sprites, retro game graphics, QR codes and tiny icons enlarged on purpose. They come out blurry.

The image-rendering property chooses the scaling algorithm:

Value Effect
auto The browser's default smoothing (the initial value)
smooth Explicitly ask for smoothing, as for photos
pixelated Nearest-neighbor scaling: each source pixel becomes a crisp square block
crisp-edges Keep edges sharp with an algorithm of the browser's choice

In practice, use pixelated for pixel art. It's supported in all major browsers, while crisp-edges is not available in Chromium browsers at the time of writing and behaves differently from engine to engine. The property applies to <img>, <canvas>, <video> and background images alike.

The demo draws a tiny 8 ร— 8 pixel heart on a <canvas>, turns it into an image, and shows it at 12 times its size twice: once smoothed, once pixelated.

Smoothed versus pixelated scaling

The smoothed heart turns into a soft, fuzzy blob, while the pixelated one keeps every square sharp. For the cleanest result, scale by whole numbers (2ร—, 3ร—, 12ร—). At a scale like 2.5ร—, some source pixels have to become 2 screen pixels wide and others 3, so the blocks look uneven.

A few more tips:

  • Canvas games often draw at a low resolution, such as 320 ร— 180, and enlarge the canvas with CSS. Add image-rendering: pixelated to the <canvas> to keep the retro look.
  • Background images follow the same rule: .tile { background: url("tile.png") 0 0 / 64px; image-rendering: pixelated; } enlarges a 16px tile without blur.
  • Don't use it on photos. Nearest-neighbor scaling makes ordinary images look jagged. And vector images such as SVG are redrawn at full resolution anyway, so the property usually makes no difference for them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is there a small gap under an image inside a bordered box?

    Inline images align to the baseline, and the space below it is reserved for letters like g and y. display: block or vertical-align: middle removes the gap.
  2. 2. A 300 ร— 200 photo gets border-radius: 50% and looks like an oval. What makes it a circle?

    A 50% radius follows the box's shape. Forcing a square box and cropping the image into it gives a true circle.
  3. 3. How do you place a caption on top of an image?

    The absolutely positioned caption is placed relative to the nearest positioned ancestor, the figure.
  4. 4. Why is a hover-only overlay not enough to show important information?

    Show the overlay on :focus-within too, and never hide essential information behind hover alone.
  5. 5. What is the main reason image sprites became less necessary?

    Sprites existed to save HTTP requests. Modern protocols handle many small files efficiently, and SVG icons are more flexible anyway.

Summary

  • Start with img { max-width: 100%; height: auto; display: block; } for responsive images without the baseline gap.
  • border-radius rounds images; for a true circle, add aspect-ratio: 1 and object-fit: cover.
  • Padding, a border and a shadow on the <img> itself make thumbnails and photo frames.
  • Captions and overlays use a position: relative figure with an absolutely positioned layer; add a gradient scrim for readable text, and :focus-within for keyboard users.
  • A grid with auto-fill, minmax(), aspect-ratio and object-fit makes a tidy responsive gallery.
  • <dialog> with showModal() plus a little CSS gives you an accessible lightbox.
  • Sprites are a legacy technique; prefer separate files, inline SVG, SVG symbols or mask-image.

Next: Filters โ€” blur, brighten and recolor elements, and create frosted glass with backdrop-filter.