@media screen and (orientation: portrait) {
/* 竖屏 */
}
@media screen and (orientation: landscape) {
/* 横屏 */
}
请注意! 在横竖屏切换的时候, 使用em单位和rem单位的(特别是根据屏幕宽度计算的rem)是不变的,也就是说如果一开始用户是竖屏浏览, 我们计算出屏幕宽度(屏幕短边)=10rem, 那么在用户切换横屏的时候, 仍然是(屏幕短边)=10rem! 这时候需要绑定onorientationchange(屏幕翻转事件)进行重新计算, 并刷新页面
另外, 如果你写在两个css中, 那么引用的时候要这么写
<link rel="stylesheet" media="all and (orientation:portrait)" href="竖屏.css"> /* 伪代码, 写中文一眼就理解 */
<link rel="stylesheet" media="all and (orientation:landscape)" href="横屏.css">
还有一种用js事件判断的(参考 https://www.w3cways.com/1772.html, 侵删)
//判断手机横竖屏状态:
window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {
if (window.orientation === 180 || window.orientation === 0) {
alert('竖屏状态!');
}
if (window.orientation === 90 || window.orientation === -90 ){
alert('横屏状态!');
}
}, false);
//移动端的浏览器一般都支持window.orientation这个参数,通过这个参数可以判断出手机是处在横屏还是竖屏状态。
注: window.orientation是获取当前用户设备旋转了多少度. 0代表一开始加载时的位置, -90就是向左旋转了, 180就是头朝下, 90度就是向右旋转了
以上!