CSS - Fonts Reference
Font Family
The font-family
property in CSS sets the font or list of fonts to be used for displaying text in an element. It lets you define the typeface for your web page, making it an important part of typography in web design.
When setting the font-family
, you can use specific font names (e.g., "Arial", "Times New Roman") or generic font families (e.g., serif, sans-serif, monospace). Generic font families provide a backup option if the specified font is not available on the user's device.
Here are some commonly used generic font families:
Generic Font Family | Description | Examples |
---|---|---|
serif |
Fonts with small decorative lines at the ends of characters, giving them a traditional and elegant look. | Times New Roman, Georgia |
sans-serif |
Fonts without the decorative lines, offering a clean and modern appearance. | Arial, Helvetica |
monospace |
Fonts where all characters have the same fixed width, often used for code snippets or technical content. | Courier, Consolas |
To make sure your web page looks consistent across different devices, it's a good idea to use web safe fonts. These are fonts that are widely available on most operating systems. Some popular web safe fonts include Arial, Verdana, Times New Roman, and Courier New.
If you want to use a custom font that is not widely available, you can use web fonts. Web fonts are loaded from a remote server and embedded into your web page using the @font-face
rule. This allows you to use any font you want, as long as you have the necessary font files and license to use them.
When specifying the font-family
, you can provide a comma-separated list of font names, known as a font stack. The browser will try to use the first font in the list and will fall back to the next font if the first one is not available. It's a good practice to include a generic font family at the end of the font stack as a final fallback.
Example: Using the font-family
Property with a Font Stack
body {
font-family: "Arial", sans-serif;
}
In the example, the browser will try to use Arial first. If Arial is not available, it will fall back to the generic sans-serif font family.
Font Size
The font-size
property in CSS sets the size of the font used for an element's text content. It controls the visual hierarchy and readability of your web page.
You can set the font-size
using absolute and relative units. Absolute units, such as pixels (px
), set a fixed size for the font. For example, setting font-size: 16px;
will display the text at 16 pixels, regardless of the parent element's font size.
Relative units, such as em
and rem
, let you define the font size in relation to other elements. The em
unit is relative to the font size of the parent element, while the rem
unit is relative to the root element's font size (usually the <html>
element). Using relative units makes it easier to create responsive designs that adapt to different screen sizes.
Example: Using relative units for font sizes
html {
font-size: 16px;
}
h1 {
font-size: 2rem; /* 32px (2 * 16px) */
}
p {
font-size: 1.2em; /* 1.2 times the parent's font size */
}
To create responsive font sizes, you can use CSS media queries to adjust the font size based on the screen size. This optimizes the readability of your content across different devices.
Example: CSS media queries for responsive font sizes
html {
font-size: 14px;
}
@media (min-width: 768px) {
html {
font-size: 16px;
}
}
@media (min-width: 1200px) {
html {
font-size: 18px;
}
}
To control the range of font sizes, you can use the min-font-size
and max-font-size
properties. These properties set the minimum and maximum bounds for the font size, preventing it from becoming too small or too large.
Example: Using min-font-size and max-font-size properties
p {
font-size: 1.2em;
min-font-size: 12px;
max-font-size: 24px;
}
In this case, the font size of the paragraph will be 1.2 times the parent's font size, but it will never go below 12 pixels or above 24 pixels.
Font Weight
The font-weight
property in CSS sets the weight or boldness of the font used for an element's text content. It helps create visual contrast and emphasize important information within your web page.
Font weights can be specified using numeric values or keywords. The numeric values range from 100 to 900 in increments of 100, with 400 being the default (normal) weight and 700 being bold. Some common keyword values include normal
, bold
, lighter
, and bolder
.
Example: Numeric and Keyword Font Weights
p {
font-weight: 400; /* Normal weight */
}
h1 {
font-weight: bold; /* Bold weight */
}
h2 {
font-weight: 600; /* Semi-bold weight */
}
By default, font weights are inherited from parent elements. This means that if you set a font weight on a parent element, its child elements will inherit the same font weight unless explicitly overridden.
Example: Inherited and Overridden Font Weights
div {
font-weight: bold;
}
div p {
/* Inherits the bold font weight from the parent div */
}
div p.normal {
font-weight: normal; /* Overrides the inherited font weight */
}
You can combine font weights with font styles, such as italic or oblique, to create different variations of the font. When using the font-style
property along with font-weight
, make sure to specify both properties separately.
Example: Combining Font Weights with Font Styles
p {
font-weight: bold;
font-style: italic;
}
h1 {
font-weight: 600;
font-style: oblique;
}
It's important to note that not all fonts support the full range of font weights. Some fonts may only have a few weight variations available, such as normal and bold. When using a custom font, check the font files or documentation to see which font weights are supported.
When choosing font weights for your web page, consider the readability and visual hierarchy of your content. Use bold or higher font weights sparingly to highlight important information and create contrast. Overusing bold text can make your content look cluttered and reduce its impact.
Font Style
The font-style
property in CSS sets the style of the font used for an element's text content. It lets you set whether the text should be normal, italic, or oblique. Using different font styles helps create visual emphasis and difference within your web page.
The three main font style values are:
-
normal
: This is the default font style. It shows the text in a standard, upright way. -
italic
: This value sets the text in an italic style, which is usually a cursive or slanted version of the font. Italic text is often used for emphasis, quotes, or to show titles of works. -
oblique
: This value sets the text in an oblique style, which is similar to italic but with a slanted look. Oblique text is less common than italic and is often used as a fallback when an italic version of the font is not available.
Example: CSS for font styles
p {
font-style: normal;
}
em {
font-style: italic;
}
.oblique-text {
font-style: oblique;
}
Just like other font properties, font styles are inherited from parent elements by default. This means that if you set a font style on a parent element, its child elements will inherit the same style unless explicitly overridden.
Example: Inherited and overridden font styles
div {
font-style: italic;
}
div p {
/* Inherits the italic font style from the parent div */
}
div p.normal {
font-style: normal; /* Overrides the inherited font style */
}
It's important to note that not all fonts have separate italic or oblique versions. In such cases, the browser may try to create an italic or oblique style by slanting the normal version of the font. However, this created style may not always look as good as a true italic or oblique font.
When using font styles, think about the readability and overall design of your web page. Italic and oblique styles can be helpful for emphasizing specific words or phrases, but overusing them can make your text harder to read. Use font styles carefully and in line with your content's tone and purpose.
Font Variant
The font-variant
property in CSS lets you set whether the text should be displayed in a normal or small-caps variant. Small-caps is a typographic style where lowercase letters are shown as smaller versions of uppercase letters. Using small-caps can add visual interest and variety to your text.
The two main font variant values are:
Value | Description |
---|---|
normal |
This is the default font variant. It shows the text in the standard way, with lowercase letters appearing as lowercase and uppercase letters appearing as uppercase. |
small-caps |
This value sets the text in a small-caps variant. Lowercase letters are shown as smaller versions of uppercase letters, while uppercase letters remain in their original size. |
Example: Using Normal and Small-Caps Font Variants
p {
font-variant: normal;
}
h1 {
font-variant: small-caps;
}
In the example above, the paragraph text will be displayed in the normal font variant, while the heading text will be displayed in the small-caps variant.
Font variants, like other font properties, are inherited by default. This means that if you set a font variant on a parent element, its child elements will inherit the same variant unless explicitly overridden.
Example: Inherited Font Variants
div {
font-variant: small-caps;
}
div p {
/* Inherits the small-caps font variant from the parent div */
}
It's important to note that not all fonts have a small-caps variant. If a font does not have a small-caps variant, the browser will simulate the effect by scaling down the uppercase letters. However, this simulated effect may not always look as good as a true small-caps font.
When using font variants, consider the readability and design of your web page. Small-caps can be useful for adding visual interest to headings, subheadings, or short phrases. However, using small-caps for long blocks of text can make it harder to read, so use them sparingly and appropriately.
Font Stretch
The font-stretch
property in CSS lets you set the stretch or width of the font used for an element's text content. It lets you control whether the text should be displayed in a condensed, normal, or expanded style. Font stretching can be used to create visual variety and adjust the text density within your web page.
The font-stretch
property accepts keyword values that define the desired stretch of the font. Here are the main keyword values:
Keyword | Description |
---|---|
normal |
This is the default font stretch. It displays the text with the normal width of the font. |
ultra-condensed |
This value sets the text in an ultra-condensed style, making it much narrower than the normal width. |
extra-condensed |
This value sets the text in an extra-condensed style, making it narrower than the normal width, but not as narrow as ultra-condensed. |
condensed |
This value sets the text in a condensed style, making it slightly narrower than the normal width. |
semi-condensed |
This value sets the text in a semi-condensed style, making it slightly narrower than the normal width, but not as narrow as condensed. |
semi-expanded |
This value sets the text in a semi-expanded style, making it slightly wider than the normal width. |
expanded |
This value sets the text in an expanded style, making it wider than the normal width. |
extra-expanded |
This value sets the text in an extra-expanded style, making it much wider than the normal width. |
ultra-expanded |
This value sets the text in an ultra-expanded style, making it even wider than extra-expanded. |
Example
p {
font-stretch: normal;
}
h1 {
font-stretch: condensed;
}
.expanded-text {
font-stretch: expanded;
}
In the example above, the paragraph text will be displayed with the normal font stretch, the heading text will be displayed in a condensed style, and the elements with the class "expanded-text" will be displayed in an expanded style.
Like other font properties, font stretch is inherited by default. This means that if you set a font stretch on a parent element, its child elements will inherit the same stretch unless explicitly overridden.
Example
div {
font-stretch: condensed;
}
div p {
/* Inherits the condensed font stretch from the parent div */
}
It's important to note that not all fonts support the full range of font stretching. Some fonts may only have a few stretch variations available, such as normal and condensed. When using a custom font, check the font files or documentation to see which font stretches are supported.
When using font stretching, consider the readability and overall design of your web page. Condensed or expanded text can be useful for creating visual hierarchy, emphasizing specific words or phrases, or fitting more text into a limited space. However, overusing extreme font stretches can make your text harder to read, so use them thoughtfully and in moderation.
Line Height
The line-height
property in CSS sets the height of a line box, which is the distance between the baselines of two consecutive lines of text. It controls the vertical spacing between lines of text within an element. Setting a good line height can make your text more readable and visually appealing.
The line-height
property accepts length values (such as pixels or ems), percentages, or a unitless value. When using a length value, you set an absolute height for the line box. For example, line-height: 20px;
sets the line height to 20 pixels.
Percentage values are relative to the font size of the element. For instance, line-height: 150%;
sets the line height to 1.5 times the font size of the element. This means that if the font size is 16 pixels, the line height will be calculated as 24 pixels (16 * 150%).
A unitless value is a number without any units, such as line-height: 1.5;
. When using a unitless value, the line height is calculated by multiplying the specified number by the element's font size. For example, if the font size is 16 pixels and the line height is set to 1.5, the actual line height will be 24 pixels (16 * 1.5).
Examples of line-height usage
p {
font-size: 16px;
line-height: 24px; /* Absolute length value */
}
h1 {
font-size: 24px;
line-height: 150%; /* Percentage value */
}
.text {
font-size: 18px;
line-height: 1.5; /* Unitless value */
}
``>
The default value for line-height
is normal
, which is typically around 1.2 times the font size. This default value may vary slightly between browsers and font families. When using the normal
value, the browser calculates the line height based on the font's built-in line height information.
Like other font properties, line height is inherited by default. This means that if you set a line height on a parent element, its child elements will inherit the same line height unless explicitly overridden.
Example: Inheritance of line-height in CSS
div {
font-size: 18px;
line-height: 1.5;
}
div p {
/* Inherits the line height from the parent div */
}
``>
When setting the line height, it's important to find a balance between readability and vertical spacing. A line height that is too small can make the text feel cramped and difficult to read, while a line height that is too large can create too much vertical space and make the text appear disconnected.
A good rule of thumb is to set the line height to around 1.5 times the font size for body text. This provides enough vertical spacing without compromising readability. For headings or other specific elements, you can adjust the line height as needed to achieve the desired visual effect.
Font Shorthand
The font
shorthand property in CSS lets you set multiple font-related properties in a single declaration. This makes your code more concise and easier to read. The font
shorthand combines the following properties: font-style
, font-variant
, font-weight
, font-size
, line-height
, and font-family
.
When using the font
shorthand, you specify the values for these properties in a specific order. Here's the correct order:
Example: CSS font shorthand
font: font-style font-variant font-weight font-size/line-height font-family;
For example:
Example: Using font shorthand with multiple properties
h1 {
font: italic small-caps bold 24px/1.5 Arial, sans-serif;
}
In this case, the heading will have an italic style, small caps variant, bold weight, 24 pixels font size, 1.5 times line height, and Arial (with a fallback to sans-serif) as the font family.
It's important to note that when using the font
shorthand, the font-size
and font-family
values are required. If you omit either of these values, the declaration will be invalid and ignored by the browser.
You can also use the font
shorthand with only the required font-size
and font-family
values, like this:
Example: Required font-size and font-family values
p {
font: 16px Arial, sans-serif;
}
In this case, the browser will set the font-style
, font-variant
, and font-weight
to their default values (normal
), and the line-height
will be set to normal
as well.
When using the font
shorthand, you can provide fallback values for the font-family
property. This makes sure that if the first specified font is not available, the browser will try the next one in the list. To specify fallback fonts, separate them with commas in the font
shorthand.
Example: Providing fallback values for font-family
body {
font: 16px Arial, Helvetica, sans-serif;
}
Using the font
shorthand can help simplify your CSS code and make it more maintainable. However, if you need to set only one or two font-related properties, it's better to use the individual properties instead of the shorthand to avoid accidentally overriding other values.
Web Fonts
Web fonts let you use custom fonts on your web pages, giving you more control over the design and typography of your site. With web fonts, you're not limited to the standard set of fonts available on most devices. Instead, you can use the @font-face
CSS rule to load custom font files from a server and apply them to your text elements.
To use web fonts, you first need to have the font files in the right format. The most common font formats for web usage are:
Format | Description |
---|---|
WOFF (Web Open Font Format) | This is the recommended format for modern browsers. WOFF files are compressed, making them smaller in size and faster to load. |
WOFF2 | This is an updated version of WOFF that offers better compression and faster loading times. It's supported by most modern browsers. |
TTF (TrueType Font) | This is a widely supported font format that has been around for a long time. TTF files are larger than WOFF and WOFF2 files. |
EOT (Embedded OpenType) | This format was created by Microsoft for Internet Explorer. It's less commonly used now but can be included for older browser support. |
To load a web font, you use the @font-face
rule in your CSS.
Example: Define a custom font using @font-face
@font-face {
font-family: 'CustomFont';
src: url('path/to/font.woff2') format('woff2'),
url('path/to/font.woff') format('woff'),
url('path/to/font.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
In this code, we define a custom font family called "CustomFont" and specify the paths to the font files. The src
property lists the font file URLs along with their formats. The browser will try to load the fonts in the order specified, using the first one that it supports.
After defining the @font-face
rule, you can use the custom font family in your CSS styles:
Example: Use the custom font family in CSS
body {
font-family: 'CustomFont', Arial, sans-serif;
}
When using web fonts, it's important to think about font loading strategies and performance. Loading large font files can slow down your web page, especially on slower networks. Here are a few strategies to optimize font loading:
-
Use WOFF and WOFF2 formats: These formats are compressed and offer faster loading times compared to TTF and EOT.
-
Subset your fonts: If you only need a few characters from a font, you can create a subset of the font file that includes only the necessary characters. This reduces the file size and speeds up loading.
-
Use
font-display
property: This CSS property lets you control how a font is shown while it's loading. For example, you can usefont-display: swap
to show a fallback font until the custom font is loaded, avoiding a flash of unstyled text (FOUT). -
Preload important fonts: You can use the
<link rel="preload">
tag to preload critical font files, enabling them to load early in the page load process.
Remember to test your web pages with web fonts on different devices and network conditions to make sure they load quickly and provide a good user experience.
Font Matching
When you specify a font family in your CSS styles, browsers use a font matching process to pick the best available font for displaying the text. This involves looking for the specified font on the user's device and falling back to alternative fonts if the desired one is not found.
Here's how the font matching process typically works:
- The browser checks if the specified font family is available on the user's device. It looks for an exact match first.
- If an exact match is found, the browser uses that font to display the text.
- If an exact match is not found, the browser looks for a font with the same name but a different style (e.g., bold or italic) within the same font family.
- If no matching font is found within the specified font family, the browser moves on to the next font family in the fallback list (if provided).
- The browser repeats steps 1-4 for each font family in the fallback list until a match is found.
- If no match is found after exhausting the fallback list, the browser uses a default font based on the generic font family keywords (e.g., serif, sans-serif, monospace) specified in the CSS.
To provide a fallback mechanism, you can specify multiple font families in your CSS, separated by commas. This is known as a font stack.
Example: CSS Font Stack
body {
font-family: "Arial", "Helvetica", sans-serif;
}
In this case, the browser will first try to use Arial. If Arial is not available, it will fall back to Helvetica. If neither Arial nor Helvetica is found, the browser will use the default sans-serif font on the user's device.
When choosing fallback fonts, it's a good idea to pick fonts that have similar characteristics to your preferred font. This helps maintain a consistent look and feel for your text, even when the desired font is not available.
In some cases, even if a font is available on the user's device, the browser may perform font substitution. This can happen when the specified font doesn't support certain characters or languages. In such scenarios, the browser tries to find a font that can display the missing characters while preserving the visual style as much as possible.
To make sure your text is displayed correctly across different devices and platforms, you can use web fonts instead of relying solely on system fonts. With web fonts, you have control over the exact font files that are loaded and used on your web pages.
When working with font matching and fallbacks, keep the following in mind:
Consideration | Description |
---|---|
Testing | Test your font stacks on various devices and browsers to see how the text appears when different fonts are used. |
Generic Font Family | Include a generic font family keyword (like serif, sans-serif, or monospace) as the last option in your font stack to provide a broad fallback. |
Performance | Be mindful of the performance impact of using web fonts. Loading many or large font files can slow down your pages. |
Font Display | Consider using the font-display CSS property to control how fonts are shown while they are loading, to avoid flash of unstyled text (FOUT) or flash of invisible text (FOIT). |
Accessibility
When working with fonts in web design, consider accessibility to make your content readable and accessible to all users, including those with visual impairments or disabilities.
Legibility and readability are two factors that can impact the accessibility of your fonts. Legibility refers to how easy it is to tell apart individual characters within a font, while readability refers to how easy it is to read and understand the text as a whole. To improve legibility and readability, choose fonts with clear, distinct letterforms and enough spacing between characters.
Font size and contrast also play a big role in accessibility. Small font sizes can make text hard to read, especially for users with visual impairments. As a general guideline, use a minimum font size of 16 pixels for body text. This helps make your text legible across different devices and screen sizes.
Contrast refers to the difference in brightness between the text color and its background. Low contrast can make text hard to read, particularly for users with color vision deficiencies or low vision. To meet accessibility standards, aim for a contrast ratio of at least 4.5:1 for normal text and 3:1 for large text (18 point or larger, or 14 point and bold).
Here are some examples of good color contrast:
Text Color | Background Color |
---|---|
Black | White |
Dark Blue | Light Gray |
White | Dark Green |
You can use online contrast checkers to test the contrast ratio of your text and background colors and make sure they meet accessibility guidelines.
Another accessibility consideration is avoiding text in images. Screen readers cannot read the text within images, so the information is lost to those users.
Instead of using images with text, use real text elements in your HTML and style them with CSS. This makes your content accessible to all users and can be translated, resized, or adjusted as needed.
Example: Using real text in HTML
<h1>Company Name</h1>
h1 {
font-family: "Custom Font", Arial, sans-serif;
font-size: 36px;
color: #333;
}
By using real text instead of an image, the heading stays accessible and can be read by screen readers, translated to different languages, and scaled according to the user's preferences.
When designing with fonts, always keep accessibility in mind. Choose legible and readable fonts, use proper font sizes and contrast, and avoid using text in images.