Starting Good CSS Habits: Part 3

The series of posts on Starting Good CSS Habits begins here.

Now that we have work on improving our HTML in the previous articles, we are ready to start applying some CSS to the page. We will begin by discussing text and fonts.

As a refresher, below is the current state of our document.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<html>
  <head>
    <title>My Site</title>
  </head>
  <body>
    <table cellPadding="10" cellSpacing="0" border="0" bgcolor="#FFFFFF">
      <tr>
        <td height="100" colspan="2" bgcolor="#1166FF" valign="middle">
          <center>
            <font size="6" color="#FFFFFF" face="Helvetica">
              My Site
            </font>
          </center>
        </td>
      </tr>
      <tr>
        <td width="150" valign="top">
          <br /><br />
          <strong><font size="4">Menu</font></strong>
          <ul style="list-style-type: none; padding-left: 10px;">
            <li><a href="#">Homepage</a></li>
            <li><a href="#">Next Page</a></li>
            <li><a href="#">Last Page</a></li>
          </ul>
        </td>
        <td height="500" width="750" valign="top">
          <br />
          <h1>
            <font color="#1166FF" face="Helvetica">
              Homepage
            </font>
          </h1>
          <p><em>Lorem ipsum dolor sit amet,</em> consectetur adipiscing
          elit. Pellentesque ullamcorper est id tortor. Praesent
          fermentum vehicula tellus. Duis sem sem, hendrerit eu, porta
          at, dapibus quis, urna. Aenean non dui eu purus elementum
          blandit. Duis eu urna. Cum sociis natoque penatibus et
          magnis dis parturient montes, nascetur ridiculus mus.
          Vivamus sit amet quam non erat vehicula condimentum. In eu
          lacus et sapien vulputate lobortis. Aenean elit. Etiam
          tristique elit sed turpis. Sed pharetra. Aenean ornare
          laoreet urna. Integer tincidunt. Nunc condimentum ultricies
          sem. Aenean imperdiet, elit sollicitudin blandit convallis,
          orci ligula porta diam, et ultrices elit leo at ipsum.</p>
         
          <p>Praesent accumsan sodales orci. Ut sit amet diam. Mauris
          nec augue sed lectus aliquet cursus. Nulla quam. Quisque non
          risus. Morbi rutrum odio vitae nulla. Integer mi. In
          ullamcorper fringilla eros. Cras tristique luctus tellus.
          Vivamus rhoncus. Nulla varius pretium magna. Mauris aliquam,
          turpis nec condimentum lacinia, tellus leo eleifend ante, at
          aliquet nisi ipsum nec dui. Curabitur erat sapien, iaculis
          fermentum, suscipit non, pulvinar non, nisl. Fusce mi. Sed
          tincidunt nisi. Curabitur sit amet tortor ac urna congue
          lacinia. In auctor tincidunt augue. In hac habitasse platea
          dictumst.</p>

          <p>In magna. Praesent euismod ligula ac mi. Morbi
          condimentum, enim sit amet consequat blandit, mi nibh
          tincidunt turpis, eu pulvinar sem nulla quis lorem. In id
          eros. Aliquam quis orci. Praesent nec lacus. Phasellus
          dictum orci et urna. Pellentesque ac diam. Vivamus
          tincidunt. Fusce condimentum risus eu turpis volutpat
          viverra. Nulla facilisi. Donec varius neque a eros.
          Curabitur semper feugiat leo. Curabitur tellus tellus,
          convallis laoreet, malesuada nec, accumsan ac, felis. In at
          lorem.</p>
        </td>
      </tr>
      <tr>
        <td height="50" colspan="2" valign="top" align="center">
          <hr />
          &copy; 2009 My Site, Inc.
        </td>
      </tr>
    </table>
  </body>
</html>

Font Tags to Span Tags

Font tags were deprecated as of HTML 4.0 and XHTML 1.0. In programming, “deprecated” typically means “stop using it now because it will go away soon and maybe even suddenly”. It means that no browser has to support it and, if they support it, it may be buggy. You will want to avoid using anything that is deprecated—it is yesterday’s news.

Instead we can use CSS and have better code now and for the future. First, let’s replace every font tag with a span tag. A span tag is an inline element, just like the font tag, but it is more versatile. Instead of saying to the browser, “Hey browser, apply this font information to everything in these tags,” span tags say, “Hey browser, apply this style information to everything in these tags.” That could be font information but it can include much more.

Replacing them is easy. Change “font” to “span” and move all the font attributes into a single “style” attribute. For the value of the style attribute, you will need to use CSS syntax which is super easy: property: value; property: value;. A property name followed by a colon and then its value (with no quotes). Semicolons separate the property-value pairs. The final semicolon is optional since there is nothing to separate. I always add it so that if I need to add another property the semicolon is already there and I won’t forget it.

The table below shows how the font tag’s attribute names correspond to the CSS property names.

HTML font tag attribute CSS property
color color
size font-size
face font-family

For example:

10
11
12
<span style="font-size: 6; color: #FFFFFF; font-family: Helvetica;">
  My Site
</span>

Font Size Conversion

But there is one more important change you will need to make. The font tag’s size attribute was specified as a number 1 though 7. If you plug that same number into the CSS property, you will get a very small size because a browser will most likely interpret it as pixel height (e.g. 3 = 3 pixels high).

So how to equate them? The HTML 3.2 spec says “Font sizes are given in terms of a scalar range defined by the user agent with no direct mapping to point sizes etc.” (Anytime an official technical specification uses “etc.” you can be sure trouble is nearby.) The user agent is the browser, so basically, every browser has to have 7 sizes and can make those sizes anything they like. Thus, our conversion will be from a non-standardized number that displays differently in different browsers to a standard unit of measure that displays the same in all browsers. You will need to make your best guess and then adjust from there.

In CSS we generally measure size in either em (the size of the letter M in the current font family and font size) or in px (pixel height). I prefer to use em when I am working with text so that it remains a relative size. So as an example, 1.2em would be 20% larger than the M-height in the current font family and size. Here are rough equivalents from Safari—remember every browser is different and it depends on your browser’s default settings too.

old size ems pixels
7 3.0em 48px
6 2.0em 32px
5 1.5em 24px
4 1.15em 18px
3 1.0em 16px
2 0.8em 13px
1 0.65em 10px

Results

Finally, here are the changes to our HTML page.

10
11
12
<span style="font-size: 2em; color: #FFFFFF; font-family: Helvetica;">
  My Site
</span>
19
<strong><span style="font-size: 1.15em;">Menu</span></strong>
29
30
31
<span style="color: #1166FF; font-family: Helvetica;">
  Homepage
</span>

Before we go on, let’s take a moment to appreciate why this code is better.

  • It no longer uses a deprecated HTML tag.
  • It uses font sizes that are specific and the same across browsers.
  • CSS allows additional text styling (such as font-weight, font-style, line-height, letter-spacing, and word-spacing).
  • It gets us closer to our goal of writing clean, clear, syntactic HTML pages will all style information in external stylesheets.

Font-weight

Take a look at this line:

19
<strong><span style="font-size: 1.15em;">Menu</span></strong>

While there is nothing wrong with that line per se, it can be improved. A strong tag is essentially a span tag that applies some preset CSS styles. By default, the CSS style for a strong tag is simply a font weight of bold (font-weight: bold;).

Which makes that line essentially the same as:

<span style="font-weight: bold;">
  <span style="font-size: 1.15em;">Menu</span>
</span>

If that is the case, then there is no reason not to go ahead and combine those two span tags into one. Unless you either defined the strong tag with a different set of styles that you want to keep, or you really mean “strong” semantically (like at the beginning of this sentence) and are not just trying to give the text bold styling. In this case, the strong tag is just there to make the text bold, so we should combine them. (We will come back and make it even better later.)

19
<span style="font-weight: bold; font-size: 1.15em;">Menu</span>

Font weights in CSS can also be specified using numbers instead of simply “bold” or “normal”. Unfortunately these numbers are still not widely supported by browsers, so also notice what the fall back values will be if you decide to use them.

Numerical Weight Typographical Equivalent If Not Supported
100 Ultra-light, Extra-light Defaults to Normal
200 Light, Thin
300 Book
400 Regular, Normal
500 Medium
600 Semibold, Demibold Defaults to Bold
700 Bold
800 Heavy, Black, Extra-bold
900 Ultra-black, Extra-black, Fat, Poster

Font-style

In CSS the style of the text is declared with a property called font-style. But there is only one font-style (at the moment), italic. You can specific three options: normal, italic and oblique (which is the same as italic).

<span style="font-style: italic;">Italicized text</span>

Just like with strong tags, emphasis tags (<em>) by default are essentially just span tags with font-style set to italic. Our document has some emphasis-tags on line 33.

33
<p><em>Lorem ipsum dolor sit amet,</em> consectetur adipiscing

To decide whether these should be turned into span tags or left as emphasis tags, we have to consider how the styles are set up and how the tags are being used semantically. Do em tags still have their default style or are we doing something custom? Are we just trying to get the text to be italic (then go with span tags), or are we really saying that that text should have emphasis (then leave as emphasis tags)?

In our document, I could argue either side but would tend to say that what we intend is for the first few words to be emphasized. That emphasis could be italic, or it could be bold or larger text or a different color. So I will leave them as emphasis tags.

Font-family

We have already moved the font tag’s face attribute to the CSS font-family property, but there is a bit more that needs to be said about it.

First, the font family on our page was always Helvetica. But if it had a name that contained a space in the middle, like Times New Roman, then we would need to put the name in quotes. Either single-quotes or double-quotes are acceptable in an external stylesheet, but only single-quotes should be used inside the style attribute (to avoid confusion with the double quotes the surround the entire style value.)

10
11
12
<span style="font-size: 2em; color: #FFFFFF; font-family: 'Times New Roman';">
  My Site
</span>

Second, you can and should always provide fall-back options for your font family in case the user does not have that font installed. You can do that by putting other font names after your preferred name with commas between them. You can also (and should always) put a generic serif or sans-serif entry at the end to use the browser’s default font.

So if your first choice is Lucida Grande (a sans-serif font), you might have:

<span style="font-family: 'Lucida Grande', Lucida, Verdana, Arial, Helvetica, sans-serif;">

Or to illustrate a typical serif font listing:

<span style="font-family: Georgia, 'Times New Roman', Times, serif;">

Even though you may feel confident that all users would have a common font, like Helvetica, installed, it is always possible that the user did something crazy to their computer, threw it out, or disabled it. We want to be in the habit of allowing for that possibility.

I will change our HTML document to include a fall-back font family.

10
11
12
<span style="font-size: 2em; color: #FFFFFF; font-family: Helvetica, sans-serif;">
  My Site
</span>
29
30
31
<span style="color: #1166FF; font-family: Helvetica, sans-serif;">
  Homepage
</span>

Body Font

The last point I want to make is that our work-in-progress HTML document does not have a default font set. In the places we specified the font-family, we will get that font (or a fall-back font), but most of our document will use the browser or the user’s default font. That is not ideal if we care about the look of our page. So even though it may change the behavior (and look) of the page from the old HTML version which relied on default settings, let’s go ahead and specify a default font style in the body tag. I will include the font color and background color while I am at it.

29
<body style="font-face: Georgia, 'Times New Roman', Times, serif; color: #000000; background: #FFFFFF;">

It is okay to leave out font-size, line-height, font-weight, and font-style unless you know you want something different. In our case, where we did not have anything different, we could have put font-size: 1em; line-height: normal; font-weight: normal; font-style: normal; but those are the same values as the CSS default values. The same is true for the color and background but I simply decided it was worth being explicit on those values.

There is much more to fonts in CSS—more style properties, a shorthand syntax, best practices. I am not trying to be comprehensive. But I hope this is enough to break the habit if you use deprecated font tags and get you started writing good CSS instead.

Next we will look at improving our use of header tags…

Bookmark and Share

5 Responses to “Starting Good CSS Habits: Part 3”

  1. John Walsh Says:

    Hi Kevin

    So I might be jumping the gun, Tables! I noticed you still use tables for strictly tabular data, is this Ok? Do tables still have a future? But in their right place of course as small snippets of code that illustrate boring data and not as tags to structure a complete page!

  2. Kevin Skoglund Says:

    @John: I am planning to cover that topic. The short answer is that tables for tabular data and lists is appropriate. Tables for page structure is not. So a list of customers? Use a table. A report on recent product sales? Use a table.

  3. Jaime Bulmer Says:

    These are good. I actually didn’t even know about . So I guess the big question to you Kevin, is when are you going apply these habits inside of a new up to date Ruby on Rails training course? :P

  4. John Walsh Says:

    I adopted these rules a couple of years ago and then one of my Lecturers told me not to use etc because they are windows based, I trusted her word and actively changed strong and emphasis tags in Dreamweaver. Another Lecturer thought me to use tables for layout………

  5. Kevin Skoglund Says:

    @John: Bad advice on both counts. But now you will know better!

Leave a Reply