Font Size
CSS Font Size
The text’s size is determined by the font-size parameter.
In web design, controlling the text size is crucial. On the other hand, you shouldn’t utilize font size adjustments to change the appearance of headings or paragraphs within headings.
Use <p> for paragraphs and <h1> through <h6> for headings when using HTML tags.
There are two possible font-size values: absolute and relative.
Size in absolute terms:
- sets the text’s size to a given value.
- does not enable text size modification across all browsers (unfavorable for accessibility reasons)
- When the physical size of the output is known, absolute size is helpful.
Comparative dimensions:
- sets the size in relation to the components around it.
- enables users to modify the size of text in browsers
Note: The default font size for regular text, such as paragraphs, is 16px (16px=1em), unless you specify a different size.
Set Font Size With Pixels
You have complete control over the text size when you set the text size in pixels:
Example
h1 {
font-size: 40px;
}
h2 {
font-size: 30px;
}
p {
font-size: 14px;
}
Advice: You can still enlarge the entire page using the zoom tool if you’re using pixels.
Set Font Size With Em
Em is a common substitute for pixels in web development when allowing users to resize text via the browser menu.
The current font size is equivalent to one em. 16 pixels is the text size that browsers default to. Hence, 16px is the default size for 1em.
The following formula can be used to convert pixels to em: pixels/16=em.
Example
h1 {
font-size: 2.5em; /* 40px/16=2.5em */
}
h2 {
font-size: 1.875em; /* 30px/16=1.875em */
}
p {
font-size: 0.875em; /* 14px/16=0.875em */
}
The font size in the aforementioned example is the same in em as it was in pixels in the preceding example. Nonetheless, all browsers allow you to change the font size using the em size.
Regretfully, an issue persists with earlier iterations of Internet Explorer. When the text is made bigger than it should be, it gets smaller than it should get.
Use a Combination of Percent and Em
Setting the <body> element’s default font-size in percent is the workaround that is compatible with all browsers:
Example
body {
font-size: 100%;
}
h1 {
font-size: 2.5em;
}
h2 {
font-size: 1.875em;
}
p {
font-size: 0.875em;
}
Now, our code functions flawlessly! All browsers display the text at the same size and have the ability to resize or zoom in!
Responsive Font Size
A “viewport width” (vw) unit can be used to adjust the text size.
In this manner, the text size will match the browser window’s size:
Hello World
Resize the browser window to see how the font size scales.
Example
Hello World
Viewport is the browser window size. 1vw = 1% of viewport width. If the viewport is 50cm wide, 1vw is 0.5cm.