CSS Media Queries
CSS2 Introduced Media Types
The @media
rule, which came into CSS2, allowed us to create distinct style rules for various types of media.
Examples: You can create different sets of style instructions for various devices like computers, printers, handheld gadgets, televisions, and more.
Regrettably, these types of media formats didn't receive much support from devices, except for the print media format.
CSS3 Introduced Media Queries
CSS3's media queries expanded on the concept of media types from CSS2. Instead of focusing on the type of device, they consider what the device can do.
Media queries are a way to examine various aspects, like:
- width and height of the viewport
- width and height of the device
- orientation (is the tablet/phone in landscape or portrait mode?)
- resolution
Media queries are commonly used to provide a customized style sheet for different devices like desktops, laptops, tablets, and mobile phones, including iPhones and Android phones.
Media Query Syntax
A media query is made up of a type of media and can have one or more conditions that can be either true or false.
CSS-Code;
}
The query's outcome is "true" when the chosen media type matches the device the document appears on, and all conditions in the media query are also "true." If a media query is "true," it means that the corresponding style sheet or style rules will be used, following the usual cascading rules.
If you don't use the 'not' or 'only' operators, you don't have to specify the media type, and it will automatically be set to 'all'.
You can use separate stylesheets for various types of screens or devices:
CSS3 Media Types
Value | Description |
---|---|
all | This code is designed to work with all types of devices. |
Used for printers | |
screen | This is for computer screens, tablets, and smartphones, among other devices. |
speech | This is for screen readers, which are tools that read web pages aloud. |
Media Queries Simple Examples
You can use media queries by adding another section of CSS code directly within your stylesheet.
In this example, when the screen is 480 pixels wide or wider, the background color becomes light green. If the screen is less than 480 pixels wide, the background color turns pink.
Example
body {
background-color: lightgreen;
}
}
In this example, there's a menu that moves to the left side of the page if the screen is 480 pixels wide or wider. If the screen is less than 480 pixels wide, the menu will be on top of the content.
Example
#leftsidebar {width: 200px; float: left;}
#main {margin-left: 216px;}
}
More Media Query Examples
For much more examples on media queries, go to the next page: CSS MQ Examples.