CSS - Fonts
Font Families
Generic Font Families
In CSS, there are five generic font families that can be used to specify the appearance of text on a web page:
-
Serif: Serif fonts have small lines or strokes at the ends of the letters. They are often used for body text in print media and can give a formal look to the text. Examples of serif fonts include Times New Roman, Georgia, and Garamond.
-
Sans-serif: Sans-serif fonts do not have lines at the ends of the letters. They have a clean look, making them popular for digital screens. Sans-serif fonts are often used for headings, menus, and body text on websites. Examples of sans-serif fonts include Arial, Helvetica, and Verdana.
-
Monospace: Monospace fonts have characters that are all of the same fixed width. Each character occupies the same amount of horizontal space, which makes them ideal for displaying code snippets or tabular data. Examples of monospace fonts include Courier, Courier New, and Lucida Console.
-
Cursive: Cursive fonts mimic handwritten text and have an informal appearance. They are often used for special headings or quotes but should be used sparingly as they can be harder to read in large amounts. Examples of cursive fonts include Brush Script, Lucida Handwriting, and Comic Sans.
-
Fantasy: Fantasy fonts are decorative and imaginative that do not fit into other categories. They can have unique shapes or designs but should be used carefully as they can be difficult to read in long passages. Examples include Impact, Papyrus, and Chiller.
Font Stacks
A font stack is a list of fonts specified in the CSS font-family
property. It allows you to define multiple fallback options if the primary font is not available on the user's device. To create a font stack, you list names separated by commas. The browser will try the first one, then move to the next until it finds an available one.
Font Stack Example
body {
font-family: Arial, Helvetica, sans-serif;
}
The browser will first try Arial. If unavailable, it falls back on Helvetica. If both are unavailable, it uses the generic sans-serif. When creating stacks, consider these practices:
- Start with the preferred option then add fallbacks.
- Use the generic family last so the text remains readable even if none of the specified ones are available.
- Pick similar types (e.g., serif, sans-serif) to keep a consistent look.
- Limit the number since each extra may slow page load time.
- Test stacks across devices and browsers to achieve the intended display.
Font Properties
Font Size
The font-size
property in CSS sets the size of the text. You can use various units to specify the font size, such as pixels (px), em, and rem.
- Pixels (px): Setting the font size in pixels gives you precise control over the text size. However, using pixels can make it difficult for users to resize the text in their browsers.
Pixels Example
font-size: 16px;
- Em (em): The em unit is relative to the font size of the parent element. If the parent element's font size is 16px, setting the child element's font size to
1.5em
would result in a font size of 24px (16px * 1.5). Using em allows for more flexible and scalable font sizes.
Em Example
font-size: 1.2em;
- Rem (rem): The rem unit is similar to em but it is relative to the root element's (html) font size instead of the parent element’s font size. This makes it easier to maintain consistent sizes throughout a document by defaulting at 16px so setting a value like
1.5rem
results into having an equivalent value like that seen with pixel-based values such as being equal up-to around about twenty-four-pixels(24 px).
Rem Example
font-size: 1.2rem;
When deciding between absolute and relative sizes consider:
- Absolute sizes give you precise control but may not be easily resizable by users.
- Relative sizes allow for more flexibility and responsiveness as they adapt based on either parent or root elements' respective sizing properties.
To create responsive fonts that adapt across different screen widths use CSS media queries adjusting accordingly based upon viewport width:
Responsive Fonts Example
body {
font-size: 16px;
}
@media screen and (min-width: 768px) {
body {
font-size: 18px;
}
}
@media screen and (min-width: 1200px) {
body {
font-size: 20px;
}
}
Font Weight
The font-weight
property sets how thick or thin characters appear using keyword/numeric values:
- Keywords:
normal(default)
,bold
,lighter
,bolder
- Numeric:
100
,200
,300
,400(normal)
,500
,600
,700(bold)
,800
,900
Not all weights are available for every family when using numeric values consider these best practices:
Use four hundred (400
)for normal texts while seven hundred(700
)for bolded texts ensuring consistent results across different fonts.
Avoid extreme weights like one hundred (100
)or nine hundred(900
)as they may not be legible smaller-sized contexts.
Stick to common weights (four-hundred/seven-hundred) for body texts while utilizing additional ones if needed within headings contextually speaking.
Font Weight Example
body {
font-weight: 400;
}
h1 {
font-weight: 700;
}
Font Style
The font-style
property sets styles normal/italic/oblique respectively italic slants cursive version oblique slants normally avoid large blocks reducing readability contextually speaking emphasizing words titles works technical terms phrases another language usage italicized forms better suited overall usage scenarios.
Font Style Example
p {
font-style: normal;
}
em {
font-style: italic;
}
Font Variant
The font-variant
property allows setting small-caps displaying lowercase letters smaller uppercase versions abbreviations acronyms making them stand out without uppercase adding visual interest headings subheadings contextually speaking.
Font Variant Example
h2 {
font-variant: small-caps;
}
abbr {
font-variant: small-caps;
}
Line Height
The line-height
property sets space between lines length units(px/em/rem/unitless-values recommended scaling proportionally starting point range one-point-two(one-point-six depending family sizing contexts).
Line Height Example
body {
line-height: 1.5;
}
h1 {
line-height: 1.2;
}
Web Fonts
What are Web Fonts?
Web fonts are custom fonts that can be loaded and used on a website. They allow designers to go beyond the limited set of system fonts available on users' devices. They enable more diverse typographic design, improving the visual appeal and branding of a website.
The main advantages of using web fonts include:
-
Increased design flexibility: Web fonts offer many styles and options, allowing designers to choose fonts that match their desired look and brand identity.
-
Consistency across devices: By using web fonts, designers can make sure that the typography remains consistent across different devices and platforms since the fonts are loaded from a remote server rather than relying on the user's system fonts.
-
Improved user experience: Web fonts can improve readability, making content more engaging for users to read.
How to Use Web Fonts
There are several ways to use web fonts on a website:
- Importing web fonts using
@font-face
: The@font-face
CSS rule lets you specify a custom font file to be downloaded and used on your website. You can host the font files on your own server or use a font service provider.
Example: Importing web fonts using @font-face
@font-face {
font-family: 'CustomFont';
src: url('path/to/font-file.woff2') format('woff2'),
url('path/to/font-file.woff') format('woff');
font-weight: normal;
font-style: normal;
}
-
Hosting web fonts locally: You can download the font files and host them on your own server, giving you full control over them but requiring more setup and maintenance.
-
Using web font services: Many providers like Google Fonts and Adobe Fonts offer many web fonts that can be easily integrated into your website without needing self-hosting.
Web Font Formats
There are several web font formats available, each with its own characteristics and browser support:
-
TTF (TrueType Font): TTF is an old format supported by most browsers but has larger file sizes compared to newer formats.
-
WOFF (Web Open Font Format): WOFF is designed for the web with compression features; it is widely supported by modern browsers.
-
WOFF2: WOFF2 offers better compression than WOFF, resulting in smaller file sizes and faster loading times; it has good browser support but may not work in older browsers.
-
EOT (Embedded OpenType): EOT was used by Internet Explorer; it has limited support in modern browsers so it's generally not recommended for new projects.
-
SVG Fonts: SVG fonts are vector-based and can be scaled without losing quality. However, they have limited browser support and are not widely used.
When using web fonts, it is good practice to provide multiple formats to maximize browser compatibility. You can use the @font-face
rule to specify different file formats, and the browser will choose the most suitable one it supports.
Font Icons
What are Font Icons?
Font icons are symbols that are part of a font. They can be used as icons on websites and styled with CSS, like regular text. Font icons are vector-based, so they can be scaled without losing quality and adapt to different screen sizes.
The main advantages of using font icons include:
-
Flexibility: You can easily style font icons using CSS properties such as color, size, and shadows to match the design of your website.
-
Performance: Font icons load faster compared to traditional image icons because they are part of a font file.
-
Scalability: Being vector-based, font icons remain sharp at any size without pixelation or loss of quality.
-
Accessibility: You can make font icons accessible to screen readers by using proper semantic markup and providing alternative text.
How to Use Font Icons
To use font icons on a website, you can either import an existing library or create your own custom ones:
- Importing libraries: There are many popular libraries available like Font Awesome, Material Icons, and Ionicons. These libraries offer pre-designed icons that you can easily include in your project by linking to the library's CSS file and using the provided class names.
Example: Importing Font Awesome
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<i class="fas fa-home"></i>
- Creating custom fonts: If existing libraries do not meet your needs, you can create custom fonts using tools like Icomoon or Fontello which allow you to select or upload SVGs and generate a custom font file along with necessary CSS code.
When using font icons:
- Choose a reliable library.
- Use semantic markup such as
<i>
or<span>
elements for displaying the icon. - Optimize the icon file by including only necessary glyphs.
- Provide fallback options for users who have disabled custom fonts.
- Use CSS for consistent sizing and alignment of the icon.
Font icons offer an efficient way to add scalable and stylish symbols to your website while maintaining good performance practices.