A @media query returns data about the device the page displays on.
This includes device type, dimensions, resolution, orientation, and more.
This data helps with creating an optimal user experience for each device.
Media queries are key to building responsive web solutions.
In this example, the style changes with the device width.
Resize the browser to see the background change at multiple stages.
<style>
.my-style {
background-color: aliceblue;
padding: 30px;
}
@media (min-width: 254px) {
.my-style {
background-color: greenyellow;
}
}
@media (min-width: 456px) {
.my-style {
background-color: lightyellow;
}
}
@media (min-width: 576px) {
.my-style {
background-color: lavenderblush;
}
}
@media (min-width: 768px) {
.my-style {
background-color: honeydew;
}
}
@media (min-width: 992px) {
.my-style {
background-color: cornsilk;
}
}
@media (min-width: 1200px) {
.my-style {
background-color: aliceblue;
}
}
</style>
<div class="my-style">
Resize the browser and see
the background change
</div>
Media queries were introduced in CSS3.
Not only do they detect the device type, but also the device capabilities.
Media queries check for these characteristics:
Syntax for media queries.
@media not|only mediatype and (expressions) { CSSCode; }
mediatype
-- can have any of these values:
all
-- all media type devices. default.print
-- printersscreen
-- computer screens, tablets, smart-phones etc.speech
-- screenreaders that read the page out loudexpression
-- a logical expression with media capabilities:
min-width
max-width
min-height
max-height
orientation
resolution
color, monochrome
aspect-ratio
hover
and more...
Logical expressions can include and
, only
, and not
.
Expression also support operators like >=
, <
, ==
, !=
, and more.
If the query returns true the CSS style takes effect.
Media queries are used also by HTML elements with a media attribute. These include <link>, <style>, <source>, and others. Below is an example.
<link rel="stylesheet" media="mediatype and|not|only (expressions)" href="style.css">
For each browser see which version and on what date support started for the CSS media queries.
Chrome
|
21.0 | Jul 2012 |
Firefox
|
3.5 | Jun 2009 |
IE/Edge
|
9.0 | Mar 2011 |
Opera
|
9.0 | Jun 2006 |
Safari
|
4.0 | Jun 2009 |