Menas Eru
Menas Eru

Reputation: 118

CSS - Can different images be uploaded based on device resolution?

We have images in different sizes for desktop, tablet and phone devices. Can we tell browser what image to load using only CSS?

Can I use something like this?

<div class="image"></div>

<style>
  .image {background-image: url("/BIG/imageName.jpg");}
  @media only screen and (max-width: 400px) {
     .image {background-image: url("/SMALL/imageName.jpg");}
  }
<style>

Will it load SMALL image if browser resolution will be 300px from start?

Thank you.

Upvotes: 0

Views: 433

Answers (2)

Krzysiek
Krzysiek

Reputation: 2495

This should

.image {background-image: url("/BIG/imageName.jpg");}
@media (max-width: 400px) {
    .image {background-image: url("/SMALL/imageName.jpg");}
}

Or (for readability):

@media (min-width: 401px) {
    .image {background-image: url("/BIG/imageName.jpg");}
}
@media (max-width: 400px) {
    .image {background-image: url("/SMALL/imageName.jpg");}
}

Edit:

Oh, just one thing: Instead writing "only screen" I recommend to use https://github.com/scottjehl/Respond for older browser support.

Upvotes: 0

Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13978

You need to set width and height for the image. Otherwise it will not show. Check my fiddle.

  .image {background-image: url("https://blogs.ubc.ca/CourseBlogSample01/wp-content/themes/thesis/rotator/sample-1.jpg"); width:400px; height:300px;}
  @media only screen and (max-width: 400px) {
 .image {background-image: url("http://res.cloudinary.com/demo/image/upload/t_demo_combined/sample.jpg"); width:100px; height:100px;}
   }

DEMO

Upvotes: 1

Related Questions