官术网_书友最值得收藏!

Media query syntax

So what does a CSS media query look like and more importantly, how does it work?

Enter the following code at the bottom of any CSS file and preview the related web page. Alternatively, you can open example_02-01:

body {
  background-color: grey;
}
@media screen and (min-width: 320px) {
  body {
    background-color: green;
  }
}
@media screen and (min-width: 550px) {
  body {
    background-color: yellow;
  }
}
@media screen and (min-width: 768px) {
  body {
    background-color: orange;
  }
}
@media screen and (min-width: 960px) {
  body {
    background-color: red;
  }
}

Now, preview the file in a browser and resize the window. The background color of the page will vary depending upon the current viewport size. We'll cover how the syntax works in more detail shortly. First, it's important to know how and where you can use media queries.

Media queries in link tags

Those that have been working with CSS since version 2 will know it's possible to specify the type of device (for example, screen or print) applicable to a style sheet with the media attribute of the <link> tag. Consider this example (which you'd place in the <head> tags of your markup):

<link rel="style sheet" type="text/css" media="screen" href="screen-styles.css">

Media queries add the ability to target styles based upon the capability or features of a device, rather than merely the type of device. Think of it as a question to the browser. If the browser's answer is "true", the enclosed styles are applied. If the answer is "false", they are not. Rather than just asking the browser "Are you a screen?"—as much as we could effectively ask with just CSS2—media queries ask a little more. Instead, a media query might ask, "Are you a screen and are you in portrait orientation?" Let's look at that as an example:

<link rel="stylesheet" media="screen and (orientation: portrait)" href="portrait-screen.css" />

First, the media query expression asks the type (are you a screen?), and then the feature (is your screen in portrait orientation?). The portrait-screen.css style sheet will be applied for any screen device with a portrait screen orientation and ignored for any others. It's possible to reverse the logic of any media query expression by adding not to the beginning of the media query. For example, the following code would negate the result in our prior example, applying the file for anything that wasn't a screen with a portrait orientation:

<link rel="stylesheet" media="not screen and (orientation: portrait)" href="portrait-screen.css" />
主站蜘蛛池模板: 乃东县| 三门峡市| 比如县| 东乡县| 阳曲县| 贞丰县| 武鸣县| 什邡市| 巨鹿县| 喀什市| 繁昌县| 腾冲县| 丰都县| 荥阳市| 革吉县| 吉林省| 高邑县| 台东市| 蓬莱市| 张家港市| 阿克| 墨竹工卡县| 海兴县| 甘泉县| 含山县| 岗巴县| 尚志市| 屏南县| 赤壁市| 张家港市| 七台河市| 泗水县| 花莲县| 永昌县| 海淀区| 交口县| 通河县| 甘孜县| 亳州市| 西青区| 江安县|