Responsive Font Sizes in CSS
You already know that rem units are relative to the font size of the root element, which by default is 16px:
html {
font-size: 16px; /* default value */
}
This feature is used to change font sizes en masse when the screen width changes. Let's see how it's done.
Let's say our tags have the following dimensions:
h1 {
font-size: 1.5rem; /* corresponds to 24px */
}
p {
font-size: 1rem; /* corresponds to 16px */
margin: 2rem; /* corresponds to 32px */
}
Let's make it so that when the screen width changes, the dimensions set via rem change adaptively. To do this, we will change the font size of the root element using media queries:
@media (max-width: 600px) {
html {
font-size: 16px;
}
}
@media (min-width: 600px) and (max-width: 1200px) {
html {
font-size: 18px;
}
}
@media (min-width: 1200px) {
html {
font-size: 20px;
}
}
The following code is given:
@media (max-width: 300px) {
h1 {
font-size: 32px;
}
h2 {
font-size: 24px;
}
p {
font-size: 16px;
}
}
@media (min-width: 300px) and (max-width: 900px) {
h1 {
font-size: 36px;
}
h2 {
font-size: 27px;
}
p {
font-size: 18px;
}
}
@media (min-width: 900px) {
h1 {
font-size: 40px;
}
h2 {
font-size: 30px;
}
p {
font-size: 20px;
}
}
Simplify the given code using the technique described in the tutorial.