The font-size property determines the size of text displayed on a webpage.
Managing text size is crucial in web design. However, it’s essential to avoid using font size adjustments to mimic different text elements, such as paragraphs resembling headings or vice versa.
It’s recommended to utilize proper HTML tags like <h1> – <h6> for headings and <p> for paragraphs.
The font-size value can be either absolute or relative:
Absolute size:
Relative size:
Note: In the absence of a specified font size, the default size for regular text such as paragraphs is 16px (which equals 1em). |
Defining the text size in pixels provides complete control over its appearance.
Example
h1 { font-size: 40px; } h2 { font-size: 30px; } p { font-size: 14px; } |
Tip: Even when using pixels, you can utilize the zoom tool to resize the entire page.
To enable users to adjust text size via the browser menu, numerous developers opt for using “em” instead of pixels.
One “em” corresponds to the current font size. In browsers, the default text size is typically 16px. Hence, the default size of 1em equals 16px.
You can convert size from pixels to em using this formula: pixels divided by 16 equals 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 */ } |
In the aforementioned example, the text size in “em” remains consistent with the previous example using pixels. However, utilizing “em” size permits adjusting text size across all browsers.
Regrettably, there persists an issue with older versions of Internet Explorer. Text tends to become larger than intended when enlarged and smaller than intended when reduced.
A universal solution across all browsers involves defining a default font size in percentage for the <body> element.
Example
body { |
Our code is now performing exceptionally well! It ensures consistent text size across all browsers and enables users to zoom or resize the text seamlessly.
Text size can be defined using the vw unit, representing the “viewport width.”
This approach ensures that the text size adjusts according to the size of the browser window.
Resize the browser window to see how the font size scales.
Example
<h1 style=”font-size:10vw”>Hello World</h1> |
The viewport refers to the size of the browser window. In this context, 1vw equates to 1% of the viewport width. For instance, if the viewport measures 50cm in width, then 1vw would correspond to 0.5cm. |