Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing images depending on device orientation

I'm building a basic web App using PhoneGap for a local company. I have created two images for the header/banner at the top of the App. One is optimised for portrait orientation and one is optimised for landscape. I want to be able to show either one depending which way the device is held. I have been reading about media queries and frankly its a little bit over complicated for my needs, as JQuery mobile will take care of rest of the functionality for me, and I'm only using one CSS for the whole App.

Does anyone have a few simple lines of code I can add to help solve this issue?

like image 849
user1942412 Avatar asked Jan 02 '13 09:01

user1942412


1 Answers

You can use CSS media queries for portrait and landscape orientations, it is not complicated at all:

@media screen and (orientation: portrait) { ... }
@media screen and (orientation: landscape) { ... }

Using these media queries you can override background-image for any orientation.

Official documentation: http://www.w3.org/TR/css3-mediaqueries/#orientation

There are two ways of using it:

Presume you have <div> with class header:

@media screen and (orientation: portrait)
{
    div.header { background-image:url(image1.jpg); }
}
@media screen and (orientation: landscape)
{
    div.header { background-image:url(image2.jpg); }
}

Alternatively, you may wish to use <img> tags. In this case you will need two of them, and hide/show only one with CSS rules. Let's say, <img> tags have classes header-land and header-portrait respectively:

@media screen and (orientation: portrait)
{
    .header-land { display:none; }
    .header-portrait { display:inline-block; }
}
@media screen and (orientation: landscape)
{
    .header-land { display:inline-block; }
    .header-portrait { display:none; }
}
like image 149
keaukraine Avatar answered Nov 15 '22 23:11

keaukraine