Chapter 1. HTML and CSS

CSS isn’t anything without HTML. HTML provides web pages with content and meaningful structure, and while it may not be pretty by itself, the web wouldn’t exist without it. So to get the most out of your CSS training, you need to know how to write HTML to create a solid, well-built foundation. This chapter introduces you to the basics of CSS and shows you how to write better, more CSS-friendly HTML.

The good news is that when you use CSS throughout your site, HTML actually becomes easier to write. You don’t need to try to turn HTML into the design maven it was never intended to be. Instead, CSS offers most of the graphic design touches you’ll likely ever want, and HTML pages written to work with CSS are easier to create, since they require less code and less typing. They’ll also download faster—a welcome bonus your site’s visitors will appreciate (see Figure 1-1).

HTML: Past and Present

HTML provides the foundation for every page you encounter on the Web. When you add CSS into the mix, HTML becomes simpler, because you don’t need to use HTML tags (like the old <font> tag) to control how a web page looks. That job is for CSS. But before jumping into CSS, here’s a quick walk through HTML’s past (and present).

HTML Past: Whatever Looked Good

When a bunch of scientists created the Web to share technical documentation, nobody called in the graphic designers. All the scientists needed HTML to do was structure information for easy comprehension. For example, the <h1> tag indicates an important headline, while the <h2> tag represents a lesser heading, usually a subheading of the <h1> tag. Another favorite, the <ol> (ordered list) tag, creates a numbered list for things like “Top 10 reasons not to play with jellyfish.”

CSS-driven web design makes writing HTML easier. The two designs pictured here look similar, but the top page is styled completely with CSS, while the bottom page uses only HTML. The size of the HTML file for the top page is only 4k, while the HTML-only page is nearly four times that size at 14k. The HTML-only approach requires a lot more code to achieve nearly the same visual effects: 213 lines of HTML code compared with 71 lines for the CSS version.
Figure 1-1. CSS-driven web design makes writing HTML easier. The two designs pictured here look similar, but the top page is styled completely with CSS, while the bottom page uses only HTML. The size of the HTML file for the top page is only 4k, while the HTML-only page is nearly four times that size at 14k. The HTML-only approach requires a lot more code to achieve nearly the same visual effects: 213 lines of HTML code compared with 71 lines for the CSS version.

But as soon as people other than scientists started using HTML, they wanted their web pages to look good. So web designers started to use tags to control appearance rather than structure information. For example, you can use the <blockquote> tag (intended for material that’s quoted from another source) on any text that you want to indent a little bit. You can use heading tags to make any text bigger and bolder—regardless of whether it functions as a heading.

In an even more elaborate workaround, designers learned how to use the <table> tag to create columns of text and accurately place pictures and text on a page. Unfortunately, since that tag was intended to display spreadsheet-like data—research results, train schedules, and so on—designers had to get creative by using the <table> tag in unusual ways, sometimes nesting a table within a table within a table to make their pages look good.

Meanwhile, browser makers introduced new tags and attributes for the specific purpose of making a page look better. The <font> tag, for example, let you specify a font color, typeface, and one of seven different sizes. (If you’re keeping score at home, that’s about 100 fewer sizes than you can get with, say, Microsoft Word.)

Finally, when designers couldn’t get exactly what they wanted, they often resorted to using graphics. For example, they’d create a large graphic to capture the exact font and layout for web page elements and then slice the Photoshop files into smaller files and piece them back together inside tables to recreate the original design.

While all of the preceding techniques—using tags in creative ways, taking advantage of design-specific tag attributes, and making extensive use of graphics—provide design control over your pages, they also add a lot of additional HTML code. More code makes your site more difficult to build and much slower for your visitors to download.

HTML Present: Scaffolding for CSS

No matter what content your web page holds—the fishing season calendar, driving directions to the nearest IKEA, or pictures from your kid’s birthday party—it’s the page’s design that makes it look like either a professional enterprise or a part-timer’s hobby. Good design enhances the message of your site, helps visitors find what they’re looking for, and determines how the rest of the world sees your website. That’s why web designers went through the contortions described in the previous section to force HTML to look good. By taking on those design duties, CSS lets HTML go back to doing what it does best—structuring content.

Using HTML to control the look of text and other web page elements is obsolete. Don’t worry if HTML’s <h1> tag is too big for your taste or bulleted lists aren’t spaced just right. You can take care of that later using CSS. Instead, think of HTML as a method of adding structure to the content you want up on the Web. Use HTML to organize your content and CSS to make that content look great.

Writing HTML for CSS

If you’re new to web design, you may need some helpful hints to guide your forays into HTML (and to steer clear of well-intentioned, but out-of-date HTML techniques). Or if you’ve been building web pages for a while, you may have picked up a few bad habits that you’re better off forgetting. The rest of this chapter introduces you to some HTML-writing habits that will make your mom proud—and help you get the most out of CSS.

Think Structure

HTML adds meaning to text by logically dividing it and identifying the role it plays on the page: For example, the <h1> tag is the most important introduction to a page’s content. Other headers let you divide the content into less important, but related sections. Just like this book, a web page needs a logical structure. Each chapter in this book has a title (think <h1>) and several sections (think <h2>), which in turn contain smaller subsections. Imagine how much harder it would be to read these pages if the words just ran together as one long paragraph.


For a tutorial on HTML, visit For a quick list of all available HTML tags, visit the detailed (but a bit technical) reference at the Mozilla Developer network:

HTML provides many other tags besides headers for marking up content to identify its role. (After all, the M in HTML stands for markup.) Among the most popular are the <p> tag for paragraphs of text and the <ul> tag for creating bulleted (non-numbered) lists. Lesser-known tags can indicate very specific types of content, like <abbr> for abbreviations and <code> for computer code.

When writing HTML for CSS, use a tag that comes as close as possible to matching the role the content plays in the page, not the way it looks (see Figure 1-2). For example, a bunch of links in a navigation bar isn’t really a headline, and it isn’t a regular paragraph of text. It’s most like a bulleted list of options, so the <ul> tag is a good choice. If you’re saying, “But items in a bulleted list are stacked vertically one on top of the other, and I want a horizontal navigation bar where each link sits next to the previous link,” don’t worry. With CSS magic you can convert a vertical list of links into a stylish horizontal navigation bar, as you’ll see in Chapter 9.

More HTML Tags to Keep in Mind

HTML’s motley assortment of tags doesn’t cover the wide range of content you’ll likely have on a web page. Sure, <code> is great for marking up computer program code, but most folks would find a <recipe> tag handier. Too bad there isn’t one. Fortunately, HTML provides several “structural” tags that let you better identify and group content, and, in the process, provide “handles” that let you attach CSS styles to different page elements. Two of those tags—<div> and <span>—have been around nearly since the beginning of HTML. HTML5 introduced a much wider range of tags that let you group content that serves a particular function, like the <footer> tag, which you can use to group supplementary information like a copyright notice, contact information, or a list of resources.

Old school, new school. Before CSS, designers had to resort to the <font> tag and other extra HTML to achieve certain visual effects (top). You can achieve the same look (and often a better one) with a lot less HTML code (bottom). In addition, using CSS for formatting frees you up to write HTML that follows the logical structure of the page’s content.
Figure 1-2. Old school, new school. Before CSS, designers had to resort to the <font> tag and other extra HTML to achieve certain visual effects (top). You can achieve the same look (and often a better one) with a lot less HTML code (bottom). In addition, using CSS for formatting frees you up to write HTML that follows the logical structure of the page’s content.

Understanding the <div> and <span> Tags

The <div> and <span> tags have been around for much of the life of the Web. They’ve traditionally been used to organize and group content that doesn’t quite lend itself to other HTML tags. Think of them as like empty vessels that you fill with content. A div is a block, meaning it has a line break before it and after it, while a span appears inline, as part of a paragraph. Otherwise, divs and spans have no inherent visual properties, so you can use CSS to make them look any way you want. The <div> (for division) tag indicates any discrete block of content, much like a paragraph or a headline. But more often it’s used to group any number of other elements, so you can insert a headline, a bunch of paragraphs, and a bulleted list inside a single <div> block. The <div> tag is a great way to subdivide a page into logical areas, like a banner, footer, sidebar, and so on. Using CSS, you can later position each area to create sophisticated page layouts (a topic that’s covered in Part 3).

The <span> tag is used for inline elements: words or phrases that appear inside a larger paragraph or heading. Treat it just like other inline HTML tags, such as the <a> tag (for adding a link to some text in a paragraph) or the <strong> tag (for emphasizing a word in a paragraph). For example, you could use a <span> tag to indicate the name of a company, and then use CSS to highlight the name by using a different font, color, and so on. Here’s an example of these tags in action, complete with a sneak peek of a couple of attributes—id and class—frequently used to attach styles to parts of a page.

<div id="footer">
  <p>Copyright 2015, <span class="bizName"></span></p>
  <p>Call customer service at 555-555-5501 for more information.</p>

This brief introduction isn’t the last you’ll see of these tags. They’re used frequently in CSS-heavy web pages, and in this book you’ll learn how to use them in combination with CSS to gain creative control over your web pages.

Additional Tags in HTML5

The <div> tag is rather generic—it’s simply a block-level element used to divide a page into sections. One of the goals of HTML5 is to provide other, more semantic tags for web designers to choose from. Making your HTML more semantic simply means using tags that accurately describe the content they contain. As mentioned earlier in this section, you should use the <h1> (heading 1) tag when placing text that describes the primary content of a page. Likewise, the <code> tag tells you clearly what kind of information is placed inside—programming code.

HTML5 includes many different tags whose names reflect the type of content they contain, and can be used in place of the <div> tag. The <article> tag, for example, is used to mark off a section of a page that contains a complete, independent composition, like a blog post, an online magazine article, or simply the page’s main body of text. Likewise, the <header> tag indicates a header or banner: the top part of a page, usually containing a logo, sitewide navigation, page title and tagline, and so on.


To learn more about the new HTML tags, visit HTML5 Doctor ( and or grab a copy of the HTML5 Pocket Reference (O’Reilly).

Many HTML5 tags are intended to expand upon the generic <div> tag. Here are a few other HTML5 tags frequently used to structure the content on a page:

  • The <section> tag contains a grouping of related content, such as the chapter of a book. For example, you could divide the content of a home page into three sections: one for an introduction to the site, one for contact information, and another for latest news.

  • The <aside> tag holds content that is related to content around it. A sidebar in a print magazine is an example of the type of content that would go into an <aside>.

  • The <footer> tag contains information you’d usually place in a page’s footer, like a copyright notice, legal information, some site navigation links, and so on. You’re not limited to just a single <footer> per page, though; you can put a footer inside an <article>, for example, to hold related information like footnotes, references, or citations.

  • The <nav> element is used to contain primary navigation links.

  • The <figure> tag is used for an illustrative image. You can place an <img> tag inside it, as well as another new HTML5 tag—the <figcaption> tag, which is used to display a caption explaining the photo or illustration within the <figure>.


Understanding which HTML5 tag to use—should your text be an <article> or a <section>?—can be tricky. For a handy flowchart that makes sense of HTML5’s new sectioning elements, download the PDF from the at

There are other HTML5 elements, and many of them simply provide a more descriptive alternative to the <div> tag. This book uses both the <div> tag and the new HTML5 tags to help organize web-page content. The downside of HTML5 is that Internet Explorer 8 and earlier don’t recognize the new tags without a little bit of help (see the box on Getting IE8 to Understand HTML5).

In addition to letting you feel like you’re keeping up with the latest web design trends, using HTML5 tags provides you with clues about a page’s content, and may boost the site’s search engine ranking. For example, using the <article> tag to hold the main story on a web page can highlight what’s inside that tag, and is more descriptive (that is, semantic) than a plain old <div>. Even so, many web designers still use <div> tags even in places where an HTML5 tag makes sense, so there’s no harm in continuing to use the <div> tag and avoiding the HTML5 sectioning elements if you like.

In addition, even with the HTML5 tags, sometimes you still need use <div> tags simply to group other HTML tags. You’d do this to provide a way to move that group to another spot on a page, to give the group a consistent background color, or to draw an outline and add a drop shadow.

Keep Your Layout in Mind

While you’ll use the <h1> tag to identify the main topic of the page and the <p> tag to add a paragraph of text, you’ll eventually want to organize a page’s content into a pleasing layout. As you learn how to use CSS to lay out a page in Part 3, it doesn’t hurt to keep your design in mind while you write the page’s HTML.

You can think of web page layout as the artful arrangement of boxes (see Figure 1-3 for an example). After all, a two-column design consisting of two vertical columns of text is really just two rectangular boxes sitting side by side. A header consisting of a logo, tagline, search box, and site navigation is really just a wide rectangular box sitting across the top of the browser window. In other words, if you imagine the groupings and layout of content on a page, you’d see boxes sitting on top of, next to, and below one another.

This basic two-column layout includes a banner (top), a column of main content (middle, left), a sidebar (middle, right), and a footer (bottom). These are the main structural boxes making up this page’s layout.
Figure 1-3. This basic two-column layout includes a banner (top), a column of main content (middle, left), a sidebar (middle, right), and a footer (bottom). These are the main structural boxes making up this page’s layout.

In your HTML, you create these boxes, or structural units, using the <div> tag, or one of HTML5’s structural tags like <footer>, <header>, <article>, and <aside>. Simply wrap the HTML tags that make up the banner area, for example, in one div, a column’s worth of HTML in another, and so on. If you’re HTML5 savvy, you might create the design pictured in Figure 1-3, with a <header> tag for the top banner, an <article> tag for the main text, an <aside> or <section> tag for the sidebar, and a <footer> tag for the page’s footer. In other words, if you plan to place a group of HTML tags together somewhere on a page, then you’ll need to wrap those tags in a sectioning element like a <div>, <article>, <section>, or <aside>.

As you’ll learn in Part 3, CSS provides powerful layout tools. You can literally place HTML anywhere in the browser window; recent developments like flexbox (Chapter 15) give you lots of freedom in how you structure your HTML. Still, it’s always a good idea to group related content into some kind of container element like a <div> or an HTML5 structural tag.

Microsoft says it will discontinue support for Internet Explorer 8 by January 2016. At that point, Windows fans will have more incentive to upgrade IE or switch to another browser, like Chrome or Firefox. The biggest problem with IE8 is that it doesn’t understand HTML5 tags, which means you can’t directly format these tags with CSS. If you’re really worried about supporting Internet Explorer 8, either skip the HTML5 tags described on Additional Tags in HTML5 for structuring your HTML and stick to <div> tags, or use the quick JavaScript solution described in the box on Getting IE8 to Understand HTML5.

HTML to Forget

CSS lets you write simpler HTML for one big reason: There are many old HTML tags that you should abandon (if you’re still using them). The <font> tag is the most glaring example. Its sole purpose is to add a color, size and font to text. It doesn’t do anything to make the page’s structure more understandable.

Here’s a list of tags and attributes you can easily replace with CSS:

  • Ditch <font> for controlling the display of text. CSS does a much better job with text. (See Chapter 6 for text-formatting techniques.)

  • Don’t use the <b> and <i> tags to emphasize text. If you want text to really be emphasized, use the <strong> tag, which browsers normally display as bold. For a slightly less emphatic point, use the <em> tag, which browsers display as italic. You can use CSS to make any text on a page italicized, bolded, or both.

    While HTML 4 tried to phase the <b> and <i> tags out, HTML5 has brought them back. In HTML5 the <b> tag is meant to merely make text bold without adding any meaning to that text (that is, you just want the text to be bold looking but you don’t want people to treat that text like you’re shouting it). Likewise, the <i> tag is used for italicizing text, but not emphasizing its meaning.


    To italicize a publication’s title, the <cite> tag kills two birds with one stone. It puts the title in italics and tags it as a cited work for search engines’ benefit. Of course, CSS lets you do anything you want with the tag, so if you want to reference a publication and not italicize it, you can still use the <cite> tag.

  • Skip the <table> tag for page layout. Use tables only to display information like spreadsheets, schedules, and charts. As you’ll see in Part 3, you can do all your layout with CSS for much less time and code than the table-tag tango.

  • Don’t abuse the <br> tag. If you grew up using the <br> tag to insert a line break without creating a new paragraph, then you’re in for a treat. (Browsers automatically—and sometimes infuriatingly—insert a bit of space between paragraphs, including between headers and <p> tags. In the past, designers used elaborate workarounds to avoid paragraph spacing they didn’t want, like replacing a single <p> tag with a bunch of line breaks and using a <font> tag to make the first line of the paragraph look like a headline.) Using CSS’s margin controls, you can easily set the amount of space you want to see between paragraphs, headers, and other block-level elements.


In Chapter 5, you’ll learn about a technique called a “CSS Reset,” which eliminates the gaps browsers normally insert between paragraphs and other tags (see Starting with a Clean Slate).

As a general rule, adding attributes to tags that set colors, borders, background images, or alignment—including attributes that let you format a table’s colors, backgrounds, and borders—is pure old-school HTML. So is using alignment properties to position images and center text in paragraphs and table cells. Instead, look to CSS to control text placement (Aligning Text), borders (Adding Borders), backgrounds (Adding Background Images), and image alignment (Discovering CSS and the <img> Tag).

The W3C HTML validator located at lets you quickly make sure the HTML in a page is sound. You can point the validator to an already existing page on the Web, upload an HTML file from your computer, or just paste the HTML of a web page into a form box and then click the Check button.
Figure 1-4. The W3C HTML validator located at lets you quickly make sure the HTML in a page is sound. You can point the validator to an already existing page on the Web, upload an HTML file from your computer, or just paste the HTML of a web page into a form box and then click the Check button.

Tips to Guide Your Way

It’s always good to have a map to get the lay of the land. If you’re still not sure how to use HTML to create well-structured web pages, then here are a few tips to get you started:

  • Use headings to indicate the relative importance of text. Again, think outline. When two headings have equal importance in the topic of your page, use the same level header on both. If one is less important or a subtopic of the other, then use the next-level header. For example, follow an <h2> with an <h3> tag (see Figure 1-5). In general, it’s good to use headings in order and try not to skip heading numbers. For example, don’t follow an <h2> tag with an <h5> tag.

    Use the headline tags (<h1>, <h2>, and so on) as you would if you were outlining a school report: Put them in order of importance, beginning with an <h1> tag, which should shout “Listen up! This is what this whole page is about.”
    Figure 1-5. Use the headline tags (<h1>, <h2>, and so on) as you would if you were outlining a school report: Put them in order of importance, beginning with an <h1> tag, which should shout “Listen up! This is what this whole page is about.”
  • Use the <p> tag for paragraphs of text.

  • Use unordered lists (<ul>) when you’ve got a list of several related items, such as navigation links, headlines, or a set of tips like these.

  • Use numbered lists (<ol>) to indicate steps in a process or define the order of a set of items. The tutorials in this book are a good example, as is a list of rankings like “Top 10 websites popular with monks.”

  • To create a glossary of terms and their definitions or descriptions, use the <dl> (definition list) tag in conjunction with the <dt> (definition term) and <dd> (definition description) tags. (For an example of how to use this combo, visit

  • If you want to include a quotation like a snippet of text from another website, a movie review, or just some wise saying of your grandfather’s, try the <blockquote> tag for long passages or the <q> tag to place a short quote within a longer paragraph, like this:

    <p>Mark Twain is said to have written <q>The coldest winter I ever spent
    was a summer in San Francisco</q>. Unfortunately, he never actually wrote
    that famous quote.</p>
  • Take advantage of obscure tags like the <cite> tag for referencing a book title, newspaper article, or website, and the <address> tag to identify and supply contact information for the author of a page (great for a copyright notice).

  • As explained in full on HTML: Past and Present, steer clear of any tag or attribute aimed solely at changing the appearance of a text or image. CSS, as you’ll see, can do it all.

  • When there isn’t an HTML tag that fits the bill, but you want to identify an element on a page or a bunch of elements on a page so you can apply a distinctive look, use the <div> and <span> tags (see Understanding the <div> and <span> Tags). You’ll get more advice on how to use these in later chapters.

  • Don’t overuse <div> tags. Some web designers think all they need are <div> tags, ignoring tags that might be more appropriate. For example, to create a navigation bar, you could add a <div> tag to a page and fill it with a bunch of links. A better approach would be to use a bulleted list (<ul> tag), After all, a navigation bar is really just a list of links. As discussed on Additional Tags in HTML5, HTML5 provides several new tags that can take the place of the <div> tag, like the <article>, <section>, and <footer> tags. For a navigation bar, you could use the HTML5 <nav> tag.

  • Remember to close tags. The opening <p> tag needs its partner in crime (the closing </p> tag), as do all other tags, except the few self-closers like <br> and <img>.

  • Validate your pages with the W3C validator (see Figure 1-4 and the box on Validate Your Web Pages). Poorly written or typo-ridden HTML causes many weird browser errors.

The Importance of the Doctype

HTML follows certain rules. You tell a web browser which version of HTML you’re using (and which rules you’re following) by including what’s called a doctype declaration at the beginning of a web page. This doctype declaration is the first line in the HTML file, and defines what version of HTML you’re using (such as HTML5 or HTML 4.01 Transitional).

If you mistype the doctype declaration or leave it out, you can throw most browsers into an altered state called quirks mode. Quirks mode is browser manufacturers’ attempt to make their software behave like browsers did circa 1999 (in the Netscape 4 and Internet Explorer 5 days). If a modern browser encounters a page that’s missing the correct doctype, then it thinks, “Gee, this page must have been written a long time ago, in an HTML editor far, far away. I’ll pretend I’m a really old browser and display the page just as one of those buggy old browsers would display it.” That’s why, without a correct doctype, your lovingly CSS-styled web pages may not look as they should, according to current standards. If you unwittingly view your web page in quirks mode when checking it in a browser, you may end up trying to fix display problems that are related to an incorrect doctype and not the incorrect use of HTML or CSS.

Fortunately, it’s easy to get the doctype right. All you need to know is what version of HTML you’re using. Almost everyone is using HTML5 now, and the doctype is simply:

<!doctype html>

Put this at the top of your HTML file and you’re good to go. If you’re still using older versions of HTML or XHTML such as HTML 4.01 Transitional and XHTML 1.0 Transitional, then the doctype is a lot more convoluted.

If you’re using HTML 4.01 Transitional, for example, type the following doctype declaration at the very beginning of every page you create:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.">

The doctype declaration for XHTML 1.0 Transitional is similar. It’s also necessary to add a little code to the opening <html> tag that’s used to identify the file’s XML type—in this case, it’s XHTML—like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.">
<html xmlns="">

If this entire discussion is making your head ache and your eyes slowly shut, keep your life simple by using the HTML5 doctype. It’s short, easy to remember, works in all browsers, and what almost all new web pages use. You can use this doctype even if you don’t touch any of the new HTML5 tags.


Most visual web page tools like Dreamweaver add a doctype declaration whenever you create a new web page, and many HTML-savvy text editors have shortcuts for adding doctypes.

How CSS Works

Now that you have a solid background on writing HTML for CSS, you’re ready for what this book is all about. CSS is the styling language used to format HTML-based web pages. While HTML provides the page’s structure, CSS works hand in hand with the web browser to make HTML look good on screen.

For example, you might use HTML to turn a phrase into a top-level heading, indicating that it introduces the content on the rest of the page. You’d use CSS to format that heading with, say, big and bold red type and position it 50 pixels from the left edge of the window. In CSS, that text formatting is a style—a rule describing the appearance of a particular portion of a web page. A style sheet is a set of these styles.

You can create styles to work with any HTML tag. For example, you can create styles specifically to format the images on a page. For instance, a style can align an image along the page’s right edge, surround the image with a colorful border, and place a 50-pixel margin between the image and the surrounding text.

The web browser applies the styles you create to text, images, headings, and other page elements. For example, you can create a style that applies to a single paragraph on your page to instantly change the text’s size, color, and font within that paragraph. You can create styles that apply to specific HTML tags, so, for example, a browser displays every first-level heading (<h1> tag) in your site in the same way, no matter where those headings appear. You can even create styles that apply only to specific tags that you’ve marked up in a special way in the HTML.

Creating styles is all about determining what you want to style (a single image, every image, every other item in a list, and so on) and how you want that selected element or elements to look. In fact, determining what you want to style is such a big topic, Chapters Chapter 3, Chapter 4, and Chapter 5 of this book are devoted to the subject. All of the different ways you can make page elements look is an even bigger topic, and is covered in Part 2.

Get CSS: The Missing Manual, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.