In CSS, a media query is a technique used to apply different styles to different devices based on characteristics like screen size, resolution, orientation, and more. This helps make your web pages responsive, ensuring they look good on all devices, from mobile phones to large desktop monitors.
A media query is composed of a media type and one or more expressions that check for conditions of particular media features. Here's a simple example:
In this example:
@media
is the media query keyword.
only screen
specifies the media type (in this case, screen devices).
(max-width: 600px)
is the media feature, which means this CSS will only apply if the viewport width is 600 pixels or less.
The CSS inside the {}
brackets will apply when the conditions are met.
Here are some commonly used media features:
width
and height
– The width and height of the viewport.
min-width
and max-width
– Minimum and maximum width of the viewport.
orientation
– Checks if the device is in portrait or landscape mode.
resolution
– Checks the resolution of the device in dots per inch (DPI) or dots per centimeter (DPCM).
Here' a more comprehensive example:
In this example:
The default body
background color is white.
For screens between 600px and 768px wide (typically tablets), the background color is light green.
For screens 599px wide or smaller (typically mobile devices), the background color is light blue.
Media queries are very useful when you want to ensure that your website provides an optimal viewing experience across a wide range of devices. By adjusting layout, typography, and other stylistic elements, you can make your content more accessible and enjoyable for all users.
Would you like to delve deeper into any specific aspect of media queries?