2021-08-12
|~2 min read
|345 words
When working with adaptive designs that handle different view ports, we may want to reach for a Media Query.
The simplest rules are based on screen widths. For example1:
.my-class {
padding: 2rem;
}
@media screen and (min-width: 900px) {
.my-class {
padding: 1rem;
}
}
Now, when the screen exceeds 900px in width, the padding for elements which have the class my-class
will have a padding of 1rem
instead of the default 2rem
.
What about the case where you want to have multiple break points?
For example, what if you want to have an responsive design that needs a few break points to handle the content appropriately?
One way to handle that is by defining the default and then using media queries for the extremes. This works if we have three breakpoints. For example:
.my-class {
padding: 2rem;
}
@media screen and (min-width: 900px) {
.my-class {
padding: 1rem;
}
}
@media screen and (max-width: 300px) {
.my-class {
padding: 0.5rem;
}
}
Now, on small screens, the padding is .5rem
on normal screens it’s 2rem
and on large screens it’s 1rem
.
And now, what about the case where you don’t want to be limited to just three? Or your default is for an extreme (e.g., anything larger than X)? In that case, we would take advantage of combining media queries. For example:
.my-class {
padding: 2rem;
}
@media screen and (max-width: 900px) and (min-width: 300px) {
.my-class {
padding: 1rem;
}
}
@media screen and (max-width: 300px) {
.my-class {
padding: 0.5rem;
}
}
In contrast to the preceding example, in this case, our default is padding of 2rem
, for a middle sized screen width (between 300px
and 900px
), we have 1rem
and for narrow screens (below 300px
) we have .5rem
.
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!