<picture>
<source media="(prefers-color-scheme: light)" srcset="https://via.placeholder.com/180/ffff00/000000?text=Light%20image">
<source media="(prefers-color-scheme: dark)" srcset="https://via.placeholder.com/180/002244/ffffff?text=Dark%20image">
<img src="https://via.placeholder.com/180/ffff00/000000?text=Light%20image%20fallback" alt="" />
</picture>
<div>
<button onclick="setPicturesThemed('light')">Set to 'light'</button>
<button onclick="setPicturesThemed('dark')">Set to 'dark'</button>
</div>
/***************************************
Presentational styles for demo only!
***************************************/
body {
display: flex;
font-family: sans-serif;
}
img {
display: block;
width: 100%;
}
div {
display: flex;
flex-direction: column;
margin-left: 15px;
}
button {
margin-bottom: 5px;
white-space: nowrap;
}
function setPicturesThemed(colorScheme = undefined) {
document.querySelectorAll(`picture > source[media*="(prefers-color-scheme: ${colorScheme})"]`).forEach(el => {
const cloned = el.cloneNode();
cloned.removeAttribute('media');
cloned.setAttribute('data-cloned-theme', colorScheme);
el.parentNode.prepend(cloned);
});
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.