传统的CSS只支持数量有限的设备显示规则,如:all
、screen
、print
、handheld
、television
和projector
。这些对于设备的尺寸、方向或分辨率没有任何的定论。CSS2.1及以上的版本提供给了媒体查询技术(media queries)来让我们控制各种设备的不同样式。
<link rel="stylesheet" href="styles.css"> <link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="styles_h.css" />
在上面的代码中,styles_h.css
将只会被用于设备显示器屏幕并且最大的宽度为480像素。注意这是设备的宽度,如果你希望浏览器的大小在480像素时用某个样式表来显示,应该使用下面的语法:
<link rel=stylesheet media="only screen and (max-width: 480px)" href="styles_small.css" />
上面的这个样式规则可以同时在小屏幕的智能手机和缩小为480像素的桌面浏览器上使用,这样做是一个非常好的选择。然而,为每一个设备和屏幕尺寸都写一个单独的样式表是非常不现实的。当浏览器加载页面的时候,不管当前的屏幕分辨率是说明,它都会调用所有的样式表文件。过多的HTTP请求将会拖慢你的网页加载速度。通常更好的做法是将所有的样式表都放到一个style.css
文件中,然后通过媒体查询技术(media queries),使用@media
语法来适配各种设备和屏幕分辨率。
/* standard CSS rules read by all devices and applicable to all resolutions */ html, body { } @media print { /* specific CSS rules for print, added only if they conflict with the rules above */ } @media only screen and (max-width : 1200px) { /* style rules for desktops and laptops with smaller screens, again only added if the rules here conflict with those at the topof the stylesheet */ } @media only screen and (min-width : 768px) and (max-width : 1024px) { } @media only screen and (max-width : 480px) { }
你需要注意的是,这些“breakpoints”不应取决于流行的设备的尺寸,而是由你的网站的需要来决定。
即使不使用@media
媒体查询,一个设计为流式布局的响应式网站在浏览器缩小或小屏幕设备上也会被正确的缩放。如果你发现显示不正确,可以查看<l;head>
中的<meta>
标签是否书写正确。
<meta name="viewport" content="width=device-width, initial-scale=1">
最后需要注意的是,媒体查询是可以嵌套的:
@media screen { body { background: yellow } @media (min-width: 0px) { body { background: green } } }
IE浏览器和Safari 6.1之前的浏览器不支持嵌套媒体查询。