Languages

CSS - how to detect orientation for media queries?

0 points
Asked by:
nickkk0
647

Is there any way to detect device orientation in CSS? I need it for media queries in my project.

Something like:

@media (width > height) {
    /* ... */
}
1 answer
0 points
Answered by:
nickkk0
647

Quick solution:

@media (orientation: portrait) {
    /* portrait styles here (width <= height) */
}

@media (orientation: landscape) {
    /* landscape styles here (width > height) */
}

 

Practical example

In this example, div element background will be yellow on portrait orientation (vertical) and orange on landscape orientation (horizontal).

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
<head>
  <style>
    
    div {
        width: 100%;
        height: 500px;
    }
   
    @media (orientation: portrait) {
        div {
          background: yellow;
        }
    }

    @media (orientation: landscape) {
        div {
          background: orange;
        }
    }

  </style>
</head>
<body>
  <div>Web page content here...</div>
</body>
</html>

 

References

  1. orientation - CSS: Cascading Style Sheets | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join