To switch images in desktop and mobile view using CSS media queries, you can use the following approach:
HTML:
<img src="desktop-image.jpg" class="desktop-image" alt="Desktop Image">
<img src="mobile-image.jpg" class="mobile-image" alt="Mobile Image">
CSS:
.mobile-image {
display: none;
}
@media only screen and (max-width: 768px) {
.desktop-image {
display: none;
}
.mobile-image {
display: block;
}
}
In this example, the .desktop-image is displayed by default, and the .mobile-image is hidden. When the screen width is 768px or less ( typical mobile screen width), the .desktop-image is hidden, and the .mobile-image is displayed.
Alternatively, you can use the picture element and srcset attribute to achieve the same result:
<picture>
<source srcset="mobile-image.jpg" media="(max-width: 768px)">
<img src="desktop-image.jpg" alt="Desktop Image">
</picture>
This approach allows the browser to choose the correct image based on the screen width, without needing to use CSS media queries.
You can also use CSS background images and media queries to achieve the same result:
.image-container {
background-image: url('desktop-image.jpg');
}
@media only screen and (max-width: 768px) {
.image-container {
background-image: url('mobile-image.jpg');
}
}
Note that the image container element should have a fixed height and width for this approach to work.

Top comments (0)