CSS - Media Query
Table of Contents
About
Media queries extend the functionality of media types (print, screen) by allowing more conditional expressions in the application of style sheets.
Example:
- landscape or not,
- from a certain width (viewport width),
- …
Syntax
A media query consists of a:
- and zero or more expressions that check for the conditions of particular media features (width, height, color, …).
A string matches the environment of the user if it is:
- the empty string,
- a string consisting of only space characters,
- a media query that matches the user's environment
A string is a valid media query if it matches the media_query_list production of the Media Queries specification.
Example
Inline
Below a viewport of 768 px, the element
@media only screen and (min-width: 768px) and (orientation: landscape) {
.navbar-toggle {
display: none;
}
}
In Less:
.navbar-toggle {
@media (min-width: @grid-float-breakpoint) {
display: none;
}
}
Link
With a Link element in the header.
<link rel="stylesheet" media="screen and (min-width: 300px)" href="myStyleSheet.css">
Import
With the import rule
@import url("mySteelSheet.css") only screen and (min-width: 500px);
The import rule will fire an new HTTP request after the reception of the parent stylesheet and therefore has a lower performance than the two others methods
Specification
- Media Queriesspecification, H. Lie, T. Çelik, D. Glazman, A. van Kesteren. W3C.
Support
It's not working
If your media query are not working be sure to have defined the viewport in html
Example:
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>