Reputation: 195
Is there anyway to change an in-line background image so if screen size gets down to 767px in width the background URL is changed.
I have the following code at the moment:
<section class="inner-header" style="background:url(/images/sports-glasses.jpg) no-repeat center top;">
I know that I can set a class or ID to this section and use CSS instead and then use @media queries to change the image but for quickness I would like to know is there a way to change it inline?
Upvotes: 0
Views: 1011
Reputation: 431
I can't find a way around using CSS in an independant file, but here is my hybrid inline CSS solution:
.inner-header {
height: 300px;
background-position: top;
background-size: cover;
}
.responsive-bg {
background-image: var(--mobile-bg);
}
@media (min-width: 1024px) {
.responsive-bg {
background-image: var(--desktop-bg);
}
}
<section class="inner-header responsive-bg" style="--mobile-bg: url(https://cdn.pixabay.com/photo/2017/07/22/15/21/cat-2528935_1280.jpg); --desktop-bg: url(https://cdn.pixabay.com/photo/2016/01/19/17/54/dog-1149964_1280.jpg)">
Lorem ipsum
</section>
Upvotes: 0
Reputation: 318232
There is a way to change the inline styles, with javascript
$(window).on('resize', function() {
if ( $(this).width < 767 ) {
$('.inner-header').css('background', 'url(/images/other.jpg) no-repeat center top');
} else {
$('.inner-header').css('background', 'url(/images/sports-glasses.jpg) no-repeat center top');
}
});
Upvotes: 1
Reputation: 10440
There is a newish answer to responsive inline images using srcset="" which looks like this:
<img src="small.jpg"
srcset="large.jpg 1024w, medium.jpg 640w, small.jpg 320w"
sizes="(min-width: 36em) 33.3vw, 100vw"
alt="A rad wolf">
see this link for more info http://responsiveimages.org/
Upvotes: 1