Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background image in mobile view using vue.js

Tags:

vue.js

I need to show different background image in mobile and desktop view using vue.js.

Here is the code.

<img :style="{ backgroundImage: 'url(' + offer.image + ')' }"/>
like image 449
User2893 Avatar asked Jan 28 '23 02:01

User2893


1 Answers

Basicly you want a Responsive Image, you could use Media Queries and load different sizes/image depending on your usage. The problem with that is that your image source is dynamic and the :style doesn´t support Media Queries.

I suggest you to use the src of the image instead of setting a background image. This way you can make use of srcset which lets you define breakpoints and loads images depending on that.

<img src="small.jpg" srcset="small.jpg 320w, medium.jpg 600w, large.jpg 900w" alt="">

Just as an example, depending on the window width the according image gets loaded.

Or you could use the <picture> tag for extended functionality:

<picture>
  <source media="(min-width: 56.25em)" srcset="large.webp" type="image/webp">
  <source media="(min-width: 56.25em)" srcset="large.jpg">

  <source media="(min-width: 37.5em)" srcset="medium.webp" type="image/webp">
  <source media="(min-width: 37.5em)" srcset="medium.jpg">

  <source srcset="small.webp" type="image/webp">
  <source srcset="small.jpg">
  <img src="fallback.jpg" alt="">
</picture>

I will also link you a AWESOME Guide about Images in the Web, reading this will help you a ton:

https://developers.google.com/web/fundamentals/design-and-ux/responsive/images?hl=en

like image 151
Badgy Avatar answered Mar 03 '23 20:03

Badgy