彻底弄明白CSS3的Media Queries(跨平台设计)

2020-05-15 08:01:01易采站长站整理

Dconstruct-protofluid-crop in How To Use CSS3 Media Queries To  Create a Mobile Version of Your Website

在 ProtoFluid 使用 Media Queries,你需要同时加上 max-width 和 max-device-width 属性,这意味着,Media Queires 不仅可以针对不同的移动设备,还可以针对桌面系统中某些人为的小窗口情形。

@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {

}

code hosted by snipt.net

@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {

}

code hosted by snipt.net

@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {

}

使用上面的代码,在桌面浏览器上,当你改变窗口尺寸到达 480 像素的时候,就会看到布局的改变。需要注意的是,上面的 max-width 部分仅仅为了测试,如果你不希望用户在桌面浏览器中因为改变了窗口大小而导致你的布局改变,可以去掉 max-width 部分,而只针对那些移动设备。

对现有网站的整改

上面的例子为了说明问题起见都很简单,现实中的站点不可能这样,下面的例子,作者将使用他自己的公司网站,说明如何使用 Media Queries 对现有网站进行移动化整改。

桌面布局

作者自己的网站是几年前设计的,那是还没有考虑 Media Queries 问题,这是一个三栏式布局。

Edgeofmyseat-browser-crop in How To Use CSS3 Media Queries To  Create a Mobile Version of Your Website

增加新的式样表

为了适应移动设备,将使用 Media Queries 加载独立的式样表:

<link
rel="stylesheet"
type="text/css"
media="only screen and (max-width: 480px), only screen and (max-device-width: 480px)"
href="/assets/css/small-device.css"
/>

code hosted by snipt.net

<link
rel="stylesheet"
type="text/css"
media="only screen and (max-width: 480px), only screen and (max-device-width: 480px)"
href="/assets/css/small-device.css"
/>

code hosted by snipt.net

<link
rel="stylesheet"
type="text/css"
media="only screen and (max-width: 480px), only screen and (max-device-width: 480px)"
href="/assets/css/small-device.css"
/>

作者的做法是,将他站点中原来的 CSS 文件另存为 small-device.css ,在这个基础上针对移动设备进行整改。