What is the best approach to change a css file when a mobile application page orientation changes from landscape to portrait and vice versa. I need to suport both Android and iPhone only. It seems media queries aren't the cleanest way, any other ideas?
Asked
Active
Viewed 6,091 times
4
-
Isn't there any option to bind to window resize event, and if X is bigger then Y it is landscape? And Y bigger then X you got portrait? Keep 1 var as a boolean, isLandscape and if it's changed, edit your stylesheet? – Niels Nov 11 '11 at 23:35
-
1Why you think that CSS media queries aren't clean solution? – Wojciech Bednarski Nov 11 '11 at 23:47
4 Answers
7
Example
/* For portrait */
@media screen and (orientation: portrait) {
#toolbar {
width: 100%;
}
}
/* For landscape */
@media screen and (orientation: landscape) {
#toolbar {
position: fixed;
width: 2.65em;
height: 100%;
}
p {
margin-left: 2em;
}
}
For more details see here

isxaker
- 8,446
- 12
- 60
- 87
-
@Mike Welcome. You can express your gratitude, if voting for my answer. – isxaker Nov 21 '14 at 06:35
-
1
1
First give your style sheet include line an id="cssElement" or something.
Then Using jQuery:
$(document).ready(function(){
// The event for orientation change
var onChanged = function() {
// The orientation
var orientation = window.orientation;
if(orientation == 90) {
$('#cssElement').attr('href', '/path/to/landscape.css');
} else {
$('#cssElement').attr('href', '/path/to/portrait.css');
}
};
// Bind the orientation change event and bind onLoad
$(window).bind(orientationEvent, onChanged).bind('load', onChanged);
});

Rick Kukiela
- 1,135
- 1
- 15
- 34
-
-
^^icktoofay You are right (fixed). I read something incorrectly. Anyway, this /should/ work when on a phone browser. – Rick Kukiela Nov 15 '11 at 20:53
1
The below JQuery code seems to work best for me...the binding examples did not.
$(document).ready(function() {
$(window).resize(function() {
alert(window.orientation);
});
});

c12
- 9,557
- 48
- 157
- 253