Changing the font size in CSS is an essential skill for web developers and designers. By altering the font size, you can improve the readability of your website and enhance its overall appearance.
This tutorial will guide you through various techniques to change the font size in CSS.
Step 1: Inline CSS
Using inline CSS is a straightforward option to modify the font size of a specific element.
Add the style
attribute inside the HTML tag, then set the font size with the help of the font-size
property. Take a look at the example below:
1 |
<p style="font-size:20px;">This text will have a font size of 20px.</p> |
In this example, the font size of the paragraph will be 20 pixels.
Step 2: Internal CSS
If you wish to style multiple elements of the same type within an HTML page, an internal CSS would be more appropriate.
Use the <style> tag inside the <head> section of the page and define the styles for the desired elements:
1 2 3 4 5 6 7 |
<head> <style> p { font-size: 20px; } </style> </head> |
This code will set the font size to 20 pixels for all the <p> elements of the page.
Step 3: External CSS
For large web projects, using an external CSS file is best for managing styling efficiently.
Create a separate CSS file and add the font-size property to the desired elements. Then, link it to the HTML page using the <link> tag in the <head> section:
1 2 3 |
p { font-size: 20px; } |
1 2 3 |
<head> <link rel="stylesheet" href="styles.css"> </head> |
This method will set the font size of all <p> elements to 20 pixels, by linking the external CSS file to the HTML page.
Step 4: Using units for font size
Various units can be used for font size, such as pixels (px), em, rem, and percentages (%). Choose the one that best suits your needs:
1 2 3 4 5 6 7 8 9 10 11 12 |
p { font-size: 20px; /* Pixels */ } h1 { font-size: 2em; /* Relative to the parent element's font size */ } h2 { font-size: 1.5rem; /* Relative to the root (html tag) font size */ } h3 { font-size: 150%; /* Sets the font size as a percentage of the parent element's font size */ } |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Font Size Example</title> <style> p { font-size: 20px; } h1 { font-size: 2em; } h2 { font-size: 1.5rem; } h3 { font-size: 150%; } </style> </head> <body> <p style="font-size: 20px;">This text will have a font size of 20px.</p> <h1>This is an H1 heading</h1> <h2>This is an H2 heading</h2> <h3>This is an H3 heading</h3> </body> </html> |
Output
Conclusion
In this tutorial, you have learned several techniques to change the font size of elements in CSS. You can now apply inline CSS, Internal CSS, or external CSS while considering the various units for font size. These techniques will offer greater control over the appearance of your website and help you create a more visually appealing user experience.