Styling text and fonts with CSS
Styling text and fonts with CSS is a fundamental skill for web designers and developers. CSS (Cascading Style Sheets) allows us to control the appearance of our text and fonts, giving us the freedom to customise our websites according to our needs and preferences.
1. Change font colour and size
One of the most basic ways to style text is to change its colour and font size. To change the colour, you can use the "colour" property followed by a hexadecimal value or colour name. For example:
p {
color: #ff0000; /* rojo */
}
To change the font size, use the "font-size" property followed by a value in pixels, em or percentage. For example:
h1 {
font-size: 24px;
}
2. Bold and italic style
CSS allows us to add bold and italic styling to our text. To add a bold style, use the "font-weight" property and set the value to "bold". For example:
h2 {
font-weight: bold;
}
To add italic style, use the "font-style" property and assign the value "italic". For example:
p {
font-style: italic;
}
3. Text decoration
With CSS, we can also add decorations to the text, such as underlining, strikethrough or highlighting. To add underlining, use the "text-decoration" property and assign the value "underline". For example:
a {
text-decoration: underline;
}
To add strikethrough, use the value "line-through":
del {
text-decoration: line-through;
}
And for highlighting, use the value "highlight":
mark {
background-color: yellow;
}
4. Text alignment
CSS offers us the possibility of aligning our text, either aligning it to the left, right, centre or justifying it. To align the text to the left, use the "text-align" property and assign the value "left". For example:
p {
text-align: left;
}
To align it to the right, use the value "right", to centre it, use the value "centre" and to justify it, use the value "justify".
5. Specifying sources
In addition to styling the text itself, we can also control the fonts that are used. CSS allows us to specify a custom font or use external web fonts. To specify a custom font, use the "font-family" property and assign the font of your choice. For example:
body {
font-family: Arial, sans-serif;
}
To use external web sources, you can use services such as Google Fonts. Simply add the link provided in the head of your HTML and you can use the source in your CSS.
6. Use of em and rem units
CSS uses different units of measurement to specify font size. In addition to pixel units (px) and percentages (%), you can also use em and rem units.
The em unit sets the font size relative to the font size of the parent element. For example:
h1 {
font-size: 2em;
}
This will set the font size of the h1 to twice the font size of the parent element.
The rem unit sets the font size relative to the font size of the root (usually the HTML element). For example:
h1 {
font-size: 2rem;
}
This will set the h1 font size to twice the root font size.