什么是CSS3 Media Queries?如何利用Media queries开发响应式页面?最详解!

Media Queries 介绍:

Media Queries 是CSS3属性,它可以让你针对不同的终端(例如不同分辨率的屏幕)应用不同的css样式,例如通过Media Queries你可以为移动端设置特有的样式,也可以设置打印版特有的样式。

基本用法介绍:

// 常规样式
#header-image {
    background-repeat: no-repeat;
    background-image:url('image.gif');
}

// 针对大号屏幕设置大号背景图
@media screen and (min-width: 1200px) {
    #header-image {
        background-image:url('large-image.gif');
    }
}

// 针对打印版隐藏头部的图片
@media print {
    #header-image {
        display: none;
    }
}

同样你也可以这样使用:

<link rel='stylesheet' media='all' href='normal.css' />
<link rel='stylesheet' media='print' href='print.css' />
<link rel='stylesheet' media='screen and (min-width: 701px)' href='medium.css' />

这种用法的优势是浏览器只会加载用到的css样式表,所以print.css只会在打印预览页面被加载

因为这种方式采用串联的方式,所以没有被重写的样式依然生效。

举例如下:

#block1, #block2 { 
    float: left; 
    width: 100%; 
} 

@media (min-width: 1000px) { 
    #block1, #block2 { 
        width: 50%; 
    } 
}

例子展示的是在大屏幕的时候block1和block2是并列摆放的,而在小于1000px的屏幕时会改为上下摆放,因为float:left;一直保持生效

浏览器支持情况:

所有的现代浏览器都支持 Media Queries,ie9往上支持,所有现代移动端浏览器都支持包括Blackberry 7.0和10.0

Media Queries特性:

Media Queries有个最大的优点就是可以实时监听屏幕变化,好处就是开发响应式页面的时候不用准备各种各样的终端,只需要拉动浏览器改变可视区域大小即可,页面会实时响应!

注:0101后花园就采用了响应式模板,你可以改变浏览器大小试试看,很神奇哦~

支持的媒体类型:

all:All devices listen to this
braille:Used for braille tactile feedback devices.
embossed:Used for paged braille printers.
handheld:Used for handheld devices (Smartphones and tablets do NOT listen to this!).
print:Used for paged material and for documents viewed on screen in print preview mode.
projection:Used for projected presentations, for example projectors.
screen:Used primarily for color computer screens and smartphones.
speech:Used for speech synthesizers.. (Whatever that may be)
tty:Used for media using a fixed-pitch character grid (such as teletypes, terminals, or portable devices with limited display capabilities).
tv:Used for television-type devices (low resolution, color, limited-scrollability screens, sound available).

支持的CSS表达式:

width:The width of the current window
height:The height of the current window
device-width:The width of the device
device-height:The height of the device
orientation:Either landscape or portrait
aspect-ratio:The aspect ratio of the current window
device-aspect-ratio:The aspect ratio of the device
color:The number of color bits per color component
color-index:The number of available colors on the device
monochrome:The number of bits per pixel in a monochrome frame buffer
resolution:The resolution of the device
scan:Eiter progressive or interlace
grid:Is the device grid-based?

附上:CSS3在线手册

附上:响应式页面演示站