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

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" />
主站蜘蛛池模板: 临江市| 固安县| 资阳市| 通化市| 理塘县| 南充市| 禹州市| 梨树县| 绵竹市| 新巴尔虎左旗| 方城县| 招远市| 余江县| 玛多县| 衡山县| 曲阜市| 苗栗县| 东辽县| 资源县| 新化县| 米脂县| 新巴尔虎左旗| 牟定县| 松江区| 怀安县| 高密市| 东莞市| 平昌县| 同心县| 新乐市| 赣榆县| 新建县| 当涂县| 江西省| 建平县| 南宫市| 平邑县| 兴业县| 平昌县| 门源| 青铜峡市|