Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Window: matchMedia() method

BaselineWidely available

TheWindow interface'smatchMedia() methodreturns a newMediaQueryList object that can then be used to determine ifthedocument matches themedia query string,as well as to monitor the document to detect when it matches (or stops matching) thatmedia query.

Syntax

js
matchMedia(mediaQueryString)

Parameters

mediaQueryString

A string specifying the media query to parse into aMediaQueryList.

Just like in CSS, anymedia feature must be wrapped in parentheses inside the expression. For example:matchMedia("(width <= 600px)") ormatchMedia("(orientation: landscape)") work, whereasmatchMedia("width < 600px") ormatchMedia("orientation: landscape") do not. Keywords for media types (all,print,screen) and logical operators (and,or,not,only) do not need to be wrapped in parentheses.

Return value

A newMediaQueryList object for the media query. Use this object'sproperties and events to detect matches and to monitor for changes to those matches overtime.

Usage notes

You can use the returned media query to perform both instantaneous and event-drivenchecks to see if the document matches the media query.

To perform a one-time, instantaneous check to see if the document matches the mediaquery, look at the value of thematchesproperty, which will betrue if the document meets the media query'srequirements.

If you need to be kept aware of whether or not the document matches the media query atall times, you can instead watch for thechange event to be delivered to the object.There'sa good example of thisin the article onWindow.devicePixelRatio.

Examples

This example runs the media query(width <= 600px) and displays thevalue of the resultingMediaQueryList'smatches property in a<span>; as a result, the output will say "true" if the viewport is lessthan or equal to 600 pixels wide, and will say "false" if the window is wider than that.

JavaScript

js
let mql = window.matchMedia("(width <= 600px)");document.querySelector(".mq-value").innerText = mql.matches;

The JavaScript code passes the media query to match intomatchMedia() to compile it, then sets the<span>'sinnerText to the value of the results'matches property, so that it indicates whether or not the document matches the media query at the moment the page was loaded.

HTML

html
<span></span>

A simple<span> to receive the output.

.mq-value {  font:    18px arial,    sans-serif;  font-weight: bold;  color: #88f;  padding: 0.4em;  border: 1px solid #dde;}

Result

SeeTesting media queries programmatically for additional code examples.

Specifications

Specification
CSSOM View Module
# dom-window-matchmedia

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp