• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Media Query
2
3[Media queries](../reference/apis/js-apis-mediaquery.md) are at the core of responsive design and widely used on mobile devices. You can use them to create different application styles depending on the device type or device state. Specifically, media queries allow you to:
4
51. Design a layout style based on the device and application attributes (such as display area, dark light color, and resolution).
6
72. Update the page layout to adapt to dynamic screen changes (for example, screen splitting or switching between landscape and portrait modes).
8
9
10
11## Usage
12
13Invoke 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.
14
15First, import the **mediaquery** module, as shown below:
16
17```ts
18import mediaquery from '@ohos.mediaquery'
19```
20
21Then, use the **matchMediaSync** API to set the media query condition and save the returned listener, as shown below:
22
23```ts
24listener = mediaquery.matchMediaSync('(orientation: landscape)')
25```
26
27Finally, register the **onPortrait** 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:
28
29```ts
30onPortrait(mediaQueryResult) {
31    if (mediaQueryResult.matches) {
32        // do something here
33    } else {
34        // do something here
35    }
36}
37listener.on('change', onPortrait)
38```
39
40## Media Query Conditions
41
42The media query condition consists of the media type (optional), logical operator, and media feature. The logical operator is used to connect different media types and media features. A media feature must be enclosed in parentheses (). There may be multiple media features. The specific rules are as follows:
43
44### Syntax
45
46```
47[media-type] [and|not|only] [(media-feature)]
48```
49
50Examples are as follows:
51
52**screen and (round-screen: true)**: The query is valid when the device screen is round.
53
54**(max-height: 800)**: The query is valid when the height is less than or equal to 800.
55
56**(height <= 800)**: The query is valid when the height is less than or equal to 800.
57
58**screen and (device-type: tv) or (resolution < 2)**: The query is valid when the device type is TV or the device resolution is less than 2. This is a multi-condition query that contains multiple media features.
59
60###  media-type
61
62| Type    | Description            |
63| ------ | -------------- |
64| screen | Media query based on screen-related parameters.|
65
66### Media Logic Operation (and|or|not|only)
67
68You 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.
69
70  **Table 1** Media logical operators
71
72| Type      | Description                                      |
73| -------- | ---------------------------------------- |
74| 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 and (device-type: wearable) and (max-height: 600)** indicates that the query is valid when the device type is wearable and the maximum height of the application is 600 pixel units.|
75| 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 and (max-height: 1000) or (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.|
76| 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.<br>For example, **not screen and (min-height: 50) and (max-height: 600)** 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>You must specify the media type when using the **not** operator.|
77| 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  and  (min-height:  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>You must specify the media type when using the **only** operator.|
78| , (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 and (min-height: 1000), (round-screen: true)** indicates that the query is valid when the minimum height of the application is 1000 pixel units or the device screen is round.|
79
80At 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.
81
82  **Table 2** Logical operators for range query
83
84| Type   | Description                                      |
85| ----- | ---------------------------------------- |
86| &lt; = | Less than or equal to, for example, **screen and (50 &lt;= height)**.|
87| &gt; = | Greater than or equal to, for example, **screen and (600 &gt;= height)**.|
88| &lt; | Less than, for example, **screen and (50 &lt; height)**.|
89| &gt; | Greater than, for example, **screen and (600 &gt; height)**.|
90
91### media-feature
92
93| Type             | Description                                                        |
94| ----------------- | ------------------------------------------------------------ |
95| height            | Height of the display area on the application page.               |
96| min-height        | Minimum height of the display area on the application page.       |
97| max-height        | Maximum height of the display area on the application page.       |
98| width             | Width of the display area on the app page.                        |
99| min-width         | Minimum width of the display area on the application page.        |
100| max-width         | Maximum width of the display area on the application page.        |
101| resolution        | Resolution of the device. The unit can be dpi, dppx, or dpcm.<br>- **dpi** indicates the number of physical pixels per inch. 1 dpi ≈ 0.39 dpcm.<br>- **dpcm** indicates the number of physical pixels per centimeter. 1 dpcm ≈ 2.54 dpi.<br>- **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 = 96 dpi.|
102| min-resolution    | Minimum device resolution.                                        |
103| max-resolution    | Maximum device resolution.                                        |
104| orientation       | Screen orientation.<br>Options are as follows:<br>- orientation: portrait<br>- orientation: landscape|
105| device-height     | Height of the device.                                             |
106| min-device-height | Minimum height of the device.                                     |
107| max-device-height | Maximum height of the device.                                     |
108| device-width      | Width of the device.                                              |
109| min-device-width  | Minimum width of the device.                                      |
110| max-device-width  | Maximum width of the device.                                      |
111| device-type       | Type of the device.<br/>Value range: **default** |
112| round-screen      | Screen type. The value **true** means that the screen is round, and **false** means the opposite. |
113| 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.                       |
114
115## Example Scenario
116
117In the following example, media queries are used to apply different content and styles to the page text when the screen is switched between landscape and portrait modes.
118
119```ts
120import mediaquery from '@ohos.mediaquery'
121
122let portraitFunc = null
123
124@Entry
125@Component
126struct MediaQueryExample {
127  @State color: string = '#DB7093'
128  @State text: string = 'Portrait'
129  listener = mediaquery.matchMediaSync('(orientation: landscape)') // The query is valid when the device is in landscape mode.
130
131  onPortrait(mediaQueryResult) {
132    if (mediaQueryResult.matches) {
133      this.color = '#FFD700'
134      this.text = 'Landscape'
135    } else {
136      this.color = '#DB7093'
137      this.text = 'Portrait'
138    }
139  }
140
141  aboutToAppear() {
142    portraitFunc = this.onPortrait.bind(this) // Bind to the current application instance.
143    this.listener.on('change', portraitFunc)
144  }
145
146  build() {
147    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
148      Text(this.text).fontSize(50).fontColor(this.color)
149    }
150    .width('100%').height('100%')
151  }
152}
153```
154
155When the device is in landscape orientation, the text content is displayed in landscape mode in the color of #FFD700.
156
157![en-us_image_0000001262954829](figures/en-us_image_0000001262954829.png)
158
159When the device is not in landscape orientation, the text content is displayed in portrait mode in the color of #DB7093.
160
161![en-us_image_0000001263074739](figures/en-us_image_0000001263074739.png)
162