CSS `font-size`: Mastering Text Size Control in Web Design
Learn how to control font size in your CSS stylesheets using the `font-size` property. This tutorial covers various units (pixels, ems, rems, percentages), keywords, and techniques for creating responsive and accessible text sizes across different devices and screen sizes.
Controlling Font Size with CSS `font-size`
Understanding `font-size`
The CSS `font-size` property controls the size of text within an HTML element. It affects the height and visual size of the font. The default value is `medium`, but this can vary across browsers and is often relative to the parent element's size. You can specify font size using various units and keywords.
`font-size` Syntax
The basic syntax is:
font-size:
Absolute vs. Relative Font Sizes
- Absolute: Sets a fixed font size (e.g., using pixels, points, etc.). The exact rendered size might vary slightly across browsers due to different font rendering engines. Useful when you need precise control over the font size regardless of the surrounding context.
- Relative: Sets the font size relative to another size (e.g., using
em
,rem
,vw
, etc.). This allows the font size to scale proportionally with other elements, making it better for responsive design.
If no `font-size` is specified, the default for normal text (like paragraphs) is generally 16 pixels (equivalent to 1em).
Specifying Font Size
Using Pixels (px
)
Pixels provide direct control over font size. The example shows paragraphs with explicitly defined pixel sizes.
CSS Example
p { font-size: 40px; }
p { font-size: 20px; }
Using Ems (em
)
Ems are relative to the parent element's font size. If the parent has a font size of 16px, 1em is 16px, 2em is 32px, and so on. The default browser text size is generally 16px (1em). Using ems is generally preferred for better scalability and responsiveness. This allows font sizes to adjust based on the user's browser settings.
CSS Example
p { font-size: 1.2em; } /* 1.2 times the parent's font size */
Responsive Font Size with Viewport Units (vw
)
Viewport width (vw
) units are relative to the browser window's width (1vw = 1% of viewport width). This creates responsive text that scales with the screen size.
CSS Example
p { font-size: 5vw; } /* Font size scales with the viewport width */
Using Length Units
You can also specify font size using other length units like centimeters (cm), points (pt), etc. Negative values are not allowed.
CSS Example
p { font-size: 5cm; }