Media queries enable the conditional application of CSS styles based on media types, such as screen and print, and the conditions of media features, such as viewport and device height and width. They are part of the W3C CSS3 specification.
CSS Media Queries allow you to limit the scope of CSS rules based on, for example, screen size, device orientation, or display density. Introduced in the CSS3 specification, the use of media queries has become the de facto standard behind building websites that utilize responsive-design.
Every media query usually consists of a media type and can optionally contain one or more expressions which resolve to either true
or false
. If the media type matches the device the page is being viewed on and all expressions resolve to true
, the corresponding style sheet or style rules are applied to the document.
<!-- Media Query on a link element -->
<link rel="stylesheet" href="style.css" media="(max-width: 750px)" />
<!-- Media Query within a stylesheet -->
<style>
@media (max-width: 750px) {
footer {
display: none;
}
}
</style>
NOTE: Stylesheets that have media queries attached to their <link>
elements will still download even if their media queries would return false
.
Media Query Types
There are a handful of different media types, but the most commonly used are all
, screen
, and print
. Including a media type is not always required based on whether or not your expression, or your own conditions, require it.
Media Query Expressions
Media query expressions can be created using the logical operators and
, not
, and only
. Additionally, comma separated expressions constitutes the "or" operator.
The
and
operator is used to combine multiple media features into a single query. Each feature must returntrue
for the entire query to be evaluate astrue
.The
min-width
means greater than or equal to. Similarlymax-width
means less than or equal to.@media (min-width: 650px) and (orientation: landscape) { ... }
The
not
operator must be used with an explicit media type and is used to reverse the logic of an entire media query.@media not all and (max-width: 650px) { ... }
The
only
operator must be used with an explicit media type and tells older browsers not to process the query.@media only print { ... }
Comma separated expressions evaluates each expression with an "or" operator between them.
@media (max-width: 600px), (min-width: 800px) { ... }
Additional Information on CSS Media Queries