Reputation: 1024
I'm using some CSS to set the size of an image element on my page. The problem is, if a user rotates their mobile it stays fixed to the original dimensions. Is there a way to detect the rotation, and recalculate the sizes elements should be on the page?
Here's what I've found so far...
window.addEventListener("orientationchange", function() {}, false);
Upvotes: 1
Views: 375
Reputation: 71150
Sure, you can use CSS media queries for this type of thing:
/* Portrait */
@media screen and (orientation:portrait) {
/* Portrait styles */
}
/* Landscape */
@media screen and (orientation:landscape) {
/* Landscape styles */
}
A media query consists of a media type and at least one expression that limits the style sheets' scope by using media features, such as width, height, and color. Media queries, added in CSS3, let the presentation of content be tailored to a specific range of output devices without having to change the content itself.
You can extend media queries to be fairly specific if you want to extend and target desktop vs mobile devices etc..
Alternatively- using JS you could simply do:
var orientation = null;
window.onresize = function (event) {
orientation = parseInt(window.innerHeight / window.innerWidth) !== 0 ? 'portrait' : 'landscape';
/* logic for if orientation == portrait etc goes here */
};
Upvotes: 2