chill8888
chill8888

Reputation: 37

Apply CSS to div according to screen orientation

I need a div to have a different height when the screen is either landscape or portrait. I would use media query but not sure if that auto resizes the div if the device is rotated in hand.

I have this so far but it doesn't seem to be working.

<style type="text/css">
  #header {
    position:relative;
    height:100vh;
  }
</style>

<script type="text/javascript">
  $(window).resize(function() {
    if ($(this).height() > $(this).width() {
      $('#header').css("height","50vh"); }
  }
</script>

Upvotes: 0

Views: 1468

Answers (3)

Sreekanth
Sreekanth

Reputation: 3130

You could use landscape and portrait orientation in media queries and can acheive this.

Some things like this.

@media screen and (orientation: portrait) {
  #header {
    position: relative;
    height: 50vh;
    background-color: blue;
  }
}
@media screen and (orientation: landscape) {
  #header {
    position: relative;
    height: 100vh;
    background-color: red;
  }
}
<header id="header">
</header>

Upvotes: 0

user2693928
user2693928

Reputation:

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) and (orientation : landscape) {
    // styles
}

landscape can be changed with portrait.

Upvotes: 1

fbelanger
fbelanger

Reputation: 3568

Before you start messing around with JQuery to style your elements, maybe take a deeper look into CSS media queries:

https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries#orientation

Upvotes: 0

Related Questions