认知Media Queries让浏览器人性化

Media Queries最近比较火的一个话题,通常用于响应式布局设计,它可以让浏览器根据当前窗口尺寸自动在样式表中选择一种样式并使用。

我们知道,在不同的设备中,浏览器的窗口尺寸可能是不同的。如果只针对某种窗口尺寸制作不同的网页,在其它设备中呈现该网页时就会产生很多问题;如果针对不同的窗口尺寸制作不同的网页,则要制作的网页就会太多。

为了解决这个问题,CSS3 中单独增加了Media Queries模块,使用这个模块,网页制作者只需要针对不同的浏览器窗口尺寸来编写不同的样式,然后让浏览器根据不同的窗口尺寸来选择使用不同的样式即可。

格式:@media 设备类型 and (设备特性) {样式代码}  具休参数说明这里就不一一列举介绍了,可参考CSS3手册。

用途:主要还是用在移动终端设备上,现在主流的智能终端都是基于iOS和Android的,而它们自带的浏览器都是基于webkit内核,所以我们可以完全使用media query技术。(PC端浏览器就要用现代浏览器才支持。)

demo如下:(至今还不知道贴可运行代码方法,所以要看效果还得自行测式。)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>根据不同的窗口尺寸来选择使用不同的样式的示例</title>
<style type="text/css">
body
{
margin
: 20px 0;
}
#container
{
width
: 960px;
margin
: auto;
}
#wrapper
{
width
: 740px;
float
: left;
}
p
{
line-height
: 600px;
text-align
: center;
font-weight
: bold;
font-size
: 2em;
margin
: 0 0 20px 0;
}
#main
{
width
: 520px;
float
: right;
background
: yellow;/* 黄色 */
}
#sub01
{
width
: 200px;
float
: left;
background
: orange;/* 橙色 */
}
#sub02
{
width
: 200px;
float
: right;
background
: green;/* 緑色 */
}
/* 窗口宽度在1000px以上 */
@media screen and (min- 1000px)
{
/* 3栏显示*/
#container{
width
: 1000px;
}
#wrapper
{
width
: 780px;
float
: left;
}
#main
{
width
: 560px;
float
: right;
}
#sub01
{
width
: 200px;
float
: left;
}
#sub02
{
width
: 200px;
float
: right;
}
}
/* 窗口宽度在640px以上、999px以下 */
@media screen and (min- 640px) and (max- 999px)
{
/* 2栏显示 */
#container{
width
: 640px;
}
#wrapper
{
width
: 640px;
float
: none;
}
p
{
line-height
: 400px;
}
#main
{
width
: 420px;
float
: right;
}
#sub01
{
width
: 200px;
float
: left;
}
#sub02
{
width
: 100%;
float
: none;
clear
: both;
line-height
: 150px;
}
}
/* 窗口宽度在639px以下 */
@media screen and (max- 639px)
{
/* 1栏显示 */
#container{
width
: 100%;
}
#wrapper
{
width
: 100%;
float
: none;
}
body
{
margin
: 20px;
}
p
{
line-height
: 300px;
}
#main
{
width
: 100%;
float
: none;
}
#sub01
{
width
: 100%;
float
: none;
line-height
: 100px;
}
#sub02
{
width
: 100%;
float
: none;
line-height
: 100px;
}
}
</style>
</head>
<body>
<div id="container">
<div id="wrapper">
<p id="main">
MAIN
</p>
<p id="sub01">
SUB 01
</p>
</div>
<p id="sub02">
SUB 02
</p>
</div>
</body>
</html>

最后要说的是,CSS 3中的Media Queries模块中也支持对外部样式表的引用,使用方法类似如下所示:

@import url(public.css) screen and (min-1000px);

<link href="public.css" rel="stylesheet" type="text/css" media="screen and (min-1000px)" />



原文地址:https://www.cnblogs.com/radom/p/2243750.html