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 eyecatching 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 your first 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 canned styles.

CSS is not HTML. HTML provides structure to a document by organizing information into headers, paragraphs, bulleted lists, and so on. CSS is another language altogether. It 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 positioned 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 could 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 that, 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, as you’ll see later in this introduction, 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 Web masters can make pages look pretty good using only HTML. But the result’s often sluggish, unpredictable 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 book 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 how (and whether) 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. 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 tags used solely for formatting the look of HTML (the <font> tag, for example). (For a list of other obsolete tags, see http://www.codehelp.co.uk/html/deprecated.html.)

What You Need to Know

This book assumes you’ve already got some knowledge of HTML (and perhaps some CSS experience as well); 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 doesn’t do anything without HTML, so to move forward you need to know how to create a Web page using basic HTML.

If you have used HTML to create Web pages, but feel like your knowledge is a bit rusty, the next section provides a basic refresher.

Note

If you’re just getting your feet wet learning HTML, then check out these free online tutorials: HTML Dog (http://www.htmldog.com/guides/htmlbeginner/) and W3Schools (http://www.w3schools.com/html/). If you’re a printed page fan, then you may want to pick up a copy of Creating Web Sites: The Missing Manual, 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:

	<html>
	<head>
	<title>Hey, I am the title of this Web page.</title>
	</head>
	<body>
	Hey, I am some body text on this Web page.
	</body>
	</html>

It may not be exciting, but this example has all the basic elements a Web page needs. You’ll notice html (between brackets) at the very beginning and very end of the code, a header, a body, and some stuff—the actual page contents—inside the body.

How HTML Tags Work

In the above 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 three tags:

  • 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’s 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 trunk. Springing from the trunk are two branches that represent the two main parts of any Web page: the head and the body.

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

    In addition, the head can contain information that’s used by the Web browser for displaying the Web page and for adding interactivity. You put Cascading Style Sheets, for example, in the head of the document. In addition, JavaScript scripts, functions, and variables can be declared in the head of the document.

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

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

  • 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 hyperlink in 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 Web site. 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.

Like any technology, HTML’s showing its age. Although it’s served its purpose well, it’s always been a somewhat sloppy language. Among other things, it allows uppercase, lowercase, or mixed case letters in tags (<body> and <BODY> are both correct, for example), and permits unclosed tags (so that 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 want to display your pages. Furthermore, HTML doesn’t work with one of the hottest up-and-coming Internet languages: XML or Extensible Markup Language.

XML is a tag-based language, somewhat like HTML, that’s used to organize data in a clear, easy to understand way so that 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. XHTML, which you’ll read about next, is one example of XML—but there are many others: from RSS feeds to iTunes playlists.

XHTML: HTML for the New Era

To keep pace with the times, an “improved” version of HTML, called XHTML is finding its way into more and more Web sites. If you already understand HTML, don’t worry—XHTML isn’t a revolutionary new language that takes years to learn. It’s basically HTML, but with stricter guidelines.

The hot debate’s whether HTML or XHTML is the best approach. To judge by some of the online discussions, you’d think HTML and XHTML are completely different languages. They aren’t. You can build snazzy and functional Web sites with HTML now and will probably be able to continue in the future. If you continue using HTML, the most important thing is that you follow the guidelines discussed in Chapter 1: in particular, an HTML page must use the correct “Doctype” (Section 1.3) or your CSS will fall apart in certain browsers, and it must “validate” (Section 1.2.4) so that you know for sure 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 because it’s stricter than HTML it enforces rules that make sure the page works (for example, a Doctype isn’t absolutely required in HTML; it is with XHTML).

XHTML’s the future of Web page languages: there won’t be any future versions of HTML, but there’s a lot of work being put into creating the next generation of XHTML. (Don’t hold your breath, though—it’ll be years before there’s wide support in browsers for it.)

Note

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

The HTML page code shown in Section 3.3 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=iso-
	8859-1" />
	</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 declaration. That’s the first few lines in the code above, starting with <!DOCTYPE. The document type declaration is the most important part of an XHTML page, as you’ll see in the next section.

  • 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 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’s one example. To close an empty tag, include a forward slash at the end of the tag, like this: <br />.

What the Doctype Does

In the example XHTML code, everything below the <head> is exactly the same as the HTML page you looked at earlier. The information that begins the page, however, is very different. Each XHTML page begins with a few lines that state what type of document the page is and which standard it conforms to. This document type declaration—doctype for short—also points the Web browser to files on the Internet that contain definitions for that type of file.

In this case, it merely says that the page is a type of XML document, in particular, an XHTML document. The doctype plays a key role in how a Web browser displays CSS—in fact a missing or incorrect doctype’s enough to make Internet Explorer completely mishandle the presentation of a CSS-heavy Web page. You’ll learn much more about doctypes—and their importance to CSS—in Chapter 1.

Note

This may seem like a lot to take in if you’re relatively new to building Web pages. Don’t worry—it is. In Chapter 1, you’ll also learn a cool tool for making sure you’re creating correct XHTML—the W3C Validator. It checks your page and lets you know if everything’s OK. Even more importantly, you’ll learn how to create CSS-friendly XHTML.

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-style 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:

HTML-Kit (Windows, http://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, http://www.barebones.com/products/textwrangler/). This free software’s actually a pared-down version of BBEdit, the sophisticated, well-known text editor for the Mac. TextWrangler doesn’t have all of BBEdit’s built-in HTMLtools, but it does include syntax-coloring (meaning that tags and properties are highlighted in different colors so it’s easy to scan a page and identify its parts), FTP support (so you can upload files to a Web server), and more.

Commercial Software

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

EditPlus (Windows, http://www.editplus.com) is an inexpensive ($30) text editor that includes syntax-coloring, FTP, auto-completion and other wrist-saving features.

skEdit (Mac, http://www.skti.org) is a cheap ($25) Web page editor, complete with FTP/ SFTP support, code hints and other useful features.

BBEdit (Mac, http://www.barebones.com/products/bbedit). This much-loved Mac text editor ($199) has plenty of tools for working with HTML, XHTML, CSS and more. Includes many useful Web building tools and shortcuts.

Dreamweaver (Mac and Windows, http://www.macromedia.com/software/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: The Missing Manual for the full skinny on how to use this powerful program.

Expression Web Designer (Windows, http://www.microsoft.com) is Microsoft’s new entry in the Web design field. It replaces FrontPage and includes many professional Web design tools including very good support for creating CSS.

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’ve already got 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 C.

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 http://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 the finer points regarding CSS 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 in Section 2.5. 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 shaded 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 Media—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 1, 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 2, 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 3, 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 4, Advanced CSS, teaches you how to make web pages look good when printed and covers advanced techniques for using CSS more effectively and efficiently.

  • Part 5, 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 Web sites 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 http://www.sawmac.com/css/. 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 the Missing Manuals Web site (http://www.missingmanuals.com), you’ll find articles, tips, and updates to the book. 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 Web site, so that you can mark important corrections into your own copy of the book, if you like. (Click the book’s name, and then click the Errata link, to see the changes.) In the meantime, we’d love to hear your suggestions for new books in the Missing Manual line. There’s a place for that on the Web site, too, as well as a place to sign up for free email notification of new titles in the series.

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). To double-click, of course, 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.

  • Operating-system basics. 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) and the Dock or menu (Macintosh), as well as the Control Panel (Windows), or System Preferences (Mac OS X).

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 I-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 I-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® Enabled

When you see a Safari® Enabled icon on the cover of your favorite technology book, that means it’s 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 for free at http://safari.oreilly.com.

Get CSS: The Missing Manual now with O’Reilly online learning.

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