In this tutorial, we will learn how to style text using font and size utilities in CSS. By the end of the tutorial, you will be able to select and apply different fonts and text sizes to your web content.
What you will learn:
* How to change the font of the text
* How to change the size of the text
* How to apply these styles to different HTML elements
Prerequisites:
* Basic knowledge of HTML and CSS
CSS provides several properties to style text such as font-family
, font-size
, font-weight
, etc.
font-family
: This property is used to change the font of the text. You can specify a custom font or use the system fonts.
font-size
: This property is used to change the size of the text. You can specify the size in px
, em
, %
etc.
em
or rem
instead of absolute units like px
./* CSS */
p {
font-family: Arial, sans-serif; /* If Arial is not available, the browser will use any sans-serif font */
}
The above CSS will apply the Arial font to all paragraph elements. If Arial is not available, the browser will use a sans-serif font.
/* CSS */
h1 {
font-size: 2em; /* 2em means 2 times the size of the current font */
}
The above CSS will apply the font size of 2em to all h1 elements.
In this tutorial, we learned how to change the font and size of the text using CSS. We also discussed best practices like providing fallback fonts and using relative units for font size.
Next steps for learning:
Explore other CSS properties to style text such as font-weight
, font-style
, text-decoration
, etc.
Additional resources:
* MDN Web Docs: font-family
* MDN Web Docs: font-size
Exercise 1: Change the font of all headings (h1, h2, h3) to 'Verdana' and provide a suitable fallback font.
Solution:
h1, h2, h3 {
font-family: Verdana, sans-serif;
}
In the above CSS, we apply the Verdana font to all h1, h2, and h3 elements. If Verdana is not available, the browser will use a sans-serif font.
Exercise 2: Change the font size of all paragraph elements to 1.5em.
Solution:
p {
font-size: 1.5em;
}
In the above CSS, we apply the font size of 1.5em to all paragraph elements.
Tips for further practice: Practice using different fonts and sizes for different HTML elements. Also, try to apply these styles to a real project.