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

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" />
主站蜘蛛池模板: 普定县| 绍兴市| 盐边县| 合山市| 芜湖县| 兰州市| 阿克| 中山市| 绍兴县| 怀柔区| 内乡县| 凤冈县| 囊谦县| 清水河县| 象州县| 宁强县| 新沂市| 隆安县| 镇坪县| 涿州市| 高雄县| 曲阳县| 左云县| 镶黄旗| 安福县| 林甸县| 阳新县| 南靖县| 京山县| 武威市| 雅江县| 加查县| 白银市| 安多县| 深泽县| 芒康县| 湖北省| 洪洞县| 青龙| 凭祥市| 石狮市|