Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap change image according to device

I want to show different images in different devices (not background image). Is it possible to do using bootstrap 3.x like the following?

For large screen

<img src="large-image.jpg" />

for medium device

<img src="medium-image.jpg" />

for small device

<img src="small-image.jpg" />

and so on.

Thanks in advance.

N.B. Finally I have found a good solution by myself. See the accepted answer below.

like image 607
Siddiqui Noor Avatar asked Aug 25 '14 09:08

Siddiqui Noor


People also ask

How do you make images responsive using Bootstrap?

Images in Bootstrap are made responsive with .img-fluid . max-width: 100%; and height: auto; are applied to the image so that it scales with the parent element.

Which class will you use to create a responsive image that changes its width based on the browser width?

Create responsive images by adding an .img-responsive class to the <img> tag. The image will then scale nicely to the parent element.

What does IMG-fluid do?

img-fluid class makes an image responsive by automatically applying max-width: 100%; and height: auto; to it. As a result: The image scales with the parent element's width. The browser does not make the image larger than its container.


2 Answers

Use the <img> tag and provide other images in the srcset attribute

<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" alt="yah">

It is described in detail here:

https://css-tricks.com/responsive-images-youre-just-changing-resolutions-use-srcset/

like image 123
René Winkler Avatar answered Sep 22 '22 13:09

René Winkler


If you want to load only the image relevant to the screen-size, I think the best way is with javascript. Create versions of your photos, and in this case the script looks for an img with "600x400" in the filename, and replaces it with "1200x800" when the screensize is bigger than 767px.

DEMO: http://www.bootply.com/Y8XECJpGjS#

Javascript

if ($(window).width() > 767) {
    $("img[src$='600x400']").each(function() {
        var new_src = $(this).attr("src").replace('600x400', '1200x800'); 
        $(this).attr("src", new_src); 
    });
}

HTML

<div class="thumbnail">
  <img src="//placehold.it/600x400">
</div>

NOTE: this example uses placehold.it images, but obviously you will create your own image versions, include something to identify them in the filename (i.e. 600px, small, v1, etc), and then use that unique string as the find/replace strings in the script. i.e. If your filenames are photo-small.jpg, photo-mediumd.jpg, photo-large.jpg, then the script looks for "small" and replaces with "medium" or "large" where appropriate.

NOTE: once the image loads, that's it - it does not dynamically change image out as you change the screensize. There is surely a solution that does that, but overkill if not needed.

like image 24
Shawn Taylor Avatar answered Sep 20 '22 13:09

Shawn Taylor