Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change an image path based on screen width?

I'm trying to change the folder that my images are read from depending on the window width.

I have two folders that contain the different image sizes and I'm wondering if anyone could give me any advice on how to change the path depending on the screens width.

If the screen is regular the <img> would look like

<img src="images/620x410/image1.jpg" alt="">

and If the screen was in the tablet width it would load

<img src="images/310x205/images1.jpg" alt="">

310X205

image1.jpg
image2.jpg

620X410

image1.jpg
image2.jpg
like image 758
Mitchell Layzell Avatar asked May 28 '13 08:05

Mitchell Layzell


People also ask

How do I adjust an image in HTML?

One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels. For example, the original image is 640×960.

What is the effect of applying height and width attributes to an image 1 point?

The effect will be that the page layout will change during loading (while the images load). Tip: Downsizing a large image with the height and width attributes forces a user to download the large image (even if it looks small on the page). To avoid this, rescale the image with a program before using it on a page.

How do I resize an image using CSS?

We can resize the image by specifying the width and height of an image. A common solution is to use the max-width: 100%; and height: auto; so that large images do not exceed the width of their container. The max-width and max-height properties of CSS works better, but they are not supported in many browsers.


1 Answers

If CSS using media queries is an option for you, you could use a CSS only solution.

Add the media queries to your CSS similar to the below:

@media screen and (max-width: 310px) {
  .yourClass {
    content:url("images/310x205/image1.jpg");
  }
}

@media screen and (min-width: 620px) {
  .yourClass {
    content:url("images/620x410/image1.jpg");
  }
}

Add the myClass to your effected image elements similar to the below:

<img class="yourClass">

You might need to tweak the values a little for your needs.

like image 178
Nope Avatar answered Sep 28 '22 05:09

Nope