Media queries are used in CSS to apply specific styles based on the characteristics of the device being used to view a webpage. These queries are written using the @media rule, which includes one or more conditions that define the targeted device. Once the conditions of the media query are met, the CSS styles within the query are applied to the webpage. This allows developers to create pixel-perfect styling for different screen resolutions, such as mobile phones or tablets. However, using media queries can result in larger CSS file sizes due to the additional code needed to target specific devices.
In the below example, the min-width property is used to specify the minimum screen width that the media query should target. The only screen part ensures that the media query only applies to screens and not other types of devices like printers or speech synthesizers.
@media only screen and (min-width: 768px) {
/* Your CSS styles for devices with a screen width of 768 pixels or larger go here */
}
A more intricate example might specify that the background-color of a webpage should be red, but only when the device is in portrait mode, has a width of at least 911 pixels, and a resolution over 120 DPI.
@media only screen and (min-width: 911px) and (orientation: portrait) and (resolution: > 120dpi) {
body {
background-color: red;
}
}
There are several conditions that you can use with @media queries to apply different styles based on specific device characteristics. Here are a few examples:
This condition targets devices with a screen width that is smaller or equal to a specific value. For example,
@media screen and (max-width: 768px)
would target devices with a screen width of 768 pixels or smaller.
This condition targets devices with a screen width that is greater or equal to a specific value. For example,
@media screen and (min-width: 768px)
would target devices with a screen width of 768 pixels or larger.
This condition targets devices with a specific orientation, either portrait or landscape. For example,
@media screen and (orientation: portrait)
would target devices in portrait mode.
These conditions are similar to max-width and min-width, but instead target devices with a specific height.
This condition targets devices with a specific screen resolution. For example, @media screen and (resolution: 300dpi)
would target devices with a screen resolution of 300 dots per inch.
This condition targets devices with a specific aspect ratio. For example, @media screen and (aspect-ratio: 16/9)
would target devices with a widescreen aspect ratio of 16:9.