Loading course content...
Loading course content...
Code Playground is only enabled on larger screen sizes.
The media query is a technique that allows you to selectively apply a block of CSS code based on certain conditions.
For example, the following @media rule specifies that the enclosed styles will only be activated for viewport smaller than 767px.
@media screen and (max-width: 767px) {
.container {
/* . . . */
}
.items {
/* . . . */
}
}The @media rule has the following syntax:
@media <media_type> and (<media_feature>) {
/* . . . */
}The <media_type> argument is optional. It specifies the type of media you are targeting.
Some common media types include:
screen: electronic screens such as smartphones, laptops, and so on.print: used for print previewspeech: used for screen readersall: all devicesThe <media_feature> argument is where you can add conditions to the media query.
The condition could be the width of the viewport (min-width or max-width), the orientation of the device (orientation), or the actual screen size of the device (device-width and device-height).
The media query plays a significant role in responsive design, as it allows you to define different styles for different viewport. For instance:
.box {
background-color: #fef3c7;
color: #b45309;
padding: 1rem;
border-radius: 0.25rem;
}
@media (min-width: 200px) {
.box {
background-color: #bfdbfe;
color: #1d4ed8;
}
}
@media (min-width: 300px) {
.box {
background-color: #fecaca;
color: #b91c1c;
}
}Use the slider to widen the viewport size, and you will see the box change from yellow to blue, and then changes into red.
In practice, we often need to create breakpoints that separate small screens (such as smartphones), medium screen (tablet) and large screens (desktops).
Some of the usual breakpoints include:
@media screen and (min-width: 640px) {
/* Small devices such as smartphones */
}
@media screen and (min-width: 768px) {
/* Medium devices such as tablets */
}
@media screen and (min-width: 1024px) {
/* Large devices such as laptops */
}
@media screen and (min-width: 1280px) {
/* Largest devices such as desktops */
}Notice that we are only using min-width as the condition.
This is because when designing responsive webpages, it is recommended to follow the mobile first convention, meaning you start with the smallest viewport and work your way up to the big screens.
Of course, if you want, you can also start from the large screens, and work your way down to the smaller screens, as long as you are organized.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="/styles.css"> </head> <body> <p>Hello, World!</p> </body> </html>