Font Size CSS Property
The font-size property of css is used to define size of the text.
Syntax: font-size: value
Example: If we want to change size of the text "Make this world a better place to live" to 18px, the css for this text container element would be font-size: 18px.
Here, we have defined the font-size in px. There are other units like em, rem, vh, vw and % which can be used for the font-size. Let us see what these units are:
Px, Em, Rem, Vh, Vw and %
1. Pixel (Px): This is an absolute unit to define the size of any element. The size of the element defined in pixel doesn't change with change in the screen size. That's why while making responsive website or web applications it is not recommended to use px as the element size remains the same even in smaller screen with the same screen resolution.
2. Em: Em is a unit to set font-size relative to the parent element. Here, the parent element refers to the HTML element inside which the text exists.
Do the below activity as shown in the image to see how em works:
Image 2.6.1 Html code and the CSS code example for unit em |
Image 2.6.2 Computed font-size for em based on the parent element's font-size |
3. Rem: Rem sets the font-size relative to the size of the root element i.e HTML tag. Try changing the font size of H1 from 1em to 1rem and then see the difference by changing the font-size of the body tag. It won't affect the font-size of H1. Now, change the font-size of the root element H1, it will change the size of H1 too.
4. Viewport Height (vh): It sets the size of an element relative to the viewport height. Thus, vh is used whenever we want the size of an element to change as the viewport's height changes. Consider the below example:
Change the font-size in the above example to 5vh and then watch how the font-size reduces when we minimize the browser window and reduce the height of the browser screen i.e the view port as shown in the below images:
Image 6.2.3 Example of viewport height unit |
Image 6.2.4 Decrease in the computed font-size value as the height reduces |
Image 2.6.5 Imcrease in the computed font-size as the height increases |
5. Viewport Width (vw): vw sets the size of an element relative to the viewport width. To test this, change the font-size in the above example from 5vh to 5vw and see how it affects by changing the browser window's width
6. Percentage (%): Sets the size relative to the immediate parent element. For example: If we set the font-size of body tag to 20px and set the font-size of H1 to 50%, the computed value for the font-size of H1 would be 10px. There would be no affect on the font-size of H1 by changing the font-size of html tag.
Note: vw and vh are typically used whenever an element is supposed to cover full viewport width and height respectively. Em and Rem are only used for setting the font-size. If you want to convert px to em while setting the font-size, this website can be used.