Search code examples
cssdevice-orientation

Detect device orientation


Running a responsive single-page app, there are box objects with content. These are intended to have background images. However, for hand-held devices, orientation becomes a problem, as the boxes width and height proportions change.

Detecting devices and viewport sizes has not been a task built on uniform procedures. At appears to me that, assuming users have relatively modern browsers, CSS3 and invoking @media screen and (orientation:landscape) is the safest bet.

Assuming that images will be cropped in both a horizontal and a vertical version and a tag with orientation-less coding

<div class="box" style='background:  url("https://somewhere.amazonaws.com/general-purpose-images/splash.jpg") no-repeat fixed; background-size: 100% 100%; background-attachment: scroll;'>

How can this be effectively toggled according to orientation?


Solution

  • set a div with a class for the image

    <div class="img_a">
    

    Then define the CSS rules for the required images according to orientation or any other media queries you might need to implement

    @media screen and (orientation: portrait)
      { div.img_a 
          { background: url(https://[...]img_a.jpg) no-repeat fixed; }
      [...] }
    @media screen and (orientation: landscape)
      { div.img_a 
          { background: url(https://[...]img_a_horizontal.jpg) no-repeat fixed; }
      [...] }