facebook twitter
Webucator's Free Introduction to CSS Tutorial

Lesson: CSS Fonts

Welcome to our free Introduction to CSS tutorial. This tutorial is based on Webucator's Introduction to CSS Training course.

In this lesson, you will learn about CSS fonts.

Lesson Goals

  • Work with the font-family property.
  • Use @font-face.
  • Work with the font-size property.
  • Work with the font-style property.
  • Work with the font-variant property.
  • Work with the font-weight property.
  • Work with the line-height property.
  • Understand shorthand properties.
  • Work with the font property.

font-family

The font-family property is used in CSS to specify the font applied to an element. You can specify by font name or font category.

Specifying by Font Name

When you specify a font by font name, the browser will look for the named font on the end user's computer. If it finds it, the font will be displayed accordingly. For example, the following rule would make the font of all <p> tags Arial:

p {
  font-family: Arial;
}

If the Arial font were not found on the end user's computer, the browser would display a default font. If you are concerned that the font name you want to use might not be found on a user's computer, you can provide a list of options.

p {
  font-family: Arial, Helvetica;
}

In this case, the browser will first look for Arial. If it doesn't find Arial, it will then look for Helvetica.

Specifying Font by Category

When you specify a font by category, the browser will use the font the user's computer specifies for that category. For example, for monospace, the computer might specify Courier. The font family categories are listed below:

  • cursive
  • fantasy
  • monospace
  • sans-serif
  • serif

To be extra safe, designers often specify a couple specific options followed by a font family category, like so:

p {
  font-family: Arial, Helvetica, sans-serif;
}

This way, if neither Arial nor Helvetica is found, the browser at least knows to use some sans-serif font.

The following code samples illustrate how font-family works:

Code Sample:

Fonts/Demos/font-family-styles.css
#cursive-div {
  font-family: 'Cool Linked Font', cursive;
}

#fantasy-div {
  font-family: 'Cool Linked Font', fantasy;
}

#monospace-div {
  font-family: 'Courier New', monospace;
}

#sans-serif-div {
  font-family: Tahoma, Verdana, Arial, sans-serif;
}

#serif-div {
  font-family: Times, 'Times New Roman', Georgia, serif;
}

Code Explanation

Notice that #cursive-div and #fantasy-div both have a 'Cool Linked Font' listed before their generic family names. Cursive and fantasy fonts are not as popular or as widely supported as the other three, so it is common to download your own fonts for these two font families.

Also notice that fonts that have multi-word names (e.g., Times New Roman) should be contained in either single or double quotes.

Code Sample:

Fonts/Demos/font-family.html
---- C O D E   O M I T T E D ----
<body class="webucator">
  <div id="cursive-div">
    <h3>Cursive</h3>
    <p>This paragraph is in a cursive font.</p>
  </div>
  <div id="fantasy-div">
    <h3>Fantasy</h3>
    <p>This paragraph is in a fantasy font.</p>
  </div>
  <div id="monospace-div">
    <h3>Monospace</h3>
    <p>This paragraph is in a monospace font.</p>
  </div>
  <div id="sans-serif-div">
    <h3>Sans-serif</h3>
    <p>This paragraph is in a sans-serif font.</p>
  </div>
  <div id="serif-div">
    <h3>Serif</h3>
    <p>This paragraph is in a serif font.</p>
  </div>
</body>
</html>

Code Explanation

The code above will render as follows:font-family Demo

The web-safe fonts are those fonts that are most commonly installed on computers and are therefore safe to use in your CSS. You can read the full list of web-safe fonts on lifewire.com.

@font-face

The CSS @font-face rule enables the loading of a font file, and thus offers us the ability to use any font, not just those our users happen to have loaded on their computer or device. The @font-face rule is defined in the W3C's CSS Fonts Module Level 3 specification. As the W3C specification states:

The @font-face rule allows for linking to fonts that are automatically fetched and activated when needed. This allows authors to select a font that closely matches the design goals for a given page rather than limiting the font choice to a set of fonts available on a given platform. A set of font descriptors define the location of a font resource, either locally or externally, along with the style characteristics of an individual face. Multiple @font-face rules can be used to construct font families with a variety of faces. Using CSS font matching rules, a user agent can selectively download only those faces that are needed for a given piece of text.

In our CSS, we define our own font-family and associate it with a font file:

@font-face {
    font-family: Gentium;
    src: url('Gentium.ttf');
}

A subsequent CSS rule might style a given element with our newly defined font-family:

div.newsitem {
    font-family: Gentium;
}

Browsers will download the specified font file and will use it to render the designated content with it.

Different browsers support different font file formats. To address these differences, the specification for the @font-face rule allows for a series of font files, with format hints to aid browsers in selecting the appropriate file for the font:

@font-face {
    font-family: bodytext;
    src: url(ideal-sans-serif.woff) format("woff"),
      url(basic-sans-serif.ttf) format("opentype");
}

Here's a list of the formats supported by the W3C specification:

@font-face Font Formats
Format String Extensions Browser Support
Embedded OpenType embedded-opentype .eot Only supported in Internet Explorer.
OpenType opentype .ttf, .otf Well supported, but in Internet Explorer it only works with fonts set to installable.
SVG Font svg .svg, .svgz Not well supported.
TrueType truetype .ttf Well supported, but in Internet Explorer it only works with fonts set to installable.
WOFF (Web Open Font Format) woff .woff Well supported.
WOFF 2.0 woff2 .woff2 Supported well in most recent browsers, but not supported in Internet Explorer or older browsers.

In addition to specifying the font-family name and one or more font files for our @font-face rule, we can also specify:

  • font-style, with values normal (default), italic, or oblique.
  • font-weight, with values normal (default), bold, 100, 200, 300, 400, 500, 600, 700, 800, or 900.
  • font-stretch, with values normal (default), ultra-condensed, extra-condensed, condensed, semi-condensed, semi-expanded, expanded, extra-expanded, or ultra-expanded.

Getting Fonts

Let's look at a typical example, in which you will download the font "Great Vibes" from Font Squirrel, a popular resource for free fonts, and then convert it into several different file font formats:

  1. Search https://www.fontsquirrel.com for "Great Vibes".Hottest FontsClick on the DOWNLOAD OTF button to download the zip file containing the font.
  2. Unzip the file. You will see a GreatVibes-Regular.otf file.
  3. To convert the GreatVibes-Regular.otf to other file types, use the Font Squirrel Webfont Generator.
  4. Upload the OpenType file you just downloaded and choose four font formats to convert it to. (Note that we are in the "Expert" option. The other options do not allow for the specific selection of font formats). Font Squirrel Generator
  5. At the bottom of the generator, check the agreement box and click the DOWNLOAD YOUR KIT button: Font Kit Download
  6. Our customized font kit shows all of the new font formats we got (.eot, .ttf, .woff, .woff2) as well as a demo HTML file and a stylesheet (Don't worry about the generator_config.txt file or the specimen_files folder). The demo illustrates the use of "Great Vibes" in different sizes, shows a sample page that uses only the "Great Vibes" font, and provides charts showing special characters and glyphs. The stylesheet has a single @font-face rule that defines the font name, associates it with multiple font files, and defines the font's weight and style. Font Squirrel Stylesheet You can link right to this stylesheet from your HTML using a <link> tag just like any other external stylesheet.

Internet Explorer Bug

In the generated stylesheet, notice the ?#iefix appended to the .eot file on line 8. This tricks versions of Internet Explorer to get around a known bug for not loading multiple versions of the font file.

We made a few edits to the generated stylesheet and attached it to a simple HTML page as you can see in the samples below:

Code Sample:

Fonts/Demos/font-face-styles.css
@font-face {
  font-family: 'GreatVibes';
  src: url('fonts/greatvibes-regular-webfont.eot');
  src: url('fonts/greatvibes-regular-webfont.eot?#iefix') 
        format('embedded-opentype'),
       url('fonts/greatvibes-regular-webfont.woff2')
        format('woff2'),
       url('fonts/greatvibes-regular-webfont.woff') 
        format('woff'),
       url('fonts/greatvibes-regular-webfont.ttf') 
        format('truetype');
  font-weight: normal;
  font-style: normal;
}

p {
  font-family: GreatVibes;
}

Code Explanation

We changed the font name from what the generated stylesheet suggested, and we adjusted the paths for the urls. In the Fonts/Demos folder, we moved all of our "Great Vibes" font files into a folder called fonts, and we deleted the unnecessary generated files (e.g., the demo file, the original stylesheet, etc.).

Code Sample:

Fonts/Demos/font-face.html
---- C O D E   O M I T T E D ----
<body class="webucator">
  <h1><code>@font-face</code></h1>
  <p>When in the Course of human events, it becomes necessary
    for one people to dissolve the political bands which have
    connected them with another, and to assume among the powers
    of the earth, the separate and equal station to which the
    Laws of Nature and of Nature's God entitle them,  a decent
    respect to the opinions of mankind requires that they should
    declare the causes which impel them to the separation.</p>
</body>
</html>

Code Explanation

We used the font "Great Vibes" to style the first paragraph of the U.S. Declaration of Independence:@font-face demo

font-size

font-size is an unexpectedly complicated CSS property. It is difficult to get a good understanding of the different font-size units, how they relate to each other, and how they change depending on the font family right away. Practice and experimentation are required to find out what works best for you.

Relative font-size Terms

In addition to all the units of measurement we discussed in the Crash Course lesson, font size can be defined using the following relative terms:

  • xx-large
  • x-large
  • large
  • medium
  • small
  • x-small
  • xx-small
  • smaller
  • larger

The terms xx-small to xx-large are absolute-size keywords relative to the user's default font size (medium). The terms smaller and larger are relative-size keywords, meaning that they change the font size of an element relative to its parent element's font size. The following examples illustrate these terms:

Code Sample:

Fonts/Demos/font-size-styles.css
.biggest {
  font-size: xx-large;
}

.second-biggest {
  font-size: x-large;
}

.third-biggest {
  font-size: large;
}

.medium {
  font-size: medium;
}

.third-smallest {
  font-size: small;
}

.second-smallest {
  font-size: x-small;
}

.smallest {
  font-size: xx-small;
}

.larger {
  font-size: larger;
}

.smaller {
  font-size: smaller;
}

Code Sample:

Fonts/Demos/font-size.html
---- C O D E   O M I T T E D ----
<body class="webucator">
  <p class="biggest">This text is xx-large.</p>
  <p class="second-biggest">This text is x-large.</p>
  <p class="third-biggest">This text is large.</p>
  <p class="medium">This text is medium.</p>
  <p class="third-smallest">This text is small.</p>
  <p class="second-smallest">This text is x-small.</p>
  <p class="smallest">This text is xx-small.</p>
  <div id="compare-div" class="medium">
    <p>This text starts medium, and then gets 
      <span class="larger">larger and
        <span class="larger">larger and
          <span class="larger">larger and
            <span class="larger">even larger.
            </span>
          </span>
        </span>
      </span>
    </p>
    <p>This text starts medium, and then gets 
      <span class="smaller">smaller and
        <span class="smaller">smaller and
          <span class="smaller">smaller and
            <span class="smaller">even smaller.
            </span>
          </span>
        </span>
      </span>
    </p>
  </div>
</body>
</html>

Code Explanation

The code above will output the following:font-size Demo

Visualizing Ems and Rems

For a visual representation of fonts using ems and rems, see CrashCourse/Demos/units-of-measurement.html.

Best Practices

Most experts agree that font size should be defined in relative units (e.g., em, rem, or %) or in terms (e.g., large, small, etc.). This is because absolute font sizes can make pages inaccessible to people who have difficulty seeing. In most browsers, a user can change both the "zoom" of the page and, separately, the default font size. While "zooming" will increase the size of all elements (font included) on the page, changing the default browser font size won't have any affect on fonts whose size in CSS is specified using absolute, rather than relative, units.

font-style

Currently, the only use for font-style is to make text italic. The values are listed below:

  • normal
  • italic
  • oblique

However, italic and oblique are displayed in the same way. Since italic has better support, you should use it. For more on font-style see https://developer.mozilla.org/en-US/docs/Web/CSS/font-style.

font-variant

The most common and well-supported use of font-variant is to turn lowercase letters into small caps. The values are listed below:

  • normal
  • small-caps

The screenshot below shows an h1 tag with small-caps: font-variant Demo

font-variant is actually a shorthand property (more on shorthand properties soon) for several longhand properties, but those are rarely used and poorly supported, so you shouldn't worry about them. For more details, see https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant.

font-weight

The weight of a font determines how thick (or bold) it is. Possible values are:

  • Any number between 1 and 1000
  • bold
  • bolder
  • lighter
  • normal

The numeric values are used for fonts that can have many different degrees of boldness. Most fonts, however, are either bold or normal (not bold). bold is the same as 700 and normal is the same as 400. bolder and lighter work similarly to larger and smaller for font-size.

font-weight Values

In early versions of font-weight, only intervals of 100 (100 to 900) were accepted, so if you use a more exact number value, make sure both the font you're using and your target browsers support that value. For more on font-weight see https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight.

Code Sample:

Fonts/Demos/font-weight.html
---- C O D E   O M I T T E D ----
<body class="webucator">
  <div id="div1">
    <p>This is a normal paragraph.</p>
  </div>
  <div id="div2">
    <p>This is a bold paragraph.</p>
  </div>
  <div id="div3">
    <p>This is normal, and 
      <span class="bolder">this is bolder, and 
        <span class="bolder">this is even bolder.
        </span>
      </span>
    </p>
  </div>
  <div id="div4">
    <p>This is very bold, and 
      <span class="lighter">this is lighter, and 
        <span class="lighter">this is even lighter.
        </span>
      </span>
    </p>
  </div>
  <ol>
    <li id="li1">100 weight</li>
    <li id="li2">400 weight</li>
    <li id="li3">600 weight</li>
    <li id="li4">700 weight</li>
    <li id="li5">900 weight</li>
  </ol>
</body>
</html>

Code Explanation

The code above will render the following:font-weight Demo

To do this demo, we used the Segoe UI font because it has precise control over its weight. If we were to use a font that didn't have this control, like Times, then it would only render either bold or normal for all the values we had.

line-height

line-height determines the amount of vertical space used for lines, most commonly in text.

Although there are several options for line-height values, the best option is to use a unit-less number. This number is relative to the font-size of the text. For example, if you set line-height to 1, there will be no space between the text on a line and the text on lines before and after that line.

The default line-height value is approximately 1.2. You can set that specifically using:

line-height: 1.2;

Or you can set it using:

line-height: normal;

The latter will set the line-height to the exact default value, which is dependent on the browser and the font.

To add more space between lines, set line-height to a value higher than 1.2 and to make lines tighter, set it to a value less than 1.2.

Other Values of line-height

While line-height can also take a length with units (e.g., em or px), we recommend you stick with a unit-less number.

The following samples shows some different line heights:

Code Sample:

Fonts/Demos/line-height-styles.css
html {
  font-size: 16px;
}

#normal {
  line-height: normal;
}

#p1 {
  line-height: 1;
}

#p2 {
  line-height: 1.1;
}

#p3 {
  line-height: 1.2;
}

#p4 {
  line-height: 1.3;
}

#p5 {
  line-height: 1.5;
}

#p6 {
  line-height: 2;
}

Code Sample:

Fonts/Demos/line-height.html
---- C O D E   O M I T T E D ----
<body class="webucator">
  <p id="normal">
    line-height: normal; line-height: normal; line-height: normal;
    line-height: normal; line-height: normal; line-height: normal; 
    line-height: normal; line-height: normal; line-height: normal;
  </p>
  <p id="p1">
    line-height: 1; line-height: 1; line-height: 1; line-height: 1;
    line-height: 1; line-height: 1; line-height: 1; line-height: 1;
    line-height: 1; line-height: 1; line-height: 1; line-height: 1;
  </p>
  <p id="p2">
    line-height: 1.1; line-height: 1.1; line-height: 1.1; 
    line-height: 1.1; line-height: 1.1; line-height: 1.1;
    line-height: 1.1; line-height: 1.1; line-height: 1.1;
  </p>
  <p id="p3">
    line-height: 1.2; line-height: 1.2; line-height: 1.2;
    line-height: 1.2; line-height: 1.2; line-height: 1.2;
    line-height: 1.2; line-height: 1.2; line-height: 1.2;
  </p>
  <p id="p4">
    line-height: 1.3; line-height: 1.3; line-height: 1.3;
    line-height: 1.3; line-height: 1.3; line-height: 1.3;
    line-height: 1.3; line-height: 1.3; line-height: 1.3;
  </p>
  <p id="p5">
    line-height: 1.5; line-height: 1.5; line-height: 1.5;
    line-height: 1.5; line-height: 1.5; line-height: 1.5;
    line-height: 1.5; line-height: 1.5; line-height: 1.5;
  </p>
  <p id="p6">
    line-height: 2; line-height: 2; line-height: 2; line-height: 2;
    line-height: 2; line-height: 2; line-height: 2; line-height: 2;
    line-height: 2; line-height: 2; line-height: 2; line-height: 2; 
  </p>
</body>
</html>

Code Explanation

The code above will render the following:line-height Demo

font

font is a shorthand property that encompasses the properties we have discussed in this lesson.

Shorthand Properties

Shorthand properties set multiple CSS properties at once, allowing for more concise, more readable stylesheets that save time and space. Using shorthand properties instead of longhand properties also has the benefit of reducing file size, which increases download speed.

An important thing to note about shorthand properties is that any unspecified values will be set to their default values.

The syntax for font is shown below. Note that the font-size and font-family properties are required:

Syntax

font: font-style
      font-variant
      font-weight
      font-size/line-height
      font-family;

Some notes:

  1. font-style, font-variant, and font-weight are optional and may be written in any order before font-size.
  2. line-height is also optional, but it must be written immediately after font-size separated by a forward slash (/).
  3. If one of the optional values is not included, it will be set to the default value, overriding any rules with lower precedence.

The code below illustrates the use of font:

Code Sample:

Fonts/Demos/font-styles.css
#div1 h1 {
  font: italic small-caps bold 2em Georgia, Times, 
  'Times New Roman', sans-serif;
}

#div1 p {
  font: 1em/1.2 Arial, Helvetica, sans-serif;
}

#div2 h1 {
  font-style: italic; /* gets overridden */ 
  font-variant: small-caps; /* gets overridden */
  font: 2.5em 'Gill Sans', serif;
}

#div2 p {
  font: 0.9em/1.5 cursive;
}

Code Explanation

Notice that the font-style and font-variant declarations written in the #div2 h1 rule were not applied because they were later overridden by defaults in the font declaration, even though those defaults were not explicitly stated.

Code Sample:

Fonts/Demos/font.html
---- C O D E   O M I T T E D ----
<body class="webucator">
  <div id="div1">
    <h1>Div 1</h1>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
      Maecenas euismod tellus lorem, vitae convallis nulla 
      facilisis vel. Nam blandit vulputate elit, ac accumsan 
      elit suscipit vel. Phasellus nec metus libero.
    </p>
  </div>
  <div id="div2">
    <h1>Div 2</h1>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
      Maecenas euismod tellus lorem, vitae convallis nulla 
      facilisis vel. Nam blandit vulputate elit, ac accumsan 
      elit suscipit vel. Phasellus nec metus libero.
    </p>
  </div>
</body>
</html>

Code Explanation

The code above will render the following:font Demo

Styling Fonts

Duration: 25 to 40 minutes.

In this exercise, you will modify an HTML page by applying the font properties you just learned.

  1. Open Fonts/Exercises/index.html in your editor. You will see the homepage for a website called Runners Home.
  2. Create an external stylesheet called styles.css and link to it from index.html.
  3. Using your new knowledge of font properties, add some styles to this page. The object of this exercise is to practice using the font properties covered in this lesson. You are also welcome to download a font and use @font-face.
  4. When you are done, open index.html in your browser to see the results. You are welcome to go back to the code and continue to work.

You can design it however you like, or you can try to make it look something like this:

Font Solution

Solution:

Fonts/Solutions/styles.css
html {
  font-size: 16px;
}

body {
  font: 1rem/1.3 Verdana, Geneva, Tahoma, sans-serif;
}

#welcome {
  font-size: larger;
}

article h2 {
  font-variant: small-caps;
}

article p {
  line-height: 2;
}

aside label {
  font-weight: bold;
}

footer {
  font-size: smaller;
  font-style: italic;
}