Introduction

Cascading Style Sheets—CSS for short—give you creative control over the layout and design of your web pages. Using them, you can dress up your text with eye-catching headings, drop caps, and borders, just like the ones you see in glossy magazines. You can also arrange images with precision, create columns and banners, and highlight your text links with dynamic rollover effects.

Anything that can do all that must be pretty complicated, right? Au contraire! The purpose of CSS is to streamline the process of styling web pages. In the next few pages, you’ll learn about the basics of CSS. In Chapter 1, you’ll get right to work creating a CSS-powered web page.

How CSS Works

If you’ve used styles in word processing programs like Microsoft Word or page layout programs like Adobe InDesign, CSS will feel familiar. A style is simply a rule describing how to format a particular portion of a web page. A style sheet is a set of these styles.

CSS works with HTML, but it’s not HTML. It’s a different language altogether. While HTML provides structure to a document by organizing information into headers, paragraphs, bulleted lists, and so on, CSS works hand-in-hand with the web browser to make HTML look good.

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. However, 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. CSS is all about changing—and improving—the appearance of the HTML.

You can also create styles specifically for working with images. For instance, a style can align an image along the right edge of a web page, surround the image with a colorful border, and place a 50-pixel margin between the image and the surrounding text.

Once you’ve created a style, you can apply it to text, images, headings, or other elements on a page. For example, you can select a paragraph of text and apply a style to instantly change the text’s size, color, and font. You can also create styles for specific HTML tags, so, for example, all first-level headings (<h1> tags) in your site are displayed in the same style, no matter where they appear.

The Benefits of CSS

Before CSS, web designers were limited to the layout and styling options of HTML. And if you surfed the Web in 1995, then you understand the emphasis on limited. HTML still forms the foundation of all pages on the World Wide Web, but it’s simply not a design tool. Sure, HTML provides basic formatting options for text, images, tables, and other web page elements, and patient, meticulous webmasters can make pages look pretty good using only HTML. But the result is often sluggish web pages laden with clunky code.

CSS, in contrast, offers the following advantages:

  • Style sheets offer far more formatting choices than HTML. With CSS, you can format paragraphs as they appear in a magazine or newspaper (the first line indented and no space between each paragraph, for example) and control the leading (the space between lines of type in a paragraph).

  • When you use CSS to add a background image to a page, you get to decide whether and how it tiles (repeats). HTML can’t even begin to do that.

  • Even better, CSS styles take up much less space than HTML’s formatting options, such as the much-hated <font> tag. You can usually trim a lot of kilobytes from text-heavy web pages using CSS. As a result, your pages look great and load faster.

  • Style sheets also make updating your site easier. You can collect all of your styles into a single external style sheet that’s linked to every page in your site. Then, when you edit a style, that change immediately ripples through your site wherever that style appears. You can completely change the appearance of a site just by editing a single style sheet.

Note

HTML is so long in the tooth design-wise that the World Wide Web Consortium (W3C), the organization responsible for defining standards for the Web, has already deprecated (phased out) many HTML formatting tags (the <font> tag, for example). (For a list of other obsolete tags, see www.codehelp.co.uk/html/deprecated.html.)

What You Need to Know

This book assumes you’ve already got some knowledge of HTML (and maybe some CSS experience as well). Perhaps you’ve built a site or two (or at least a page or two) and have some familiarity with the sea of tags—<html>, <p>, <h1>, <table>, and so on—that make up the Hypertext Markup Language. CSS can’t do anything without HTML, so to move forward you need to know how to create a web page using basic HTML.

If you’ve used HTML in the past to create web pages, but feel like your knowledge is a bit rusty, the next section provides a basic refresher.

Tip

If you’re just getting your feet wet learning HTML, then check out these free online tutorials: HTML Dog (www.htmldog.com/guides/htmlbeginner/) and W3Schools (www.w3schools.com/html/). If you’re a printed page fan, then you may want to pick up a copy of Creating a Web Site: The Missing Manual, Second Edition or Head First HTML with CSS & XHTML (O’Reilly).

HTML: The Barebones Structure

HTML (Hypertext Markup Language) uses simple commands called tags to define the various parts of a web page. For example, this HTML code creates a simple web page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/
html4/strict.dtd">
<html>
<head>
<title>Hey, I am the title of this web page</title>
</head>
<body>
<p>Hey, I am a paragraph on this web page.</p>
</body>
</html>

It may not be exciting, but this example has all the basic elements a web page needs. You’ll notice something called a DOCTYPE declaration at the very beginning of the code, followed by html (between brackets), a head, a body, and some stuff—the actual page contents—inside the body, ending in a final </html>.

How HTML Tags Work

In this simple example, as in the HTML code of any web page you look at, you’ll notice that most commands appear in pairs that surround a block of text or other commands. Sandwiched between brackets, these tags are instructions that tell a web browser how to display the web page. Tags are the “markup” part of the Hypertext Markup Language.

The starting (opening) tag of each pair tells the browser where the instruction begins, and the ending tag tells it where the instruction ends. Ending or closing tags always include a forward slash (/) after the first bracket symbol (<).

For a web page to work, you must include at least these four elements:

  • The first line of a web page is the DOCTYPE declaration, which isn’t actually an HTML tag. Instead, this line tells the web browser what type of HTML the page uses. There are several different types of HTML, including the XML-based XHTML (discussed in the next section). You can leave out the DOCTYPE declaration, but your web site will look worse for it. As you’ll learn on The Importance of the Doctype, having a doctype is an important requirement to make sure your CSS designs work in all browsers.

  • The <html> tag appears once at the beginning of a web page and again (with an added slash) at the end. This tag tells a web browser that the information contained in this document is written in HTML, as opposed to some other language. All of the contents of a page, including other tags, appear between the opening and closing <html> tags.

    If you were to think of a web page as a tree, the <html> tag would be its roots. Springing from the trunk are two branches that represent the two main parts of any web page: the head and the body.

  • The web page’s head, surrounded by opening and closing <head> tags, contains the title of the page. It may also provide other, invisible information (such as search keywords) that browsers and search engines can exploit.

    In addition, the head can contain information that the web browser uses to display the web page and add interactivity. You put Cascading Style Sheets, for example, in the head of the document. You can also declare JavaScript scripts, functions, and variables in the head.

  • The body, as set apart by its surrounding <body> tags, contains all the content that appears inside a browser window—headlines, text, pictures, and so on.

Within the <body> tag, you commonly find tags like these:

  • You tell a web browser where a paragraph of text begins with a <p> (opening paragraph tag), and where it ends with a </p> (closing paragraph tag).

  • The <strong> tag emphasizes text. When you surround some text with it and its partner tag, </strong>, you get boldface type. The HTML snippet <strong> Warning!</strong> tells a web browser to strongly emphasize the word “Warning!”

  • The <a> tag, or anchor tag, creates a hyperlinkin a web page. When clicked, a hyperlink—or link —can lead anywhere on the Web. You tell the browser where the link points by putting a web address inside the <a> tags. For instance, you can type <a href="http://www.missingmanuals.com/">Click here!</a>.

    The browser knows that when your visitor clicks the words “Click here!” it should go to the Missing Manual website. The href part of the tag is called an attribute, and the URL (the Uniform Resource Locator or web address) is the value. In this example, http://www.missingmanuals.com is the value of the href attribute.

XHTML: HTML for the New Era?

Newcomers continually vie for the web language throne. HTML 4.01, which was created in the last century (granted, that’s just 10 years ago), has had its detractors. HTML has always been a somewhat sloppy language that allows, among other things, uppercase, lowercase, or mixed case letters in tags (<body> and <BODY> are both correct, for example), and permits unclosed tags (so you can use a single <p> tag without the closing </p> to create a paragraph). While this flexibility may make page writing easier, it also makes life more difficult for web browsers, PDAs, and other places you may want to display your pages.

Enter XHTML 1.0—an improved form of HTML that’s coming into widespread use. If you’re used to using HTML, don’t worry—XHTML isn’t a revolutionary new language that takes years to learn. It’s basically HTML, but was created as an XML-based language. Like HTML, XML is a tag-based language that lets you organize data in a clear, easy-to-understand way so different computers, operating systems, and programs can quickly and easily exchange data. However, unlike HTML, XML isn’t limited to a handful of tags. In fact, XML provides a set of rules for defining your own tags. In addition to forming the basis of XHTML, XML can create everything from RSS feeds to iTunes playlists and then some.

The hot debate is whether HTML 4.01 or XHTML 1.0 is the best approach. Judging by some of the online discussions, you’d think HTML and XHTML are completely different languages, which they aren’t. You can build snazzy and functional websites with HTML 4.01 now, and they’ll continue to work for years in the future.

If you continue using HTML, be sure to follow the guidelines in Chapter 1. In particular, you must give your HTML page the correct doctype (The Importance of the Doctype), or your CSS will fall apart in certain browsers. Also, you must validate your page (Validate Your Web Pages) to ensure there aren’t any typos or other mistakes that can mess up how your HTML displays. You need to do those same things for XHTML, but XHTML is stricter in that it enforces rules that make sure the page works. For example, HTML doesn’t absolutely require a doctype; XHTML does.

Tip

If you really want to delve into the innards of XHTML, then check out W3 Schools’ XHTML Tutorial at www.w3schools.com/xhtml/default.asp.

The HTML page on HTML: The Barebones Structure would look like this in XHTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title>Hey, I am the title of this web page.</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

<body>
<p>Hey, I am some body text on this web page. </p>
</body>
</html>

As you can see, this code looks a lot like HTML. To make an XHTML file comply with XML, however, there are a few strict rules to keep in mind:

  • Begin the page with a document type (DOCTYPE) declaration. That’s the first two lines in the code above. You saw a doctype in the HTML example, but if you look closely, you’ll see that the exact code is a bit different—in this case specifying a type of XHTML called XHTML 1.0 Transitional. You’ll learn much more about document types—and their importance to CSS—in Chapter 1.

  • Tags and tag attributes must be lowercase. Unlike with HTML, typing the tag <BODY> is a no-no; when you’re writing XHTML, capitalized tags aren’t invited to the party.

  • Quotation marks are required for tag attributes. For example, a link written like this: <a href=http://www.missingmanuals.com> is valid in HTML, but won’t work in XHTML. You have to enclose the value of the href property in double quotes: <a href="http://www.missingmanuals.com">.

  • All tags (even empty tags) must be closed. To create a paragraph in XHTML, for example, you must begin with <p> and end with </p>. Trouble is, some tags don’t come in pairs. These tags, called empty tags, have no closing tag. The line break tag is one example. To close an empty tag in XHTML, include a space and a forward slash at the end of the tag, like this: <br />.

HTML 5: The Wheel Turns Again

The future of the Web stretches beyond XML and XHTML. In fact, when this book’s first edition was published in 2006, the World Wide Web Consortium (W3C) was busy working on XHTML 2—a new, more powerful version of XHTML that looked like it would completely change how web designers created web pages. Unfortunately, that was just the problem: It was beginning to look like you had to have a Computer Science degree just to create a web page. As it turns out, since most of the browser creators such as Mozilla (Firefox) and Apple (Safari) said they simply weren’t going to build browsers to work with XHTML 2, the W3C changed course and formed a group to develop yet another new standard—HTML 5.

That’s right. HTML will rule once again…but not until sometime like 2022 (honest!). In other words, you don’t really have to worry about learning new HTML or XHTML for a while.

In the meantime, feel free to use either HTML 4.01 or XHTML 1.0. All browsers understand them, so if you can create a web page with those, you’re good to go. In the next chapter, you’ll learn some ways to make your HTML (or XHTML) better for working with CSS.

Software for CSS

To create web pages made up of HTML and CSS, you need nothing more than a basic text editor like Notepad (Windows) or Text Edit (Mac). But after typing a few hundred lines of HTML and CSS, you may want to try a program better suited to working with web pages. This section lists some common programs; some of them are free, and some you have to buy.

Note

There are literally hundreds of tools that can help you create web pages, so the following isn’t a complete list. Think of it as a greatest-hits tour of the most popular programs that CSS fans are using today.

Free Programs

There are plenty of free programs out there for editing web pages and style sheets. If you’re still using Notepad or Text Edit, then give one of these a try. Here’s a short list to get you started:

  • jEdit (Windows, Mac, Linux; http://jedit.org). This free, Java-based text editor works on almost any computer and includes many features that you’d find in commercial text editors, like syntax highlighting for CSS.

  • Notepad++ (Windows; http://notepad-plus.sourceforge.net/). A lot of people swear by this fast text editor. It even has built-in features that make it ideal for writing HTML and CSS, like syntax highlighting—color coding tags and special keywords to make it easier to identify the page’s HTML and CSS elements.

  • HTML-Kit (Windows; www.chami.com/html-kit/). This powerful HTML/XHTML editor includes lots of useful features like the ability to preview a web page directly in the program (so you don’t have to switch back and forth between browser and editor), shortcuts for adding HTML tags, and a lot more.

  • TextWrangler (Mac; www.barebones.com/products/textwrangler/). This free software is actually a pared-down version of BBEdit, the sophisticated, well-known Mac text editor. TextWrangler doesn’t have all of BBEdit’s built-in HTMLtools, but it does include syntax highlighting, FTP (so you can upload files to a web server), and more.

Commercial Software

Commercial website development programs range from inexpensive text editors to complete website construction tools with all the bells and whistles:

  • EditPlus (Windows; www.editplus.com) is an inexpensive ($35) text editor that includes syntax highlighting, FTP, auto-complete, and other wrist-saving features.

  • skEdit (Mac; www.skti.org) is an inexpensive ($35) web page editor, complete with FTP/SFTP, code hints, and other useful features.

  • Coda (Mac; www.panic.com/coda/) is a full-featured web development toolkit ($99). It includes a text editor, page preview, FTP/SFTP, and graphic CSS-creating tools for creating CSS.

  • Dreamweaver (Mac and Windows; www.adobe.com/products/dreamweaver/) is a visual web page editor ($399.) It lets you see how your page looks in a web browser. The program also includes a powerful text-editor and excellent CSS creation and management tools. Check out Dreamweaver CS4: The Missing Manual for the full skinny on how to use this powerful program.

  • Expression Web 2 (Windows; www.microsoft.com/expression) is Microsoft’s newest entry in the web design field ($299). It replaces FrontPage and includes many professional web design tools, including excellent CSS tools.

Note

The various types of software discussed in this section are general-purpose programs that let you edit both HTML/XHTML and CSS. With them, you need to learn only one program for your web development needs. But if you already have a beloved HTML/XHTML editor that doesn’t do CSS, then you may want to check out one of the CSS-specific editing programs covered in Appendix CSS Resources.

About This Book

The World Wide Web is really easy to use. After all, grandmothers in Boise and first graders in Tallahassee log onto the Web every day. Unfortunately, the rules that govern how the Web works aren’t so easy to understand. The computer scientists and other techie types who write the official documentation aren’t interested in explaining their concepts to the average Joe (or Joanne). Just check out www.w3.org/TR/CSS21/ to get a taste of the technical mumbo-jumbo these geeks speak.

There’s no manual for Cascading Style Sheets. People just learning CSS often don’t know where to begin. And CSS’s finer points can trip up even seasoned web pros. The purpose of this book, then, is to serve as the manual that should have come with CSS. In this book’s pages, you’ll find step-by-step instructions for using CSS to create beautiful web pages.

CSS: The Missing Manual is designed to help readers at every technical level. To get the most out of this book, you should know a sampling of HTML and maybe even CSS. So if you’ve never built a web page before, then check out the tutorial that starts on Creating an Inline Style. The primary discussions in these chapters are written for advanced-beginners or intermediates. But if you’re new to building web pages, special boxes called “Up to Speed” provide the introductory information you need to understand the topic at hand. If you’re an advanced web page jockey, on the other hand, then keep your eye out for similar boxes called “Power Users’ Clinic.” They offer more technical tips, tricks, and shortcuts for the experienced computer fan.

Note

This book periodically recommends other CSS books, covering topics that are too specialized or tangential for a manual. Sometimes the recommended titles are from Missing Manual series publisher O’Reilly—but not always. If there’s a great book out there that’s not part of the O’Reilly family, we’ll let you know about it.

About the Outline

CSS: The Missing Manual is divided into four parts, each containing several chapters:

  • Part One: CSS Basics, shows you how to create style sheets and provides an overview of key CSS concepts, like inheritance, selectors, and the cascade. Along the way, you’ll learn the best HTML/XHTML writing practices when working with CSS. Four tutorials reinforce the part’s main concepts and give you a good taste of the power of CSS.

  • Part Two: Applied CSS, takes you into the real world of web design. You’ll learn the most important CSS properties and how to use them to format text, create useful navigation tools, and enhance your page with graphics. This section also provides advice on how to make web pages look better when printed and how to make attractive tables and forms.

  • Part Three: CSS Page Layout, helps you with one of the most confusing, but most rewarding, aspects of CSS: controlling the placement of elements on a page. You’ll learn how to create common designs (like 2- and 3-column layouts) and how to add sidebars. You’ll also learn about floats and positioning—two common CSS techniques for controlling page layout.

  • Part Four: Advanced CSS, teaches you how to make web pages look good when printed and covers advanced techniques for using CSS more effectively and efficiently. You’ll also see where the future of CSS is headed and learn about some cutting edge CSS 3 that you can start using today (at least in some browsers).

  • Part Five: Appendixes, provides three sets of resources. The CSS Property Reference summarizes each CSS Property in small, easy-to-digest chunks so you can casually brush-up on what you already know or quickly learn about other useful CSS properties that you may not remember. The last two appendices cover tools and resources for creating and using CSS, from how to create CSS in Dreamweaver to lists of helpful websites and books.

Living Examples

This book is designed to get your work onto the Web faster and more professionally. It’s only natural, then, that half the value of this book lies on the Web.

As you read the book’s chapters, you’ll encounter a number of living examples—step-by-step tutorials that you can build yourself, using raw materials (like graphics and half-completed web pages) that you can download from www.sawmac.com/css2e/. You may not gain very much by simply reading these step-by-step lessons while relaxing in your porch hammock. But if you take the time to work through them at the computer, you’ll discover that these tutorials give you insight into the way professional designers build web pages.

You’ll also find, in this book’s lessons, the URLs of the finished pages, so that you can compare your work with the final result. In other words, you won’t just see pictures of how the web pages should look; you’ll find the actual, working web pages on the Internet.

About MissingManuals.com

At http://missingmanuals.com, you’ll find articles, tips, and updates to CSS: The Missing Manual. In fact, we invite and encourage you to submit such corrections and updates yourself. In an effort to keep the book as up-to-date and accurate as possible, each time we print more copies of this book, we’ll make any confirmed corrections you’ve suggested. We’ll also note such changes on the website, so that you can mark important corrections into your own copy of the book, if you like. (Go to http://missingmanuals.com/feedback, choose the book’s name from the pop-up menu, and then click Go to see the changes.)

Also on our Feedback page, you can get expert answers to questions that come to you while reading this book, write a book review, and find groups for folks who share your interest in CSS.

We’d love to hear your suggestions for new books in the Missing Manual line. There’s a place for that on missingmanuals.com, too. And while you’re online, you can also register this book at www.oreilly.com (you can jump directly to the registration page by going here: http://tinyurl.com/yo82k3). Registering means we can send you updates about this book, and you’ll be eligible for special offers like discounts on future editions of CSS: The Missing Manual.

The Very Basics

To use this book, and indeed to use a computer, you need to know a few basics. You should be familiar with these terms and concepts:

  • Clicking. This book gives you three kinds of instructions that require you to use your computer’s mouse or trackpad. To click means to point the arrow cursor at something on the screen and then—without moving the cursor at all—to press and release the clicker button on the mouse (or laptop trackpad). A right-click is the same thing using the right mouse button. (On a Mac, press Control as you click if you don’t have a right mouse button.)

  • To double-click means to click twice in rapid succession, again without moving the cursor at all. And to drag means to move the cursor while pressing the button.

    When you’re told to ⌘-click something on the Mac, or Ctrl-click something on a PC, you click while pressing the ⌘ or Ctrl key (both of which are near the space bar).

  • Menus. The menus are the words at the top of your screen or window: File, Edit, and so on. Click one to make a list of commands appear, as though they’re written on a window shade you’ve just pulled down. This book assumes that you know how to open a program, surf the Web, and download files. You should know how to use the Start menu (Windows) or the Dock or menu (Mac), as well as the Control Panel (Windows) or System Preferences (Mac OS X).

  • Keyboard shortcuts. Every time you take your hand off the keyboard to move the mouse, you lose time and potentially disrupt your creative flow. That’s why many experienced computer fans use keystroke combinations instead of menu commands wherever possible. When you see a shortcut like Ctrl+S ( ⌘-S) (which saves changes to the current document), it’s telling you to hold down the Ctrl or ⌘key, and, while it’s down, type the letter S, and then release both keys.

If you’ve mastered this much information, you have all the technical background you need to enjoy CSS: The Missing Manual.

About → These → Arrows

Throughout this book, and throughout the Missing Manual series, you’ll find sentences like this one: “Open the System → Library → Fonts folder.” That’s shorthand for a much longer instruction that directs you to open three nested folders in sequence, like this: “On your hard drive, you’ll find a folder called System. Open that. Inside the System folder window is a folder called Library; double-click it to open it. Inside that folder is yet another one called Fonts. Double-click to open it, too.”

Similarly, this kind of arrow shorthand helps to simplify the business of choosing commands in menus, as shown in Figure 1.

In this book, arrow notations help simplify menu instructions. For example, View → Text Size → Increase is a more compact way of saying, “From the View menu, choose Text Size; from the submenu that then appears, choose Increase.
Figure 1. In this book, arrow notations help simplify menu instructions. For example, View → Text Size → Increase is a more compact way of saying, “From the View menu, choose Text Size; from the submenu that then appears, choose Increase.

Safari® Books Online

When you see a Safari® Books Online icon on the cover of your favorite technology book, that means the book is available online through the O’Reilly Network Safari Bookshelf.

Safari offers a solution that’s better than e-Books. It’s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it free at http://my.safaribooksonline.com.

Get CSS: The Missing Manual, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.