• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Media Query
2
3
4Media queries are widely used on mobile devices. You can use them to modify the application style based on the device type or specific features and device parameters (such as the screen resolution). Specifically, media queries allow you to:
5
6
71. Design a layout style based on the device and app attributes.
8
92. Update the page layout to adapt to dynamic screen changes (for example, screen splitting or switching between landscape and portrait modes).
10
11
12## Usage
13
14Invoke the **mediaquery** API to set the media query condition and the callback, and change the page layout or implement service logic in the callback corresponding to the condition.
15
16First, import the mediaquery module, as shown below:
17```
18import mediaquery from '@ohos.mediaquery'
19```
20Then, use the **matchMediaSync** API to set the media query condition and save the returned listener, as shown below:
21```
22listener = mediaquery.matchMediaSync('(orientation: landscape)')
23```
24Finally, register the callback using the saved listener, and change the page layout or implement service logic in the callback. When the media query condition is matched, the callback is triggered. The sample code is as follows:
25```
26onPortrait(mediaQueryResult) {
27    if (mediaQueryResult.matches) {
28        // do something here
29    } else {
30        // do something here
31    }
32}
33listener.on('change', onPortrait)
34```
35
36## Syntax of Media Query Conditions
37```
38[media-type] [and|not|only] [(media-feature)]
39```
40Examples are as follows:
41
42 ` screen and (round-screen: true) `  // The query is valid when the device screen is round.
43
44 ` (max-height: 800) `  // The query is valid when the height does not exceed 800.
45
46 ` (height <= 800) `   // The query is valid when the height does not exceed 800.
47
48 ` screen and (device-type: tv) or (resolution < 2) `  // The query is valid only when all media features are true.
49
50###  media-type
51
52| Type    | Description            |
53| ------ | -------------- |
54| screen | Media query based on screen-related parameters.|
55
56
57### Media Logic Operation (and|not|only)
58
59You can use logical operators (**and**, **or**, **not**, and **only**) to compose complex media queries. You can also combine them using comma (,). The following table describes the operators.
60
61  **Table 1** Media logical operators
62
63| Type      | Description                                      |
64| -------- | ---------------------------------------- |
65| and      | The **and** operator is used to combine multiple media features into one media query, in a logical AND operation. The query is valid only when all media features are true. It can also combine media types and media functions.<br>For example, **screen&nbsp;and&nbsp;(device-type:&nbsp;wearable)&nbsp;and&nbsp;(max-height:&nbsp;600)&nbsp;** indicates that the query is valid when the device type is wearable and the maximum height of the application is 600 pixel units.|
66| not      | The **not** operator is used to perform a logical negation for a media query. **true** is returned if the query condition is not met. Otherwise, **false** is returned. In a media query list, logical negation is performed only for the media query using the **not** operator.<br>For example, **not&nbsp;screen&nbsp;and&nbsp;(min-height:&nbsp;50)&nbsp;and&nbsp;(max-height:&nbsp;600)&nbsp;** indicates that the query is valid when the height of the application is less than 50 pixel units or greater than 600 pixel units.<br>>&nbsp;![icon-note.gif](public_sys-resources/icon-note.gif)&nbsp;**NOTE**<br>>&nbsp;When the **not** operator is used, the media type must be specified.|
67| only     | The **only** operator applies the selected style only when the entire expression is matched. It can be used to prevent ambiguity on browsers of earlier versions. The statements that contain both media types and media features produce ambiguity when they are received by some browsers of earlier versions. For example:<br>screen&nbsp;and&nbsp;(min-height:&nbsp;50)<br>The browsers of earlier versions would mislead this sentence into screen, causing the fact that the specified style is applied when only the media type is matched. In this case, the **only** operator can be used to avoid this problem.<br>>&nbsp;![icon-note.gif](public_sys-resources/icon-note.gif)&nbsp;**NOTE**<br>>&nbsp;When the **only** operator is used, the media type must be specified.|
68| ,(comma) | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true. The effect of a comma operator is equivalent to that of the **or** operator.<br>For example, **screen&nbsp;and&nbsp;(min-height:&nbsp;1000),&nbsp;&nbsp;(round-screen: true)&nbsp;** indicates that the query is valid when the minimum height of the application is 1000 pixel units or the device screen is round.|
69| or       | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true.<br>For example, **screen&nbsp;and&nbsp;(max-height:&nbsp;1000)&nbsp;or&nbsp;&nbsp;(round-screen: true)** indicates that the query is valid when the maximum height of the application is 1000 pixel units or the device screen is round.|
70
71At MediaQuery Level 4, range query is imported so that you can use the operators including &lt;=, &gt;=, &lt;, and &gt; besides the max- and min-operators.
72
73  **Table 2** Logical operators for range query
74
75| Type   | Description                                      |
76| ----- | ---------------------------------------- |
77| &lt;= | Less than or equal to, for example, **screen&nbsp;and&nbsp;(50&nbsp;&lt;=&nbsp;height)**.|
78| &gt;= | Greater than or equal to, for example, **screen&nbsp;and&nbsp;(600&nbsp;&gt;=&nbsp;height)**.|
79| &lt;  | Less than, for example, **screen&nbsp;and&nbsp;(50&nbsp;&lt;&nbsp;height)**.|
80| &gt;  | Greater than, for example, **screen&nbsp;and&nbsp;(600&nbsp;&gt;&nbsp;height)**.|
81
82
83### media-feature
84
85| Type               | Description                                      |
86| ----------------- | ---------------------------------------- |
87| height            | Height of the display area on the application page.                            |
88| min-height        | Minimum height of the display area on the application page.                          |
89| max-height        | Maximum height of the display area on the application page.                          |
90| width             | Width of the display area on the app page.                            |
91| min-width         | Minimum width of the display area on the application page.                          |
92| max-width         | Maximum width of the display area on the application page.                          |
93| resolution        | Resolution of the device. The unit can be dpi, dppx, or dpcm.<br>-&nbsp;**dpi** indicates the number of physical pixels per inch. 1 dpi ≈ 0.39 dpcm.<br>-&nbsp;**dpcm** indicates the number of physical pixels per centimeter. 1 dpcm&nbsp;≈&nbsp;2.54 dpi.<br>-&nbsp;**dppx** indicates the number of physical pixels in each pixel. (This unit is calculated based on this formula: 96 px = 1 inch, which is different from the calculation method of the px unit on the page.) 1 dppx&nbsp;=&nbsp;96 dpi.|
94| min-resolution    | Minimum device resolution.                               |
95| max-resolution    | Maximum device resolution.                               |
96| orientation       | Screen orientation.<br>Options are as follows:<br>-&nbsp;orientation:&nbsp;portrait<br>-&nbsp;orientation:&nbsp;landscape|
97| device-height     | Height of the device.                                  |
98| min-device-height | Minimum height of the device.                                |
99| max-device-height | Maximum height of the device.                                |
100| device-width      | Width of the device.                                  |
101| min-device-width  | Minimum width of the device.                                |
102| max-device-width  | Maximum width of the device.                                |
103| round-screen      | Screen type. The value **true** means that the screen is round, and **false** means the opposite. |
104| dark-mode         | Whether the device is in dark mode. The value **true** means that the device is in dark mode, and **false** means the opposite.                 |
105
106## Example Scenario
107
108Use media queries to apply different content and styles to the page text when the screen is switched between landscape and portrait modes.
109
110  ```
111  import mediaquery from '@ohos.mediaquery'
112  let portraitFunc = null
113
114  @Entry
115  @Component
116  struct MediaQueryExample {
117    @State color: string = '#DB7093'
118    @State text: string = 'Portrait'
119    @State fontSize: number = 24
120    listener = mediaquery.matchMediaSync('(orientation: landscape)')
121
122    onPortrait(mediaQueryResult) {
123      if (mediaQueryResult.matches) {
124        this.color = '#FFD700'
125        this.text = 'Landscape'
126      } else {
127        this.color = '#DB7093'
128        this.text = 'Portrait'
129      }
130    }
131
132    aboutToAppear() {
133      portraitFunc = this.onPortrait.bind(this) //bind current js instance
134      this.listener.on('change', portraitFunc)
135    }
136
137    build() {
138      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
139        Text(this.text).fontSize(50).fontColor(this.color)
140      }
141      .width('100%').height('100%')
142    }
143  }
144  ```
145When the device is in landscape orientation, the text content is displayed in landscape mode in the color of #FFD700.<br>
146![en-us_image_0000001262954829](figures/en-us_image_0000001262954829.png)
147
148When the device is not in landscape orientation, the text content is displayed in portrait mode in the color of #DB7093.<br>
149![en-us_image_0000001263074739](figures/en-us_image_0000001263074739.png)
150
151## Samples
152
153The following sample is provided to help you better understand how to develop the media query:
154
155- [`MediaQuery`: eTS Media Query (API 8)](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/MediaQuery)
156