准备工作
在html 文件的 head
中加入以下内容
<meta name="viewport" content="width=device-width,initial-scale=1.0">
设置meta标签来告诉浏览器,让视口宽度等于设备宽度.
具体作用可参考:https://stackoverflow.com/questions/47742580/do-we-need-meta-name-viewport-content-width-device-width-initial-scale-1-0
这里摘录一段,大意是完成了设备宽度到 css 属性 width 的映射。
The
viewport META tag
allowsdevice width
to map to thewidth
CSS property, which essentially means that device pixels correctly map to CSS pixels, allowing elements and fonts to correctly scale on mobile devices. Without this, a pixel is not a pixel in the traditional sense.
基础使用方式
写在css文件中,后面有更佳的引入方式。
@media media-type and (media-feature-rule) {
/* CSS rules go here */
}
它由以下部分组成:
- 一个媒体类型,告诉浏览器这段代码是用在什么类型的媒体上的(例如印刷品或者屏幕);
- 一个媒体表达式,是一个被包含的CSS生效所需的规则或者测试;
- 一组CSS规则,会在测试通过且媒体类型正确的时候应用。
media-type
你可以指定的媒体类型为:
all
print
会在页面被打印的时候起作用。screen
speech
media-feature-rule
为了建立响应式设计(已经广受浏览器支持),我们一般最常探测的特征是视口宽度,而且我们可以使用min-width
、max-width
和width
,orientation
媒体特征,在视口宽度大于或者小于某个大小——或者是恰好处于某个大小——的时候,应用CSS。
这些特征是用来创建响应不同屏幕大小的布局的。例如,要想在视口正好是600像素的时候,让body的文本变为红色,你可能会使用下面的媒体查询。
@media screen and (width: 600px) {
/* CSS rules go here */
}
@media screen and (max-width: 400px) {
/* CSS rules go here */
}
@media screen and (min-width:340px) and (max-width:720px) {
}
一个受到良好支持的媒体特征是orientation
,我们可以用它测得竖放(portrait mode)和横放(landscape mode)模式。要在设备处于横向的时候改变body文本颜色的话,可使用下面的媒体查询。
@media (orientation: landscape) {
}
媒体查询中的“与”逻辑
为了混合媒体特征,你可以以与在上面使用and
很相同的方式,用and
来混合媒体类型和特征。例如,我们可能会想要测得min-width
和orientation
,而body的文字只会在视口至少为400像素宽,且设备横放时变为蓝色。
@media screen and (min-width: 400px) and (orientation: landscape) {
body {
color: blue;
}
}
媒体查询中的“或”逻辑
如果你有一组查询,且要其中的任何一个都可以匹配的话,那么你可以使用逗号分开这些查询。在下面的示例中,文本会在视口至少为400像素宽的时候或者设备处于横放状态的时候变为蓝色。如果其中的任何一项成立,那么查询就匹配上了。
@media screen and (min-width: 400px), screen and (orientation: landscape) {
body {
color: blue;
}
}
媒体查询中的“非”逻辑
你可以用not
操作符让整个媒体查询失效。这就直接反转了整个媒体查询的含义。因而在下面的例子中,文本只会在朝向为竖着的时候变成蓝色。
@media not all and (orientation: landscape) {
body {
color: blue;
}
}
其它引入方式
使用@import导入(例子:宽度小于1024px),CSS3 专用,要放到css文件最前面。
@import url("css.css") screen and (max-width:1024px);
下面这个常用!
使用link方式引入(例子:宽度小于1024px),
<link rel="stylesheet" type="text/css" href="css.css" media="screen and (max-width:1024px)"/>
Bootstrap
bootstrap 利用媒体查询 + 百分比进行布局,匹配小尺寸设备的 css 在 bootstrap.css
中排列在前,大尺寸的排列在后,这样,多个媒体查询同时命中时,后声明的 css 规则其效果。
例如, .col-sm-6
位于1791行,.col-md-4
位于1955行。
具体参考:https://stackoverflow.com/questions/8790321/why-does-the-order-of-media-queries-matter-in-css