Introduction
Changing the font size in CSS is essential for adjusting the readability and hierarchy of your text. The font-size
property allows you to easily modify the size of the text to suit your design.
In this tutorial, you'll learn how to change the font size using the font-size
property in CSS. We'll explore different units, such as pixels, ems, and percentages, to give you flexible control over text size.
Problem Statement
Create a CSS code that:
- Changes the font size of text using the
font-size
property. - Demonstrates how to apply different font size units (px, em, %).
Example:
- Input: A paragraph element with the text "Font Size Example".
- Output: The text appears in different font sizes based on the applied CSS.
Solution Steps
- Use
font-size
Property: Apply thefont-size
property to change the size of the text. - Apply Different Font Size Units: Use units like pixels (
px
), ems (em
), and percentages (%
) to control the text size.
HTML Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Font Size Example</title>
<style>
/* Step 1: Change font size using pixels */
.font-size-px {
font-size: 24px;
}
/* Step 2: Change font size using em */
.font-size-em {
font-size: 1.5em;
}
/* Step 3: Change font size using percentage */
.font-size-percent {
font-size: 150%;
}
</style>
</head>
<body>
<p class="font-size-px">This text is 24px in size.</p>
<p class="font-size-em">This text is 1.5em in size.</p>
<p class="font-size-percent">This text is 150% in size.</p>
</body>
</html>
Output
You can play with the above HTML in Online HTML Editor and Compiler. Here is the output of the above HTML page.:
Explanation
Step 1: Use font-size
in Pixels
- To set a fixed font size in pixels, use the following CSS:
.font-size-px { font-size: 24px; }
Step 2: Use font-size
in Em
- To scale the font size relative to its parent, use em units:
.font-size-em { font-size: 1.5em; }
Step 3: Use font-size
in Percentage
- To set the font size as a percentage of the parent element, use this CSS:
.font-size-percent { font-size: 150%; }
Conclusion
Changing the font size with CSS is simple using the font-size
property. Whether you use pixels, ems, or percentages, you can easily control the size of text to improve readability and visual hierarchy.
Comments
Post a Comment
Leave Comment