Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > CSS

Stylin' Fonts and Text in CSS

In this chapter, you’ll learn about fonts and text, and the respective CSS properties you can use to style them. You'll also learn about the wonderful world of Web fonts, which download to your user along with your pages.
This chapter is from the book

Much of Web design deals with text, in paragraphs, headings, lists, menus, and forms, so understanding the CSS properties in this chapter is essential to making a site that looks professional. Almost more than any other factor, type makes the clearest visual statement about the quality of your site’s offerings. Graphics are the icing on the cake; typography is where good design begins.

In this chapter, you’ll learn about fonts and text, and the respective CSS properties you can use to style them. I’ll also introduce you to the wonderful world of Web fonts, which download to your user along with your pages. Now you no longer have to rely on the user having your font choices installed on his device, and you can be confident that every user will see your typography in the way you intend.

Let’s start with fonts.

Fonts

The fonts you specify in your Web pages can come from three sources.

  • The fonts that are installed on the user’s device. (Until recently, these have been the only fonts reliably available to your Web pages.)
  • Fonts that are hosted on third-party sites, most notably Typekit and Google, and linked to your page using the link tag.
  • Fonts that are hosted on your Web server and served to the user’s browser along with the page, using the @font-face rule.

In the font property descriptions that follow, the examples will show the first of these sources: the fonts that are installed on the user’s computer. See Web Fonts Demystified later in this chapter for a discussion of the other two sources.

Now let’s look at the six properties that relate to font styling:

  • font-family
  • font-size
  • font-style
  • font-weight
  • font-variant
  • font (shorthand)

Font-Family Property

Example: h2 {font-family:times, serif;}

font-family determines the font in which an element is displayed. Typically, you set a primary font for the entire page, and then only add font-family styles to elements that you want to display in a different font. To specify the font for the entire page, you set the font-family of the body element:

font-family is an inherited property, so its value is passed to all its descendants, which in the case of body is all the other elements in the markup.

Because fonts must either be on the user’s computer, or delivered over the Web, there is always a possibility that a particular font you specify might not be available to a page. For this reason, fonts are always specified in lists called font stacks.

Specifying Installed Fonts Using Font Stacks

Fonts are installed in the operating system of a device, which allows all resident applications to share them. Only a limited set of fonts come installed in the typical operating system, and fonts can be added and removed by the user, so you can never be absolutely certain what fonts will be available to display your pages. Because of this, when stating the font in which you want text to display, you must also list additional “fallback” fonts in case your first choice isn’t available on the user’s system. This list of choices is called a font stack.

In short, font stacks ensure that the user sees your page text in the intended font if it is installed on her device, and if it is not, then in a font that you specify as an acceptable substitute.

This font stack effectively tells the browser “Display this document in Trebuchet MS, and if the system doesn’t have it, use Tahoma, and if neither is installed, use whatever generic sans-serif font is available.” It is very important to make the last item of a font-family declaration a generic declaration, typically “serif” or “sans-serif”, as a final fallback.

There are five generic font-family names:

Serif—serif fonts have small details at the terminals (tips) of the characters (like this text)

Sans-serif—sans-serif fonts have no details at the terminals (like the headings of this book)

Monospace—every monospace font character occupies the same amount of horizontal space (like the code examples in this book)

Cursive—cursive fonts look like handwriting (like the headline of The Hound of the Baskervilles example later in this chapter).

Fantasy—fonts that don’t fit the other categories (typically the strange and bizarre)

The purpose of these generic fonts is to ensure, that if none of your choices are available that, at a minimum, your document displays in the right type (no pun intended) of font.

It’s worth taking some care when selecting the fonts that you put in a font stack. For example, Dreamweaver offers a list of selectable font stacks that pop up every time you type font-family: in your CSS file, but these fonts are not ideal substitutes for one another. For example, here is a font stack that Dreamweaver offers:

Verdana is a bulky font that has a much larger x-height than Arial, so if a user does not have Verdana installed, your page will be displayed in Arial, a font that is smaller than the one you intended. More words will fit on each line, and the vertical height of text blocks may be shorter.

A good test is to view your pages with each font in the stack as the first choice so that you can see how the layout changes if it displays in one of the fallback fonts.

A better fallback for Verdana might be Tahoma, which has the same large x-height.

111pro02.jpg

For a stack of lighter sans-serif fonts, you might use

111pro03.jpg

Here’s a stack of serif fonts starting with a font that the user may not have.

In a case like this, always complete the stack with fonts that are supplied with most computer’s operating systems, here Georgia and Times, and end with the generic, serif.

Font-Size Property

Example: h2 {font-size:18px;}

Every HTML text element has a default font-size set by the browser style sheet, so when you set an element’s font-size, you are changing its font size from that default. Font sizing can appear to act unpredictably if you don’t understand how the inheritance of font sizes down the hierarchy is affected by which font size units you use. There are two types of units that you can use to set the font-size: absolute units, such as pixels or points, and relative units, such as percentages or ems. Let me explain the difference between them.

font-size is an inherited property, so a change to the font size of an element will result in a proportional change of size in the font sizes of its descendant elements. This means that if you set the font-size of the body element to 200%, then the text of all the elements on your page will double in size.

This effect occurs because in the browser style sheet, all element font sizes are set in the relative unit, em. For example, the h1 element is 2em, the h2 element is 1.5em, and p (paragraph) is 1em. By default, 1em is equivalent to 16 pixels—this is known as the font-size baseline. So by default, h1 is 32 pixels (16 × 2em = 32 pixels), h2 is 24 pixels, and p is 16 pixels.

If you set the body text to 20px, you are resetting the baseline, so now h1 would be 40px (20 pixels × 2em = 40 pixels), h2 would be 30 pixels, and p would be 20 pixels. However, font-size inheritance will not occur in descendant elements that have been sized with absolute units such as pixels—these elements will always display at their specified size.

Let’s learn more about font sizing by looking at each method of sizing fonts in turn.

Absolute Font Sizing

Sizing text with absolute units such as pixels, picas, or inches is simple; when you set the size of an element using absolute units, it stays that size no matter what font sizing is applied to its ancestors. The downside of absolute sizing is that if you decide to proportionally change the overall size of the text on your page, you have to change every absolute font-size in the style sheet; an absolutely-sized page requires more effort to fine tune.

In short, if you change the size of the body tag’s font, any absolutely-sized elements do not change size, but elements that have not been sized in your CSS will change proportionally to the size stated on body.

Relative Font Sizing

Sizing text with relative units such as percentages, ems, or rems is slightly more complex; when you set the size of an element using relative units, the size of the text is set relative to the size of the nearest “sized” ancestor.

Let’s consider this simple markup

and this CSS

114pro01.jpg

In this example, the p tag text would be 12 pixels (the body tag’s 16 pixel baseline × .75 = 12). Because strong is a child of p, its point size would be 9 points. What you see is that relative sizes compound down through the hierarchy—strong is 16 pixels × .75 × .75 = 9 pixels. Relative units can take practice to master, as unlike absolute sizes, changing the relative font size of an element also changes all the child elements by the same proportion.

However, with relative sizing, you have the ability to tweak the size of all elements proportionally by resizing body, or a number of elements by changing a shared ancestor element. This can be time saving as you experiment with your layout, but it also takes planning for the same reason; a change to an element’s font-size affects all its descendant elements, too.

You cannot tweak font sizes like this if you work in absolute font-size units—each absolutely-sized element must be resized individually. Of course, if you do size in absolute units, you can size an element without getting the often-unwanted “knock-on” effect of a change of size in its ancestors.

However, with today’s wide range of screen sizes, from massive monitors to tiny phones, the need for text that can be easily scaled makes relative sizing the preferred approach.

A Note on Rem Units

The new relative rem (root em) unit is a CSS3 addition that is generating a lot of excitement in the Web community. When you size an element in rems, the size is relative, but only to the root HTML element. This gives you the best of both relative and absolute worlds; you can use relative sizing to proportionally change the overall font size by changing the font size of the HTML element, but unlike ems, font sizes are not compounded down through the hierarchy. Rems are supported by all the current browsers, but not by IE8 and earlier. The fallback is simple, however, and that is to provide absolute pixel sizing to browsers that don’t understand, and therefore ignore, rem declarations, like this

Let’s now look at the other font-related CSS properties.

Font-Style Property

Values: italic, oblique, normal

Example: h2 {font-style:italic;}

font-style determines whether a font is italicized or not. You can also write oblique instead of italic—the result is the same.

There are only two useful settings for the font-style property: italic to make regular text italicized, and normal to make a section within italicized type regular “upright” text. In this example

the code produces the result in Figure 4.1.

Figure 4.1

Figure 4.1. The normal value for the font-style property causes a specified section of text to appear normal within a bit of italicized text.

Note that the main purpose of italic text is to indicate emphasis, as in “It’s very hot today!” If you want to indicate emphasis, use the em tag, which styles the text as italic by default.

Font-Weight Property

Possible values: 100, 200, and so on to 900, or lighter, normal, bold, and bolder.

Example: a {font-weight:bold;}

Despite all the numerical options listed here, browsers only display two visual results for all font-weight values—bold or normal. Because interpretation of the numerical values differs among browsers, you’ll see the switch from normal to bold at various values—typically around 400. It’s best to avoid using all values except bold and normal, as illustrated in Figure 4.2.

Figure 4.2

Figure 4.2. The normal value for the font-weight property causes a specified section of text to appear normal within the bolded text.

Note that the primary purpose of bold text is to indicate importance, as in “Danger!” Mark up important text with the strong tag, which styles the text as bold by default.

Font-Variant Property

Values: small-caps, normal

Example: blockquote {font-variant:small-caps;}

This property accepts just one value (besides normal), and that is small-caps. This causes all lowercase letters to be set in small caps, like this:

116pro02.jpg

The code above produces the result in Figure 4.3.

Figure 4.3

Figure 4.3. Here is a heading styled in small caps. Note the first letter of this text is in uppercase in the markup and remains unchanged.

I often use small-caps with the ::first-line pseudo-element as I demonstrate in The Hound of the Baskervilles example at the end of this chapter. Use this styling sparingly because text in all uppercase is harder to read as it lacks the visual cues provided by the ascenders and descenders of lowercase type.

Font Property

Example: p {font: bold italic small-caps .9em helvetica, arial, sans-serif;}

The code above produces the result in Figure 4.4.

Figure 4.4

Figure 4.4. Bolded, italicized, small-capped, sized, and font-family specified—all in a single CSS rule.

The font property is a shorthand styling that lets you apply all of the font properties in a single declaration, reducing the amount of CSS you have to write. You must follow two rules, however, so that the browser can interpret the properties correctly.

Rule 1: Values for font-size and font-family must always be declared.

Rule 2: The sequence for the values is as follows:

  1. font-weight, font-style, font-variant, in any order, then
  2. font-size, then
  3. font-family

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020