JSFiddle - React, Tailwind, and code Playground
HTML
<div class="bg-image"
data-bg="https://cdn.pixabay.com/photo/2016/09/04/20/14/sunset-1645103_960_720.jpg,https://cdn.pixabay.com/photo/2018/05/18/16/41/globe-3411506_960_720.jpg"
>
</div>
CSS
:root {
--bg-desktop: none;
--bg-mobile: none;
}
.bg-image {
min-height: 200px;
}
@media screen and (max-width: 768px) {
.bg-image {
background-image: var(--bg-mobile);
}
}
@media screen and (min-width: 769px) {
.bg-image {
background-image: var(--bg-desktop);
}
}
JavaScript
(function () {
const div = document.querySelector('.bg-image'),
src = div.getAttribute('data-bg').split(','),
html = document.documentElement;
html.style.setProperty('--bg-desktop', `url(${src[0]})`);
html.style.setProperty('--bg-mobile', `url(${src[1]})`);
}());