Styling Text, Colours and Fonts
Most of what people read on a page is text, so knowing how to control its size, colour and typeface is one of the most useful CSS skills. This lesson covers the core text properties, how colours are written, and how to choose fonts.
Font family and web-safe fonts
The font-family property lists typefaces in order of preference. The browser uses the first one it has, so always end with a generic family such as sans-serif or serif as a fallback.
body {
font-family: Arial, Helvetica, sans-serif;
}
Size, weight and style
font-size sets the text size. Pixels (px) are fixed, while em and rem scale with a reference size; rem is relative to the root element, which makes it predictable. font-weight controls boldness (normal, bold, or numbers like 700), and font-style can be italic.
h1 {
font-size: 2rem;
font-weight: 700;
}
em {
font-style: italic;
}
Colours
You can write colours several ways. Named colours like red are simplest. Hex codes such as #3366ff give six digits for red, green and blue. The rgb() function takes three numbers from 0 to 255, and rgba() adds an alpha value from 0 to 1 for transparency.
p {
color: #333333;
background-color: rgba(0, 128, 255, 0.1);
}
Spacing and alignment
Use line-height to set the space between lines; a value around 1.5 is comfortable for reading. text-align can be left, right, center or justify. letter-spacing and text-transform (for example uppercase) give extra polish. text-decoration controls underlines, which is often set to none on links.
a {
text-decoration: none;
color: #0066cc;
}
.title {
text-align: center;
text-transform: uppercase;
letter-spacing: 2px;
}
Web fonts
To use a font a visitor may not have installed, link a web font such as Google Fonts in the head, then name it in font-family. This lets every visitor see the same typeface.
rem for font sizes and a line-height near 1.5. Text that scales predictably and has generous spacing is far easier to read on any screen.