CSS The Missing Manual 2nd Edition

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 560

DownloadCSS The Missing Manual 2nd Edition
Open PDF In BrowserView PDF
Download at Boykma.Com

CSS
THE MISSING MANUAL
The book that
should have been
in the box®

Download at Boykma.Com

Download at Boykma.Com

CSS
Second Edition

THE
MISSING
MANUAL

®

David Sawyer McFarland

Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo

Download at Boykma.Com

CSS: The Missing Manual, Second Edition
by David Sawyer McFarland
Copyright © 2009 David Sawyer McFarland. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional
sales department: (800) 998-9938 or corporate@oreilly.com.

Printing History:
August 2006:
August 2009:

First Edition.
Second Edition.

Nutshell Handbook, the Nutshell Handbook logo, the O’Reilly logo, and “The book that should have been
in the box” are registered trademarks of O’Reilly Media, Inc. CSS: The Missing Manual, The Missing Manual
logo, Pogue Press, and the Pogue Press logo are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author(s) assume
no responsibility for errors or omissions, or for damages resulting from the use of the information
contained herein.

This book uses RepKover™, a durable and flexible lay-flat binding.
ISBN: 978-0-596-80244-8
[M]

Download at Boykma.Com

Table of Contents

The Missing Credits ................................................................................. xiii
Introduction................................................................................................. 1

Part One: CSS Basics
Chapter 1: Rethinking HTML for CSS...................................................... 17
HTML: Past and Present .......................................................................................................................... 17
HTML Past: Whatever Looked Good ............................................................................................... 18
HTML Present: Scaffolding for CSS ................................................................................................. 19
Writing HTML for CSS .............................................................................................................................. 20
Think Structure ................................................................................................................................... 20
Two New HTML Tags to Learn ......................................................................................................... 20
HTML to Forget .................................................................................................................................. 22
Tips to Guide Your Way .................................................................................................................... 23
The Importance of the Doctype ............................................................................................................. 26
Getting the Most out of Internet Explorer 8 ......................................................................................... 28

Chapter 2: Creating Styles and Style Sheets .......................................... 31
Anatomy of a Style ................................................................................................................................... 31
Understanding Style Sheets .................................................................................................................... 34
Internal or External—How to Choose .............................................................................................. 34
Internal Style Sheets ................................................................................................................................ 35
External Style Sheets ................................................................................................................................ 36
Linking a Style Sheet Using HTML ................................................................................................... 37
Linking a Style Sheet Using CSS ...................................................................................................... 38

v
Download at Boykma.Com

Tutorial: Creating Your First Styles ........................................................................................................ 39
Creating an Inline Style ..................................................................................................................... 39
Creating an Internal Style Sheet ...................................................................................................... 40
Creating an External Style Sheet ...................................................................................................... 43

Chapter 3: Selectors: Identifying What to Style.....................................49
Tag Selectors: Page-Wide Styling ........................................................................................................... 50
Class Selectors: Pinpoint Control ........................................................................................................... 51
ID Selectors: Specific Page Elements ..................................................................................................... 53
Styling Groups of Tags ............................................................................................................................. 55
Constructing Group Selectors .......................................................................................................... 56
The Universal Selector (Asterisk) ..................................................................................................... 56
Styling Tags Within Tags .......................................................................................................................... 57
The HTML Family Tree ...................................................................................................................... 57
Building Descendent Selectors ......................................................................................................... 58
Pseudo-Classes and Pseudo-Elements .................................................................................................. 61
Styles for Links ................................................................................................................................... 61
Styling Paragraph Parts ..................................................................................................................... 62
More Pseudo-Classes and -Elements .............................................................................................. 62
Advanced Selectors .................................................................................................................................. 65
Child Selectors .................................................................................................................................... 66
Adjacent Siblings ................................................................................................................................ 66
Attribute Selectors .............................................................................................................................. 67
Tutorial: Selector Sampler ....................................................................................................................... 70
Creating a Group Selector ................................................................................................................ 72
Creating and Applying a Class Selector .......................................................................................... 73
Creating a Descendent Selector ....................................................................................................... 76
Creating and Applying an ID Selector ............................................................................................. 77
Finishing Touches .............................................................................................................................. 79

Chapter 4: Saving Time with Style Inheritance...................................... 81
What Is Inheritance? ................................................................................................................................ 81
How Inheritance Streamlines Style Sheets ........................................................................................... 83
The Limits of Inheritance ......................................................................................................................... 83
Tutorial: Inheritance ................................................................................................................................. 85
A Basic Example: One Level of Inheritance .................................................................................... 85
Using Inheritance to Restyle an Entire Page .................................................................................. 86
Inheritance Inaction ........................................................................................................................... 89

Chapter 5: Managing Multiple Styles: The Cascade .............................. 91
How Styles Cascade ................................................................................................................................. 92
Inherited Styles Accumulate ............................................................................................................. 92
Nearest Ancestor Wins ...................................................................................................................... 93
The Directly Applied Style Wins ....................................................................................................... 93
One Tag, Many Styles ........................................................................................................................ 94

vi

CSS: The Missing Manual
Download at Boykma.Com

Specificity: Which Style Wins .................................................................................................................. 96
The Tiebreaker: Last Style Wins ....................................................................................................... 97
Controlling the Cascade .......................................................................................................................... 99
Changing the Specificity ................................................................................................................... 99
Selective Overriding ........................................................................................................................ 100
Starting with a Clean Slate ............................................................................................................. 101
Tutorial: The Cascade in Action ........................................................................................................... 103
Resetting CSS and Styling from Scratch ........................................................................................ 103
Creating a Hybrid Style ................................................................................................................... 105
Overcoming Conflicts ...................................................................................................................... 106

Part Two: Applied CSS
Chapter 6: Formatting Text .....................................................................113
Formatting Text ...................................................................................................................................... 113
Choosing a Font ............................................................................................................................... 115
Adding Color to Text ....................................................................................................................... 118
Changing Font Size ................................................................................................................................ 119
Using Pixels ....................................................................................................................................... 120
Using Keywords, Percentages, and Ems ....................................................................................... 121
Formatting Words and Letters ............................................................................................................. 124
Italicizing and Bolding ..................................................................................................................... 124
Capitalizing ....................................................................................................................................... 125
Decorating ........................................................................................................................................ 125
Letter and Word Spacing ................................................................................................................ 127
Formatting Entire Paragraphs .............................................................................................................. 128
Adjusting the Space Between Lines .............................................................................................. 128
Aligning Text ..................................................................................................................................... 130
Indenting the First Line and Removing Margins ......................................................................... 130
Formatting the First Letter or First Line of a Paragraph ............................................................. 132
Styling Lists .............................................................................................................................................. 134
Types of Lists .................................................................................................................................... 134
Positioning Bullets and Numbers .................................................................................................. 135
Graphic Bullets ................................................................................................................................. 137
Tutorial: Text Formatting in Action ...................................................................................................... 138
Setting Up the Page ......................................................................................................................... 138
Formatting the Headings and Paragraphs ................................................................................... 140
Formatting Lists ................................................................................................................................ 143
Fine-Tuning with Classes ................................................................................................................ 144
Adding the Finishing Touches ........................................................................................................ 146

Table of Contents
Download at Boykma.Com

vii

Chapter 7: Margins, Padding, and Borders .......................................... 151
Understanding the Box Model .............................................................................................................. 151
Control Space with Margins and Padding .......................................................................................... 153
Margin and Padding Shorthand .................................................................................................... 155
Colliding Margins ............................................................................................................................. 155
Removing Space with Negative Margins ...................................................................................... 156
Displaying Inline and Block-Level Boxes ...................................................................................... 158
Adding Borders ....................................................................................................................................... 160
Border Property Shorthand ............................................................................................................ 161
Formatting Individual Borders ....................................................................................................... 162
Coloring the Background ...................................................................................................................... 164
Determining Height and Width ............................................................................................................ 164
Calculating a Box’s Actual Width and Height ............................................................................... 165
Controlling the Tap with the Overflow Property ......................................................................... 167
Wrap Content with Floating Elements ................................................................................................. 169
Backgrounds, Borders, and Floats ................................................................................................. 172
Stopping the Float ............................................................................................................................ 172
Tutorial: Margins, Backgrounds, and Borders .................................................................................... 175
Controlling Page Margins and Backgrounds ................................................................................ 175
Adjusting the Space Around Tags .................................................................................................. 178
Building a Sidebar ............................................................................................................................ 181
Fixing the Browser Bugs .................................................................................................................. 184
Going Further ................................................................................................................................... 186

Chapter 8: Adding Graphics to Web Pages .......................................... 187
CSS and the  Tag ......................................................................................................................... 187
Background Images ............................................................................................................................... 188
Controlling Repetition ............................................................................................................................ 193
Positioning a Background Image ......................................................................................................... 194
Keywords .......................................................................................................................................... 194
Precise Values ................................................................................................................................... 196
Percentage Values ............................................................................................................................ 197
Fixing an Image in Place ................................................................................................................. 199
Using Background Property Shorthand .............................................................................................. 199
Tutorial: Enhancing Images .................................................................................................................. 201
Framing an Image ............................................................................................................................ 202
Adding a Caption ............................................................................................................................. 203
Tutorial: Creating a Photo Gallery ....................................................................................................... 206
Adding Drop Shadows .................................................................................................................... 210
Tutorial: Using Background Images ..................................................................................................... 213
Adding an Image to the Page Background ................................................................................... 214
Replacing Borders with Graphics ................................................................................................... 216
Using Graphics for Bulleted Lists ................................................................................................... 218
Giving the Sidebar Personality ....................................................................................................... 219
Going Further ................................................................................................................................... 223

viii

CSS: The Missing Manual
Download at Boykma.Com

Chapter 9: Sprucing Up Your Site’s Navigation.................................... 225
Selecting Which Links to Style .............................................................................................................. 225
Understanding Link States .............................................................................................................. 226
Targeting Particular Links ............................................................................................................... 227
Styling Links ............................................................................................................................................ 228
Underlining Links ............................................................................................................................. 229
Creating a Button ............................................................................................................................. 231
Using Graphics ................................................................................................................................. 233
Building Navigation Bars ....................................................................................................................... 235
Using Unordered Lists ..................................................................................................................... 235
Vertical Navigation Bars .................................................................................................................. 236
Horizontal Navigation Bars ............................................................................................................ 238
Advanced Link Techniques ................................................................................................................... 244
Big Clickable Buttons ....................................................................................................................... 244
CSS-Style Preloading Rollovers ...................................................................................................... 246
Sliding Doors .................................................................................................................................... 248
Styling Particular Types of Links .................................................................................................... 250
Tutorial: Styling Links ............................................................................................................................ 252
Basic Link Formatting ...................................................................................................................... 252
Adding a Background Image to a Link ......................................................................................... 255
Highlighting Different Links ............................................................................................................ 256
Tutorial: Creating a Navigation Bar ..................................................................................................... 258
Adding Rollovers and Creating “You Are Here” Links ................................................................ 262
Fixing the IE Bugs ............................................................................................................................. 265
From Vertical to Horizontal ............................................................................................................ 266

Chapter 10: Formatting Tables
and Forms ......................................................................................... 271
Using Tables the Right Way .................................................................................................................. 271
Styling Tables .......................................................................................................................................... 273
Adding Padding ................................................................................................................................ 274
Adjusting Vertical and Horizontal Alignment ............................................................................... 274
Creating Borders .............................................................................................................................. 276
Styling Rows and Columns ............................................................................................................. 277
Styling Forms .......................................................................................................................................... 279
HTML Form Elements ...................................................................................................................... 280
Laying Out Forms Using CSS ......................................................................................................... 283
Tutorial: Styling a Table ......................................................................................................................... 284
Tutorial: Styling a Form ......................................................................................................................... 290

Table of Contents
Download at Boykma.Com

ix

Part Three: CSS Page Layout
Chapter 11: Introducing CSS Layout .....................................................299
Types of Web Page Layouts .................................................................................................................. 299
How CSS Layout Works ......................................................................................................................... 301
The Mighty 
Tag ...................................................................................................................... 302 Techniques for CSS Layout ............................................................................................................. 303 Layout Strategies .................................................................................................................................... 304 Start with Your Content ................................................................................................................... 304 Mock Up Your Design ..................................................................................................................... 305 Identify the Boxes ............................................................................................................................ 305 Go with the Flow .............................................................................................................................. 306 Remember Background Images .................................................................................................... 306 Pieces of a Puzzle ............................................................................................................................. 308 Layering Elements ............................................................................................................................ 308 Don’t Forget Margins and Padding ............................................................................................... 309 Chapter 12: Building Float-Based Layouts ........................................... 311 Applying Floats to Your Layouts .......................................................................................................... 315 Floating All Columns ....................................................................................................................... 315 Floats Within Floats ......................................................................................................................... 317 Using Negative Margins to Position Elements ............................................................................. 318 Overcoming Float Problems ................................................................................................................. 323 Clearing and Containing Floats ...................................................................................................... 323 Creating Full-Height Columns ........................................................................................................ 328 Preventing Float Drops .................................................................................................................... 330 Handling Internet Explorer 6 Bugs ....................................................................................................... 333 Double-Margin Bug ......................................................................................................................... 333 3-Pixel Gaps ...................................................................................................................................... 335 Other IE Problems ............................................................................................................................ 337 Tutorial: Multiple-Column Layouts ...................................................................................................... 338 Structuring the HTML ...................................................................................................................... 338 Creating the Layout Styles .............................................................................................................. 339 Adding Another Column ................................................................................................................. 340 Adding a “Faux Column” ................................................................................................................ 342 Fixing the Width ............................................................................................................................... 344 Tutorial: Negative Margin Layout ........................................................................................................ 345 Centering a Layout .......................................................................................................................... 345 Floating the Columns ...................................................................................................................... 349 Final Adjustments ............................................................................................................................ 352 x CSS: The Missing Manual Download at Boykma.Com Chapter 13: Positioning Elements on a Web Page............................... 355 How Positioning Properties Work ........................................................................................................ 356 Setting Positioning Values .............................................................................................................. 358 When Absolute Positioning Is Relative ......................................................................................... 360 When (and Where) to Use Relative Positioning .......................................................................... 363 Stacking Elements ............................................................................................................................ 365 Hiding Parts of a Page ..................................................................................................................... 367 Powerful Positioning Strategies ............................................................................................................ 367 Positioning Within an Element ....................................................................................................... 369 Breaking an Element Out of the Box ............................................................................................. 370 Using CSS Positioning for Page Layout ......................................................................................... 371 Creating CSS-Style Frames Using Fixed Positioning ................................................................... 375 Tutorial: Positioning Page Elements .................................................................................................... 380 Enhancing a Page Banner ............................................................................................................... 380 Adding a Caption to a Photo .......................................................................................................... 384 Laying Out the Page ........................................................................................................................ 387 Part Four: Advanced CSS Chapter 14: CSS for the Printed Page ...................................................395 How Media Style Sheets Work ............................................................................................................. 395 How to Add Media Style Sheets ........................................................................................................... 398 Specifying the Media Type for an External Style Sheet .............................................................. 398 Specifying the Media Type Within a Style Sheet ......................................................................... 398 Creating Print Style Sheets .................................................................................................................... 399 Using !important to Override Onscreen Styling .......................................................................... 400 Reworking Text Styles ..................................................................................................................... 400 Styling Backgrounds for Print ........................................................................................................ 402 Hiding Unwanted Page Areas ........................................................................................................ 403 Adding Page Breaks for Printing .................................................................................................... 405 Tutorial: Building a Print Style Sheet ................................................................................................... 406 Remove Unneeded Page Elements ............................................................................................... 406 Adjusting the Layout ....................................................................................................................... 409 Reformatting the Text ...................................................................................................................... 411 Displaying URLs ............................................................................................................................... 412 Chapter 15: Improving Your CSS Habits..........................................................................................415 Adding Comments ................................................................................................................................. 415 Organizing Styles and Style Sheets ...................................................................................................... 416 Name Styles Clearly ........................................................................................................................ 417 Use Multiple Classes to Save Time ................................................................................................ 418 Organize Styles by Grouping ......................................................................................................... 420 Using Multiple Style Sheets ............................................................................................................ 421 Table of Contents Download at Boykma.Com xi Eliminating Browser Style Interference ............................................................................................... 423 Using Descendent Selectors .................................................................................................................. 427 Compartmentalize Your Pages ...................................................................................................... 428 Identify the Body .............................................................................................................................. 429 Managing Internet Explorer Hacks ...................................................................................................... 432 Design for Contemporary Browsers First ..................................................................................... 433 Isolate CSS for IE with Conditional Comments ............................................................................ 433 Chapter 16: CSS 3: CSS on the Edge......................................................437 An Overview of CSS 3 ............................................................................................................................ 438 CSS 3 Selectors ....................................................................................................................................... 439 Child Selectors .................................................................................................................................. 439 Type Selectors .................................................................................................................................. 441 Opacity ..................................................................................................................................................... 443 RGBA Color ............................................................................................................................................. 445 Simulating RGBA in Internet Explorer ........................................................................................... 446 Text Shadow ............................................................................................................................................ 448 Font Freedom ......................................................................................................................................... 450 Generated Content ................................................................................................................................. 452 Part Five: Appendixes Appendix A: CSS Property Reference ...................................................459 Appendix B: CSS in Dreamweaver CS4 ................................................487 Appendix C: CSS Resources ....................................................................517 Index ........................................................................................................525 xii CSS: The Missing Manual Download at Boykma.Com The Missing Credits About the Author David Sawyer McFarland is president of Sawyer McFarland Media, Inc., a Web development and training company in Portland, Oregon. He’s been building Web sites since 1995, when he designed his first website: an online magazine for communication professionals. He’s served as the webmaster at the University of California at Berkeley and the Berkeley Multimedia Research Center, and he has helped build, design, and program websites for numerous clients including Macworld.com. In addition to building websites, David is also a writer, trainer, and instructor. He’s taught web design at the UC Berkeley Graduate School of Journalism, the Center for Electronic Art, the Academy of Art College, Ex’Pressions Center for New Media, and the Art Institute of Portland. He currently teaches in the Multimedia Program at Portland State University. He’s written articles about web design for Practical Web Design, Macworld magazine and CreativePro.com. David is also the author of Dreamweaver: The Missing Manual, and JavaScript: The Missing Manual. He welcomes feedback about this book by email: missing@sawmac.com. (If you’re seeking technical help, however, please refer to the sources listed in Appendix C.) About the Creative Team Nan Barber (editor) has worked with the Missing Manual series since the previous millennium. She lives in Massachusetts with her husband and G4 Macintosh. Email: nanbarber@oreilly.com. Nellie McKesson (production editor) lives in Brighton, Mass., where she spends her free time playing with her band Dr. & Mrs. Van der Trampp (http://myspace. com/drmrsvandertrampp) and making t-shirts for her friends (http:// mattsaundersbynellie.etsy.com). Email: nellie@oreilly.com. Marcia Simmons (copy editor) is a writer and editor living in the San Francisco Bay Area. In addition to covering technology and cocktail culture, she has a personal blog at www.smartkitty.org. Angela Howard (indexer) has been indexing for over 10 years, mostly for computer books, but occasionally for books on other topics such as travel, alternative medicine, and leopard geckos. She lives in California with her husband, daughter, and two cats. xiii CSS: TheDownload Missing Manual, eMatter Edition at Boykma.Com Copyright © 2009 O’Reilly & Associates, Inc. All rights reserved. Tony Ruscoe (technical reviewer) is a web developer living in Sheffield, England. His first computer programs were written in Sinclair BASIC on his ZX Spectrum in the mid-1980s. He’s been developing websites and web applications using a variety of programming technologies and techniques since 1997. He currently maintains his personal website (http://ruscoe.net) and a site dedicated to researching his surname (http://ruscoe.name). Christopher Schmitt (technical reviewer) is author of numerous web design and digital imaging books, including the CSS Cookbook and has also written for New Architect magazine, and the websites A List Apart, Digital Web, and Web Reference. Christopher is the founder of Heat Vision, a small new media publishing and design firm and an award-winning web designer. He is co-lead of the Adobe Task Force for the Web Standards Project (WaSP). In addition, he chairs AIGA’s In Control Web Design Workshop Conference. Web: www.christopherschmitt.com. Acknowledgements Many thanks to all those who helped with this book, including my students, who always help me see complex concepts through beginners’ eyes. Thanks to my technical editors, Christopher Schmitt and Tony Ruscoe, who saved me from any embarrassing mistakes, and Zoe Gillenwater whose valuable advice for the first edition of this book lives on. Also, we all owe a big debt of gratitude to the many web designers who have broken new ground by using CSS in creative ways, and shared their discoveries with the web design community. Finally, thanks to David Pogue whose unflagging enthusiasm and endurance is inspiring; Nan Barber for refining my writing, fixing my mistakes and keeping me on track; my wife, Scholle, for her love and support; my son, Graham, who suggested that I’d get this book done a lot faster if I just typed “Blah, blah, blah, blah, BOO!” for each chapter; my wonderful daughter, Kate, whose smile is always a great pick-me-up; and to my family: Mom, Doug, Mary, David, Marisa, Tessa, Phyllis, Les, Del, Patricia, and Mike. —David Sawyer McFarland xiv CSS: The Missing Manual CSS: TheDownload Missing Manual, eMatter Edition at Boykma.Com Copyright © 2009 O’Reilly & Associates, Inc. All rights reserved. The Missing Manual Series Missing Manuals are witty, superbly written guides to computer products that don’t come with printed manuals (which is just about all of them). Each book features a handcrafted index; cross-references to specific pages (not just chapters); and RepKover, a detached-spine binding that lets the book lie perfectly flat without the assistance of weights or cinder blocks. Recent and upcoming titles include: Access 2007: The Missing Manual by Matthew MacDonald AppleScript: The Missing Manual by Adam Goldstein AppleWorks 6: The Missing Manual by Jim Elferdink and David Reynolds Creating a Web Site: The Missing Manual by Matthew MacDonald David Pogue’s Digital Photography: The Missing Manual by David Pogue Dreamweaver 8: The Missing Manual by David Sawyer McFarland Dreamweaver CS3: The Missing Manual by David Sawyer McFarland Dreamweaver CS4: The Missing Manual by David Sawyer McFarland eBay: The Missing Manual by Nancy Conner Excel 2003: The Missing Manual by Matthew MacDonald Excel 2007: The Missing Manual by Matthew MacDonald Facebook: The Missing Manual by E.A. Vander Veer Google SketchUp: The Missing Manual by Chris Grover FileMaker Pro 9: The Missing Manual by Geoff Coffey and Susan Prosser FileMaker Pro 10: The Missing Manual by Susan Prosser and Geoff Coffey Flash 8: The Missing Manual by E.A. Vander Veer Flash CS3: The Missing Manual by E.A. Vander Veer and Chris Grover Flash CS4: The Missing Manual by Chris Grover with E.A. Vander Veer FrontPage 2003: The Missing Manual by Jessica Mantaro Google Apps: The Missing Manual by Nancy Conner The Internet: The Missing Manual by David Pogue and J.D. Biersdorfer iMovie 6 & iDVD: The Missing Manual by David Pogue iMovie ’08 & iDVD: The Missing Manual by David Pogue iMovie ’09 & iDVD: The Missing Manual by David Pogue and Aaron Miller The Missing Credits CSS: TheDownload Missing Manual, eMatter Edition at Boykma.Com Copyright © 2009 O’Reilly & Associates, Inc. All rights reserved. xv iPhone: The Missing Manual, Second Edition by David Pogue iPhoto ’08: The Missing Manual by David Pogue iPhoto ’09: The Missing Manual by David Pogue and J.D. Biersdorfer iPod: The Missing Manual, Seventh Edition by J.D. Biersdorfer and David Pogue JavaScript: The Missing Manual by David Sawyer McFarland Living Green: The Missing Manual by Nancy Conner Mac OS X: The Missing Manual, Tiger Edition by David Pogue Mac OS X: The Missing Manual, Leopard Edition by David Pogue Microsoft Project 2007: The Missing Manual by Bonnie Biafore Netbooks: The Missing Manual by J.D. Biersdorfer Office 2004 for Macintosh: The Missing Manual by Mark H. Walker and Franklin Tessler Office 2007: The Missing Manual by Chris Grover, Matthew MacDonald, and E.A. Vander Veer Office 2008 for Macintosh: The Missing Manual by Jim Elferdink Palm Pre: The Missing Manual by Ed Baig PCs: The Missing Manual by Andy Rathbone Photoshop Elements 7: The Missing Manual by Barbara Brundage Photoshop Elements 6 for Mac: The Missing Manual by Barbara Brundage PowerPoint 2007: The Missing Manual by E.A. Vander Veer QuickBase: The Missing Manual by Nancy Conner QuickBooks 2009: The Missing Manual by Bonnie Biafore QuickBooks 2010: The Missing Manual by Bonnie Biafore Quicken 2008: The Missing Manual by Bonnie Biafore Quicken 2009: The Missing Manual by Bonnie Biafore Switching to the Mac: The Missing Manual, Tiger Edition by David Pogue and Adam Goldstein Switching to the Mac: The Missing Manual, Leopard Edition by David Pogue Wikipedia: The Missing Manual by John Broughton Windows XP Home Edition: The Missing Manual, Second Edition by David Pogue xvi CSS: The Missing Manual CSS: TheDownload Missing Manual, eMatter Edition at Boykma.Com Copyright © 2009 O’Reilly & Associates, Inc. All rights reserved. Windows XP Pro: The Missing Manual, Second Edition by David Pogue, Craig Zacker, and Linda Zacker Windows Vista: The Missing Manual by David Pogue Windows Vista for Starters: The Missing Manual by David Pogue Word 2007: The Missing Manual by Chris Grover Your Body: The Missing Manual by Matthew MacDonald Your Brain: The Missing Manual by Matthew MacDonald The Missing Credits CSS: TheDownload Missing Manual, eMatter Edition at Boykma.Com Copyright © 2009 O’Reilly & Associates, Inc. All rights reserved. xvii CSS: TheDownload Missing Manual, eMatter Edition at Boykma.Com Copyright © 2009 O’Reilly & Associates, Inc. All rights reserved. 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. 1 Download at Boykma.Com Introduction 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 (

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 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 tag, for example). (For a list of other obsolete tags, see www.codehelp.co.uk/ html/deprecated.html.) 2 CSS: The Missing Manual Download at Boykma.Com Introduction 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—,

,

, , 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: Hey, I am the title of this web page

Hey, I am a paragraph on this web page.

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 . 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. Introduction Download at Boykma.Com 3 Introduction 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 page 26, having a doctype is an important requirement to make sure your CSS designs work in all browsers. • The 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 tags. If you were to think of a web page as a tree, the 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 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 tags, contains all the content that appears inside a browser window—headlines, text, pictures, and so on. Within the tag, you commonly find tags like these: • You tell a web browser where a paragraph of text begins with a

(opening paragraph tag), and where it ends with a

(closing paragraph tag). • The tag emphasizes text. When you surround some text with it and its partner tag, , you get boldface type. The HTML snippet Warning! tells a web browser to strongly emphasize the word “Warning!” 4 CSS: The Missing Manual Download at Boykma.Com Introduction • The 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 tags. For instance, you can type Click here!. 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 ( and are both correct, for example), and permits unclosed tags (so you can use a single

tag without the closing

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 (page 26), or your CSS will fall apart in certain browsers. Also, you must validate your page (page 24) 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. Introduction Download at Boykma.Com 5 Introduction 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 page 3 would look like this in XHTML: Hey, I am the title of this web page.

Hey, I am some body text on this web page.

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 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: is valid in HTML, but won’t work in XHTML. You have to enclose the value of the href property in double quotes: . • All tags (even empty tags) must be closed. To create a paragraph in XHTML, for example, you must begin with

and end with

. 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:
. 6 CSS: The Missing Manual Download at Boykma.Com Introduction 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. Introduction Download at Boykma.Com 7 Introduction • 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. 8 CSS: The Missing Manual Download at Boykma.Com Introduction 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 page 39. The primary discussions in these chapters are written for advancedbeginners 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. UP TO SPEED The Different Flavors of CSS Like operating systems and iPods, CSS spins off new versions continuously (well, not as frequently as iPod models). CSS 1, introduced in 1996, laid the groundwork for Cascading Style Sheets. The basic structure of a style, the selector concept (Chapter 3), and most of the CSS properties in this book were all in that very first version. CSS 2 added new features, including the ability to target your CSS to different printers, monitors, and other devices (page 395). CSS 2 also added new selectors and the ability to precisely position elements on a web page. This book completely covers CSS 2.1, which is the current accepted standard. It incorporates all of CSS 1, adds several new properties, and corrects a few problems with the CSS 2 guidelines. CSS 2.1 isn’t a radical change from version 2, and most web browsers have adapted to the new rules just fine, thank you. (A notable exception is Internet Explorer 6 for Windows—that’s why you’ll find helpful workarounds for dealing with browser differences sprinkled throughout this book. Thankfully, Internet Explorer 7 fixed most of the hairpulling bugs of its predecessor, and Internet Explorer 8 finally follows almost all CSS 2.1 rules correctly.) CSS 3 is just around the corner. Although the W3C still has to finalize this standard, some web browsers are already adopting a few of its new guidelines and features. Safari’s ability to add multiple images to the background of a single element, for example, is thanks to CSS 3. In fact, enough CSS 3 is trickling into current web browsers that, there’s a whole chapter dedicated to the subject (Chapter 16). One good resource for following the constant evolution of CSS 3 is the CSS3.info site (www.css3.info). 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. Introduction Download at Boykma.Com 9 Introduction 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. 10 CSS: The Missing Manual Download at Boykma.Com Introduction 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 popup 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 c-click something on the Mac, or Ctrl-click something on a PC, you click while pressing the c 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 a menu (Mac), as well as the Control Panel (Windows) or System Preferences (Mac OS X). Introduction Download at Boykma.Com 11 Introduction • 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 (c-S) (which saves changes to the current document), it’s telling you to hold down the Ctrl or c 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 I-1. 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. 12 CSS: The Missing Manual Download at Boykma.Com Introduction 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. Introduction Download at Boykma.Com 13 Download at Boykma.Com 1 Part One: CSS Basics I. Chapter 1: Rethinking HTML for CSS Chapter 2: Creating Styles and Style Sheets Chapter 3: Selectors: Identifying What to Style Chapter 4: Saving Time with Style Inheritance Chapter 5: Managing Multiple Styles: The Cascade Download at Boykma.Com Download at Boykma.Com chapter Chapter 1 1 Rethinking HTML for CSS To get the most out of CSS, your HTML code needs to provide a solid, well-built foundation. This chapter 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 no longer need to worry about trying 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 As discussed in the Introduction, HTML (or XHTML) provides the foundation for every page you encounter on the World Wide Web. When you add CSS into the mix, the way you use HTML changes. Say goodbye to repurposing awkward HTML tags merely to achieve certain visual effects. Some HTML tags and attributes—like the tag—you can forget completely. Note: Throughout this chapter, everything you read about HTML applies equally to XHTML. There are almost as many variants of HTML and XHTML as there are colors in the rainbow, though, and in the end you must pick a type and make sure your web page identifies which one you’re using. Otherwise, your visitors’ browsers may gunk up your painstakingly crafted page. You’ll learn how to tell CSS which flavor of HTML/ XHTML you’re using later in this chapter. 17 Download at Boykma.Com HTML: Past and Present 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 4 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. HTML Past: Whatever Looked Good When a bunch of scientists created the Web to help share and keep track of technical documentation, nobody called in the graphic designers. All the scientists needed HTML to do was structure information for easy comprehension. For example, the

tag indicates an important headline, while the

tag represents a lesser heading, usually a subheading of the

tag. Another favorite, the
    (ordered list) tag, creates a numbered list for things like “Top 10 reasons not to play with jellyfish.” 18 CSS: The Missing Manual Download at Boykma.Com HTML: Past and Present But as soon as people besides 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
    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

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
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 tag, for example, lets 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 above 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 (and more wrinkles to your forehead than a lifetime in the sun). 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 parttimer’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—structure content. Using HTML to control the look of text and other web page elements is obsolete. Don’t worry if HTML’s

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. Chapter 1: Rethinking HTML for CSS Download at Boykma.Com 19 Writing HTML for CSS 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 HTML-writing habits that you’re better off forgetting. The rest of this chapter introduces you to some HTML writing habits that will make your mother 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 that text plays on the page: For example, the

tag is the most important introduction to a page’s content. Other headers let you divide the content into other, less important, but related sections. Just like the book you’re holding, for example, a web page should have a logical structure. Each chapter in this book has a title (think

) and several sections (think

), which in turn contain smaller subsections. Imagine how much harder it would be to read these pages if every word just ran together as one long paragraph. Note: For a good resource on HTML/XHTML check out HTML & XHTML: The Definitive Guide by Chuck Musciano and Bill Kennedy (O’Reilly), or visit www.w3schools.com for online HTML and XHTML tutorials. For a quick list of all available HTML and XHTML tags, visit www.w3schools.com/tags/. HTML provides many other tags besides headers for marking up content to identify its role on the page. (After all, the M in HTML stands for markup.) Among the most popular are the

tag for paragraphs of text and the

tag for page layout. Use it only to display tabular information like spreadsheets, schedules, and charts. As you’ll see in Part 3 of this book, you can do all your layout with CSS for much less time and code than the table-tag tango. • Eliminate the awkward tag attributes that enhance only the presentation of the content: background, bgcolor, text, link, alink, and vlink set colors and images for the page, text, and links. CSS gets the job done better (see Chapter 7 and Chapter 8 for CSS equivalents of these attributes). Also trash the browser-specific attributes used to set margins for a page: leftmargin, topmargin, marginwidth, marginheight. CSS handles page margins easily (see Chapter 7). • Don’t abuse the
tag. If you grew up using the
tag (
in XHTML) 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

tags. In the past, designers used elaborate workarounds to avoid paragraph spacing they didn’t want, like replacing a single

tag with a bunch of line breaks and using a 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. Note: In the next chapter, you’ll learn about a technique called a “CSS Reset” which eliminates the gaps browsers normally insert between paragraphs and other tags (see page 102). 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 (see page 130), borders (page 160), backgrounds (page 164), and image alignment (page 187). Tips to Guide Your Way It’s always good to have a map for getting 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 only one

tag per page, and use it to identify the main topic of the page. Think of it as a chapter title: You only put one title per chapter. Using

correctly has the added benefit of helping the page get properly indexed by search engines (see the box on page 21). Chapter 1: Rethinking HTML for CSS Download at Boykma.Com 23 Writing HTML for CSS UP TO SPEED Validate Your Web Pages HTML follows certain rules: For example, the tag wraps around the other tags on a page, and the tag needs to appear within the <head> tag. XHTML provides an even more strict set of rules to follow. It’s easy to forget these rules or simply make a typo. Incorrect (or invalid, as the geeks would say) HTML causes problems like making your page look different in different web browsers. More importantly, you can’t create valid CSS with invalid HTML. Fortunately, there are tools for checking whether the HTML in your web pages is correctly written. The easiest way to check—that is, validate—your pages is on the W3C’s website at http://validator.w3.org/ (see Figure 1-3). Get the Web Developer extension for Firefox (http://chrispederick.com/work/web-developer); it provides a quick way to test a page in the W3C validator. The W3C, or World Wide Web Consortium, is the organization responsible for determining the standards for many of the technologies and languages of the Web, including HTML, XHTML, and XML. If the W3C validator finds any errors in your page, it tells you what those errors are. If you use Firefox, you can download an extension that lets you validate a web page directly in that browser, without having to visit the W3C site. It can even attempt to fix any problems it encounters. You can get the extension here: http://users.skynet.be/mgueury/ mozilla/. A similar tool is available for the Safari browser as well: www.zappatic.net/safaritidy/. Figure 1-3: The W3C HTML validator located at http://validator.w3.org 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 type or paste the HTML of a web page into a form box and then click the Check button. 24 CSS: The Missing Manual Download at Boykma.Com Writing HTML for CSS • 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-4). 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. Figure 1-4: 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.” <h1> <h2> <h3> <h3> • Use the <p> tag for paragraphs of text. • Use unordered lists 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 to indicate steps in a process or define the order of a set of items. The tutorials in this book (see page 143) 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 www.w3schools.com/tags/tryit.asp?filename=tryhtml_list_definition.) • 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 for one-liners. • 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). Chapter 1: Rethinking HTML for CSS Download at Boykma.Com 25 The Importance of the Doctype • As explained in full on page 22, steer clear of any tag or attribute aimed just at changing the appearance of a text or image. CSS, as you’ll see, can do it all. • When there just 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 page 26). You’ll get more advice on how to use these in later chapters (for example, page 312). • 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. • 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> (<br /> and <img /> in XHTML). • Validate your pages with the W3C validator (see Figure 1-3 and the box on page 24). Poorly written or typo-ridden HTML causes many weird browser errors. The Importance of the Doctype As discussed in the box on page 24, HTML follows certain rules—these rules are contained in a Document Type Definition file, otherwise known as a DTD. A DTD is an XML document that explains what tags, attributes, and values are valid for a particular type of HTML. And for each version of HTML, there’s a corresponding DTD. By now you may be asking, “But what’s all this got to do with CSS?” Everything—if you want your web pages to appear correctly and consistently in web browsers. You tell a web browser which version of HTML or XHTML you’re using 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 not only defines what version of HTML you’re using (such as HTML 4.01 Transitional) but also points to the appropriate DTD file on the Web. When you mistype the doctype declaration, 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. 26 CSS: The Missing Manual Download at Boykma.Com The Importance of the Doctype Note: For more (read: technical) information on quirks mode, visit www.quirksmode.org/css/ quirksmode.html and http://hsivonen.iki.fi/doctype/. Fortunately, it’s easy to get the doctype correct. All you need to know is what version of HTML you’re using. In all likelihood, you’re already creating web pages using HTML 4. You may even use XHTML for your websites (see page 5). The most popular versions of HTML and XHTML these days are HTML 4.01 Transitional and XHTML 1.0 Transitional. These types of HTML still let you use presentational tags like the <font> tag, thereby providing a transition from older HTML to the newer, stricter types of HTML and XHTML. Although it’s best not to use these tags at all, they still work in the Transitional versions, so you can phase out these older tags at your own pace. In the strict versions of HTML and XHTML, some older tags don’t work at all. Note: In general, the strict versions of both HTML and XHTML disallow tags and attributes aimed at making a page look good, like the <font> tag and a paragraph’s center attribute. They also disallow a number of once-popular properties like a link’s target property, which lets you make a link open in a new window. If you’re using HTML 4.01 Transitional, 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. w3.org/TR/html4/loose.dtd"> The doctype declaration for XHTML 1.0 Transitional is similar, but it points to a different DTD. 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. w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> Note: If you’re using frames for your web pages, then you need to use a doctype intended for framesets. See the W3C site for a list of proper doctypes: www.w3.org/QA/2002/04/valid-dtd-list.html. If this entire discussion is making your head ache and your eyes slowly shut, just make sure you use the proper doctype listed above, and always make it the first line of your HTML file (before even the opening <html> tag). Also it’s easy to make a typo in this long-winded bit of code, so always make sure you validate the page (see the box on page 36) to make sure your doctype is correct. In fact, it’s a good idea to have a blank HTML page with the proper doctype somewhere on your computer, so you can make a copy of it whenever you need to create a new web page. In the tutorial files available from www.sawmac.com/css2e, you’ll find four basic HTML files— one for each of the four main doctypes in use on the Web today. Chapter 1: Rethinking HTML for CSS Download at Boykma.Com 27 Getting the Most out of Internet Explorer 8 Note: Most visual web page tools like Dreamweaver and Expression Web automatically add a doctype declaration whenever you create a new web page, and many HTML-savvy text editors have shortcuts for adding doctypes. Getting the Most out of Internet Explorer 8 Thanks to Microsoft’s auto-update feature, the new Internet Explorer 8 has gained a healthy share of the browser market. Fortunately for web designers, IE 8 is the most standards-compliant version of the browser yet. It fixes the bugs that have plagued IE 6 and even IE 7, and works almost perfectly with version 2.1 of CSS. That means your carefully crafted web designs should look nearly the same in IE 8, Firefox, Safari, and Opera with little or no tinkering. As you’ll read later in this book (for example, pages 184 and 223), you can’t say the same about IE 6 or IE 7, which require some browser-specific code to make many designs look right. However, IE 8 is sort of like a chameleon: It can take on the appearance of a different version. If you’re not careful, it may not display your web pages the way you want it to. For example, and most importantly, you must include a proper doctype. As mentioned in the previous section, without a doctype, browsers switch into quirks mode. Well, when IE 8 goes into quirks mode, it tries to replicate the look of IE 5 (!?). But wait—there’s more! IE 8 can also pretend to be IE 7. When someone viewing your site in IE 8 clicks a “compatibility view” button, IE 8 goes into IE 7 mode, displaying pages without IE 8’s full CSS 2.1 goodness. The same thing happens if Microsoft puts your website onto its Compatibility View List—a list of sites that Microsoft has determined look better in IE 7 than in IE 8. If you’re designing a site using the guidelines in this book, you won’t want IE 8 to act like IE 7…ever. Fortunately, there’s a way to tell IE 8 to stop all this nonsense and just be IE 8. Adding a single META tag to a web page instructs IE 8 to ignore Compatibility View and the Compatibility View List and always display the page using its most standards-compliant mode: <meta http-equiv="X-UA-Compatible" content="IE=edge" /> Put this instruction in the page’s <head> section (below the <title> tag is a good place). This tag will work for future versions of IE, too: The “IE=edge” part of the tag will instruct versions of Internet Explorer that are released after IE 8 to also display web pages in their standard mode. Unfortunately, you must do this on every page of your site. Now that your HTML ship is steering in the right direction, it’s time to jump into the fun stuff (and the reason you bought this book): Cascading Style Sheets. 28 CSS: The Missing Manual Download at Boykma.Com Getting the Most out of Internet Explorer 8 UP TO SPEED Cross Browser Testing There are a lot of web browsers out there. If you use Windows, you automatically get Internet Explorer and can install additional browsers like Firefox, Safari, Opera, or Google’s Chrome. On a Mac, you can stick with the alreadyinstalled Safari browser, or run Firefox 3 or Chrome 1. While the very latest browsers are mostly comparable when displaying CSS-driven web pages, you can’t say the same for IE 6, which is still in widespread use. Even IE 7 has its share of peculiarities. To really make sure your sites work for the largest audience, you need a way to test your designs in as wide a range of browsers as possible. Here are a few techniques: Windows. Normally, Windows computers can only run one version of IE. In other words, you can’t test in IE 6, IE 7, and IE 8 on the same computer. Well, normally you can’t, but thanks to a nifty little program named IETester, you can actually see what a web page looks like in IE 5.5, IE 6, IE 7, and IE 8, all running side-by-side at the same time. Download this great program from www.my-debugbar.com/ wiki/IETester/HomePage. You should also install the other major browsers on your computer: Firefox, Safari, Opera, and Chrome. Fortunately, you don’t necessarily need a Mac for testing, since Apple’s browser—Safari—is also available for Windows. Mac. Testing is a bit trickier for Mac people. You have to test in Internet Explorer—it’s still the most used browser in the world, and the display problems in IE 6 and IE 7 mean that your painstakingly crafted design might look great for you, but fall apart in IE. You have a few options: First, you can buy (or borrow) a Windows machine; second, if you have an Intel Mac you can install Windows using Apple’s Boot Camp software (www.apple.com/macosx/features/ bootcamp.html); a third option is to install virtualization software like VMWare Fusion or Parallels Desktop on your Mac. This software lets you run a virtual Windows machine, side-by-side with the Mac OS. You can jump between Mac and Windows to test in various browsers in both operating systems. It’s the most efficient testing technique for Mac users. Both Boot Camp and virtualization software require a copy of the Windows OS. Everyone. Another option that works for both Windows and Macs and doesn’t require installing extra software is one of the many cross-browser testing services that let see what your pages look like in many different operating systems and browsers. Most of these are commercial services that cost money. Litmus (http://litmusapp.com/) takes screenshots of your pages in a ton of different browsers; CrossBrowserTesting.com (www.crossbrowsertesting.com) lets you remotely view another computer—in other words, you can actually interact with a Windows machine, running Internet Explorer 8, 7, and 6, plus Firefox and Safari. This scheme not only lets you test the visual design, but also lets you interact with the page and test how your JavaScript programming works in that browser. One of the original services, Browsercam (www.browsercam.com), offers a wide range of services including both screenshots (like Litmus) and remote access to real computers (like CrossBrowserTesting). Chapter 1: Rethinking HTML for CSS Download at Boykma.Com 29 Download at Boykma.Com chapter Chapter 2 2 Creating Styles and Style Sheets Even the most complex and beautiful websites, like the one in Figure 2-1, start with a single CSS style. As you add multiple styles and style sheets, you can develop fully formed websites that inspire designers and amaze visitors. Whether you’re a CSS novice or a Style Sheet Samurai, you need to obey a few basic rules about how to create styles and style sheets. In this chapter you’ll start at square one, learning the basics of creating and using styles and style sheets. Tip: Some people learn better by doing rather than reading. If you’d like to try your hand at creating styles and style sheets first and then come back here to read up on what you just did, then turn to page 39 for a hands-on tutorial. Anatomy of a Style A single style defining the look of one element on a page is a pretty basic beast. It’s essentially just a rule that tells a web browser how to format something on a web page—turn a headline blue, draw a red border around a photo, or create a 150pixel-wide sidebar box to hold a list of links. If a style could talk it would say something like, “Hey Browser, make this look like that.” A style is, in fact, made up of two elements: the web page element that the browser formats (the selector) and the actual formatting instructions (the declaration block). For example, a selector can be a headline, a paragraph of text, a photo, and so on. Declaration blocks can turn that text blue, add a red border around a paragraph, position the photo in the center of the page—the possibilities are endless. 31 Download at Boykma.Com Anatomy of a Style Figure 2-1: Every CSS-driven web page starts with a single CSS style. Here, a basic style (left) sets the groundwork for the body of the entire page (right). Note: Technical types often follow the lead of the W3C and call CSS styles rules. This book uses the terms “style” and “rule” interchangeably. Of course, CSS styles can’t communicate in nice clear English like the previous paragraph. They have their own language. For example, to set a standard font color and font size for all paragraphs on a web page, you’d write the following: p { color: red; font-size: 1.5em; } This style simply says, “Make the text in all paragraphs—marked with <p> tags— red and 1.5 ems tall.” (An em is a unit of measurement that’s based on a browser’s normal text size. More on that in Chapter 6.) As Figure 2-2 illustrates, even a simple style like this example contains several elements: • Selector. As described earlier, the selector tells a web browser which element or elements on a page to style—like a headline, paragraph, image, or link. In Figure 2-2, the selector (p) refers to the <p> tag. This selector makes web browsers format all <p> tags using the formatting directions in this style. With the wide range of selectors that CSS offers and a little creativity, you’ll master your pages’ formatting. (The next chapter covers selectors in depth.) 32 CSS: The Missing Manual Download at Boykma.Com Anatomy of a Style • Declaration Block. The code following the selector includes all the formatting options you want to apply to the selector. The block begins with an opening brace ({) and ends with a closing brace (}). • Declaration. Between the opening and closing braces of a declaration block, you add one or more declarations, or formatting instructions. Every declaration has two parts, a property and a value, and ends with a semicolon. • Property. CSS offers a wide range of formatting options, called properties. A property is a word—or a few hyphenated words—indicating a certain style effect. Most properties have straightforward names like font-size, margin-top, and text-align. For example, the background-color property sets—you guessed it—a background color. You’ll learn about oodles of CSS properties throughout this book. Tip: Appendix A has a handy glossary of CSS properties. • Value. Finally, you get to express your creative genius by assigning a value to a CSS property—by making a background blue, red, purple, or chartreuse, for example. As upcoming chapters explain, different CSS properties require specific types of values—a color (like red, or #FF0000), a length (like 18px, 200%, or 5em), an URL (like images/background.gif), or a specific keyword (like top, center, or bottom). Selector p Declaration block Declaration Declaration { color:red; Property Value font-size:1.5em; } Property Value Figure 2-2: A style (or rule) is made of two main parts: a selector, which tells web browsers what to format, and a declaration block, which lists the formatting instructions that the browsers use to style the selector. You don’t need to write a style on a single line, as pictured in Figure 2-2. Many styles have multiple formatting properties, so you can make them easier to read by breaking them up into multiple lines. For example, you may want to put the selector and opening brace on the first line, each declaration on its own line, and the closing brace by itself on the last line, like so: p { color: red; font-size: 1.5em; } Chapter 2: Creating Styles and Style Sheets Download at Boykma.Com 33 Understanding Style Sheets Web browsers ignore spaces and tabs, so feel free to add them to make your CSS more readable. For example, it’s helpful to indent properties, with either a tab or a couple of spaces, to visibly separate the selector from the declarations, making it easy to tell which is which. In addition, putting one space between the colon and the property value is optional but adds to the readability of the style. In fact, you can put as much white space between the two as you want. For example, color:red, color: red, and color: red all work. Note: Don’t forget to end each property/value pair with a semicolon: color: red; Leaving off that semicolon can trip up browsers, breaking your style sheet and ruining the look of your web page. Don’t worry, this mistake is very common—just make sure you use a CSS validator, as described in the box on the next page. Understanding Style Sheets Of course, a single style won’t transform a web page into a work of art. It may make your paragraphs red, but to infuse your websites with great design, you need many different styles. A collection of CSS styles comprises a style sheet. A style sheet can be one of two types—internal or external, depending on whether the style information is located in the web page itself or in a separate file linked to the web page. Internal or External—How to Choose Most of the time, external style sheets are the way to go, since they make building web pages easier and updating websites faster. An external style sheet collects all your style information in a single file that you then link to a web page with just a single line of code. You can attach the same external style sheet to every page in your website, providing a unified design. It also makes a complete site makeover as easy as editing a single text file. On the receiving end, external style sheets help web pages load faster. When you use an external style sheet, your web pages can contain only basic HTML—no byte-hogging HTML tables or <font> tags and no internal CSS style code. Furthermore, when a web browser downloads an external style sheet, it stores the file on your visitor’s computer (in a behind-the-scenes folder called a cache) for quick access. When your visitor hops to other pages on the site that use the same external style sheet, there’s no need for the browser to download the style sheet again. The browser simply downloads the requested HTML file and pulls the external style sheet from its cache—a significant savings in download time. Note: When you’re working on your website and previewing it in a browser, the cache can work against you. See the box on page 35 for a workaround. 34 CSS: The Missing Manual Download at Boykma.Com Internal Style Sheets WORKAROUND WORKSHOP Don’t Get Caught in the Cache A browser’s cache is a great speed-boost for Web surfers. Whenever the cache downloads and stores a frequently used file—like an external CSS file or an image—it saves precious moments traveling the relatively sluggish highways of the Internet. Instead of re-downloading the next time it needs the same file, the browser can go straight to the new stuff—like a yet-to-be-viewed page or graphic. But what’s good for your visitors isn’t always good for you. Because the web browser caches and recalls downloaded external CSS files, you can often get tripped up as you work on a site design. Say you’re working on a page that uses an external style sheet, and you preview the page in a browser. Something doesn’t look quite right, so you return to your web editor and change the external CSS file. When you return to the web browser and reload the page, the change you just made doesn’t appear! You’ve just been caught by the cache. When you reload a web page, browsers don’t always reload the external style sheet, so you may not be seeing the latest and greatest version of your styles. To get around this snafu, you can force reload a page (which also reloads all linked files) by pressing the Ctrl (c) key and clicking the browser’s Reload button; Ctrl+F5 also works on Windows for Internet Explorer; and Ctrl+Shift+R (c-Shift-R) is Firefox’s keyboard shortcut. Internal Style Sheets An internal style sheet is a collection of styles that’s part of the web page’s code. It always appears between opening and closing HTML <style> tags in the page’s <head> portion. Here’s an example: <style type="text/css"> h1 { color: #FF7643; font-family: Arial; } p { color: red; font-size: 1.5em; } </style> </head> <body> <!-- The rest of your page follows... --> Note: You can place the <style> tag and its styles after the <title> tag in the head of the page, but web designers usually place them right before the closing </head> tag as shown here. If you also use JavaScript in your pages, add the JavaScript code after the style sheet. Many JavaScript programs rely on CSS, so by adding your CSS first, you can make sure the JavaScript program has all the information it needs to get its job done. Chapter 2: Creating Styles and Style Sheets Download at Boykma.Com 35 External Style Sheets The <style> tag is HTML, not CSS. But its job is to tell the web browser that the information contained within the tags is CSS code and not HTML. Creating an internal style sheet is as simple as typing one or more styles between the <style> tags. Internal style sheets are easy to add to a web page and provide an immediate visual boost to your HTML. But they aren’t the most efficient method for designing an entire website composed of many web pages. For one thing, you need to copy and paste the internal style sheet into each page of your site—a time-consuming chore that adds bandwidth-hogging code to each page. But internal style sheets are even more of a hassle when you want to update the look of a site. For example, say you want to change the <h1> tag, which you originally decided should appear as large, green, bold type. But now you want small, blue type in the Courier typeface. Using internal style sheets, you’d need to edit every page. Who has that kind of time? Fortunately, there’s a simple solution to this dilemma—external style sheets. Note: It’s also possible (though rarely advisable) to add styling information to an individual HTML tag without using a style sheet. The tutorial on page 39 shows you how to perform that maneuver using an inline style. External Style Sheets An external style sheet is nothing more than a text file containing all your CSS rules. It never contains any HTML code—so don’t include the <style> tag. In addition, always end the file name with the extension .css. You can name the file whatever you like, but it pays to be descriptive. Use global.css, site.css, or main.css, for example, to indicate a style sheet used by every page on the site, or use form.css to name a file containing styles used to make a web form look good. UP TO SPEED Validate Your CSS Just as you should make sure you’ve correctly written the HTML in your web pages using the W3C HTML validator (see the box on page 24), you should also check your CSS code to make sure it’s kosher. The W3C provides an online tool for CSS checking as well: http://jigsaw.w3.org/cssvalidator/. It operates just like the HTML validator: You can type the URL of a web page (or even just the address to an external CSS file), upload a CSS file, or copy and paste CSS code into a web form and submit it for validation. 36 It’s easy to make a typo when writing CSS, and one small mistake can throw all of your carefully planned designs out of whack. When your CSS-infused web page doesn’t look as you expect, a simple CSS error may be the cause. The W3C CSS validator is a good first stop when troubleshooting your designs. You can also do a quick check using Firefox. Load the page that has the CSS you want to check and choose Tools ➝ Error Console. Click the Warnings button, and you’ll see listed any CSS code that Firefox doesn’t understand. CSS: The Missing Manual Download at Boykma.Com External Style Sheets Tip: If you have a page with an internal style sheet but want to use an external style sheet, then just cut all of the code between the <style> tags (without the tags themselves). Then create a new text file and paste the CSS into the file. Save the file with a .css extension—global.css, for example—and link it to your page, using one of the techniques described next. Once you create an external style sheet, you must connect it to the web page you wish to format. You can attach a style sheet to a web page using HTML’s <link> tag or CSS’s own @import directive—a command that basically does the same thing as the link tag. All current web browsers treat these two techniques the same, and both let you attach style sheets to a web page, so choosing one is mostly a matter of preference. Note: The @import directive can do one thing the <link> tag can’t: attach external style sheets to an external style sheet. This advanced technique is discussed on page 38. Linking a Style Sheet Using HTML The most common method of adding an external style sheet to a web page is to use the HTML <link> tag. You write the tag slightly differently depending on whether you’re using HTML or XHTML. For example, here’s HTML: <link rel="stylesheet" type="text/css" href="css/global.css"> Here’s XHTML: <link rel="stylesheet" type="text/css" href="css/global.css" /> The only difference is how you end the tag. The link tag is an empty element, since it has only an opening tag and no matching, closing </link> tag. In XHTML, you need to add a closing slash (like this: />) to terminate the tag; HTML doesn’t require the extra slash. Otherwise, the link tag is the same in HTML and XHTML and requires three attributes: • rel="stylesheet" indicates the type of link—in this case, a link to a style sheet. • type="text/css" lets the browser know what kind of data to expect—a text file, containing CSS. • href points to the location of the external CSS file on the site. The value of this property is a URL and will vary depending on where you keep your CSS file. It works the same as the src attribute you use when adding an image to a page or the href attribute of a link pointing to another page. Tip: You can attach multiple style sheets to a web page by adding multiple <link> tags, each pointing to a different style sheet file. This technique is a great way to organize your CSS styles, as you can see in Chapter 15. Chapter 2: Creating Styles and Style Sheets Download at Boykma.Com 37 External Style Sheets Linking a Style Sheet Using CSS CSS includes a built-in way to add external style sheets—the @import directive. You add the directive inside of an HTML <style> tag, like so: <style type="text/css"> @import url(css/global.css); </style> Unlike HTML’s <link> tag, @import is part of the CSS language and has some definite un-HTML-like qualities: • To make the connection to the external CSS file, you use url instead of href and enclose the path in parentheses. So in this example, css/global.css is the path to the external CSS file. Quotes around the URL are optional, so url(css/global.css) and url("css/global.css") both work. • As with the <link> tag, you can include multiple external style sheets using more than one @import: <style type="text/css"> @import url(css/global.css); @import url(css/forms.css); </style> • You can add regular CSS styles after the @import directives if you want to create a rule that applies just to that one page, but still use the site’s global design rules to format the rest of the page. Note: You’ll learn how rules interact and how you can create a rule that overrides other rules on page 100. You can even create an external CSS file that contains only @import directives linking to other external style sheets, a technique often used to help organize your styles (see page 398). Here’s an example: <style type="text/css"> @import url(css/global.css); @import url(css/forms.css); p { color:red; } </style> Technically, you should place all the @import lines before any CSS rules, as shown here, but it’s okay if you forget. Web browsers are supposed to ignore any style sheets you import after a CSS rule, but all current web browsers ignore that restriction. Which to use? Although both methods work, the <link> tag is more common. In a few cases, using the @import technique can slow your style sheets’ download speed (visit www.stevesouders.com/blog/2009/04/09/dont-use-import/ to find out when this can happen and why). So, if you don’t have a strong preference for either, just use the <link> method described on page 44. 38 CSS: The Missing Manual Download at Boykma.Com Tutorial: Creating Your First Styles Tutorial: Creating Your First Styles The rest of this chapter takes you through the basic steps for adding inline styles, writing CSS rules, and creating internal and external style sheets. As you work through this book, you’ll work through various CSS designs, from simple design elements to complete CSS-enabled web page layouts. To get started, download the tutorial files located on the book’s companion website at www.sawmac.com/css2e/. Click the tutorial link and download the Zip archive containing the files (detailed instructions for unzipping the files are on the website as well). Each chapter’s files are in a separate folder, named 02 (for chapter 2), 03 (for chapter 3), and so on. Next, launch your favorite web page editing software, whether it’s a simple text editor, like Notepad or TextEdit, or a visually oriented program, like Dreamweaver or Microsoft Expression Web (for information on selecting an editor, see page 7). Note: If you use Dreamweaver, check out Appendix B to learn how to use that program to create styles and style sheets. Dreamweaver, along with many other HTML-editing programs, also lets you work on the raw HTML code by switching to Code View. Give that a shot for this tutorial. Creating an Inline Style When you type a CSS rule (like the ones described on page 31) directly into a page’s HTML, you’re creating an inline style. Inline styles offer none of the time-and bandwidth-saving benefits of style sheets, so the pros hardly ever use them. Still, in a pinch, if you absolutely must change the styling on a single element on a single page, then you may want to resort to an inline style. (For example, when creating HTMLformatted email messages, it’s usually best to use inline styles. That’s the only way to get CSS to work in Gmail, for instance.) And if you do, you at least want the style to work properly. The important thing is to carefully place the style within the tag you want to format. Here’s an example that shows you exactly how to do it: 1. In your web page editing program, open the file 02 ➝ basic.html. This simple-but-elegant XHTML file contains a couple of different headings, a few paragraphs, and a copyright notice inside an <address> tag. You’ll start by creating an inline style for the <h1> tag. 2. Click inside the opening <h1> tag and type style="color: #C7AA8D;". The tag should look like this: <h1 style="color: #C7AA8D;"> The style attribute is HTML, not CSS, so you use the equals sign after it and enclose all of the CSS code inside quotes. Only the stuff inside the quotes is CSS. In this case, you’ve added a property named color—which affects the color of text—and you’ve set that property to #C7AA8D (a hexadecimal code for defining a color that’s grayish/brown). You’ll learn more about coloring text on page 118. The colon separates the property name from the property value that you want. Next you’ll check the results in a web browser. Chapter 2: Creating Styles and Style Sheets Download at Boykma.Com 39 Tutorial: Creating Your First Styles 3. Open the basic.html page in a web browser. For example, start up your favorite web browser and choose File ➝ Open File (or press Ctrl-O [c-O] and select the basic.html file in the 02 tutorial folder from your computer. (Or just drag the file from the desktop—or wherever you’ve saved the tutorial files—into an open browser window.) Many HTML editors also include a “Preview in Browser” function, which, with a simple keyboard shortcut or menu option, opens the page in a web browser. It’s worth checking your program’s manual to see if it includes this timesaving feature. When you view the page in a browser, the headline is now a dusty brown. Inline styles can include more than one CSS property. You’ll add another property next. 4. Return to your HTML editor, click after the semicolon following #C7AA8D and type font-size: 3em;. The semicolon separates two different property settings. The <h1> tag should look like this: <h1 style="color: #C7AA8D; font-size: 3em;"> 5. Preview the page in a web browser. For example, click your browser window’s Reload button (but make sure you’ve saved the XHTML file first). The headline is now massive in size. And you’ve had a taste of how labor-intensive inline styles are. Making all the <h1> headings on a page look like this one could take days of typing and add acres of HTML code. 6. Return to your page editor and delete the entire style property, which returns the heading tag back to its normal <h1>. Next, you’ll create a style sheet within a web page. (You’ll find a finished version of this part of the tutorial in the 02_finished folder in a file named inline.html.) Creating an Internal Style Sheet A better approach than inline styles is using a style sheet that contains multiple CSS rules to control multiple elements of a page. In this section, you’ll create a style that affects all top-level headings in one swoop. This single rule automatically formats every <h1> tag on the page. 1. With the file basic.html open in your text editor, click directly after the closing tag. Then hit Enter (Return) and type . Now, you’ll add a CSS selector that marks the beginning of your first style. 3. Click between the opening and closing 7. Save the page and preview it in a web browser. You can preview the page by opening it in a web browser as described in step 3 on page 40, or, if the page is still open in a browser window, then just click the Reload button. Next you’ll add another style. Note: Always remember to add the closing tag at the end of an internal style sheet. When you don’t, a web browser displays the CSS style code followed by a completely unformatted web page—or no web page at all. 8. Back in your text editing program, click after the closing brace of the h1 style you just created, press Enter, and then add the following rule: p { color: #616161; line-height: 150%; margin-top: 10px; margin-left: 80px; } This rule formats every paragraph on the page. Don’t worry too much right now about what each of these CSS properties is doing. Later chapters cover these properties in depth. For now, just practice typing the code correctly and get a feel for how to add CSS to a page. 9. Preview the page in a browser. The page is starting to shape up and should look like Figure 2-3. You can see what stylistic direction the page is headed in. You can see a completed version of this tutorial by opening the internal.html file in the 02_finished folder. The process you’ve just worked through is CSS in a nutshell: Start with an HTML page, add a style sheet, and create CSS rules to make the page look great. In the next part of this tutorial, you’ll see how to work more efficiently using external style sheets. 42 CSS: The Missing Manual Download at Boykma.Com Tutorial: Creating Your First Styles Figure 2-3: CSS easily formats text in creative ways, letting you change fonts, text colors, font sizes, and a lot more as you’ll see in “Creating an External Style Sheet” below. Creating an External Style Sheet Since it groups all of your styles at the top of the page, an internal style sheet is a lot easier to create and maintain than the inline style you created a few pages ago. Also, an internal style sheet lets you format any number of instances of a tag on a page, like every

tag by typing one simple rule. But an external style sheet gets even better—it can store all of the styles for an entire website. Editing one style in the external style sheet updates the whole site. In this section, you’ll take the styles you created in the previous section and put them in an external style sheet. 1. In your text editing program, create a new file and save it as main.css in the same folder as the web page you’ve been working on. External style sheet files end with the extension .css. The file name main.css indicates that the styles contained in the file apply throughout the site. (But you can use any file name you like, as long as it ends with the .css extension.) Start by adding a new style to the style sheet. 2. Type the following rule into the main.css file: body { background-color: #CDE6FF; background-image: url(images/bg_body.png); background-repeat: repeat-x; padding-top: 100px; } Chapter 2: Creating Styles and Style Sheets Download at Boykma.Com 43 Tutorial: Creating Your First Styles This rule applies to the body tag—the tag that holds all the content visible in a web browser window—and adds a background image to the page. Unlike a similar property in HTML, the CSS background-image property can display the graphic in many different ways—in this case, tiled horizontally across the top of the page. You can read more about background image properties on page 188. This style also adds a color to the page’s background and scoots its contents down 100 pixels from the top of the browser window. When you preview the page, you’ll see that this extra space moves the headline out of the way of the background graphic. Instead of recreating the work you did earlier, just copy the styles you created in the previous section and paste them into this style sheet. 3. Open the basic.html page that you’ve been working on and copy all of the text inside the . These are the opening and closing style tags—it’s a good idea to type both tags at the same time, so you don’t accidentally forget to add the closing tag. Together, these two tags tell a web browser that the information between them is Cascading Style Sheet instructions. The HTML should now look like this (the stuff you added is in bold): Selector Basics Type selectors—such as the tag selector you’re about to create—are the most basic type of selector. (If you completed the tutorial in the last chapter, you’ve already created a few.) Chapter 3: Selectors: Identifying What to Style Download at Boykma.Com 71 Tutorial: Selector Sampler 3. Click between the opening and closing style tags you just added and type p { , hit return twice and type the closing }. As mentioned on page 41, it’s a good idea to always add the closing brace immediately after typing the opening brace, just so you don’t forget. To create a tag selector, simply use the name of the HTML tag you wish to format. This style applies to all paragraphs of text within

tags. 4. Click between the style’s opening and closing braces ( { } ) and add the following four CSS properties to supply the style’s formatting—color, size, font, and left indent: p { color: #505050; font-size: 1em; font-family: "Helvetica Neue", Arial, Helvetica, sans-serif; margin-left: 100px; } Press Enter to place each CSS property on its own line. It’s also a good idea to visually organize your CSS code by indenting each property with the Tab key. Note: These property names and their values may look unfamiliar. For now, just type them as is. You’ll learn what 1em and 100px mean, along with all the ins and outs of text-formatting properties, in Chapter 6. Your style sheet is complete. Time for a look-see. 5. Open the page in a web browser to preview your work. Unless you tinker with the preference settings, most browsers display black text in a standard serif font like Times. If your CSS style works properly, then you should see seven indented paragraphs in a sans-serif font in a darkish gray color. Creating a Group Selector Sometimes you’ll want several different elements on a page to share the same look. For instance, you may want all your headings to have the same font and color for a consistent style. Instead of creating separate styles and duplicating the same property settings for each tag—

,

, and so on—you can group the tags together into a single selector. 1. Return to your text editor and the selector_basics.html file. You’ll add a new style below the

tag style you just created. 72 CSS: The Missing Manual Download at Boykma.Com Tutorial: Selector Sampler 2. Click at the end of the closing brace of the tag selector, press Enter to start a new line, and then type h1, h2, h3 { . As explained earlier in this chapter, a group selector is simply a list of selectors separated by commas. This rule applies the same formatting, which you’ll add next, to all

,

, and

tags on the page. 3. Hit Enter, and then add five CSS properties: color: #BD8100; font-family: Baskerville, "Palatino Linotype", Times, serif; border-top: 2px solid #86A100; padding-top: 7px; padding-left: 100px; There’s a lot going on here, but basically you’re setting the color and font type for the headlines, adding a border line above the headlines for visual interest, and controlling the top and left spacing using the padding property. In a nutshell, this property adds space from the edges of an element without affecting a background or border—in other words, you’re scooting the headline text in from the left and down from the top without moving the border line that spans the entire page. 4. Finally, hit Enter, and then type the closing brace to complete this style. It should look like this: h1, h2, h3 { color: #BD8100; font-family: Baskerville, "Palatino Linotype", Times, serif; border-top: 2px solid #86A100; padding-top: 7px; padding-left: 100px; } 5. Save the file, and preview it in a web browser. The

heading near the top of the page and the

and

headings lower on the page all have the same font and font color as well as green border along their tops (see Figure 3-8). Creating and Applying a Class Selector Tag selectors are quick and efficient, but they’re a bit indiscriminate in how they style a page. What if you want to style a single

tag differently than all the other

tags on a page? A class selector is the answer. 1. Return to your text editor and the selector_basics.html file. Add a new style below the group selector style you just created. Chapter 3: Selectors: Identifying What to Style Download at Boykma.Com 73 Tutorial: Selector Sampler Figure 3-8: A simple tag selector can completely transform the appearance of every instance of a tag, making quick work of styling all the paragraphs of text on a page. And in this case a group selector does even more by formatting every instance of three different headline tags! 2. Click at the end of the closing brace of the h1, h2, h3 selector, press Enter (Return), and then type .note { . This style’s name, note, indicates its purpose: to highlight paragraphs that contain extra bits of information for your site’s visitors. Once you create a class style, you can apply it wherever these notes appear—like the second paragraph, in this case. 74 CSS: The Missing Manual Download at Boykma.Com Tutorial: Selector Sampler 3. Hit Enter, and then add the following list of properties to the style: color: #333; border: 2px dashed #BD8110; background-color: #FBF8A9; margin-top: 25px; margin-bottom: 35px; padding: 20px; Most of these properties should look familiar by now, but the background-color property may be new to you. Logically enough, it adds a color to the background of the element. 4. Finally, complete the style by pressing Enter and typing the closing brace. The completed class style should look like this: .note { color: #333; border: 2px dashed #BD8110; background-color: #FBF8A9; margin-top: 25px; margin-bottom: 35px; padding: 20px; } If you preview the page now, you see no changes. Unlike tag selectors, class selectors don’t have any affect on a web page until you apply the style in the HTML code. 5. In the page’s HTML, there are two

tags that begin with the word “Note” inside tags. To apply a class style to a tag, simply add a class attribute, followed by the class selector’s name—in this case, the note style you just created. 6. Click just after the “p” in the first

tag, and then type a space followed by class="note". The HTML should now look like this (what you just typed is in bold):

NOTE: Ut enim ad Be sure not to type class=".note". In CSS, the period is necessary to indicate a class style name; in HTML, it’s verboten. Repeat this step for the second paragraph (it’s just above the

tag with the text “Not Me!”). Note: There’s no reason you can’t add this class to other tags as well, not just the

tag. If you happen to want to apply this formatting to an

tag, for example, then your HTML would look like this:

. Chapter 3: Selectors: Identifying What to Style Download at Boykma.Com 75 Tutorial: Selector Sampler 7. Save and preview the web page in a browser. The two note paragraphs are nicely highlighted on the page (see Figure 3-9). Figure 3-9: You can make detailed formatting changes with class selectors. A class style gives selected paragraphs different formatting from all other paragraphs on the page. The distinctive note box pictured here uses a class style to stand out from the crowd. Note: If your page doesn’t look like Figure 3-9, then you may have mistyped the name of a property or its value. Double-check your code with the steps on pages 71–73. Also, make sure to end each declaration—property:value combination—with a semicolon and conclude the style with a closing brace at the very end. When your style is not working correctly, missing semicolons and closing braces are frequent culprits. Creating a Descendent Selector On the selectors_basics.html page, you applied the note class to two paragraphs. Each of those paragraphs begins with the word “Note:” in bold—actually the word is wrapped inside the HTML tag, which all browsers display as bolded text. But what if you want to format those bolded words in bright orange? You could create a tag style for the tag, but that would affect all tags on the page, and you only want to change the strong tag inside those note boxes. One solution would be to create a class style—.noteText, for example—and apply it to each of the tags inside the note boxes. But that’s work, and you might forget to apply the class if you have a lot of pages with those notes. 76 CSS: The Missing Manual Download at Boykma.Com Tutorial: Selector Sampler A better method is to create a descendent selector (page 57), which targets only the tag when it’s inside one of these note boxes. Fortunately, that’s easy to do. 1. Return to your text editor and the selector_basics.html file. Create a new empty line for the descendent selector style. If you just completed the previous steps, click after the closing brace of the .note style, and then hit Enter (Return). 2. Type .note strong { The last tag in the selector—strong—is the element you ultimately want to format. In this case, the style formats the tag only when it’s inside another tag with the class note applied to it. It has no effect on tags inside other paragraphs, lists, or heading tags, for example. 3. Hit Enter, type color: #FC6512;, and then hit Enter (Return) again to create another blank line. Finish the style by typing the closing brace character. The finished style should look like this: .note strong { color: #FC6512; } 4. Save the page and preview it in a web browser. The word “Note:” should appear in orange in each of the note boxes on the page. Descendent selectors are among the most powerful CSS tools. Professional web designers use them extensively to target particular tags without littering the HTML with CSS classes. This book uses them routinely, and you can learn a lot more about descendent selectors in Chapter 15. Creating and Applying an ID Selector You can apply class selectors to multiple elements on a page. For example, earlier you created a .note class style and applied it to two paragraphs, but you could apply it to even more paragraphs (or even other tags) if you wanted to. ID selectors look and act just like classes, but you can apply an ID only once per page. Web designers frequently use ID selectors to indicate unique sections of a page, as explained on page 53. In this exercise, you’ll create a style that sets a specific width for a web page’s content, centers it in the middle of the browser window and adds a decorative background image to the page. You’ll apply the ID to the page’s tag to indicate a unique page design. 1. Return to your text editor and the selector_basics.html file. You’ll add a new style below the .note strong class style you created before. Chapter 3: Selectors: Identifying What to Style Download at Boykma.Com 77 Tutorial: Selector Sampler 2. Click after the previous style’s closing bracket (}), hit Enter (Return) to create a new line, and then type #article { . ID selectors always begin with the pound symbol (#). The style’s name indicates which type of page this is—it’s common on websites to have different designs for different types of web pages. For example, the home page will look different from a page advertising a product, which may look different from a page with the text of a blog post. In this case, you’re going to identify this page as an “article” (as in a newspaper) by creating and applying an ID to the tag. 3. Hit Enter again, and then type: background-color: #FDF8AB; background-image: url(images/bg_page.png); background-repeat: repeat-y; background-position: center top; padding: 0; margin: 0 auto; width: 760px; There are a lot of properties here, but basically you’re adding a color to the page, inserting an image in the background (and controlling how it’s positioned), removing space around the browser window’s edges, setting a fixed width for the page’s content, and centering everything in the middle of the page. 4. Finish the style by typing the closing brace. The whole thing should look like this: #article { background-color: #FDF8AB; background-image: url(images/bg_page.png); background-repeat: repeat-y; background-position: center top; padding: 0; margin: 0 auto; width: 760px; } Just as with a class, this style doesn’t do anything until you apply it to the page. So you’ll add an ID attribute to the page’s HTML, indicating where you want the ID style to apply. 5. Find the page’s opening tag and add id="article" so that the tag looks like this (your changes are in bold): 78 CSS: The Missing Manual Download at Boykma.Com Tutorial: Selector Sampler Now the tag reflects the formatting defined in the #article style. As with all things CSS, there are many ways to arrive at the same destination: You can instead use a class style and apply it to the tag (as long as you don’t apply it more than once on the page). You can even create a plain body element style with the same formatting properties as long as all the other pages on your site share these same formatting choices. But in this case, you’re using an ID selector since the point of this style—identifying the type of page—is in keeping with the general notion of ID selectors. 6. Save the page, and preview it in a browser. Everything on the page, the logo and all of the text, now have a set width and float in the center of the browser window. Even if you resize the browser window—try it!—the content remains centered. In addition, a drop shadow appears on either side of the content, thanks to the handy background-image property (you’ll learn about that cool property in depth on page 188). Finishing Touches For fun, you’ll add one more advanced style—an adjacent sibling selector discussed on page 66—to format the paragraph immediately following the first headline on the page. (You can achieve the same effect by creating a class style and applying it to that paragraph, but the adjacent sibling selector requires no changes to your HTML.) 1. Return to your text editor and the selector_basics.html file. Create a new empty line for a new style. If you just completed the previous steps, click after the closing brace of the #article style, and then hit Enter (Return). 2. Type h1+p { . This style will apply to any paragraph that immediately follows an

tag—in other words, the first paragraph after the top headline on the page. It won’t apply to the second or any subsequent paragraphs. This selector provides an easy way to create a unique look for an introductory paragraph to set it off visually and highlight the beginning of an article. 3. Hit Enter, and then add the following list of properties to the style: color: #FF6600; font-size: 1.2em; line-height: 140%; margin-top: 20px; Here you’re changing the font color and size as well as adding a bit of space above the paragraph. The line-height property (which you’ll read about on page 128) controls the space between lines in a paragraph (also know as leading). Chapter 3: Selectors: Identifying What to Style Download at Boykma.Com 79 Tutorial: Selector Sampler 4. Finally, complete the style by pressing Enter and typing the closing brace. The completed class style should look like this: h1+p { color: #FF6600; font-size: 1.2em; line-height: 140%; margin-top: 20px; } If you preview the page now, you’ll see that the top paragraph is orange and the text is larger and there’s more space between each line of text (see Figure 3-10). If you actually deleted this paragraph in the HTML, you’d see that the remaining paragraph would suddenly be orange with larger text, since it would be the new adjacent sibling of the

tag. Note: Internet Explorer 6 doesn’t understand adjacent sibling selectors, so in that browser, the first paragraph will look just like all the others on the page. And there you have it: a quick tour through various selector types. You’ll get familiar with all of these selectors (and more) as you go through the tutorials later in the book, but by now, you should be getting a hang for the different types and why you’d use one over the other. Note: You can see a completed version of the page you’ve just created in the 03_finished folder. Figure 3-10: The page has really come together. The set width, the drop shadow effect, and the typographic details have really improved the look of the boring HTML page you started with. 80 CSS: The Missing Manual Download at Boykma.Com chapter Chapter 4 4 Saving Time with Style Inheritance Children inherit traits from their parents—eye color, height, male-pattern baldness, and so on. Sometimes, we inherit traits from more distant ancestors, like grandparents or great-grandparents. As you saw in the previous chapter, the metaphor of family relations is part of the structure of HTML as well. And just like humans, HTML tags can inherit CSS properties from their ancestors. What Is Inheritance? In a nutshell, inheritance is the process by which some CSS properties applied to one tag are passed on to nested tags. For example, a

tag is always nested inside of the tag, so properties applied to the tag get inherited by the

tag. Say you created a CSS tag style (page 50) for the tag that sets the color property to a dark red. Tags that are descendents of the tag—that is, the ones inside the tag—will inherit that color property. That means that any text in those tags—

,

,

, whatever—will appear in that same dark red color. Inheritance works through multiple generations as well. If a tag like the or tag appears inside of a

tag, then the and the tags also inherit properties from any style applied to the tag. Note: As discussed in Chapter 3, any tag inside of another tag is a descendent of that tag. So a

tag inside the tag is a descendent of the , while the tag is an ancestor of the

tag. Descendents (think kids and grandchildren) inherit properties from ancestors (think parents and grandparents). 81 Download at Boykma.Com What Is Inheritance? Although this sounds a bit confusing, inheritance is a really big time saver. Imagine if no properties were passed onto nested tags and you had a paragraph that contained other tags like the tag to emphasize text or the tag to add a link. If you created a style that made the paragraph purple, 24px tall, using the Arial font, it would be weird if all the text inside the tag reverted to its regular, “browser boring” style (see Figure 4-1). You’d then have to create another style to format the tag to match the appearance of the

tag. What a drag. Figure 4-1: Inheritance lets tags copy properties from the tags that surround them. Top: The paragraph tag is set with a specific font-family, size, and color. The tags inside each paragraph inherit those properties so they look like the rest of the paragraph. Bottom: If inheritance didn’t exist, the same page would look like this figure. Notice how the strong, em, and a tags inside the paragraph retain the font-family, size, and color defined by the browser. To make them look like the rest of the paragraph, you’d have to create additional styles—a big waste of time. 82 CSS: The Missing Manual Download at Boykma.Com The Limits of Inheritance Inheritance doesn’t just apply to tag styles. It works with any type of style; so when you apply a class style (see page 51) to a tag, any tags inside that tag inherit properties from the styled tag. Same holds true for ID styles, descendent selectors, and the other types of styles discussed in Chapter 3. How Inheritance Streamlines Style Sheets You can use inheritance to your advantage to streamline your style sheets. Say you want all the text on a page to use the same font. Instead of creating styles for each tag, simply create a tag style for the tag. (Or create a class style and apply it to the tag.) In the style, specify the font you wish to use, and all of the tags on the page inherit the font: body { font-family: Arial, Helvetica, sans-serif; }. Fast and easy. You can also use inheritance to apply style properties to a section of a page. For example, like many web designers, you may use the

tag (page 26) to define an area of a page like a banner, sidebar, or footer. By applying a style to a
tag, you can specify particular CSS properties for all of the tags inside just that section of the page. If you want all the text in a sidebar to be the same color, you’d create a style setting the color property, and then apply it to the
. Any

,

, or other tags inside the
inherit the same font color. Note: You’ll find lots more uses for the
tag when laying out a page using CSS in Part 3. The Limits of Inheritance Inheritance isn’t all-powerful. Many CSS properties don’t pass down to descendent tags at all. For example, the border property (which lets you draw a box around an element) isn’t inherited, and with good reason. If it were, then every tag inside an element with the border property would also have a border around it. For example, if you added a border to the tag, then every bulleted list would also have a box around it, and each bulleted item in the list would also have a border (Figure 4-2). Note: There’s a complete list of CSS properties in Appendix A, CSS Property Reference, including details on which ones get inherited. Here are examples of times when inheritance doesn’t strictly apply: • As a general rule, properties that affect the placement of elements on the page or the margins, background colors, and borders of elements aren’t inherited. Chapter 4: Saving Time with Style Inheritance Download at Boykma.Com 83 The Limits of Inheritance Figure 4-2: Fortunately, not all properties are inherited. The border applied to the paragraphs at top isn’t inherited by the tags inside those paragraphs. If they were, you’d end up with an unattractive mess of boxes within boxes within boxes (bottom). • Web browsers use their own inherent styles to format various tags: Headings are big and bold, links are blue, and so on. When you define a font-size for the text on a page and apply it to the tag, headings still appear larger than paragraphs, and

tags are still larger than

tags. It’s the same when you apply a font color to the ; the links on the page still appear in good old-fashioned, web-browser blue. 84 CSS: The Missing Manual Download at Boykma.Com Tutorial: Inheritance Note: It’s usually a good idea to eliminate these built-in browser styles—it’ll make designing sites that work consistently among different browsers easier. In the next chapter, on page 102, you’ll learn how to do that. • When styles conflict, the more specific style wins out. In other words, when you’ve specifically applied CSS properties to an element—like specifying the font size for an unordered list—and those properties conflict with any inherited properties—like a font-size set for the tag—the browser uses the font size applied to the

272 CSS: The Missing Manual Download at Boykma.Com Styling Tables
Table 1: CosmoFarmer.com's Indoor Mower Roundup
Brand Price Power Source
Chinook Push-o-matic Indoor Mower $247.00 Mechanical
Sampson Deluxe Apartment Mower $370.00 Mechanical
Even with only three rows and three columns, the table uses nine unique HTML tags: , , , , ,
,
, and . In general, more HTML isn’t a good thing, but a table’s various tags give you lots of useful hooks to hang CSS styles on. The headers of each column—the tags—can look different from other table cells if you create a tag style. This saves you the hassle of having to create lots of classes—like .tableHeader—and then apply them by hand to individual table cells. In the next section, you’ll see examples of how you can use these different tags to your advantage. border padding Figure 10-2: Data tables, like this one, usually have headers created with the tag. Header cells announce what type of information appears in a row or column. Price tells you that you’ll find the cost of each lawn mower listed in the cells below. The actual data presented in a table is enclosed in tags. Note: For an in-depth article on the HTML used to create tables, visit www.456bereastreet.com/archive/ 200410/bring_on_the_tables. Styling Tables You can use many of the CSS properties you’ve read about to dress up the appearance of a table and its contents. The color property, for example, sets a table’s text color, just like anywhere else. You’ll find a few properties, however, that are particularly useful with tables, as well as a couple aimed specifically at formatting tables. Chapter 10: Formatting Tables and Forms Download at Boykma.Com 273 Styling Tables Because tables are composed of several HTML tags, it helps to know which tag to apply a particular CSS property to. Applying padding to a tag has no effect. The next few sections cover CSS properties for formatting tables and which HTML tags they get along with. Adding Padding As you read on page 153, padding is the space between an element’s border and its content. You can use padding to provide a little space between the edges of a paragraph’s text and its border. When it comes to tables, the borders are the edges of a cell, so padding adds space around any content you’ve placed inside of a table cell (see Figure 10-2). It works a lot like the
tag’s cellpadding attribute, with the added benefit that you can individually control space between a cell’s content and each of its four edges. You apply padding to either a table header or a table cell tag, but not to the
tag itself. So, to add 10 pixels of space to the inside of all table cells, you’d use this style: td, th { padding: 10px; } You can also control the spacing separately for each edge. To add 10 pixels of space to the top of each table data cell, 3 pixels to the bottom of that cell, and 5 pixels on both the left and right sides, create this style: td { padding-top: 10px; padding-right: 5px; padding-bottom: 3px; padding-left: 5px; } Or, use the padding shortcut property: td { padding: 10px 5px 3px 5px; } Tip: If you place an image into a table cell using the tag and notice that there’s unwanted space below the image, then set its display property to block. For more information, see http://developer. mozilla.org/en/docs/Images,_Tables,_and_Mysterious_Gaps. Adjusting Vertical and Horizontal Alignment To control where content is positioned within a table cell, use the text-align and vertical-align properties. 274 CSS: The Missing Manual Download at Boykma.Com Styling Tables Text-align controls horizontal positioning and can be set to left, right, center, and justify (see Figure 10-3). It’s an inherited property. (See Chapter 4 for more on inheritance.) When you want to right align the contents of all table cells, create a style like this: table { text-align: right; } This property comes in handy with
tags, since browsers usually center align them. A simple style like th { text-align: left; } makes table headers align with table cells. left center right justified Figure 10-3: When applied to table cells, the CSS text-align property works like the tag’s align attribute. Use the CSS approach, however, since it lets you store the style information in an external style sheet. That way, if you decide you need to change alignment in your table cells from right to left, then you need to update only the external style sheet, not 10,000 individual tags. Table cells have a height as well. web browsers normally align content vertically in the middle of a table cell (see the middle example in Figure 10-4). You can control this behavior using the vertical-align property. Use one of these four values: top, baseline, middle, or bottom. Top pushes content to the top of the cell, middle centers content, and bottom pushes the bottom of the content to the bottom of the cell. Baseline works just like top, except the browser aligns the baseline of the first line of text in each cell in a row (Figure 10-4). (Unless you’re a real perfectionist, you won’t even notice the subtlety of the baseline option. More importantly, neither will your visitors.) Unlike text-align, the vertical-align property isn’t inherited, so you can use it only on styles that apply directly to and tags. Note: So far, the table formatting you’ve learned applies to all your tables. When you want to style individual tables (or table cells), change the selector you use. To apply a special design to a certain table, give it a class name——and create descendent selectors like .stocks td, or .stocks th to uniquely format individual cells. If you want to style a particular cell differently than other cells in a table, then apply a class to the tag—
—and create a class style to format that cell. Chapter 10: Formatting Tables and Forms Download at Boykma.Com 275 Styling Tables Figure 10-4: The vertical-align property is the CSS equivalent of the tag’s valign top attribute. When padding is applied to a cell, the content never actually aligns to the bottom or top border lines: baseline There’s always a gap equal to the padding setting. You can control the size of the padding (see page 154). middle bottom Creating Borders The CSS border property (page 160) works pretty much the same with tables as with other elements, but you need to keep a couple of things in mind. First, applying a border to a style that formats the tag outlines just the table, not any of the individual cells. Second, applying borders to cells (td { border: 1px solid black; }) leaves you with a visual gap between cells, as shown in Figure 10-5, top. To gain control of how borders appear, you need to understand the
tag’s cellspacing attribute and the CSS border-collapse property. • Controlling the space between table cells. Unless instructed otherwise, browsers separate table cells by a couple of pixels. This gap is really noticeable when you apply a border to table cells. CSS 2.1 gives you the border-spacing property to control this space, but since Internet Explorer 7 and earlier doesn’t recognize border-spacing, you’re better off using the
tag’s cellspacing attribute for now. Here’s the HTML to insert 10 pixels of space between each cell:
. (Setting the value to 0 eliminates the space entirely, but if you want to do that, then use the CSS border-collapse property, discussed next.) • Eliminating double borders. Even if you eliminate the cell spacing of a table, borders applied to table cells double up. That is, the bottom border of one cell adds to the top border of the under-hanging cell, creating a line that’s twice as thick as the border setting (Figure 10-5, middle). The best way to eliminate this (and eliminate cell spacing at the same time) is to use the border-collapse property. It accepts two values—separate and collapse. The separate option is normally how tables are displayed, with the cell spaces and doubled borders. Collapsing a table’s borders eliminates the gaps and doubled borders (Figure 10-5, bottom). Apply the collapse value to a style formatting a table, like so: table { border-collapse: collapse; } 276 CSS: The Missing Manual Download at Boykma.Com Styling Tables Note: HTML tags that are used to build tables include attributes that accomplish a lot of the same tasks as CSS. The border attribute can add a border to the table and each cell. You should avoid these attributes: CSS can do a much better job with less code. Styling Rows and Columns Adding stripes, like the ones in Figure 10-6, is a common table design technique. By alternating the appearance of every other row of data, you make it easier for people to spot the data in each row. Unfortunately, CSS (at least at this point) doesn’t offer a way to say, “Hey browser, make every other row look this way!” The basic solution is to apply a class (like ) to every other row, and then create a style to format that row: .odd { background-color: red; } Figure 10-5: Browsers normally insert space between each table cell. (You probably won’t notice this extra space unless you’ve added a border, as shown here, at top.) If you use the
tag’s cellspacing attribute to remove the extra space, you’re left with double border lines where adjoining borders touch (middle). The border-collapse property solves both dilemmas (bottom). Chapter 10: Formatting Tables and Forms Download at Boykma.Com 277 Styling Tables You’re not limited to colors either. You can use background images (see page 188) to create more sophisticated looks like the slight gradation in the table header row of Figure 10-6. (You’ll see a similar example of this in the tutorial on page 288.) You can use a descendent selector to target cells in that row as well. This technique is great for when you style all of the cells in one column with their own class and look: and tags to indicate groups of columns and individual columns, respectively. You include one tag for each column in the table and can identify them with either a class or ID. (See the HTML code on page 272.) Only two sets of properties work on these tags: width and the background properties (background-color, background-image, and so on). But they can come in mighty handy. When you want to set the width of all of the cells in a column, you can skip any HTML attributes and just style the column using a style applied to the tag. For example, say you have this bit of HTML: . You can add this style to a stylesheet to set the width of each cell in that column to 200 pixels: #price { width: 200px; } Figure 10-6: Alternating the background color from row to row in a table makes it easier to quickly identify the data for each row. 278 CSS: The Missing Manual Download at Boykma.Com Styling Forms Likewise, the tag groups several columns together. When you set a width for that tag, a web browser automatically applies the specified width to each column in the group. A table displaying airline schedules might have several columns displaying the different dates a plane travels from Boston to Chicago. You can use to organize those columns and apply an ID to the tag to identify it: . Then, to set each date column to a set width of 10ems, you can create this style: #dates{ width: 10em; } Even though the width property here applies to the tag, a browser actually applies the value—10em—to each column in the group. To highlight a column, you can use the background properties. Again, assume you have a tag with an ID of price applied to it: #price { background-color: #F33; } Keep in mind, however, that backgrounds for columns appear under table cells, so if you set a background color or image for
, for example. To create a unique look for that cell when it appears in an odd row, create a style with this selector: .odd .price. Tip: For a quicker, CSS 3 solution to striping tables see page 440. This technique only works in some browsers, so another technique, that works for all browsers is to use JavaScript to quickly stripe tables. Check out www.creativepro.com/article/view-source-javascript-designers for the details. Formatting columns is a bit trickier. HTML provides the
or tags, then a column’s background won’t be visible. Styling Forms Web forms are the primary way visitors interact with a website. By supplying information on a form, you can join a mailing list, search a database of products, update your personal profile on MySpace, or order that Star Wars Lego set you’ve had your eye on. There’s no reason your forms need to look like all the others on the Internet. With a little CSS, you can style form fields to share the same formatting as other site elements like fonts, background colors, and margins. There aren’t any CSS properties specific to forms, but you can apply just about any property in this book to a form element. The results, however, can be mixed (see Figure 10-7). Browsers vary widely in how they handle the styling of form elements. Safari 2 and earlier limits styling to only a few form elements like text fields and the
and tags. It won’t let you change the look of buttons, checkboxes, radio buttons, or pull-down menus. Even Internet Explorer and Firefox may display the same form elements differently. The next section tells you which properties work best with which form tags and also lists which browsers interpret them properly. Chapter 10: Formatting Tables and Forms Download at Boykma.Com 279 Styling Forms UP TO SPEED Staying True to Form Quite apart from the varying browser support for CSSstyled forms (page 283), there are good reasons to tread lightly when altering the look of universally recognized interface elements like Submit buttons and pull-down menus. Most web surfers are already very familiar with how forms look and work. The generic look of a Submit button is the same from site to site. When people see it, they instantly know what that button does and how to use it. If you alter the look of a form too much, you may make it harder for visitors to fill out your form correctly. Adding a dotted border to a form field can turn an easily recognizable text field into an easily skipped box. (See the examples at bottom right and bottom center of Figure 10-7.) If that text box is intended to capture email addresses for your newsletter, you may lose a few visitors who skip right over it. At the very least, make sure people can recognize the forms on your sites as forms. HTML Form Elements A variety of HTML tags help you build forms. You can format some of them (like text fields) more successfully than others (submit buttons). Here are a few common form tags and the types of properties they get along with: • Fieldset. The
tag groups related form questions. Most browsers do a good job of displaying background colors, background images, and borders for this tag. However, Internet Explorer lets the background flow up and over the top line of the fieldset. (Look at the top of the middle image in Figure 10-7, left column.) Padding places space from the edges of the fieldset to the content inside it. (Although Internet Explorer unfortunately ignores top padding, you can simulate it by adding a top margin to the first element inside the fieldset.) Tip: Matt Heerema has found a way to prevent Internet Explorer from adding a background above a fieldset’s top borderline. Read about it at www.mattheerema.com/archive/getting-fieldset-backgroundsand-legends-to-behave-in-ie. • Legend. The tag follows the HTML for the
tag and provides a label for the group of fields. The legend appears vertically centered on the top borderline of a fieldset. If the form elements for collecting a shipping address appear inside the fieldset, you might add a legend like this: Shipping Address. You can use CSS to change the tag’s font properties, add background colors and images, and add your own borders. • Text fields. The ( in XHTML), (), and the