Media query is a CSS technique introduced in CSS3.It is a technique to apply different styles or layouts to a web page based on the characteristics of the user's device or screen size. Media queries allow web developers to create designs that adapt and look well-organized on various devices, such as desktop computers, laptops, tablets, and smartphones.
With
media queries, you can set specific CSS rules to trigger only when certain conditions are met, such as the width of the viewport. This enables you to create flexible and
responsive designs that provide an optimal viewing experience regardless of the device being used to access the website.
Here's an example of a media query in CSS:
/* This CSS rule will apply to screens with a maximum width of 600 pixels */
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}
In this example, the
`@media` rule specifies a condition for when the screen width is at most 600 pixels. If the screen width matches this condition (i.e., the screen is 600 pixels wide or narrower), the styles inside the curly braces will be applied. In this case, the background color of the `body` element will be changed to light blue.
You can also have multiple conditions within a single media query, allowing you to target different screen sizes with different styles:
/* Styles for screens up to 600 pixels wide */
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}
/* Styles for screens between 601 and 1200 pixels wide */
@media (min-width: 601px) and (max-width: 1200px) {
body {
background-color: lightgreen;
}
}
In this second example, the first media query targets screens up to
600 pixels wide with a light blue background color, and the second media query targets screens between
601 and 1200 pixels wide with a light green background color.
These examples showcase how media queries allow you to apply different styles based on the characteristics of the screen, creating a responsive design that adapts to various devices.