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

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" />
主站蜘蛛池模板: 拉萨市| 齐齐哈尔市| 临安市| 漳浦县| 东宁县| 库伦旗| 常熟市| 黄平县| 肇州县| 巴南区| 华阴市| 桦甸市| 苏州市| 宜州市| 泊头市| 乐山市| 阿合奇县| 德庆县| 乐亭县| 民县| 缙云县| 镇远县| 洛扎县| 临高县| 成安县| 富锦市| 哈尔滨市| 东安县| 禄丰县| 金沙县| 南投市| 邳州市| 夏河县| 苍山县| 衡山县| 远安县| 岳池县| 平阳县| 九江市| 舟山市| 灵璧县|