CSS Typography
Learn how to style text with CSS to control fonts, sizes, and layout for beautiful and readable web pages.
Controlling Font Family
The font-family
property is used to specify the font for an element. It's a best
practice to provide a "font stack"—a list of fonts in order of preference. The browser will use
the first font it finds on the user's system. Always end your font stack with a generic family
(serif
, sans-serif
, or monospace
) as a fallback.
/* Using a font stack with a generic fallback */ body { font-family: 'Inter', Arial, sans-serif; } h1 { font-family: 'Georgia', Times, serif; }
Setting Font Size
The font-size
property controls the size of the text. While pixels
(px
) are fixed and absolute, it's often better to use relative units like
em
, rem
, or percentages for better accessibility and responsiveness.
📏 Relative vs. Absolute Units
Absolute units (like px
) have the same size on all media.
Relative units (like em
, rem
, and %
)
scale relative to another length, making them ideal for responsive design.
/* Examples of font sizes using different units */ p { font-size: 16px; /* Absolute unit */ } .large-text { font-size: 1.5rem; /* Relative to the root element's font-size */ } .small-text { font-size: 0.8em; /* Relative to the parent element's font-size */ }
Font Weight and Style
You can adjust the boldness and style of your text using the font-weight
and
font-style
properties.
font-weight
:normal
,bold
,bolder
,lighter
, or a number from 100 to 900.font-style
:normal
,italic
, oroblique
.
/* Setting font weight and style */ h2 { font-weight: 700; /* Bold */ } em { font-style: italic; }
Line Height and Letter Spacing
These properties control the spacing around text, which is critical for readability.
line-height
sets the space between lines of text, while letter-spacing
adjusts the space between individual characters.
/* Adjusting line height and letter spacing */ p { line-height: 1.6; /* A unitless value is recommended for proportionality */ letter-spacing: 0.5px; /* Tighter or looser spacing */ }