The font-size property in CSS is used to specify the size of the font for an element.
Basic Usage
You can set the font size using various units, keywords, or percentages:
/* Using pixels */
p {
font-size: 16px;
}
/* Using em units (relative to parent font size) */
h1 {
font-size: 2em;
}
/* Using relative keywords */
body {
font-size: medium;
}
Available Units and Keywords
- Absolute units:
px: Pixelscm: Centimetersmm: Millimetersin: Inchespt: Pointspc: Picas
- Relative units:
em: Relative to the font size of the parent elementrem: Relative to the font size of the root element (html)%: Relative to the font size of the parent elementvw: Relative to the viewport width (1vw = 1% of viewport width)vh: Relative to the viewport height (1vh = 1% of viewport height)vmin: Relative to the smaller of vw or vhvmax: Relative to the larger of vw or vh
- Keywords:
xx-smallx-smallsmallmediumlargex-largexx-largelargersmaller
Example with Different Units
html {
font-size: 16px; /* Base font size */
}
body {
font-size: 1.2rem; /* 19.2px */
}
h1 {
font-size: 2.5em; /* Relative to parent (body) */
}
p {
font-size: 18px;
}
.small-text {
font-size: 0.8em; /* Relative to parent */
}
Important Considerations
- Base font size: It’s recommended to set a base font size for the
htmlelement to establish a consistent baseline for your typography. - Relative units: Using
emandremunits can create flexible and responsive designs. - Viewport units:
vw,vh,vmin, andvmaxare useful for creating designs that adapt to different screen sizes. - Browser compatibility: Be aware of browser compatibility when using different units and keywords.
Additional Tips
- Use a consistent font size scale for better readability and hierarchy.
- Consider using CSS preprocessors (like Sass or Less) for easier management of font sizes.
- Test your designs on different devices and screen sizes to ensure optimal display.
By understanding these concepts and experimenting with different values, you can effectively control the font size in your CSS and create visually appealing designs.