Introduction to Media Queries in CSS
There is a special command @media that allows you to execute different code depending on the screen width.
In the following example, some code will run if the screen width is between 300px and 1200px:
@media (min-width: 300px) and (max-width: 1200px) {
/* some code */
}
In the following example, some code will fire if the screen width is greater than 300px:
@media (min-width: 300px) {
/* some code */
}
In the following example, some code will fire if the screen width is less than 1200px:
@media (max-width: 1200px) {
/* some code */
}
Let's write some code in our media query. For example, at certain screen sizes, we'll color the paragraphs red:
@media (min-width: 300px) and (max-width: 1200px) {
p {
color: red;
}
}
@media (min-width: 300px) and (max-width: 1200px) {
p {
color: red;
}
}
Now let's color the paragraphs in different colors depending on the screen width:
@media (max-width: 300px) {
p {
color: red;
}
}
@media (min-width: 300px) and (max-width: 900px) {
p {
color: green;
}
}
@media (min-width: 900px) and (max-width: 1200px) {
p {
color: blue;
}
}
@media (min-width: 1200px) {
p {
color: orange;
}
}
Let's apply the following code on a screen width from 0 to 800px:
p {
font-size: 20px;
}
And let the following code be applied on a screen with a width of 800px and more:
p {
font-size: 30px;
}
Let's apply the following code on a screen width from 0 to 500px:
p {
font-size: 15px;
}
The following code should be applied on a screen width from 500px to 900px:
p {
font-size: 20px;
}
The following code should be applied on a screen width of 900px and larger:
p {
font-size: 30px;
}