Home > Web Front-end > CSS Tutorial > Detailed explanation of Media media queries in CSS

Detailed explanation of Media media queries in CSS

青灯夜游
Release: 2020-10-28 17:56:52
forward
3664 people have browsed it

Detailed explanation of Media media queries in CSS

When it comes to responsive design, media query media is definitely inseparable. It is generally believed that media queries are new additions to CSS3. In fact, CSS2 already exists, and CSS3 adds new media attributes and usage scenarios (not supported by IE8-browser). This article explains in detail what a media query is.

(Recommended tutorial: CSS Tutorial)

Media Type

In CSS2, media The query is only used in

The media attribute is used to specify different styles for different media types

screen Computer Screen (default)
tty                                                                                                                                         -                                                                                             but but                                                  
Devices (small screen, limited bandwidth)
print Print preview mode/print page
braille Braille feedback device for the blind
aural Speech synthesizer
all Suitable for all devices


The really widely used media types that are compatible with all browsers are 'screen' and 'all'
<style media="screen">
.box{height: 100px;width: 100px; background-color: lightblue;}    
</style>
<div class="box"></div>
Copy after login

Media attributesMedia attributes are new content in CSS3. Most media attributes are prefixed with "min-" and "max-", which are used to express "less than or equal to" and "greater than or equal to". This avoids the use of "<" and ">" characters that conflict with HTML and XML.

[Note] Media attributes must be enclosed in brackets (), otherwise they will be invalid.

All media properties are listed in the following table:

width | min-width | max-width

height | min-height | max-height

device-width | min-device-width | max-device-width

device-height | min-device-height | max-device-height

aspect- ratio | min-aspect-ratio | max-aspect-ratio

device-aspect-ratio | min-device-aspect-ratio | max-device-aspect-ratio

color | min- color | max-color

color-index | min-color-index | max-color-index

monochrome | min-monochrome | max-monochrome

resolution | min -resolution | max-resolution

scan | grid

【1】Color (color)

Specifies each pixel unit of the output device bit value. If the device does not support output color, the value is 0

Apply the style sheet to all devices that can display color

<style>
@media (color){
    .box{height: 100px;width: 100px;background-color: lightblue;}    
}    
</style>
<div class="box"></div>
Copy after login

[2]Color index (color-index)

The color index specifies the number of entries in the color lookup table in the output device. If no color lookup table is used, the value is equal to 0

Applies to all devices using at least 256 indexed colors Style sheet (the following code is not displayed, indicating that the return value is 0)

<style>
@media (min-color-index: 256){
    .box{height: 100px; width: 100px;background-color: lightgreen;}    
}    
</style>    
<div class="box"></div>
Copy after login

【3】Aspect-ratio (aspect-ratio)

The aspect ratio describes the output The aspect ratio of the device's target display area. The value consists of two positive integers separated by "/". Represents the ratio of the number of horizontal pixels (the first value) to the number of vertical pixels (the second value).

Apply style sheets to devices whose viewing area is square or widescreen

<style>
@media (min-aspect-ratio: 1/1) {
    .box{height: 100px;width: 100px; background-color: lightgreen; }        
}
</style>
<div class="box"></div>
Copy after login

[4]Device-aspect-ratio

Device aspect ratio describes the aspect ratio of the output device. The value consists of two positive integers separated by "/". Represents the ratio of the number of horizontal pixels (the first value) to the number of vertical pixels (the second value).

Apply style sheets to special widescreen devices with an aspect ratio of 16:9

<style>
@media (device-aspect-ratio:16/9) {
    .box{ height: 100px;width: 100px; background-color: pink;}        
}
</style>
<div class="box"></div>
Copy after login

[5]Device-height

Device height describes the height of the output device

Apply a style sheet to a document displayed on a screen with a minimum height of 1000px

<style>
@media (min-device-height: 1000px) {
    .box{ height: 100px;width: 100px; background-color: pink;}        
}
</style>
<div class="box"></div>
Copy after login

[6]Device-width(device-width)

Device width describes the width of the output device

Apply a style sheet to a document displayed on a screen with a minimum width of 1000px

<style>
@media (min-device-width: 1000px) {
    .box{ height: 100px; width: 100px;background-color: lightblue; }        
}
</style>
<div class="box"></div>
Copy after login

[7] Grid (grid)

Grid determines whether the output device is a grid device or a bitmap device. This value is 1 if the device is grid-based (such as a teletype terminal or a telephone that can only display one glyph), 0 otherwise.

Apply style sheets to non-grid devices

<style>
@media (grid:0) {
    .box{height: 100px;width: 100px; background-color: lightgreen;}        
}
</style>
<div class="box"></div>
Copy after login

[8]Height (height)

Height describes the output device rendering area (if possible The height of the view area or the height of the printer tray)

Apply the style sheet to devices with a height greater than the 800px viewable area

<style>
@media (min-height:800px) {
    .box{ height: 100px; width: 100px;background-color: lightgreen; }        
}
</style>
<div class="box"></div>
Copy after login

[9]Width (width)

Width describes the width of the rendering area of ​​the output device

Apply style sheets to devices with a width greater than 800px in the visible area

<style>
@media (min-width:800px) {
    .box{ height: 100px;width: 100px; background-color: lightgreen;}        
}
</style>
<div class="box"></div>
Copy after login

[10] Black and White (monochrome)

黑白指定了一个黑白(灰度)设备每个像素的比特数。如果不是黑白设备,值为0

向非黑白设备应用样式表

<style>
@media (monochrome:0) {
    .box{height: 100px; width: 100px; background-color: lightgreen;}        
}
</style>
<div class="box"></div>
Copy after login

【11】方向(orientation)

方向指定了设备处于横屏(宽度大于宽度)模式还是竖屏(高度大于宽度)模式

值:landscape(横屏) | portrait(竖屏)

向竖屏设备应用样式表

<style>
@media (orientation: portrait) {
    .box{height: 100px;width: 100px;background-color: lightgreen; }        
}
</style>
<div class="box"></div>
Copy after login

【12】分辨率(resolution)

分辨率指定输出设备的分辨率(像素密度)。分辨率可以用每英寸(dpi)或每厘米(dpcm)的点数来表示

[注意]关于屏幕三要素(屏幕尺寸、分辨率、像素密度)的相关内容移步至此

向每英寸至少90点的设备应用样式

<style>
@media (min-resolution: 90dpi) {
    .box{height: 100px;width: 100px; background-color: lightgreen; }        
}
</style>
<div class="box"></div>
Copy after login

【13】扫描(scan)

扫描描述了电视输出设备的扫描过程

值: progressive | interlace

语法

媒体查询包含了一个CSS2已有的媒介类型(或称为媒体类型)和CSS3新增的包含一个或多个表达式的媒体属性,这些媒体属性会被解析成真或假。

当媒体查询为真时,相关的样式表或样式规则就会按照正常的级联规则被应用。即使媒体查询返回假, 标签上带有媒体查询的样式表仍将被下载(只不过不会被应用)。

<link rel="stylesheet" href="style.css" media="print">
<div class="box"></div>
Copy after login

media并不是'print',所以媒体查询为假。但是,style.css文件依然被下载

Detailed explanation of Media media queries in CSS

逻辑操作符:

操作符not、and、only和逗号(,)可以用来构建复杂的媒体查询

and

and操作符用来把多个媒体属性组合起来,合并到同一条媒体查询中。只有当每个属性都为真时,这条查询的结果才为真

[注意]在不使用not或only操作符的情况下,媒体类型是可选的,默认为all

满足横屏以及最小宽度为700px的条件应用样式表

@media all and (min-width: 700px) and (orientation: landscape) { ... }
Copy after login

由于不使用not或only操作符的情况下,媒体类型是可选的,默认为 all,所以可以简写为

@media (min-width: 700px) and (orientation: landscape) { ... }
Copy after login

or

将多个媒体查询以逗号分隔放在一起;只要其中任何一个为真,整个媒体语句就返回真,相当于or操作符

满足最小宽度为700像素或是横屏的手持设备应用样式表

@media (min-width: 700px), handheld and (orientation: landscape) { ... }
Copy after login

not

not操作符用来对一条媒体查询的结果进行取反

[注意]not关键字仅能应用于整个查询,而不能单独应用于一个独立的查询

@media not all and (monochrome) { ... }
//等价于
@media not (all and (monochrome)) { ... }
Copy after login

only

only操作符表示仅在媒体查询匹配成功时应用指定样式。可以通过它让选中的样式在老式浏览器中不被应用

media="only screen and (max-width:1000px)"{...}
Copy after login

上面这行代码,在老式浏览器中被解析为media="only",因为没有一个叫only的设备,所以实际上老式浏览器不会应用样式

media="screen and (max-width:1000px)"{...}
Copy after login

上面这行代码,在老式浏览器中被解析为media="screen",它把后面的逻辑表达式忽略了。所以老式浏览器会应用样式

所以,在使用媒体查询时,only最好不要忽略

方法

window.matchMedia()方法用来检查CSS的mediaQuery语句

[注意]IE9-浏览器不支持,可以使用第三方函数库matchMedia.js

属性

window.matchMedia()方法接受一个mediaQuery语句的字符串作为参数,返回一个MediaQueryList对象。该对象有media和matches两个属性。

media:返回所查询的mediaQuery语句字符串

matches:返回一个布尔值,表示当前环境是否匹配查询语句

var result = window.matchMedia(&#39;(min-width: 600px)&#39;);
console.log(result.media); //&#39;(min-width: 600px)&#39;
console.log(result.matches); // true
Copy after login

可以根据matchMedia()方法的matches属性的不同结果,进行对应的设置

var result = window.matchMedia(&#39;(min-width: 600px)&#39;);
if (result.matches) {
  //
}else{
 //
}
Copy after login

[注意]如果window.matchMedia无法解析mediaQuery参数,matches属性返回的总是false,而不是报错

var result = window.matchMedia(&#39;123&#39;);
console.log(result.matches);//false
Copy after login

事件

window.matchMedia方法返回的MediaQueryList对象有两个方法,用来监听事件:addListener方法和removeListener方法

// 指定回调函数
mql.addListener(mqCallback);
// 撤销回调函数
mql.removeListener(mqCallback);
Copy after login

注意,只有mediaQuery查询结果发生变化时,才调用指定的回调函数

所以,如果想要mediaQuery查询未变化时,就显示相应效果,需要提前调用一次函数

下面这个例子是当页面宽度小于1000px时,页面背景颜色为品红色;否则为淡蓝色

var mql = window.matchMedia("(min-width: 1000px)");
mqCallback(mql);
mql.addListener(mqCallback);
function mqCallback(mql) {
  if (mql.matches) {
    document.body.background = &#39;pink&#39;;
  }else{
      document.body.background = &#39;lightblue&#39;;
  }
}
Copy after login

打印样式

媒体查询的一个常用功能是打印样式的设置,主要是背景清除、字体颜色变黑等

@media print{
    *,*:before,*:after{
        background:transparent!important;
        color:#000 !important;
        box-shadow: none !important;
        text-shadow: none !important;
    }
    a,a:visited{
        text-decoration: underline;
    }
    a[href]:after{
        content:"(" attr(href) ")";
    }
    abbr[title]:after{
        content:"(" attr(title) ")";
    }
    a[href^="#"]:after,a[href^="javascript:;"]:after{
        content:"";
    }
    pre,blockquote{
        border: 1px solid #999;
        /*只有opera浏览器起作用,避免在元素内部插入分页符*/
        page-break-inside:avoid;
    }
    thead{
        display:table-header-group;
    }
    tr,img{
        page-break-inside:avoid;
    }
    img{
        max-width:100%!important;
    }
    p,h2,h3{
        /*元素内部发生分页时,最少保留3行*/
        orphans:3;
        /*元素内部发生分页时,元素顶部最少保留3行*/
        windows:3;
    }
    h2,h3{
        /*避免在元素后面插入一个分页符*/
        page-break-after:avoid;
    }
}
Copy after login

相对单位

如果媒体查询@media使用的是相对单位,如rem,这里有一个坑需要着重强调一下。

一般而言,rem是相对于HTML的字体大小的。但是,由于媒体查询的级别非常高,它并不是HTML的子元素,不是相对于HTML,而是相对于浏览器的,而浏览器的默认字体大小是16px。

如果HTML设置字体大小为12px,设置如下媒体查询:

media="only screen and (max-width:1rem)"
Copy after login

实际上,max-width等于16px,而不是12px

而正是由于媒体查询是相对于浏览器的, 所以使用rem就没有必要,完全可以使用em来替代

media="only screen and (max-width:1em)"
Copy after login

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Detailed explanation of Media media queries in CSS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template