Balalayka
Balalayka

Reputation: 357

How to change the src of an image dynamically with media queries in css or sass

I have a responsive website created with bootstrap and sass. I load the background image in the home page dynamically using bootstrap break points in sass.

At the same page I have other images that load heavily. I have created a way to load images based on width such that <img src='assets/img/myImage?width=500'> so that I reduce the size based on the viewport. But I coulnd't find a way to control the src of the img tag in sass file so that I use @media query and decide the width dynamically.

Any idea how to implement this?

Upvotes: 0

Views: 1464

Answers (1)

Quentin
Quentin

Reputation: 943759

You can't.

Images are content, not style. You can't use CSS to change them.

You can use media queries to change them, but you need to use a <picture> element to do so, not CSS.

Here is an example from MDN:

<picture>
    <source srcset="/media/cc0-images/surfer-240-200.jpg"
            media="(min-width: 800px)">
    <img src="/media/cc0-images/painted-hand-298-332.jpg" alt="" />
</picture>

Upvotes: 2

Related Questions