media type(媒体类型)与media query(媒体查询)简介及使用方法介绍

2020-04-30 15:04:03易采站长站整理

Google的iPhone横屏样式:
Google之前通过以下方式为iPhone手机提供横屏样式(因为最早的3代iPhone手机不支持orientation属性):


@media screen and (max-height:300px){
#linksDiv{
margin-top:10px;
}

}

android手机的多分辨率问题
android系统的开放性导致其终端的多样性,那么对于各种各样的android手机来说,屏幕分辨率的差异导致针对android手机的页面重构复杂性增加,那么我们可以用media query为每种分辨率提供特定样式:


/* for 240 px width screen */
@media only screen and (max-device-width:240px){
selector{
}
}
/* for 360px width screen */
@media only screen and (min-device-width:241px) and (max-device-width:360px){
selector{
}
}
/* for 480 px width screen */
@media only screen (min-device-width:361px)and (max-device-width:480px){
selector{
}
}

device-aspect-ratio
device-aspect-ratio可以用来适配特定屏幕长宽比的设备,这也是一个很有用的属性,比如,我们的页面想要对长宽比为4:3的普通屏幕定义一种样式,然后对于16:9和16:10的宽屏,定义另一种样式,比如自适应宽度和固定宽度:


/* for 4:3 screen */
@media only screen and (device-aspect-ratio:4/3){
selector{
}
}
/* for 16:9 and 16:10 screen */
@media only screen and (device-aspect-ratio:16/9) and (device-aspect-ratio:16/10){
selector{
}
}

当然,对于手机也可以使用这个属性,比如对于480px*800px的Nexus One和Desire等手机,可以用下面的样式来匹配:


/* for 480px*800px width screen */
@media only screen (device-aspect-ratio:5/3){
selector{
}
}

O’Reilly区分iPhone和iPad的方法
O’Reilly为其网站制作了针对iPad和iPhone设备的不同版本,从而提供最适合相关设备阅读的界面,他们的做法就是使用media query:


<link rel=”stylesheet” media=”all and (max-device-width: 480px)” href=”iphone.css”>
<link rel=”stylesheet” media=”all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)” href=”ipad-portrait.css”>
<link rel=”stylesheet” media=”all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)” href=”ipad-landscape.css”>
<link rel=”stylesheet” media=”all and (min-device-width: 1025px)” href=”ipad-landscape.css”>

总结
CSS 3的media query是一个很强大也很好用的工具,它为我们在不同的设备和环境下实现丰富的界面提供了一种快捷方法,虽然现在各个浏览器对它的支持还有些差异,但是大家都在改进,IE 9已经开始支持media query了。不过目前media query的最大舞台是在高端手持设备,相信随着移动互联网的快速发展,media query也会很好发挥自己的作用。