Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@media queries and image swapping [closed]

I want the image in my site to completely change when the browser is resized.

I've been using media-queries, but I can't seem to get it right. Any thoughts/tips?

like image 459
Aarati Akkapeddi Avatar asked Jan 09 '15 04:01

Aarati Akkapeddi


People also ask

What is the difference between @media and @media only screen?

@media is the actually media query. The word screen is adding the 'conditions' to the media query. So @media screen is telling the media query to apply (whatever other conditions) to screens. For example, @media screen and (max-width: 360px) will target only screens with a max-width of 360px.

What is @media rule?

The @media rule is used in media queries to apply different styles for different media types/devices. Media queries can be used to check many things, such as: width and height of the viewport. width and height of the device. orientation (is the tablet/phone in landscape or portrait mode?)

What does @media in CSS do?

The @media CSS at-rule can be used to apply part of a style sheet based on the result of one or more media queries. With it, you specify a media query and a block of CSS to apply to the document if and only if the media query matches the device on which the content is being used.


2 Answers

In the future please add code you've tried.

if it's an image tag you can use a class. Hide the second image on page load and show + hide image 1 at a certain screen size like so:

HTML

<img src="image.jpg" class="image1"/> <img src="image.jpg" class="image2"/> 

CSS

.image2{    display: none; }  @media only screen and (max-width: 500px){ //some value    .image1{      display: none;    }     .image2{      display: block;    } } 

EXAMPLE 1 - SHRINK BROWSER

OR

If it's a background-image you can simply swap the image:

HTML

<div class="example"></div> 

CSS

.example{    background-image: url("example.jpg"); }  @media only screen and (max-width: 500px){ //some value     .example{       background-image: url("example2.jpg");    } } 

EXAMPLE 2 - SHRINK BROWSER

like image 149
jmore009 Avatar answered Oct 21 '22 12:10

jmore009


This can be done using the HTML5 picture element which doesn't require CSS for changing img elements on specified media queries. If you're intrested in this approach, do be aware of its browser support which does NOT include IE, though there is a polyfill for older browsers.

<h1>Resize Window</h1> <picture>   <source srcset="https://via.placeholder.com/1400" media="(min-width: 1400px)"/>   <source srcset="https://via.placeholder.com/1200" media="(min-width: 1200px)"/>   <source srcset="https://via.placeholder.com/800" media="(min-width: 800px)"/>   <source srcset="https://via.placeholder.com/600" media="(min-width: 600px)"/>   <img src="https://via.placeholder.com/400" alt="example"/> </picture>
like image 41
ekfuhrmann Avatar answered Oct 21 '22 12:10

ekfuhrmann