Sub topic 11
Adapting Images and Media
Switching CSS colors does not change an image file. A logo with dark text on a transparent background can vanish on a dark page. A bright photo can glare against a #121212 background. This chapter covers the main ways to adapt images, icons, canvas drawings, and embedded content to the active theme.
This chapter assumes you have already built the color tokens, the data-theme attribute, and the toggle from earlier chapters. Those tokens are the variables --bg and --text. The key problem here is that some image techniques follow only the system setting, so they can disagree with a manual toggle.
The working model
An image can react to the theme in three ways.
- The browser picks the file. The
<picture>element evaluates a media query and loads one source. - CSS restyles the same file. A
filter, or SVG colors that come from CSS, changes how one asset looks. - Script redraws it. Canvas and chart libraries paint pixels from values you pass in, so they need to be told when the theme changes.
The first way listens to the operating system only. It knows nothing about your data-theme attribute. The second way can follow either, because you write the selectors yourself. The third way follows whichever signals you wire up.
Swapping files with picture
The <picture> element lets the browser choose a source by media condition. The browser uses the first <source> whose condition matches. If none match, it uses the <img>.
<picture>
<source srcset="logo-dark.png" media="(prefers-color-scheme: dark)">
<img src="logo-light.png" alt="Company logo">
</picture>The alt text belongs on the <img>, which is always the rendered element. Do not repeat it on the <source> elements, which do not take an alt attribute.
Swapping files when you have a toggle
To make images obey data-theme, render both and let CSS hide one. This uses the same selector pattern as the color tokens from earlier chapters.
<img class="only-light" src="logo-light.png" alt="Company logo">
<img class="only-dark" src="logo-dark.png" alt="Company logo" loading="lazy">.only-dark {
display: none;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) .only-light {
display: none;
}
:root:not([data-theme="light"]) .only-dark {
display: inline;
}
}
:root[data-theme="dark"] .only-light {
display: none;
}
:root[data-theme="dark"] .only-dark {
display: inline;
}The rules cover three cases.
- No
data-themeset, system dark: the media query matches and the dark image shows. data-theme="light", system dark: the:not([data-theme="light"])guard stops the media rule, so the light image stays.data-theme="dark", system light: the explicit rule shows the dark image.
An element with display: none is removed from the accessibility tree, so screen readers hear the logo once. Browsers may still download a hidden image. loading="lazy" on the image that starts hidden usually prevents that download until it is shown, but the behavior is browser-dependent. Test it in the Network panel instead of assuming.
Dimming photos with a filter
Photos do not need a second file. A mild brightness reduction keeps them from dominating a dark page.
@media (prefers-color-scheme: dark) {
img.photo {
filter: brightness(0.85);
}
}That version follows only the system setting. To honor the toggle, repeat the guard pattern. A custom property keeps the value in one place.
:root {
--photo-filter: none;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--photo-filter: brightness(0.85);
}
}
:root[data-theme="dark"] {
--photo-filter: brightness(0.85);
}
img.photo {
filter: var(--photo-filter);
}Now each theme block sets one token, and img.photo is written once. Values between about 0.8 and 0.9 are a common starting range. Lower values start to make photos look muddy, so check real photographs and not only test gradients.
SVG icons that follow the text color
An SVG placed inline in the HTML is part of the page, so CSS reaches inside it. Setting fill="currentColor" makes the shape use the element's color value, which is already themed through --text.
<button class="icon-button" aria-label="Search">
<svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true">
<circle cx="10" cy="10" r="6" fill="none" stroke="currentColor" stroke-width="2"/>
<line x1="15" y1="15" x2="21" y2="21" stroke="currentColor" stroke-width="2"/>
</svg>
</button>.icon-button {
color: var(--text);
background: none;
border: 0;
}The icon changes with the theme and needs no extra rules. For multi-color SVGs, use custom properties inside the markup, such as fill="var(--accent)", and define --accent as a token.
An SVG loaded through <img src="icon.svg"> or as a CSS background is a separate document. It cannot see your page's custom properties or currentColor. A file like that can contain its own <style> with a prefers-color-scheme media query. That follows the system setting and is not affected by data-theme.
Background images
CSS background images can be swapped through a token, which works with both the system setting and the toggle. Put the url() in the custom property.
:root {
--hero-image: url("hero-light.jpg");
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--hero-image: url("hero-dark.jpg");
}
}
:root[data-theme="dark"] {
--hero-image: url("hero-dark.jpg");
}
.hero {
background-image: var(--hero-image);
background-size: cover;
}Relative URLs inside a custom property are resolved against the stylesheet where var() is used. If your stylesheet and the tokens live in different folders, use root-relative paths such as /img/hero-dark.jpg.
Transparent logos
Transparent PNGs and SVGs are the most common source of invisible content. Dark text with a transparent background disappears on a dark page. You have three options.
| Option | Cost | Best for |
|---|---|---|
| Provide a second, light-colored version | Two assets to maintain | Brand logos |
| Place the image on a light badge with `background` and padding | Looks like a deliberate chip | Partner logos you cannot edit |
| Use `filter: invert(1)` | Hue shifts, wrong for colored art | Pure black or white glyphs only |
Inversion is quick for a black icon, but it rotates colors. It makes a blue logo orange, so avoid it for brand colors.
Canvas, charts, and embedded content
Canvas pixels are drawn once and do not respond to CSS. Read the current token values with getComputedStyle and redraw when the theme changes. Two signals can change the theme: the system setting and the data-theme attribute.
const canvas = document.querySelector("#chart");
const ctx = canvas.getContext("2d");
function draw() {
const styles = getComputedStyle(document.documentElement);
const bg = styles.getPropertyValue("--bg").trim();
const text = styles.getPropertyValue("--text").trim();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = bg;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = text;
ctx.font = "20px sans-serif";
ctx.fillText("Monthly sales", 20, 40);
}
draw();
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", draw);
new MutationObserver(draw).observe(document.documentElement, {
attributes: true,
attributeFilter: ["data-theme"],
});This assumes the --bg and --text tokens from earlier chapters, with <canvas id="chart" width="400" height="120"> in the page. Chart libraries usually accept colors as options. Pass them in the same way and call the library's update method from draw.
Videos do not change with the theme. If a video has a white background, consider a subtle border or rounded corners so it reads as a deliberate panel.
Iframes need care. When an embedded page uses a different color-scheme from the page that contains it, browsers give the iframe an opaque background so the content stays readable. You may see a white or dark rectangle around an otherwise transparent embed. Fix this by making the embedded page declare the same color-scheme, or by styling the iframe's container so the box looks intentional.
Common errors
- Using
<picture>with a toggle. The image follows the system and disagrees with the page. Use the class-based swap. - Forgetting the guard selector. A bare
@media (prefers-color-scheme: dark)block forces dark styles even when the user chose light. - Expecting an external SVG to inherit page colors. Only inline SVG can use
currentColorfrom the page. - Darkening every image. Filters distort screenshots and brand art.
- Not redrawing canvases. The chart stays in the old theme until the next redraw.
- Missing alt text on the swapped image. Both versions need the same
alt, or a decorative image needsalt="".
Exercise
A page has a theme toggle that sets data-theme on the root element. The logo uses a picture element with a source whose media attribute is (prefers-color-scheme: dark). A user on a dark-mode operating system clicks the toggle to choose light, and the page turns light but the logo shows its dark-theme version. Why does this happen, and how do you fix it?
Show answer
The media attribute on a source element reads the operating system preference. It does not see the data-theme attribute, so the browser still selects the dark source. Replace the picture element with two img elements that have the classes only-light and only-dark. Show one of them with CSS rules keyed to data-theme, and use the :not([data-theme="light"]) guard inside a prefers-color-scheme media query so the system setting still applies when no choice has been saved.
Exercise
You define --photo-filter: none in :root and set it to brightness(0.85) for dark themes. The rule img.photo { filter: var(--photo-filter); } is written once. What is the advantage over writing filter: brightness(0.85) inside each theme block?
Show answer
The filter declaration appears in one place, and each theme block only sets a token. Adding a third theme or adjusting the value later means changing the token, with no duplicated selectors for img.photo.