Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Media queries and background images

I have a div

<div id="page">

</div>

With the following css:

   #page {
    background: url('images/white-zigzag.png') repeat-x;
    }

    @media (max-width: 600px) {
  #page {      
  background: url('images/white-zigzag-mobile.png') repeat-x;
  }
}

I notice when I resize my browser, I see the "mobile" background (good) but if I go back and make my browser large, my previous "large" background does not always reappear.

It's an intermittent problem but it's happening often enough that I think I should address it.

Is there any way to get around this "background image not appearing" problem or a way to resize background images, so that the media query "shrinks" the background image to fit the new size? As far as I know there is no (widespread) way to change the size of a background image...

like image 663
redconservatory Avatar asked Feb 29 '12 20:02

redconservatory


2 Answers

According to this test:

If you want only the desktop version of the image to be downloaded on the desktop...

and only the mobile image to be downloaded on the mobile device -

You need to use a min-width declaration to specify a minimum browser width for the desktop image...

and a max-width for the mobile image.

So your code would be:

@media (min-width: 601px) {
  #page {
    background: url('images/white-zigzag.png') repeat-x;
  }
}

@media (max-width: 600px) {
  #page {      
     background: url('images/white-zigzag-mobile.png') repeat-x;
  }
}
like image 196
Danield Avatar answered Nov 03 '22 15:11

Danield


The code you provided is a little buggy which is probably a good place to start currently you have

#page {
background: url('images/white-zigzag.png') repeat-x;
}

@media (max-width: 600px) {
background: url('images/white-zigzag-mobile.png') repeat-x;
}

The media query portion isn't complete. You still need to provide the CSS selector that you used outside of the query:

#page {
background: url('images/white-zigzag.png') repeat-x;
}

@media (max-width: 600px) {
  #page {      
  background: url('images/white-zigzag-mobile.png') repeat-x;
  }
}

Start with that and let me know if that fixes things.

like image 45
ckaufman Avatar answered Nov 03 '22 14:11

ckaufman