Font Size
Part of the Styling with CSS section of Coddy's HTML journey — lesson 19 of 76.
In CSS, the font-size property is used to control the size of text within an HTML element.
Here are some common units used for specifying font sizes:
- Pixels (px): An absolute unit that specifies the font size in pixels. This is the most straightforward and commonly used unit for setting font sizes.
- Ems (em): A relative unit that is based on the font size of the parent element. For example, if the parent element has a font size of
16px, then1emis equal to16px,2emis equal to32px, and so on.
- Rems (rem): A relative unit that is based on the font size of the root element (
<html>). This unit provides more consistency across the document, as it is not affected by the font size of parent elements.
- Percentages (%): A relative unit that is based on the font size of the parent element, similar to
em. For example, if the parent element has a font size of16px, then100%is equal to16px,150%is equal to24px, and so on.
For example:
p {
font-size: 16px;
}
h1 {
font-size: 2.5em;
}
body {
font-size: 1.4rem;
}
.small-text {
font-size: 80%;
}In this example, the font size of all <p> (paragraph) elements is set to 16px, all <h1> headings are set to 2.5em (which will be relative to the font size of their parent element), the base font size of the document is set to 1.4rem, and all elements with the class small-text have a font size of 80% (which will be relative to the font size of their parent element).
Challenge
EasyYou are given an HTML document with a heading (<h1>), a paragraph (<p>), and a division (<div>). Your task is to use the font-size property to style these elements. Follow the steps below:
- Write a CSS rule that targets the
<h1>element. Set thefont-sizeto32px. - Write a CSS rule that targets the
<p>element. Set thefont-sizeto1.2em. - Write a CSS rule that targets the
<div>element. Set thefont-sizeto120%.
Cheat sheet
The font-size property controls the size of text within an HTML element.
Common units for font sizes:
- Pixels (px): Absolute unit specifying font size in pixels
- Ems (em): Relative unit based on parent element's font size
- Rems (rem): Relative unit based on root element's font size
- Percentages (%): Relative unit based on parent element's font size
p {
font-size: 16px;
}
h1 {
font-size: 2.5em;
}
body {
font-size: 1.4rem;
}
.small-text {
font-size: 80%;
}Try it yourself
<html>
<head>
<title>Font Size</title>
<style>
/* Write CSS rules here */
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<div>This is a division.</div>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Styling with CSS
4Text Fundamentals
Text ColorFont FamilyFont SizeFont WeightText AlignmentText DecorationRecap Challenge #1Recap Challenge #25 Colors and Backgrounds
Background ColorHEX ColorsRGB ColorsTransparency with RGBARecap Challenge #1