Domanda

I looked around but found nothing, I was wondering is it possible to change the header's img when you try to make a responsive website?

For example: show normal img when screen width is more than 800px and when you go below 800px replace that img with another one.

Thanks!

È stato utile?

Soluzione

You can use CSS3 media queries to achieve responsive web design.

Let us assume you have a header with id : headerID

default css:

 #headerId {
        background: url("default-image-url.png");
    }

Then you just need to add the following to your CSS file:

@media (max-width: 800px) {
    #headerId {
        background: url("different-image-url.png") !important;
    }
}

Then in your HTML at the <head> add

<meta name="viewport" content="width=device-width">

Altri suggerimenti

With JQuery it would be:

if ($(window).width() < 800) {
   $('#divID').css("background-image", "url(/myimage.jpg)");
   //image when windows is less than 800px  
}
else {
   $('#divID').css("background-image", "url(/myimage.jpg)");
   //image when windows is more than 800px  
}

You can't do this with one <img> tag unless you use javascript.

To use CSS only you need to use background images as mohamedrias says, or have two images and show or hide one, based on the screen width by using a media query:

@media (max-width: 800px) {
    #headerImg1 {
        display: none;
    }
    #headerImg2 {
        display: block;
    }
}

@media (min-width: 801px) {
    #headerImg1 {
        display: block;
    }
    #headerImg2 {
        display: none;
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top