CSS: The Missing Manual [1 ed.] 0596526873, 9780596526870

I love being able to purchase my school books from Amazon. However, it's a good thing I ordered my book way in adva

239 98 12MB

English Pages 592 Year 2006

Report DMCA / Copyright

DOWNLOAD PDF FILE

Recommend Papers

CSS: The Missing Manual [1 ed.]
 0596526873, 9780596526870

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

CSS: The Missing Manual

CSS: The Missing Manual By David Sawyer McFarland ............................................... Publisher: O'Re illy Pub Dat e: Au gu st 2 0 0 6 Print I SBN- 10: 0 - 5 9 6 - 5 2 6 8 7 - 3 Print I SBN- 13: 9 7 8 - 0 - 5 9 - 6 5 2 6 8 7 - 0 Pages: 4 9 4

Table of Cont ent s | I ndex

Web sit e design has grown up. Unlike t he old days, when designers cobbled t oget her chunky HTML, bandwidt h- hogging graphics, and a prayer t o m ake t heir sit es look good, Cascading St yle Sheet s ( CSS) now let s your inner designer com e out and play. But CSS isn't j ust a t ool t o pret t y up your sit e; it 's a reliable m et hod for handling all kinds of present at ion- from font s and colors t o page layout . CSS: The Missing Manual clearly explains t his powerful design language and how you can use it t o build sparklingly new Web sit es or refurbish old sit es t hat are ready for an upgrade.

Like t heir count erpart s in print page- layout program s, st yle sheet s allow designers t o apply t ypographic st yles, graphic enhancem ent s, and precise layout inst ruct ions t o elem ent s on a Web page. Unfort unat ely, due t o CSS's com plexit y and t he m any challenges of building pages t hat work in all Web browsers, m ost Web aut hors t reat CSS as a kind of window- dressing t o spruce up t he appearance of t heir sit es. I nt egrat ing CSS wit h a sit e's underlying HTML is hard work, and oft en frust rat ingly com plicat ed. As a result m any of t he m ost powerful feat ures of CSS are left unt apped. Wit h t his book, beginners and Web- building vet erans alike can learn how t o navigat e t he ins- and- out s of CSS and t ake com plet e cont rol over t heir Web pages' appearance.

Aut hor David McFarland ( t he best selling aut hor of O'Reilly's Dream weaver: The Missing Manual) com bines cryst al- clear explanat ions, real- world exam ples, a dash of hum or, and dozens of st ep- by- st ep t ut orials t o show you ways t o design sit es wit h CSS t hat work consist ent ly across browsers. You'll learn how t o:



Creat e HTML t hat 's sim pler, uses less code, is search- engine friendly, and

CSS: The Missing Manual

works well wit h CSS ●

St yle t ext by changing font s, colors, font sizes, and adding borders



Turn sim ple HTML links int o com plex and at t ract ive navigat ion bars- com plet e wit h CSS- only rollover effect s t hat add int eract ivit y t o your Web pages



St yle im ages t o creat e effect ive phot o galleries and special effect s like CSS- based drop shadows



Make HTML form s look great wit hout a lot of m essy HTML



Overcom e t he m ost hair- pulling browser bugs so your Web pages work consist ent ly from browser t o browser



Creat e com plex layout s using CSS, including m ult i- colum n designs t hat don't require using old t echniques like HTML t ables



St yle Web pages for print ing

Unlike com pet ing books, t his Missing Manual doesn't assum e t hat everyone in t he world only surfs t he Web wit h Microsoft 's I nt ernet Explorer; our book provides support for all m aj or Web browsers and is one of t he first books t o t horoughly docum ent t he newly expanded CSS support in I E7, current ly in bet a release.

Want t o learn how t o t urn hum drum Web sit es int o dest inat ions t hat will capt ure viewers and keep t hem longer? Pick up CSS: The Missing Manual and learn t he real m agic of t his t ool.

Table of Contents

CSS: The Missing Manual By David Sawyer McFarland ............................................... Publisher: O'Re illy Pub Dat e: Au gu st 2 0 0 6 Print I SBN- 10: 0 - 5 9 6 - 5 2 6 8 7 - 3 Print I SBN- 13: 9 7 8 - 0 - 5 9 - 6 5 2 6 8 7 - 0 Pages: 4 9 4

Table of Cont ent s | I ndex

Copyright The Missing Credits Introduction Part I: CSS Basics Chapter 1. Rethinking HTML for CSS Section 1.1. HTML: Past and Present Section 1.2. Writing HTML for CSS Section 1.3. The Importance of the Doctype Chapter 2. Creating Styles and Style Sheets Section 2.1. Anatomy of a Style Section 2.2. Understanding Style Sheets Section 2.3. Internal Style Sheets Section 2.4. External Style Sheets Section 2.5. Tutorial: Creating Your First Styles Chapter 3. Selector Basics: Identifying What to Style Section 3.1. Tag Selectors: Page-Wide Styling Section 3.2. Class Selectors: Pinpoint Control Section 3.3. ID Selectors: Specific Page Elements Section 3.4. Styling Tags Within Tags Section 3.5. Styling Groups of Tags Section 3.6. Pseudo-Classes and Pseudo-Elements Section 3.7. Advanced Selectors Section 3.8. Tutorial: Selector Sampler Chapter 4. Saving Time with Inheritance Section 4.1. What Is Inheritance? Section 4.2. How Inheritance Streamlines Style Sheets

Table of Contents

Section 4.3. The Limits of Inheritance Section 4.4. Tutorial: Inheritance Chapter 5. Managing Multiple Styles: The Cascade Section 5.1. How Styles Cascade Section 5.2. Specificity: Which Style Wins Section 5.3. Controlling the Cascade Section 5.4. Tutorial: The Cascade in Action Part II: Applied CSS Chapter 6. Formatting Text Section 6.1. Formatting Text Section 6.2. Changing Font Size Section 6.3. Formatting Words and Letters Section 6.4. Formatting Entire Paragraphs Section 6.5. Styling Lists Section 6.6. Tutorial: Text Formatting in Action Chapter 7. Margins, Padding, and Borders Section 7.1. Understanding the Box Model Section 7.2. Control Space with Margins and Padding Section 7.3. Adding Borders Section 7.4. Coloring the Background Section 7.5. Determining Height and Width Section 7.6. Wrap Content with Floating Elements Section 7.7. Tutorial: Margins, Backgrounds, and Borders Chapter 8. Adding Graphics to Web Pages Section 8.1. CSS and the Tag Section 8.2. Background Images Section 8.3. Controlling Repetition Section 8.4. Positioning a Background Image Section 8.5. Using Background Property Shorthand Section 8.6. Tutorial: Creating a Photo Gallery Section 8.7. Tutorial: Using Background Images Chapter 9. Sprucing Up Your Site's Navigation Section 9.1. Selecting Which Links to Style Section 9.2. Styling Links Section 9.3. Building Navigation Bars Section 9.4. Advanced Link Techniques Section 9.5. Tutorial: Styling Links

Table of Contents

Chapter 10. Formatting Tables and Forms Section 10.1. Using Tables the Right Way Section 10.2. Styling Tables Section 10.3. Styling Forms Section 10.4. Tutorial: Styling a Table Section 10.5. Tutorial: Styling a Form Part III: CSS Page Layout Chapter 11. Building Float-Based Layouts Section 11.1. How CSS Layout Works Section 11.2. Types of Web Page Layouts Section 11.3. Float Layout Basics Section 11.4. Applying Floats to Your Layouts Section 11.5. Overcoming Float Problems Section 11.6. Handling Internet Explorer Bugs Section 11.7. Tutorial: Multiple Column Layouts Section 11.8. Tutorial: Negative Margin Layout Chapter 12. Positioning Elements on a Web Page Section 12.1. How Positioning Properties Work Section 12.2. Powerful Positioning Strategies Section 12.3. Tutorial: Positioning Page Elements Part IV: Advanced CSS Chapter 13. CSS for the Printed Page Section 13.1. How Media Style Sheets Work Section 13.2. How to Add Media Style Sheets Section 13.3. Creating Print Style Sheets Section 13.4. Tutorial: Building a Print Style Sheet Chapter 14. Improving Your CSS Habits Section 14.1. Adding Comments Section 14.2. Organizing Styles and Style Sheets Section 14.3. Eliminating Browser Style Interference Section 14.4. Using Descendent Selectors Section 14.5. Managing Internet Explorer Hacks Part V: Appendixes Appendix A. CSS Property Reference Section A.1. CSS Values Section A.2. Text Properties Section A.3. List Properties

Table of Contents

Section A.4. Padding, Borders, and Margins Section A.5. Backgrounds Section A.6. Page Layout Properties Section A.7. Table Properties Section A.8. Miscellaneous Properties Appendix B. CSS in Dreamweaver 8 Section B.1. Creating Styles Section B.2. Adding Styles to Web Pages Section B.3. Editing Styles Section B.4. Managing Styles Section B.5. Examining Your CSS in the Styles Panel Section B.6. CSS Properties Appendix C. CSS Resources Section C.1. References Section C.2. CSS Help Section C.3. CSS Navigation Section C.4. CSS and Graphics Section C.5. CSS Layout Section C.6. Browser Bugs Section C.7. Showcase Sites Section C.8. CSS Books Section C.9. Must-Have RSS Feeds Section C.10. CSS Software Colophon Index

Copyright

Copyright © 2006 O'Reilly Media, I nc. All right s reserved. Print ed in t he Unit ed St at es of Am erica. Published by O'Reilly Media, I nc., 1005 Gravenst ein Highway Nort h, Sebast opol, CA 95472. O'Reilly books m ay be purchased for educat ional, business, or sales prom ot ional use. Online edit ions are also available for m ost t it les ( safari.oreilly.com ) . For m ore inform at ion, cont act our corporat e/ inst it ut ional sales depart m ent : ( 800) 998- 9938 or corporat [email protected] .

Pr in t in g H ist or y: August 2006:

First Edit ion.

Nut shell Handbook, t he Nut shell Handbook logo, t he O'Reilly logo, and " The book t hat should have been in t he box" are regist ered t radem arks of O'Reilly Media, I nc. CSS: The Missing Manual, The Missing Manual logo, Pogue Press, and t he Pogue Press logo are t radem arks of O'Reilly Media, I nc. Many of t he designat ions used by m anufact urers and sellers t o dist inguish t heir product s are claim ed as t radem arks. Where t hose designat ions appear in t his book, and O'Reilly Media, I nc. was aware of a t radem ark claim , t he designat ions have been print ed in caps or init ial caps. While every precaut ion has been t aken in t he preparat ion of t his book, t he publisher and aut hor assum e no responsibilit y for errors or om issions, or for dam ages result ing from t he use of t he inform at ion cont ained herein. I SBN- 10: 0- 596- 52687- 3 I SBN- 13: 978- 0- 596- 52687- 0 [ C]

The Missing Credits

The Missing Credits About the Author

D a vid Sa w ye r M cFa r la n d is president of Sawyer McFarland Media, I nc., a Web developm ent and t raining com pany in Port land, Oregon. He's been building Web sit es since 1995, when he designed his first Web sit e: an online m agazine for com m unicat ion professionals. He's served as t he Webm ast er at t he Universit y of California at Berkeley and t he Berkeley Mult im edia Research Cent er, and oversaw a com plet e CSS- driven redesign of Macworld.com . I n addit ion t o building Web sit es, David is also a writ er, t rainer, and inst ruct or. He's t aught Web design at UC Berkeley Graduat e School of Journalism , t he Cent er for Elect ronic Art , t he Academ y of Art College, Ex'Pressions Cent er for New Media, and Port land St at e Universit y. He's writ t en art icles about t he Web for Pract ical Web Design, MX Developer's Journal, Macworld m agazine, and Creat ivePro.com . He welcom es feedback about t his book by em ail: m issing@sawm ac.com . ( I f you're seeking t echnical help, however, please refer t o t he sources list ed in Appendix C.)

About the Creative Team N a n Ba r be r ( edit or) has worked wit h t he Missing Manual series since it s incept ionlong enough t o rem em ber boot ing up her com put er from a floppy disk. Em ail: [email protected] . Pe t e r M e ye r s ( edit or) works as an edit or at O'Reilly Media on t he Missing Manual series. He lives wit h his wife in New York Cit y. Em ail: pet er.m eyers@gm ail.com . M ich e le Filsh ie ( copy edit or) is O'Reilly's assist ant edit or for Missing Manuals and edit or of Don't Get Burned on eBay. Before t urning t o t he world of com put er- relat ed books, Michele spent m any happy years at Black Sparrow Press. She lives in Sebast opol. Em ail: m [email protected] . M a r k Le vit t ( t ech reviewer) is a Senior Web Producer for O'Reilly Media's Online Publishing Group. His background includes Com put er Science, I nt eract ive & Educat ional Media, and Web Developm ent . He's known t o eat cereal at all hours of t he day. Em ail: m ark@levit t at ion.com . Ju st in W a t t ( t ech reviewer) is current ly an aut hor- services engineer for Federat ed Media Publishing, a blog advert ising com pany based in Sausalit o, California. He blogs at j ust insom nia.org, where you can read about his advent ures in Nort hern California. Em ail: j wat t @federat edm edia.net .

The Missing Credits

Rose Ca ssa n o ( cover illust rat ion) has worked as an independent designer and illust rat or for 20 years. Assignm ent s have ranged from t he nonprofit sect or t o corporat e client ele. She lives in beaut iful Sout hern Oregon, grat eful for t he m iracles of m odern t echnology t hat m ake working t here a realit y. Em ail: cassano@highst ream .net . Web: www.rosecassano.com .

Acknowledgements Many t hanks t o all t hose who helped wit h t his book, including m y st udent s, who always help m e see t echnical issues t hrough beginners' eyes. Thanks t o m y t echnical edit ors, Mark Levit t and Just in Wat t , who saved m e from any em barrassing m ist akes, Zoe Gillenwat er for her valuable advice, and all of t he generous souls on t he CSS- Discuss m ailing list who share t heir hard one wisdom about CSS. Also, we all owe a big debt of grat it ude t o t he m any Web designers who have broken new ground by using CSS in creat ive ways, and shared t heir discoveries wit h t he Web design com m unit y. Finally, t hanks t o David Pogue whose unflagging ent husiasm and endurance is inspiring; Nan Barber for refining m y writ ing; Pet er Meyers for polishing m y prose and keeping m e on t rack; m y wife, Scholle, for m ot ivat ing m e t o get t his proj ect done; and m y son, Graham , who doesn't know what I do for a living and doesn't care.

The Missing Manual Series Missing Manuals are wit t y, superbly writ t en guides t o com put er product s t hat don't com e wit h print ed m anuals ( which is j ust about all of t hem ) . Each book feat ures a handcraft ed index and RepKover, a det ached- spine binding t hat let s t he book lie perfect ly flat wit hout t he assist ance of weight s or cinder blocks. Recent and upcom ing t it les include: Access for St art ers: The Missing Manual by Kat e Chase and Scot t Palm er AppleScript : The Missing Manual by Adam Goldst ein AppleWorks 6: The Missing Manual by Jim Elferdink and David Reynolds Creat ing Web Sit es: The Missing Manual by Mat t hew MacDonald Digit al Phot ography: The Missing Manual by Chris Grover and Barbara Brundage Dream weaver 8: The Missing Manual by David Sawyer McFarland eBay: The Missing Manual by Nancy Conner Excel: The Missing Manual by Mat t hew MacDonald Excel for St art ers: The Missing Manual by Mat t hew MacDonald FileMaker Pro 8: The Missing Manual by Geoff Coffey and Susan Prosser

The Missing Credits

Flash 8: The Missing Manual by Em ily Moore Front 2003: The Missing Manual by Jessica Mant aro GarageBand 2: The Missing Manual by David Pogue Google: The Missing Manual, Second Edit ion by Sarah Milst ein, J.D. Biersdorfer, and Mat t hew MacDonald Hom e Net working: The Missing Manual by Scot t Lowe iLife '05: The Missing Manual by David Pogue iMovie 6 & iDVD: The Missing Manual by David Pogue iPhot o 6: The Missing Manual by David Pogue iPod & iTunes: The Missing Manual, Fourt h Edit ion by J.D. Biersdorfer iWork '05: The Missing Manual by Jim Elferdink Mac OS X Power Hound, Pant her Edit ion by Rob Griffit hs Mac OS X: The Missing Manual, Tiger Edit ion by David Pogue Office 2004 for Macint osh: The Missing Manual by Mark H. Walker and Franklin Tessler PCs: The Missing Manual by Andy Rat hbone Phot oshop Elem ent s 4: The Missing Manual by Barbara Brundage QuickBooks 2006: The Missing Manual by Bonnie Biafore Quicken for St art ers: The Missing Manual by Bonnie Biafore Swit ching t o t he Mac: The Missing Manual, Tiger Edit ion by David Pogue and Adam Goldst ein The I nt ernet : The Missing Manual by David Pogue and J.D. Biersdorfer Windows 2000 Pro: The Missing Manual by Sharon Crawford Windows XP for St art ers: The Missing Manual by David Pogue Windows XP Hom e Edit ion: The Missing Manual, Second Edit ion by David Pogue

The Missing Credits

Windows XP Pro: The Missing Manual, 2nd Edit ion by David Pogue, Craig Zacker, and Linda Zacker Windows Vist a: The Missing Manual by David Pogue

Introduction

Introduction Cascading St yle Sheet sCSS for short give you creat ive cont rol over t he layout and design of your Web pages. Using t hem , you can dress up your t ext wit h eyecat ching headings, drop caps, and borders, j ust like t he ones you see in glossy m agazines. You can also arrange im ages wit h precision, creat e colum ns and banners, and highlight your t ext links wit h dynam ic rollover effect s. Anyt hing t hat can do all t hat m ust be pret t y com plicat ed, right ? Au cont raire! The purpose of CSS is t o st ream line t he process of st yling Web pages. I n t he next few pages, you'll learn about t he basics of CSS. I n Chapt er 1, you'll get right t o work creat ing your first Web page.

How CSS Works I f you've used st yles in word processing program s like Microsoft Word or page layout program s like Adobe I nDesign, CSS will feel fam iliar. A st yle is sim ply a rule describing how t o form at a part icular port ion of a Web page. A st yle sheet is a set of t hese canned st yles. CSS is not HTML. HTML provides st ruct ure t o a docum ent by organizing inform at ion int o headers, paragraphs, bullet ed list s, and so on. CSS is anot her language alt oget her. I t works hand- in- hand wit h t he Web browser t o m ake HTML look good. For exam ple, you m ight use HTML t o t urn a phrase int o a t op- level heading, indicat ing t hat it int roduces t he cont ent on t he rest of t he page. However, you'd use CSS t o form at t hat heading wit h, say, big and bold red t ype and posit ioned 50 pixels from t he left edge of t he window. CSS is all about changing ( and im proving) t he appearance of t he HTML. You can also creat e st yles specifically for working wit h im ages. For inst ance, a st yle can align an im age along t he right edge of a Web page, surround t he im age wit h a colorful border, and place a 50- pixel m argin bet ween t he im age and t he surrounding t ext . Once you've creat ed a st yle, you can apply it t o t ext , im ages, headings, or ot her elem ent s on a page. For exam ple, you could select a paragraph of t ext and apply a st yle t o inst ant ly change t he t ext 's size, color, and font . You can also creat e st yles for specific HTML t ags, so t hat , for exam ple, all first - level headings ( < h1> t ags) in your sit e are displayed in t he sam e st yle, no m at t er where t hey appear.

The Benefits of CSS Before CSS, Web designers were lim it ed t o t he layout and st yling opt ions of HTML. And if you surfed t he Web in 1995, t hen you underst and t he em phasis on lim it ed. HTML, as you'll see lat er in t his int roduct ion, st ill form s t he foundat ion of all pages on t he World Wide Web, but it 's sim ply not a design t ool. Sure, HTML provides basic form at t ing opt ions for t ext , im ages, t ables, and ot her Web page elem ent s and pat ient , m et iculous Web m ast ers can m ake pages look pret t y good using only HTML. But t he result 's oft en sluggish, unpredict able Web pages laden wit h clunky code. CSS, in cont rast , offers t he following advant ages:

Introduction ●







St yle sheet s offer far m ore form at t ing choices t han HTML. Wit h CSS, you can form at paragraphs as t hey appear in a book or newspaper ( t he first line indent ed and no space bet ween each paragraph, for exam ple) and cont rol t he leading ( t he space bet ween lines of t ype in a paragraph) . When you use CSS t o add a background im age t o a page, you get t o decide how ( and whet her) it t iles ( repeat s) . HTML can't even begin t o do t hat . Even bet t er, CSS st yles t ake up m uch less space t han HTML's form at t ing opt ions, such as t he m uchhat ed < font > t ag. You can usually t rim a lot of kilobyt es from t ext - heavy Web pages using CSS. As a result , your pages look great and load fast er. St yle sheet s also m ake updat ing your sit e easier. You can collect all of your st yles int o a single ext ernal st yle sheet t hat 's linked t o every page in your sit e. When you edit a st yle, t hat change im m ediat ely ripples t hrough your sit e wherever t hat st yle appears. You can com plet ely change t he appearance of a sit e j ust by edit ing a single st yle sheet .

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

What You Need to Know This book assum es you've already got som e knowledge of HTML ( and perhaps som e CSS experience as well) ; you've built a sit e or t wo ( or at least a page or t wo) and have som e fam iliarit y wit h t he sea of t ags< ht m l> , < p> , < h1> , < t able> , and so ont hat m ake up t he Hypert ext Markup Language. CSS doesn't do anyt hing wit hout HTML, so t o m ove forward you need t o know how t o creat e a Web page using basic HTML. I f you have used HTML t o creat e Web pages, but feel like your knowledge is a bit rust y, t he next sect ion provides a basic refresher.

Note: 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 Web Sites: The Missing Manual, or Head First HTML with CSS & XHTML (O'Reilly).

HTML: The Barebones Structure HTML ( Hypert ext Markup Language) uses sim ple com m ands called t ags t o define t he various part s of a Web page. For exam ple, t his HTML code creat es a sim ple Web page:

Hey, I am the title of this Web page.

Introduction

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

I t m ay not be excit ing, but t his exam ple has all t he basic elem ent s a Web page needs. You'll not ice ht m l ( bet ween bracket s) at t he very beginning and very end of t he code, a header, a body, and som e st ufft he act ual page cont ent sinside t he body.

How HTML Tags Work I n t he above exam ple, as in t he HTML code of any Web page you look at , you'll not ice t hat m ost com m ands appear in pairs t hat surround a block of t ext or ot her com m ands. Sandwiched bet ween bracket s, t hese t ags are inst ruct ions t hat t ell a Web browser how t o display t he Web page. Tags are t he " m arkup" part of t he Hypert ext Markup Language. The st art ing ( opening) t ag of each pair t ells t he browser where t he inst ruct ion begins, and t he ending t ag t ells it where t he inst ruct ion ends. Ending or closing t ags always include a forward slash ( / ) aft er t he first bracket sym bol ( < ) . For a Web page t o work, you m ust include at least t hese t hree t ags: ●





The < h t m l> t ag appears once at t he beginning of a Web page and again ( wit h an added slash) at t he end. This t ag t ells a Web browser t hat t he inform at ion cont ained in t his docum ent 's writ t en in HTML, as opposed t o som e ot her language. All of t he cont ent s of a page, including ot her t ags, appear bet ween t he opening and closing < ht m l> t ags. I f you were t o t hink of a Web page as a t ree, t he < ht m l> t ag would be it s t runk. Springing from t he t runk are t wo branches t hat represent t he t wo m ain part s of any Web page: t he head and t he body. The head of a Web page, surrounded by < h e a d> t ags, cont ains t he t it le of t he page. I t m ay also provide ot her, invisible inform at ion ( such as search keywords) t hat browsers and Web search engines can exploit . I n addit ion, t he head can cont ain inform at ion t hat 's used by t he Web browser for displaying t he Web page and for adding int eract ivit y. You put Cascading St yle Sheet s, for exam ple, in t he head of t he docum ent . I n addit ion, JavaScript script s, funct ions, and variables can be declared in t he head of t he docum ent . The body of a Web page, as set apart by it s surrounding < body> t ags, cont ains all t he inform at ion t hat appears inside a browser windowheadlines, t ext , pict ures, and so on.

Wit hin t he < body> t ag, you com m only find t he following t ags: ●





You t ell a Web browser where a paragraph of t ext begins wit h a < p> ( opening paragraph t ag) , and where it ends wit h a < / p> ( closing paragraph t ag) . The < st r on g> t ag em phasizes t ext . When you surround som e t ext wit h it and it s part ner t ag, < / st rong> , you get boldface t ype. The HTML snippet < st rong> Warning! < / st rong> t ells a Web browser t o st rongly em phasize t he word " Warning! " The < a > t ag, or anchor t ag, creat es a hyperlink in a Web page. When clicked, a hyperlinkor linkcan lead anywhere on t he Web. You t ell t he browser where t he link point s by put t ing a Web address inside t he < a> t ags. For inst ance, you can t ype < a href= " ht t p: / / www.m issingm anuals.com / " > Click

Introduction

here! < / a> . The browser knows t hat when your visit or clicks t he words " Click here! " it should go t o t he Missing Manual Web sit e. The href part of t he t ag is called an at t ribut e and t he URL ( t he Uniform Resource Locat or or Web address) is t he value. I n t his exam ple, ht t p: / / www.m issingm anuals.com is t he value of t he href at t ribut e. Like any t echnology, HTML's showing it s age. Alt hough it 's served it s purpose well, it 's always been a som ewhat sloppy language. Am ong ot her t hings, it allows uppercase, lowercase, or m ixed case let t ers in t ags ( < body> and < BODY> are bot h correct , for exam ple) , and perm it s unclosed t ags ( so t hat you can use a single < p> t ag wit hout t he closing < / p> t o creat e a paragraph) . While t his flexibilit y m ay m ake page writ ing easier, it also m akes life m ore difficult for Web browsers, PDAs, and ot her places you want t o display your pages. Furt herm ore, HTML doesn't work wit h one of t he hot t est up- and- com ing I nt ernet languages: XML or Ext ensible Markup Language. XML is a t ag- based language, som ewhat like HTML, t hat 's used t o organize dat a in a clear, easy t o underst and way so t hat different com put ers, operat ing syst em s, and program s can quickly and easily exchange dat a. However, unlike HTML, XML isn't lim it ed t o a handful of t ags, I n fact , XML provides a set of rules for defining your own t ags. XHTML, which you'll read about next , is one exam ple of XMLbut t here are m any ot hers: from RSS feeds t o iTunes playlist s.

XHTML: HTML for the New Era To keep pace wit h t he t im es, an " im proved" version of HTML, called XHTML is finding it s way int o m ore and m ore Web sit es. I f you already underst and HTML, don't worryXHTML isn't a revolut ionary new language t hat t akes years t o learn. I t 's basically HTML, but wit h st rict er guidelines. The hot debat e's whet her HTML or XHTML is t he best approach. To j udge by som e of t he online discussions, you'd t hink HTML and XHTML are com plet ely different languages. They aren't . You can build snazzy and funct ional Web sit es wit h HTML now and will probably be able t o cont inue in t he fut ure. I f you cont inue using HTML, t he m ost im port ant t hing is t hat you follow t he guidelines discussed in Chapt er 1: in part icular, an HTML page m ust use t he correct " Doct ype" ( Sect ion 1.3) or your CSS will fall apart in cert ain browsers, and it m ust " validat e" ( Sect ion 1.2.4) so t hat you know for sure t here aren't any t ypos or ot her m ist akes t hat can m ess up how your HTML displays. You need t o do t hose sam e t hings for XHTML, but because it 's st rict er t han HTML it enforces rules t hat m ake sure t he page works ( for exam ple, a Doct ype isn't absolut ely required in HTML; it is wit h XHTML) . XHTML's t he fut ure of Web page languages: t here won't be any fut ure versions of HTML, but t here's a lot of work being put int o creat ing t he next generat ion of XHTML. ( Don't hold your breat h, t houghit 'll be years before t here's wide support in browsers for it .)

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

The HTML page code shown in Sect ion 3.3 would look like t his in XHTML:

Introduction



Hey, I am the title of this Web page.

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



As you can see, t his code looks a lot like HTML. To m ake an XHTML file com ply wit h XML, however, t here are a few st rict rules t o keep in m ind: ●







Be gin t h e pa ge w it h a docu m e n t t ype de cla r a t ion . That 's t he first few lines in t he code above, st art ing wit h < ! DOCTYPE. The docum ent t ype declarat ion is t he m ost im port ant part of an XHTML page, as you'll see in t he next sect ion. Ta gs a n d t a g a t t r ibu t e s m u st be low e r ca se . Unlike wit h HTML, t yping t he t ag < BODY> is a nono; when you're writ ing XHTML, capit alized t ags aren't invit ed t o t he part y. Qu ot a t ion m a r k s a r e r e qu ir e d for t a g a t t r ibu t e s. For exam ple, a link writ t en like t his: < a href= ht t p: / / www.m issingm anuals.com > is valid in HTML, but won't work in XHTML. You have t o enclose t he value of t he Href propert y in quot es: < a href= " ht t p: / / www.m issingm anuals.com " > . All t a gs ( e ve n e m pt y t a gs) m u st be close d. To creat e a paragraph in XHTML, for exam ple, you m ust begin wit h < p> and end wit h < / p> . Trouble is, som e t ags don't com e in pairs. These t ags, called em pt y t ags have no closing t ag. The line break t ag's one exam ple. To close an em pt y t ag, include a backslash at t he end of t he t ag, like t his: < br / > .

What the Doctype Does I n t he exam ple XHTML code, everyt hing below t he < head> is exact ly t he sam e as t he HTML page you looked at earlier. The inform at ion t hat begins t he page, however, is very different . Each XHTML page begins wit h a few lines t hat st at e what t ype of docum ent t he page is and which st andard it conform s t o. This docum ent t ype declarat iondoct ype for short also point s t he Web browser t o files on t he I nt ernet t hat cont ain definit ions for t hat t ype of file. I n t his case, it m erely says t hat t he page is a t ype of XML docum ent , in part icular, an XHTML docum ent . The doct ype plays a key role in how a Web browser displays CSSin fact a m issing or incorrect doct ype's enough t o m ake I nt ernet Explorer com plet ely m ishandle t he present at ion of a CSS- heavy Web page. You'll learn m uch m ore about doct ypesand t heir im port ance t o CSSin Chapt er 1.

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

Introduction

Software for CSS To creat e Web pages m ade up of HTML and CSS you need not hing m ore t han a basic t ext edit or like Not epad ( Windows) or Text Edit ( Mac) . But aft er t yping a few hundred lines of HTML and CSS you m ay want t o t ry a program bet t er suit ed t o working wit h Web pages. This sect ion list s som e com m on program s; som e of t hem are free and som e you have t o buy.

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

Free Programs There are plent y of free program s out t here for edit ing Web pages and st yle sheet s. I f you're st ill using Not epad or Text Edit , t hen give one of t hese a t ry. Here's a short list t o get you st art ed: H TM L- Kit ( Windows, www.cham i.com / ht m l- kit / ) . This powerful HTML/ XHTML edit or includes lot s of useful feat ures like t he abilit y t o preview a Web page direct ly in t he program ( so you don't have t o swit ch back and fort h bet ween browser and edit or) , short cut s for adding HTML t ags, and a lot m ore. Te x t W r a n gle r ( Mac, www.barebones.com / product s/ t ext wrangler/ ) . This free soft ware's act ually a paired down version of BBEdit , t he sophist icat ed, well- known t ext edit or for t he Mac. Text Wrangler doesn't have all of BBEdit 's built - in HTMLt ools, but it does include synt ax- coloring ( m eaning t hat t ags and propert ies are highlight ed in different colors so it 's easy t o scan a page and ident ify it s part s) , FTP support ( so you can upload files t o a Web server) , and m ore.

Commercial Software Com m ercial Web sit e developm ent program s range from inexpensive t ext edit ors t o com plet e Web sit e const ruct ion t ools wit h all t he bells and whist les: Edit Plu s ( Windows, www.edit plus.com ) is an inexpensive ( $30) t ext edit or t hat includes synt ax- coloring, FTP, aut o- com plet ion and ot her wrist - saving feat ures. sk Edit ( Mac, www.skt i.org) is a cheap ( $25) Web page edit or, com plet e wit h FTP/ SFTP support , code hint s and ot her useful feat ures. BBEdit ( Mac, www.barebones.com / product s/ bbedit ) . This m uch- loved Mac t ext edit or ( $199) has plent y of t ools for working wit h HTML, XHTML, CSS and m ore. I ncludes m any useful Web building t ools and short cut s. D r e a m w e a ve r ( Mac and Windows, www.m acrom edia.com / soft ware/ dream weaver) is a visual Web page edit or ( $399.) I t let s you see how your page looks in a Web browser. The program also includes a powerful t ext - edit or and excellent CSS creat ion and m anagem ent t ools. Check out Dream weaver: The Missing Manual for t he full skinny on how t o use t his powerful program .

Introduction

Ex pr e ssion W e b D e sign e r ( Windows, www.m icrosoft .com ) is Microsoft 's new ent ry in t he Web design field. I t replaces Front Page and includes m any professional Web design t ools including very good support for creat ing CSS.

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

About This Book The World Wide Web is really easy t o use. Aft er all, grandm ot hers in Boise and first graders in Tallahassee log ont o t he Web every day. Unfort unat ely, t he rules t hat govern how t he Web works aren't so easy t o underst and. The com put er scient ist s and ot her t echie t ypes who writ e t he official docum ent at ion aren't int erest ed in explaining t heir concept s t o t he average Joe ( or Joanne) . Just check out www.w3.org/ TR/ CSS21/ t o get a t ast e of t he t echnical m um bo- j um bo t hese geeks speak. There's no m anual for Cascading St yle Sheet s. People j ust learning CSS oft en don't know where t o begin. And t he finer point s regarding CSS can t rip up even seasoned Web pros. The purpose of t his book, t hen, is t o serve as t he m anual t hat should have com e wit h CSS. I n t his book's pages, you'll find st ep- by- st ep inst ruct ions for using CSS t o creat e beaut iful Web pages. CSS: The Missing Manual is designed t o help readers at every t echnical level. To get t he m ost out of t his book, you should know a sam pling of HTML and m aybe even CSS. So if you've never built a Web page before, t hen check out t he t ut orial t hat st art s in Sect ion 2.5. The prim ary discussions in t hese chapt ers are writ t en for advanced- beginners or int erm ediat es. But if you're new t o building Web pages, special boxes called " Up t o Speed" provide t he int roduct ory inform at ion you need t o underst and t he t opic at hand. I f you're an advanced Web page j ockey, on t he ot her hand, t hen keep your eye out for sim ilar shaded boxes called Power Users' Clinic. They offer m ore t echnical t ips, t ricks, and short cut s for t he experienced com put er fan.

UP TO SPEED The Different Flavors of CSS

Introduction

Like operat ing syst em s and iPods, CSS spins off new versions cont inuously. CSS 1, int roduced in 1996, laid t he groundwork for Cascading St yle Sheet s. The basic st ruct ure of a st yle, t he select or concept ( Chapt er 3) , and m ost of t he CSS propert ies in t his book were all in t hat very first version. CSS 2 added new feat ures, including t he abilit y t o t arget your CSS t o different print ers, m onit ors, and ot her devices ( Sect ion 13.1) . CSS 2 also added new select ors and t he abilit y t o precisely posit ion elem ent s on a Web page. This book covers CSS 2.1, which is t he current accept ed st andard for Cascading St yle Sheet s. I t incorporat es all of CSS 1, adds several new propert ies, and correct s a few problem s wit h t he CSS 2 guidelines. CSS 2.1 isn't a radical change from version 2, and m ost Web browsers have adapt ed t o t he new rules j ust fine, t hank you. ( A not able except ion is I nt ernet Explorer 6 for Windowst hat 's why you'll find helpful workarounds for dealing wit h browser differences sprinkled t hroughout t his book. Thankfully, I nt ernet Explorer 7 has fixed m ost of t he hair- pulling bugs of it s ancest ors.) CSS 3 is j ust around t he corner. Alt hough t he W3C st ill has t o finalize t his st andard, som e Web browsers are already adopt ing a few of it s new guidelines and feat ures. Safari's abilit y t o add m ult iple im ages t o t he background of a single elem ent , for exam ple, is t hanks t o CSS 3. However, since CSS 3 is st ill evolving, m ost browsers don't deal wit h it m uchand neit her does t his book.

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 Mediabut not always. If there's a great book out there that's not part of the O'Reilly family, we'll let you know about it.

About the Outline CSS: The Missing Manual is divided int o four part s, each cont aining several chapt ers: ●







Part 1, CSS Ba sics, shows you how t o creat e st yle sheet s and provides an overview of key CSS concept s, like inherit ance, select ors, and t he cascade. Along t he way, you'll learn t he best HTML/ XHTML writ ing pract ices when working wit h CSS. Four t ut orials reinforce t he part 's m ain concept s and give you a good t ast e of t he power of CSS. Part 2, Applie d CSS, t akes you int o t he real world of Web design. You'll learn t he m ost im port ant CSS propert ies and how t o use t hem t o form at t ext , creat e useful navigat ion t ools, and enhance your page wit h graphics. This sect ion also provides advice on how t o m ake Web pages look bet t er when print ed and how t o m ake at t ract ive t ables and form s. Part 3, CSS Pa ge La you t , helps you wit h one of t he m ost confusing, but m ost rewarding, aspect s of CSS: cont rolling t he placem ent of elem ent s on a page. You'll learn how t o creat e com m on designs ( like 2 and 3- colum n layout s) and how t o add sidebars. You'll also learn about float s and posit ioningt wo com m on CSS t echniques for cont rolling page layout . Part 4, Adva n ce d CSS, t eaches you how t o m ake web pages look good when print ed and covers

Introduction



advanced t echniques for using CSS m ore effect ively and efficient ly. Part 5, Appe n dix e s, provides t hree set s of resources. The CSS Propert y Reference sum m arizes each CSS Propert y in sm all, easy- t o- digest , chunks so you can casually brush- up on what you already know, or quickly learn about ot her useful CSS propert ies t hat you m ay not rem em ber. The last t wo appendices cover t ools and resources for creat ing and using CSS, from how t o creat e CSS in Dream weaver t o list s of helpful Web sit es and books.

Living Examples This book is designed t o get your work ont o t he Web fast er and m ore professionally. I t 's only nat ural, t hen, t hat half t he value of t his book lies on t he Web. As you read t he book's chapt ers, you'll encount er a num ber of living exam plesst ep- by- st ep t ut orials t hat you can build yourself, using raw m at erials ( like graphics and half- com plet ed Web pages) t hat you can download from www.sawm ac.com / css/ . You m ay not gain very m uch by sim ply reading t hese st ep- by- st ep lessons while relaxing in your porch ham m ock. But if you t ake t he t im e t o work t hrough t hem at t he com put er, you'll discover t hat t hese t ut orials give you insight int o t he way professional designers build Web pages. You'll also find, in t his book's lessons, t he URLs of t he finished pages, so t hat you can com pare your work wit h t he final result . I n ot her words, you won't j ust see pict ures of how t he Web pages should look: You'll find t he act ual, working Web pages on t he I nt ernet .

About MissingManuals.com At t he Missing Manuals Web sit e ( www.m issingm anuals.com ) , you'll find art icles, t ips, and updat es t o t he book. I n fact , we invit e and encourage you t o subm it such correct ions and updat es yourself. I n an effort t o keep t he book as up- t o- dat e and accurat e as possible, each t im e we print m ore copies of t his book, we'll m ake any confirm ed correct ions you've suggest ed. We'll also not e such changes on t he Web sit e, so t hat you can m ark im port ant correct ions int o your own copy of t he book, if you like. ( Click t he book's nam e, and t hen click t he Errat a link, t o see t he changes.) I n t he m eant im e, we'd love t o hear your suggest ions for new books in t he Missing Manual line. There's a place for t hat on t he Web sit e, t oo, as well as a place t o sign up for free em ail not ificat ion of new t it les in t he series.

The Very Basics To use t his book, and indeed t o use a com put er, you need t o know a few basics. You should be fam iliar wit h t hese t erm s and concept s: ●



Click in g. This book gives you t hree kinds of inst ruct ions t hat require you t o use your com put er's m ouse or t rackpad. To click m eans t o point t he arrow cursor at som et hing on t he screen and t henwit hout m oving t he cursor at allt o press and release t he clicker but t on on t he m ouse ( or lapt op t rackpad) . To double- click, of course, m eans t o click t wice in rapid succession, again wit hout m oving t he cursor at all. And t o drag m eans t o m ove t he cursor while pressing t he but t on. - click som et hing on t he Mac, or Ct rl- click som et hing on a PC, you click while When you're t old t o or Ct rl key ( bot h of which are near t he Space bar) . pressing t he M e n u s. The m enus are t he words at t he t op of your screen or window: File, Edit , and so on. Click one t o m ake a list of com m ands appear, as t hough t hey're writ t en on a window shade you've j ust pulled down.

Introduction ●

Ope r a t in g- syst e m ba sics. This book assum es t hat you know how t o open a program , surf t he Web, and download files. You should know how t o use t he St art m enu ( Windows) and t he Dock or m enu ( Macint osh) , as well as t he Cont rol Panel ( Windows) , or Syst em Preferences ( Mac OS X) .

I f you've m ast ered t his m uch inform at ion, you have all t he t echnical background you need t o enj oy CSS: The Missing Manual.

About

These

Arrows

Throughout t his book, and t hroughout t he Missing Manual series, you'll find sent ences like t his one: " Open Library Font s folder." That 's short hand for a m uch longer inst ruct ion t hat direct s you t he Syst em t o open t hree nest ed folders in sequence, like t his: " On your hard drive, you'll find a folder called Syst em . Open t hat . I nside t he Syst em folder window is a folder called Library; double- click it t o open it . I nside t hat folder is yet anot her one called Font s. Double- click t o open it , t oo." Sim ilarly, t his kind of arrow short hand helps t o sim plify t he business of choosing com m ands in m enus, as shown in Figure I - 1.

Figu r e I - 1 . I n t h is book , a r r ow n ot a t ion s h e lp sim plify m e n u in st r u ct ion s. For e x a m ple , Vie w Te x t Size I n cr e a se is a m or e com pa ct w a y of sa yin g, " Fr om t h e Vie w m e n u , ch oose Te x t Size ; fr om t h e su bm e n u t h a t t h e n a ppe a r s, ch oose I n cr e a se .

Introduction

Safari® Enabled

When you see a Safari® Enabled icon on t he cover of your favorit e t echnology book, t hat m eans it 's available online t hrough t he O'Reilly Net work Safari Bookshelf. Safari offers a solut ion t hat 's bet t er t han e- books: it 's a virt ual library t hat let s you easily search t housands of t op t ech books, cut and past e code sam ples, download chapt ers, and find quick answers when you need t he m ost accurat e, current inform at ion. Try it for free at ht t p: / / safari.oreilly.com .

Part I: CSS Basics

Part I: CSS Basics Ch a pt e r 1 : Re t h in k in g H TM L for CSS Ch a pt e r 2 : Cr e a t in g St yle s a n d St yle Sh e e t s Ch a pt e r 3 : Se le ct or Ba sics: I de n t ifyin g W h a t t o St yle Ch a pt e r 4 : Sa vin g Tim e w it h I n h e r it a n ce Ch a pt e r 5 : M a n a gin g M u lt iple St yle s: Th e Ca sca de

Chapter 1. Rethinking HTML for CSS

Chapter 1. Rethinking HTML for CSS To get t he m ost out of CSS, your HTML code needs t o provide a solid, well- built foundat ion. This chapt er shows you how t o writ e bet t er, m ore CSS- friendly HTML. The good news is t hat when you use CSS t hroughout your sit e, HTML act ually becom es easier t o writ e. You no longer need t o worry about t rying t o t urn HTML int o t he design m aven it was never int ended t o be; inst ead, CSS offers all t he graphic design t ouches you'll likely ever want . And your j ob becom es sim pler since HTML pages writ t en t o work wit h CSS require less code, less t yping, and are easier t o creat e. They'll also download fast era welcom e bonus your sit e's visit ors will appreciat e ( see Figure 1- 1) .

Section 1.1. HTML: Past and Present

1.1. HTML: Past and Present As discussed in t he I nt roduct ion, HTML and it s successor, XHTML, provide t he foundat ion for every page you encount er on t he World Wide Web. When you add CSS int o t he m ix, t he way you use HTML changes. Say goodbye t o repurposing awkward HTML t ags m erely t o achieve cert ain visual effect s. Som e HTML t ags and at t ribut eslike t he < font > t agyou can forget com plet ely. The following sect ions explain why.

Note: Throughout this chapter, everything you read about HTML applies equally to XHTML. There are 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 painfully crafted page. You'll learn how to tell CSS which flavor of HTML/ XHTML you're using later in this chapter.

Figu r e 1 - 1 . CSS- dr ive n W e b de sign m a k e s w r it in g H TM L e a sie r . Th e t w o de sign s pict u r e d h e r e look sim ila r , bu t t h e t op pa ge is st yle d com ple t e ly w it h CSS, w h ile t h e bot t om pa ge u se s on ly H TM L. Th e size of t h e H TM L file for t h e t op pa ge is on ly 4 k , w h ile t h e H TM L- on ly pa ge is n e a r ly 4 t im e s t h a t size a t 1 4 k . Th e H TM Lon ly a ppr oa ch r e qu ir e s a lot m or e code t o a ch ie ve n e a r ly t h e sa m e visu a l e ffe ct s: 2 1 3 t o 7 1 lin e s of H TM L code for t h e CSS ve r sion .

Section 1.1. HTML: Past and Present

1.1.1. HTML Past: Whatever Looked Good When a bunch of scient ist s creat ed t he Web t o help share and keep t rack of t echnical docum ent at ion, nobody called in t he graphic designers. All t he scient ist s needed HTML t o do was t o clearly st ruct ure inform at ion for easy com prehension. For exam ple, t he < h1> t ag indicat es an im port ant headline, while t he < h2> t ag represent s a lesser heading, usually a subheading of t he < h1> t ag. Anot her favorit e, t he < ol> ( ordered list ) t ag, creat es a num bered list for t hings like " Top 10 reasons not t o play wit h j ellyfish." But as soon as people besides scient ist s st art ed using HTML, t hey want ed t heir Web pages t o look good. So Web designers st art ed t o use t ags t o cont rol appearance rat her t han st ruct ure inform at ion. For exam ple, you can use t he < blockquot e> t ag ( int ended for m at erial t hat 's quot ed from anot her source) on any t ext t hat you want t o indent a lit t le bit . You can use heading t ags t o m ake any t ext bigger and bolderregardless of whet her it funct ions as a heading. I n an even m ore elaborat e workaround, designers learned how t o use t he < t able> t ag t o creat e colum ns of t ext , and t o accurat ely place pict ures and t ext on a page. Unfort unat ely, since t hat t ag was int ended t o display spreadsheet - like dat aresearch result s, t rain schedules, and so ondesigners had t o get creat ive by

Section 1.1. HTML: Past and Present

using t he < t able> t ag in unusual ways, som et im es nest ing a t able wit hin a t able wit hin a t able in order t o m ake t heir pages look good. Meanwhile, browser m akers int roduced new t ags and at t ribut es for t he specific purpose of m aking a page look bet t er. The < font > t ag, for exam ple, let s you specify a font color, t ypeface, and one of seven different sizes. ( I f you're keeping score at hom e, t hat 's about 100 fewer sizes t han you can get wit h, say, Microsoft Word.) Finally, when designers couldn't get exact ly what t hey want ed, t hey oft en resort ed t o using graphics. For exam ple, t hey'd use a very large graphic as background for a Web page or slice it up int o sm aller graphic files and piece t hem back t oget her inside t ables t o recreat e t he original im age. While all of t he above t echniquesusing t ags in creat ive ways, t aking advant age of design- specific t ag at t ribut es, and m aking ext ensive use of graphicsprovide design cont rol over your pages, t hey also add a lot of addit ional HTML code ( and m ore wrinkles t o your forehead t han a lifet im e in t he sun) .

1.1.2. HTML Present: Scaffolding for CSS No m at t er what cont ent your Web page holdst he fishing season calendar, driving direct ions t o t he nearest I KEA, or pict ures from your kid's last birt hday part yit 's t he page's design t hat m akes it look like eit her a professional ent erprise or a part - t im er's hobby. Good design enhances t he m essage of your sit e, helps visit ors find what t hey're looking for and det erm ines how t he rest of t he world sees your Web sit e. That 's why Web designers went t hrough t he cont ort ions described in t he previous sect ion t o force HTML t o look good. By t aking on t hose design dut ies, CSS let s HTML go back t o doing what it does best st ruct ure cont ent ( m ore on what t hat m eans in a m om ent ) . Using HTML t o cont rol t he look of t ext and ot her Web page elem ent s is obsolet e. Don't worry if HTML's < h1> t ag is t oo big for your t ast e or bullet ed list s aren't spaced j ust right . You can t ake care of t hat lat er using CSS. I nst ead, t hink of HTML as a m et hod of adding st ruct ure t o t he cont ent you want up on t he Web. Use HTML t o organize your cont ent , and CSS t o m ake t hat cont ent look great .

Section 1.2. Writing HTML for CSS

1.2. Writing HTML for CSS I f you're new t o Web design, you m ay need som e helpful hint s t o guide your forays int o HTML ( and t o st eer clear of wellint ent ioned, but out - of- dat e HTML t echniques) . And if you've been building Web pages for a while, t hen you m ay have picked up a few bad HTML- writ ing habit s t hat you're bet t er off forget t ing. The rest of t his chapt er int roduces you t o som e HTML writ ing habit s t hat will m ake your m ot her proudand help you get t he m ost out of CSS.

1.2.1. Think Structure HTML adds m eaning t o t ext by logically dividing it and ident ifying t he role t hat t ext plays on t he page: for exam ple, t he < h1> t ag's t he m ost im port ant int roduct ion t o a page's cont ent . Ot her headers let you divide up t he cont ent int o ot her, less im port ant , but relat ed sect ions. Just like t he book you're holding, for exam ple, a Web page should have a logical st ruct ure. Each chapt er in t his book has a t it le ( t hink < h1> ) ; and several sect ions ( t hink < h2> ) , which in t urn cont ain sm aller subsect ions. I m agine how m uch harder it would be t o read t hese pages if every word j ust ran t oget her as one long paragraph.

Note: For a good resource on HTML/ XHTML check out HTML & XHTML: The Definitive Guide (O'Reilly) by Chuck Musciano and Bill Kennedy, 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 m any ot her t ags besides headers for m arking up ( t hat 's t he M in HTML) cont ent t o ident ify it s role on t he page. Am ong t he m ost popular are t he < p> t ag for paragraphs of t ext , and t he < ul> t ag for creat ing bullet ed ( non- num bered) list s. Lesser- known t ags can indicat e very specific t ypes of cont ent , like < abbr> for abbreviat ions and < code> for com put er code. When writ ing HTML for CSS, use a t ag t hat com es close t o m at ching t he role t he cont ent plays in t he page, not t he way it looks ( see Figure 1- 2) . For exam ple, a bunch of links in a navigat ion bar isn't really a headline and it isn't a regular paragraph of t ext . I t 's m ost like a bullet ed list of opt ions, so t he < ul> t ag is a good choice. I f you're saying " but it em s in a bullet ed list are st acked vert ically one on t op of t he ot her, and I want a horizont al navigat ion bar where each link sit s next t o t he previous link," don't worry. Wit h CSS m agic you can convert a vert ical list of links int o a st ylish horizont al navigat ion bar as described in Chapt er 9.

1.2.2. Two New HTML Tags to Learn HTML's m ot ley assort m ent of t ags doesn't cover t he wide range of cont ent you'll probably add t o a page. Sure, < code> is great for m arking up com put er program code, but m ost folks would find a < recipe> t ag handier. Too bad t here isn't one. Fort unat ely, HTML provides t wo generic t ags t hat let you bet t er ident ify cont ent , and, in t he process, provide " handles" t hat let you at t ach CSS st yles t o different elem ent s on a page.

Figu r e 1 - 2 . Old Sch ool, N e w Sch ool. Be for e CSS, de sign e r s h a d t o r e sor t t o t h e < fon t > t a g a n d ot h e r e x t r a H TM L t o a ch ie ve ce r t a in visu a l e ffe ct s ( t op) . You ca n a ch ie ve t h e sa m e ( a n d oft e n be t t e r ) look w it h a lot le ss H TM L code ( bot t om .) I n a ddit ion , by u sin g CSS t o for m a t you r W e b pa ge s, you 'r e fr e e t o w r it e H TM L t h a t follow s t h e logica l st r u ct u r e of t h e pa ge 's con t e n t .

Section 1.2. Writing HTML for CSS

GEM IN THE ROUGH Simple HTML Is Search Engine Friendly Once you t ake t he m ent al leap of pict uring HTML as t he way t o st ruct ure a docum ent 's cont ent , and CSS as t he t ool for m aking t hat cont ent look good, you'll discover addit ional benefit s t o writ ing lean, m ean HTML. For one t hing, you m ay boost your search engine ranking as det erm ined by sit es like Google, Yahoo, and MSN. That 's because when search engines crawl t he Web, indexing t he cont ent on Web sit es, t hey m ust go t hrough all t he HTML on a page t o discover t he act ual cont ent . The old HTML- way of using special t ags ( like < font > ) and lot s of t ables t o design a page, get s in t he way of a search engine's j ob. I n fact , som e search engines st op reading a page's HTML aft er a cert ain num ber of charact ers. When you use a lot of HTML j ust for design, t he search engine m ay m iss im port ant cont ent on t he page, or even fail t o rank it at all. By cont rast , sim ple, st ruct ured HTML is easy for a search engine t o read and index. Using an < h1> t ag t o indicat e t he m ost im port ant t opic of t he page ( as opposed t o j ust m aking t he t ext big and bold) is sm art st rat egy: Search engines give great er weight t o t he cont ent s inside t hat t ag while indexing t he page. To see Google's suggest ions for building search- friendly Web sit es, visit www.google.com / webm ast ers/ guidelines. ht m l. You can also hear a podcast of an excellent speech on SEO ( search engine opt im izat ion) from t he 2005 Web Visions

Section 1.2. Writing HTML for CSS

conference at ht t p: / / www.webvisionsevent .com / podcast s/ WV05_Alan_Knecht .m p3 and read an art icle by t hat speaker covering t he sam e t opic at : www.digit al- web.com / art icles/ seo_and_your_web_sit e/ .

The < div> t ag and t he < span> t ag are like em pt y vessels t hat you fill wit h cont ent . Since t hey have no inherent visual propert ies, you can use CSS t o m ake t hem look any way you want . The < div> ( for division) t ag indicat es any discret e block of cont ent , m uch like a paragraph or a headline. But you can also use it t o surround any num ber of ot her elem ent s, so you can insert a headline, a bunch of paragraphs, and a bullet ed list inside a single < div> block. The < div> t ag is a great way t o subdivide a page int o logical areas, like a banner, foot er, sidebar, and so on. Using CSS, you can lat er posit ion each area t o creat e sophist icat ed page layout s ( a t opic t hat 's covered in Part Three of t his book) . The < span> t ag is used for inline elem ent s; t hat is, words or phrases t hat appear inside of a larger paragraph or heading. Treat it j ust like ot her inline HTML t ags such as t he < a> t ag ( for adding a link t o som e t ext in a paragraph) or t he < st rong> t ag ( for em phasizing a word in a paragraph) . For exam ple, you could use a < span> t ag t o indicat e t he nam e of a com pany, and t hen use CSS t o highlight t he nam e using a different font , color, and so on. Here's an exam ple of t hose t ags in act ion, com plet e wit h a sneak peek of a couple of at t ribut esid and classfrequent ly used t o at t ach st yles t o part s of a page.

Copyright 2006, CosmoFarmer.com

Call customer service at 555-555-5501 for more information



This brief int roduct ion isn't t he last you'll see of t hese t ags. They're used frequent ly in CSS- heavy Web pages, and in t his book you'll learn how t o use t hem in com binat ion wit h CSS t o gain creat ive cont rol over your Web pages ( Sect ion 3.1) .

1.2.3. HTML to Forget CSS let s you writ e sim pler HTML for one big reason: You can st op using a bunch of t ags and at t ribut es t hat only m ake a page bet t er looking. The < font > t ag is t he m ost glaring exam ple. I t s sole purpose is t o add a color, size and font t o t ext . I t doesn't do anyt hing t o m ake t he st ruct ure of t he page m ore underst andable. Here's a list of t ags and at t ribut es you can easily replace wit h CSS: ●



Dit ch < fon t > for cont rolling t he display of t ext . CSS does a m uch bet t er j ob wit h t ext . ( See Chapt er 6 for t ext - form at t ing t echniques.) St op using < b> and < i> t o m ake t ext bold and it alic. CSS can m ake any t ag bold or it alic, so you don't need t hese form at t ing- specific t ags. However, if you want t o really em phasize a word or phrase, t hen use t he < st r on g> t ag ( browsers display < st rong> t ext as bold anyway) . For slight ly less em phasis, use t he < e m > t ag t o em phasize t ext ( browsers it alicize cont ent inside t his t ag) .

Note: To italicize a publication's title, the tag kills two birds with one stone. It puts the title in italics and tags it as a cited work for search engines' benefit. This one's a keeper. ●





Skip t he < t a ble > t ag for page layout . Use it only t o display t abular inform at ion like spreadsheet s, schedules, and chart s. As you'll see in Part 3 of t his book, you can do all your layout wit h CSS for m uch less t im e and code t han t he t able t ag t ango. Elim inat e t he awkward < body> t ag at t ribut es t hat enhance only t he present at ion of t he cont ent : ba ck gr ou n d, bgcolor , t e x t , lin k , a lin k , and vlin k set colors and im ages for t he page, t ext , and links. CSS get s t he j ob done bet t er ( see Chapt er 7 and Chapt er 8 for CSS equivalent s of t hese at t ribut es) . Also t rash t he browser- specific at t ribut es used t o set m argins for a page: le ft m a r gin , t opm a r gin , m a r gin w idt h , m a r gin h e igh t . CSS handles page m argins easily ( see Chapt er 7) . Don't abuse t he < br / > t ag. I f you grew up using t he < br / > t ag ( < br> in HTML) t o insert a line break wit hout creat ing a new paragraph, t hen you're in for a t reat . ( Browsers aut om at icallyand som et im es infuriat inglyinsert a bit of space bet ween paragraphs, including bet ween headers and < p> t ags. I n t he past , designers used elaborat e workarounds t o avoid paragraph spacing t hey didn't want , like replacing a single < p> t ag wit h a bunch of line breaks and using a < font > t ag t o m ake t he first line of t he paragraph look like a headline.) Using CSS's m argin cont rols you can easily set t he am ount of space you want t o see bet ween paragraphs, headers and ot her block- level elem ent s ( see Sect ion 7.2) .

As a general rule, adding at t ribut es t o t ags t hat set colors, borders, background im ages, or alignm ent including at t ribut es t hat let you form at a t able's colors, backgrounds, and bordersis pure old- school HTML. So is using alignm ent propert ies t o posit ion im ages and cent er t ext in paragraphs and t able cells. I nst ead, look t o CSS t o cont rol t ext placem ent ( see Sect ion 6.4.1.2) , borders ( Sect ion

Section 1.2. Writing HTML for CSS

7.3) , backgrounds ( page145) , and im age alignm ent ( Sect ion 8.2) .

1.2.4. Tips to Guide Your Way I t 's always good t o have a m ap for get t ing t he lay of t he land. I f you're st ill not sure how t o use HTML t o creat e well- st ruct ured Web pages, t hen here are a few t ips t o get you st art ed: ●



Use only one < h 1 > t ag per page, and use it t o ident ify t he m ain t opic of t he page. Think of it as a chapt er t it le: you only put one t it le per chapt er. Using < h1> correct ly has t he added benefit of helping t he page get properly indexed by search engines ( see t he box in Sect ion 1.2.1) . Use headings t o indicat e t he relat ive im port ance of t ext . Again, t hink out line. When t wo headings have equal im port ance in t he t opic of your page, use t he sam e level header on bot h. I f one is less im port ant or a subt opic of t he ot her, t hen use t he next level header. For exam ple, follow a < h2> wit h a < h3> t ag ( see Figure 1- 4) . I n general, it 's good t o use headings in order and t ry not t o skip heading num bers. For exam ple, don't follow a < h2> t ag wit h a < h5> t ag.

UP TO SPEED Validate Your Web Pages HTML follows cert ain rules: For exam ple, t he < ht m l> t ag wraps around t he ot her t ags on a page and t he < t it le> t ag needs t o appear wit hin t he < head> t ag. XHTML provides an even m ore st rict set of rules t o follow. I t 's easy t o forget t hese rules, or sim ply m ake a t ypo. I ncorrect ( or invalid, as t he geeks would say) HTML causes problem s like m aking your page look different in different Web browsers. More im port ant ly, you can't creat e valid CSS wit h invalid HTML. Fort unat ely, t here are t ools for checking whet her t he HTML in your Web pages is correct ly writ t en. The easiest way t o checkt hat is, validat eyour pages is on t he W3C's Web sit e at ht t p: / / validat or.w3.org/ ( see Figure 1- 3) . The W3C, or World Wide Web Consort ium , is t he organizat ion responsible for det erm ining t he st andards for m any of t he t echnologies and languages of t he Web, including HTML, XHTML, and XML. I f t he W3C validat or finds any errors in your page, it t ells you what t hose errors are. I f you use Firefox, you can download an ext ension t hat let s you validat e a Web page direct ly in t hat browser, wit hout having t o visit t he W3C sit e. I t can even at t em pt t o fix any problem s it encount ers. You can get t he ext ension here: ht t p: / / users.skynet .be/ m gueury/ m ozilla/ . A sim ilar t ool is available for t he Safari browser as well: www.zappat ic. net / safarit idy/ .

Figu r e 1 - 3 . Th e W 3 C H TM L va lida t or loca t e d a t h t t p:/ / va lida t or .w 3 .or g le t s you qu ick ly m a k e su r e t h e H TM L in a pa ge is sou n d. You ca n e it h e r poin t t h e va lida t or t o a n a lr e a dy e x ist in g pa ge on t h e W e b, u ploa d a n H TM L file fr om you r com pu t e r , or j u st t ype or pa st e t h e H TM L of a W e b pa ge in t o a for m box a n d pr e ss t h e su bm it bu t t on t o ch e ck it .

Section 1.2. Writing HTML for CSS

● ●

Use t he < p> t ag for, duh, paragraphs of t ext . Use unordered list s when you've got a list of several relat ed it em s, such as navigat ion links, headlines, or a set of t ips like t hese.

Figu r e 1 - 4 . Use t h e h e a dlin e t a gs ( < h 1 > , < h 2 > a n d so on ) lik e you w ou ld if you w e r e ou t lin in g a sch ool r e por t : pu t t h e m in or de r of im por t a n ce , be gin n in g w it h a n < h 1 > t a g, w h ich sh ou ld sh ou t " List e n u p! Th is is w h a t t h is w h ole pa ge is a bou t ."

Section 1.2. Writing HTML for CSS

















Use num bered list s t o indicat e st eps in a process, or define t he order of a set of it em s. The t ut orials in t his book ( see Sect ion 6.6.1) are a good exam ple, as is a list of rankings like " Top 10 Web sit es popular wit h Monks." To creat e a glossary of t erm s and t heir definit ions or descript ions, use t he < dl> ( definit ion list ) t ag in conj unct ion wit h t he < dt > ( definit ion t erm ) and < dd> ( definit ion descript ion) t ags. ( For an exam ple of how t o use t his com bo visit www. w3schools.com / t ags/ t ryit .asp?filenam e= t ryht m l_list _definit ion .) I f you want t o include a quot at ion like a snippet of t ext from anot her Web sit e, a m ovie review, or j ust som e wise saying of your grandfat her's, t ry t he < block qu ot e > t ag for long passages, or t he < q> t ag for one- liners. Take advant age of obscure t ags like t he < cit e > t ag for referencing a book t it le, newspaper art icle or Web sit e, and t he < a ddr e ss> t ag t o ident ify and supply cont act inform at ion for t he aut hor of a page ( great for a copyright not ice) . As explained in full in Sect ion 1.2.3, st eer clear of any t ag or at t ribut e aim ed j ust at changing t he appearance of a t ext or im age. CSS, as you'll see, can do it all. When t here j ust isn't an HTML t ag t hat fit s t he bill, but you want t o ident ify an elem ent on a page or a bunch of elem ent s on a page so t hat you can apply a dist inct ive look, use t he < div> and < spa n > t ags ( see Sect ion 1.2.1) . You'll get m ore advice on how t o use t hese in lat er chapt ers ( for exam ple, Sect ion 3.1) . Rem em ber t o close t ags. The opening < p> t ag needs it s part ner in crim e ( t he closing < / p> t ag) , as do all ot her t ags, except t he few self- closers like < br / > and < im g / > . Validat e your pages wit h t he W3C validat or ( see Figure 1- 3 and t he box in Sect ion 1.2.4) . Poorly writ t en or t ypo- ridden HTML causes m any weird browser errors.

Section 1.3. The Importance of the Doctype

1.3. The Importance of the Doctype As discussed in t he box in Sect ion 1.2.4, HTML follows cert ain rulest hese rules are cont ained in a Docum ent Type Definit ion file, ot herwise known as a DTD. A DTD is an XML docum ent t hat explains what t ags, at t ribut es, and values are valid for a part icular t ype of HTML. And for each version of HTML, t here's a corresponding DTD. By now you m ay be asking, " But what 's all t his got t o do wit h CSS?" Everyt hing, if you want your Web pages t o appear correct ly and consist ent ly in Web browsers. You t ell a Web browser which version of HTML or XHTML you're using by including what 's called a doct ype declarat ion at t he beginning of a Web page. This doct ype declarat ion is t he first line in t he HTML file and not only defines what version of HTML you're using ( such as HTML 4.01 t ransit ional) but also point s t o t he appropriat e DTD file out on t he Web. When you m ist ype t he doct ype declarat ion, you can t hrow m ost browsers int o an alt ered st at e called quirks m ode. Quirks m ode is browser m anufact urers' at t em pt s t o m ake t heir soft ware behave like browsers did circa 1999 ( in t he Net scape 4 and I nt ernet Explorer 5 days) . I f a m odern browser encount ers a page t hat 's m issing t he correct doct ype, t hen it t hinks " Gee, t his page m ust have been writ t en a long t im e ago, in an HTML edit or far, far away. I 'll pret end I 'm a really old browser and display t he page j ust as one of t hose buggy old browsers would display it ." That 's why, wit hout a correct doct ype, your lovingly CSS- st yled Web pages m ay not look as t hey should, according t o current st andards. I f you unwit t ingly view your Web page in quirks m ode when checking it in a browser, you m ay end up t rying t o fix display problem s t hat are relat ed t o an incorrect doct ype and not t he incorrect use of HTML or CSS.

Note: For more (read: technical) information on quirks mode, visit www.quirksmode.org/index.html?/css/quirksmode.html and http://hsivonen.iki.fi/doctype/.

Fort unat ely, it 's easy t o get t he doct ype correct . All you need t o know is what version of HTML you're using. I n all likelihood, you're already creat ing Web pages using HTML 4. You m ay even have st art ed using XHTML for your Web sit es ( Sect ion 3.5) . The m ost popular versions of HTML and XHTML t hese days are HTML 4.01 Transit ional and XHTML 1.0 Transit ional. These t ypes of HTML st ill let you use present at ional t ags like t he < font > t ag, t hereby providing a t ransit ion from older HTML t o t he newer, st rict er t ypes of HTML and XHTML. Alt hough it 's best not t o use t hese t ags at all, t hey st ill work in t he Transit ional versions, so you can phase out t hese older t ags at your own pace. I n t he st rict versions of HTML and XHTML, som e older t ags 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 tag and a paragraph's center attribute. They also disallow a number of once-popular properties like a link's target property, which let you make a link open in a new window.

I f you're using HTML 4.01 Transit ional, t ype t he following doct ype declarat ion at t he very beginning of every page you creat e:

Section 1.3. The Importance of the Doctype

The doct ype declarat ion for XHTML 1.0 Transit ional is sim ilar, but it point s t o a different DTD. I t 's also a good idea t o add a lit t le code t o t he opening < ht m l> t ag t hat ident ifies t he language t he page is in, like t his:

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.

I f t his ent ire discussion is m aking your head ache and your eyes slowly shut , j ust m ake sure you use t he proper doct ype list ed above, and always m ake it t he first line of your HTML file ( before even t he opening < ht m l> t ag) . I f you want a basic t em plat e t o use when building eit her HTML or XHTML pages, visit t his book's Web sit e at www.sawm ac.com / css/ . I n fact , it 's a good idea t o have a blank HTML page wit h t he proper doct ype som ewhere on your com put er, so you can m ake a copy of it whenever you need t o creat e a new Web page. Using an HTML validat or, like t he one described in t he box in Sect ion 1.2.4, is also a great way t o ensure you've t yped t he doct ype declarat ion correct ly.

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

Now t hat your HTML ship is st eering in t he right direct ion, it 's t im e t o j um p int o t he fun st uff ( and t he reason you bought t his book) : Cascading St yle Sheet s.

Chapter 2. Creating Styles and Style Sheets

Chapter 2. Creating Styles and Style Sheets Even t he m ost com plex and beaut iful Web sit es, like t he one in Figure 2- 1, st art wit h a single CSS st yle. As you add m ult iple st yles and st yle sheet s, you can develop fully form ed Web sit es t hat inspire designers and am aze visit ors. Whet her you're a CSS novice or a St yle Sheet Sam urai, you need t o obey a few basic rules about how t o creat e st yles and st yle sheet s. I n t his chapt er you'll st art at square one, learning t he basics of creat ing and using st yles and st yle sheet s.

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 Section 2.5 for a hands-on tutorial.

Section 2.1. Anatomy of a Style

2.1. Anatomy of a Style A single st yle defining t he look of one elem ent on a page is a pret t y basic beast . I t 's essent ially j ust a rule t hat t ells a Web browser how t o form at som et hing on a Web paget urn a headline blue, draw a red border around a phot o, or creat e a 150- pixel- wide sidebar box t o hold a list of links. I f a st yle could t alk it would say som et hing like, " Hey Browser, m ake t his look like t hat ." A st yle is, in fact , m ade up of t wo elem ent s: The Web- page elem ent t hat t he browser form at s ( t he select or) and t he act ual form at t ing inst ruct ions ( t he declarat ion block) . For exam ple, a select or can be a headline, a paragraph of t ext , a phot o, and so on. Declarat ion blocks can t urn t hat t ext blue, add a red border around a paragraph, posit ion t he phot o in t he cent er of t he paget he possibilit ies are endless.

Figu r e 2 - 1 . Eve r y CSS- dr ive n W e b pa ge st a r t s w it h a sin gle CSS st yle . H e r e , a ba sic st yle ( le ft ) se t s t h e gr ou n dw or k for t h e body of t h e e n t ir e pa ge ( r igh t ) .

Section 2.1. Anatomy of a Style

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 st yles can't com m unicat e in nice clear English like t he previous paragraph. They have t heir own language. For exam ple, t o set a st andard font color and font size for all paragraphs on a Web page, you'd writ e t he following: p { color: red; font-size: 1.5em; }

This st yle sim ply says, " Make t he t ext in all paragraphsm arked wit h < p> t agsred and 1.5 em s t all." ( An em is a unit of m easurem ent t hat 's based on a browser's norm al t ext size. More on t hat in Chapt er 6.) As Figure 2- 2 illust rat es, even a sim ple st yle like t his exam ple cont ains several elem ent s: ●







Se le ct or . As described earlier, t he select or t ells a Web browser which elem ent or elem ent s on a page t o st ylelike a headline, paragraph, im age, or link. I n Figure 2- 2, t he select or ( p) refers t o t he < p> t ag, which m akes Web browsers form at all < p> t ags using t he form at t ing direct ions in t his st yle. Wit h t he wide range of select ors t hat CSS offers and a lit t le creat ivit y, you'll m ast er your pages' form at t ing. ( The next chapt er covers select ors in dept h.) D e cla r a t ion Block . The code following t he select or includes all t he form at t ing opt ions you want t o apply t o t he select or. The block begins wit h an opening brace ( { ) and ends wit h a closing brace ( } ) . D e cla r a t ion . Bet ween t he opening and closing braces of a declarat ion block, you add one or m ore declarat ions, or form at t ing inst ruct ions. Every declarat ion has t wo part s, a propert y and a value, and ends wit h a sem icolon. Pr ope r t y. CSS offers a wide range of form at t ing opt ions, called propert ies. A propert y is a wordor a few hyphenat ed wordsindicat ing a cert ain st yle effect . Most propert ies have st raight forward nam es like font - size, m argin- t op, and background- color. For exam ple, t he background- color propert y set syou guessed it a background color. You'll learn about oodles of CSS propert ies t hroughout t his book.

Tip: Appendix A has a handy glossary of CSS properties. ●

Va lu e . Finally, you get t o express your creat ive genius by assigning a value t o a CSS propert yby m aking a background blue, red, purple, or chart reuse, for exam ple. As upcom ing chapt ers explain, different CSS propert ies require specific t ypes of valuesa color ( like red, or # FF0000) , a lengt h ( like 18px, 2in, or 5em ) , an URL ( like im ages/ background.gif) , or a specific keyword ( like t op, cent er, or

Section 2.1. Anatomy of a Style

bot t om ) .

Figu r e 2 - 2 . A st yle ( or r u le ) is m a de of t w o m a in pa r t s: a se le ct or , w h ich t e lls W e b br ow se r s w h a t t o for m a t , a n d a de cla r a t ion block , w h ich list s t h e for m a t t in g in st r u ct ion s t h a t t h e br ow se r s u se t o st yle t h e se le ct or .

You don't need t o writ e a st yle on a single line as pict ured in Figure 2- 2. Many st yles have m ult iple form at t ing propert ies, so you can m ake t hem easier t o read by breaking t hem up int o m ult iple lines. For exam ple, you m ay want t o put t he select or and opening brace on t he first line, each declarat ion on it s own line, and t he closing brace by it self on t he last line, like so: p { color: red; font-size: 1.5em; }

I t 's also helpful t o indent propert ies, wit h eit her a t ab or a couple of spaces, t o visibly separat e t he select or from t he declarat ions, m aking it easy t o t ell which is which. And finally, put t ing one space bet ween t he colon and t he propert y value is opt ional, but adds t o t he readabilit y of t he st yle. I n fact you can put as m uch whit e space bet ween t he t wo as your want . For exam ple color: red, color: red and color: red all work.

Section 2.2. Understanding Style Sheets

2.2. Understanding Style Sheets Of course, a single st yle won't t ransform a Web page int o a work of art . I t m ay m ake your paragraphs red, but t o infuse your Web sit es wit h great design, you need m any different st yles. A collect ion of CSS st yles com prises a st yle sheet . A st yle sheet can be one of t wo t ypes int ernal or ext ernal, depending on where t he st yle inform at ion's locat ed: in t he Web page it self, or in a separat e file linked t o t he Web page.

2.2.1. Internal or ExternalHow to Choose Most of t he t im e, ext ernal st yle sheet s are t he way t o go, since t hey m ake building Web pages easier and updat ing Web sit es fast er. They cont ain all your st yle inform at ion in a single file. Wit h j ust a line of code, you at t ach t he ext ernal st yle sheet t o an HTML page and com plet ely alt er t hat page's appearance. You can revam p t he look of an ent ire sit e by edit ing a single t ext file: t he st yle sheet . On t he receiving end, ext ernal st yle sheet s help Web pages open fast er. When you use an ext ernal st yle sheet , your Web pages can cont ain only basic HTMLno byt e- hogging HTML t ables or < font > t ags, and no int ernal CSS st yle code. Furt herm ore, when a Web browser downloads an ext ernal st yle sheet , it st ores t he file on your visit or's com put er ( in a behind- t he- scenes folder called a cache) for quick access. When your visit or hops t o ot her pages on t he sit e t hat use t he sam e ext ernal st yle sheet , t here's no need for t he browser t o download t he st yle sheet again. The browser sim ply pulls t he ext ernal st yle sheet from it s cachea significant savings in download t im e.

Note: When you're working on your Web site and previewing it in a browser, the cache can work against you. See the box in Section 2.5.1 for a workaround.

Section 2.3. Internal Style Sheets

2.3. Internal Style Sheets An int ernal st yle sheet is a collect ion of st yles t hat 's part of t he Web page's code, always bet ween opening and closing HTML < st yle> t ags in t he page's < head> port ion. Here's an exam ple:

/* The rest of your page follows…*/

Note: You can place the

Unlike HTML's < link> t ag, @im port is part of t he CSS language and has som e definit e un- HTML- like qualit ies: ●

To m ake t he connect ion t o t he ext ernal CSS file, you use url inst ead of href, and enclose t he pat h in parent heses. So in t his exam ple, css/ global.css is t he pat h t o t he ext ernal CSS file. Quot es around t he URL are opt ional, so url( css/ global.css) and url( " css/ global.css" ) bot h work.

Note: Not only does quoting the path of an URL in CSS add a couple of extra characters to the file, Internet Explorer 5 for the Mac has trouble understanding URLs with quotes. ●

As wit h t he < link> t ag, you can include m ult iple ext ernal st yle sheet s using m ore t han one @im port :



You can add regular CSS st yles aft er t he @im port direct ives if, for exam ple, you want t o creat e a rule t hat applies j ust t o t hat one page, but t ake advant age of t he sam e design rules used t hroughout t he sit e t o form at t he rest of t he page.

Note: You'll learn how rules interact and how you can create a rule that overrides other rules in Section 5.3. 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 Section 14.2.3.1).

Here's an exam ple:

Technically, you should place all t he @im port lines before any CSS rules, as shown here, but it 's okay if you forget . Web browsers are supposed t o ignore any st yle sheet s you im port aft er a CSS rule, but all current Web browsers ignore t hat rest rict ion.

Section 2.5. Tutorial: Creating Your First Styles

2.5. Tutorial: Creating Your First Styles The rest of t his chapt er t akes you t hrough t he basic st eps for adding inline st yles, writ ing CSS rules, and creat ing int ernal and ext ernal st yle sheet s. As you work t hrough t his book, you'll help design a fict it ious Web sit e called Cosm oFarm er.com , creat ing various aspect s of it s design, and event ually st yling ent ire pages of t he sit e. To get st art ed, you need t o download t he t ut orial files locat ed on t he book's com panion Web sit e at www.sawm ac.com / css/ . Click t he t ut orial link and download t he Zip archive cont aining t he files ( det ailed inst ruct ions for unzipping t he files are on t he Web sit e as well) . Each chapt er's files are in a separat e folder, nam ed chapt er_2, chapt er_3, and so on. Next , you need t o launch your favorit e Web page edit ing soft ware, whet her it 's a sim ple t ext edit or like Not epad or Text Edit , or a visually orient ed program like Dream weaver or Microsoft Expression Web Designer ( for inform at ion on select ing an edit or, see Sect ion 3.6) .

WORKAROUND WORKSHOP Don't Get Caught in the Cache A browser's cache is a great speed- boost for Web surfers. Whenever t he cache downloads and st ores a frequent ly used filelike an ext ernal CSS file or an im ageit saves precious m om ent s t raveling t he relat ively sluggish highways of t he I nt ernet . I nst ead of redownloading t he next t im e it needs t he sam e file, t he browser can go st raight t o t he new st ufflike a yet - t obe- viewed page or graphic. But what 's good for your visit ors isn't always good for you. Because t he Web browser caches and recalls downloaded ext ernal CSS files, you can oft en get t ripped up as you work on a sit e design. Say you're working on a page t hat uses an ext ernal st yle sheet , and you preview t he page in a browser. Som et hing doesn't look quit e right , so you ret urn t o your Web edit or and change t he ext ernal CSS file. When you ret urn t o t he Web browser and reload t he page, t he change you j ust m ade doesn't appear! You've j ust been caught by t he cache. When you reload a Web page, browsers don't always reload t he ext ernal st yle sheet , so you m ay not be seeing t he lat est and great est version of your st yles. You have t wo ways around t his snafu: t urn off t he cache or force t he browser t o reload everyt hing. I n m ost browsers you can force reload a page ( which also reloads all linked files) by pressing t he Ct rl ( ) key and pressing t he browser's Reload but t on; Ct rl+ F5 also works on Windows - Shift - R) is Firefox's keyboard short cut . for I nt ernet Explorer; and Ct rl+ Shift + R ( I nt ernet You can also com plet ely t urn off t he cache. I n I nt ernet Explorer, choose Tools General t ab; in t he Tem porary I nt ernet Files sect ion, click Set t ings. Make sure Opt ions t he " Check for newer versions of st ored pages" opt ion's set t o " Every visit t o t he page." Click Opt ions ( on OK t wice t o close t he I nt ernet Opt ions window. I n Firefox, choose Tools Preferences ( Mac) t o open Firefox's Preferences window; click t he Windows) , or Firefox Privacy but t on, t hen t he Cache t ab, and t hen set t he cache disk space t o 0.

Section 2.5. Tutorial: Creating Your First Styles

For Safari on t he Mac, download t he free Safari Enhancer at www.versiont racker.com / dyn/ m oreinfo/ m acosx/ 17776. Turning off t he cache can drast ically slow your regular Web surfing act ivit y, so m ake sure you t urn it back on once you're done edit ing your CSS files.

Note: If you use Dreamweaver, then 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.

2.5.1. Creating an Inline Style When you t ype a CSS rule ( j ust like t he ones described in Sect ion 2.1) direct ly int o a page's HTML, you're creat ing an inline st yle. I nline st yles offer none of t he t im e- and bandwidt h- saving benefit s of st yle sheet s, so t he pros hardly ever use t hem . St ill, in a pinch, if you absolut ely m ust change t he st yling on a single elem ent on a single page, t hen you m ay want t o resort t o an inline st yle. And if you do, you at least want t he st yle t o work properly. The im port ant t hing is t o carefully place t he st yle wit hin t he t ag you want t o form at . Here's an exam ple t hat shows you exact ly how t o do it : 1. I n you r W e b pa ge e dit in g pr ogr a m , ope n t h e file ch a pt e r _ 2

ba sic.h t m l.

This sim ple- but - elegant XHTML file cont ains a couple of different headings, a paragraph, an unordered list , and a copyright not ice inside an < address> t ag. You'll st art by creat ing an inline st yle for t he < h1> t ag. 2. Click in side t h e ope n in g < h 1 > t a g a n d t ype st yle = " color : r e d;" . The t ag should look like t his:

The st yle at t ribut e is HTML, not CSS so you use t he equals sign aft er it and enclose all of t he CSS code inside quot es. Only t he st uff inside t he quot es is CSS. I n t his case, you've added a propert y nam ed colorwhich affect s t he color of t ext and you've set t hat propert y t o red ( Sect ion 6.1.2 t alks m ore about coloring t ext ) . The colon separat es t he propert y nam e from t he propert y value t hat you want . Next you'll check t he result s in a Web browser. 3.

Section 2.5. Tutorial: Creating Your First Styles

Ope n t h e ba sic.h t m l pa ge in a W e b br ow se r . Open File, depending on your browser. Many HTML edit ors also For exam ple, choose File include a " Preview in Browser" funct ion, which, wit h a sim ple keyboard short cut , or m enu opt ion, opens t he page in a Web browser. I t 's wort h checking your program 's m anual t o see if it includes t his t im esaving feat ure. When you view t he page in a browser, t he headline is now red. I nline st yles can include m ore t han one CSS propert y. You'll add anot her propert y next . 4. Re t u r n t o you r H TM L e dit or , click a ft e r t h e se m icolon follow in g t h e w or d " r e d" a n d t ype fon t - size : 4 e m ;. The sem icolon separat es t wo different propert y set t ings. The < h1> t ag should look like t his:

5. Pr e vie w t h e pa ge in a W e b br ow se r . For e x a m ple , click you r br ow se r w in dow 's Re loa d bu t t on ( bu t m a k e su r e you 've sa ve d t h e XH TM L file fir st .) . The headline's now m assive in size. And, you've had a t ast e of how labor- int ensive inline st yles are. Making all t he < h1> headings on a page look like t his one could t ake days of t yping and add acres of HTML code. 6. Re t u r n t o you r pa ge e dit or a n d de le t e t h e e n t ir e st yle pr ope r t y, w h ich r e t u r n s t h e h e a din g t a g ba ck t o it s n or m a l < h 1 > . Next , you'll creat e a st yle sheet wit hin a Web page.

2.5.2. Creating an Internal Style Sheet A bet t er approach t han inline st yles is using a st yle sheet t hat cont ains m ult iple CSS rules t o cont rol m ult iple elem ent s of a page. I n t his sect ion, you'll creat e a st yle t hat affect s all t op- level headings in one swoop. This single rule aut om at ically form at s every < h1> t ag on t he page. 1. W it h t h e file ba sic.h t m l ope n in you r t e x t e dit or , click dir e ct ly a ft e r t h e closin g < / t it le > t a g. Th e n h it Re t u r n a n d t ype < st yle t ype = " t e x t / css" > .

Section 2.5. Tutorial: Creating Your First Styles

The HTML should now look like t he following ( t he st uff you've added is in bold) : Basic Web Page

7. Pr e vie w t h e pa ge in a W e b br ow se r . You can preview t he page by opening it in a Web browser as described in st ep 3 in Sect ion 2.5.2, or, if t he page is st ill open in a browser window, t hen j ust click t he Reload but t on. I n eit her case, t he page should now look like Figure 2- 3. Next you'll add anot her st yle.

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 pageor no Web page at all. 8. Ba ck in you r t e x t e dit in g pr ogr a m , click a ft e r t h e closin g br a ce of t h e h 1 st yle you j u st cr e a t e d, pr e ss Re t u r n , a n d t h e n a dd t h e follow in g r u le :

Section 2.5. Tutorial: Creating Your First Styles

p { color: #003366; font-size: .9em; line-height: 150%; margin-top: 0; }

This rule form at s every paragraph on t he page. Don't worry t oo m uch right now about what each of t hese CSS propert ies is doing. Lat er chapt ers cover t hese propert ies in dept h. 9. Pr e vie w t h e pa ge in a br ow se r . The page is st art ing t o shape up. You can see what st ylist ic direct ion t he page is headed in. To finish t he page, add rules t o form at t he Heading 2, unordered list , and copyright not ice.

Figu r e 2 - 3 . CSS e a sily for m a t s t e x t in cr e a t ive w a ys, le t t in g you ch a n ge fon t s, t e x t color s, fon t size s, a n d e ve n a ddin g de cor a t ive bor de r s a n d u n de r lin e s.

Section 2.5. Tutorial: Creating Your First Styles

The process you've j ust worked t hrough is CSS in a nut shell: St art wit h an HTML page, add a st yle sheet , and creat e CSS rules t o m ake t he page look great . I n t he next part of t his t ut orial, you'll see how t o work m ore efficient ly using ext ernal st yle sheet s.

2.5.3. Creating an External Style Sheet Since it groups all of your st yles at t he t op of t he page, an int ernal st yle sheet 's a lot easier t o creat e and m aint ain t han t he inline st yle you creat ed a few pages ago. Also, an int ernal st yle sheet let s you form at any num ber of inst ances of a t ag on a page, like t he < h1> t ag by t yping one sim ple rule. But an ext ernal st yle sheet 's even bet t erit can st ore all of t he st yles for an ent ire Web sit e. Edit ing one st yle in t he ext ernal st yle sheet updat es t he whole sit e. I n t his sect ion, you'll t ake t he st yles you creat ed in t he previous sect ion and put t hem in an ext ernal st yle sheet . 1. I n you r t e x t e dit in g pr ogr a m , cr e a t e a n e w file a n d sa ve it a s globa l.css in t h e sa m e folde r a s t h e W e b pa ge you 've be e n w or k in g on .

Section 2.5. Tutorial: Creating Your First Styles

Ext ernal st yle sheet files end wit h t he ext ension .css. The file nam e global.css indicat es t hat t he st yles cont ained in t he file apply t hroughout t he sit e. ( But you can use any file nam e you like, as long as it ends wit h t he .css ext ension.) St art by adding a new st yle t o t he st yle sheet . 2. Type t h e follow in g r u le in t o t h e globa l.css file : body { background-image: url(images/bg.jpg); background-repeat: repeat-x; }

This rule applies t o t he body t agt he t ag t hat holds all t he cont ent visible in a Web browser windowand adds a background im age t o t he page. Unlike a sim ilar propert y in HTML, t he CSS background- im age propert y can display t he graphic in m any different waysin t his case, t iled horizont ally across t he t op of t he page. You can read m ore about background im age propert ies in Sect ion 8.2. I nst ead of recreat ing t he work you did earlier, j ust copy t he st yles you creat ed in t he previous sect ion and past e t hem int o t his st yle sheet . 3. Ope n t h e ba sic.h t m l pa ge t h a t you 've be e n w or k in g on a n d copy a ll of t h e t e x t in side t h e < st yle > t a gs. ( D on 't copy t h e < st yle > t a gs t h e m se lve s.) Copy t he st yle inform at ion t he sam e way you'd copy any t ext . For exam ple, choose Edit - C) . or press Ct rl- C (

Copy

4. I n t h e e m pt y globa l.css file , pa st e t h e st yle in for m a t ion by se le ct in g Edit pr e ssin g Ct r l- V ( - V) .

Pa st e , or

An ext ernal st yle sheet never cont ains any HTMLt hat 's why you didn't copy t he < st yle> t ags. 5. Sa ve a n d close globa l.css. Now you j ust need t o clean up your old file and link t he new st yle sheet t o it . 6.

Section 2.5. Tutorial: Creating Your First Styles

Re t u r n t o t h e ba sic.h t m l file in you r t e x t e dit or a n d de le t e t h e < st yle > t a gs a n d a ll of t h e CSS r u le s you t ype d in e a r lie r . You no longer need t hese st yles, since t hey're in t he ext ernal st yle sheet you're about t o at t ach. 7. I n t h e spa ce w h e r e t h e st yle s u se d t o be ( be t w e e n t h e closin g < / t it le > t a g a n d t h e ope n in g < body> t a g) t ype t h e follow in g:

The < link> t ag is one way t o at t ach a st yle sheet t o a page; anot her opt ion is t he CSS @im port direct ive, as discussed in Sect ion 2.4.2. The link t ag specifies t he locat ion of t he ext ernal st yle sheet . ( You can read up on t he t wo ot her at t ribut esrel and t ypein Sect ion 2.4.2.)

Note: In this example, the style sheet file's in the same folder as the Web page. If it were in a different folder from the page, then you'd use a document- or root-relative path to indicate where the file is. The routine's the same as when you link to any Web page. (For a brief primer on document-and root-relative links visit: www. communitymx.com/content/article.cfm?cid=230AD.) 8. Sa ve t h e file a n d pr e vie w it in a W e b br ow se r . I t should look t he sam e as in st ep 9 in Sect ion 2.5.2, wit h t he one addit ion of a groovy graphic running along t he t op edge of t he page ( t hanks t o t he CSS you added in st ep 2) . The CSS rules in t his ext ernal st yle sheet are t he sam e as t he ones from t he int ernal st yle sheet ; t hey're j ust locat ed in a different place. To dem onst rat e how useful it can be t o keep your st yles in t heir own ext ernal file, you'll at t ach t he st yle sheet t o anot her Web page.

Note: If the Web page doesn't have any formatting (for example, the CosmoFarmer heading isn't red), then you've probably mistyped the code from step 6, or saved the global.css file in a folder other than the one where the basic.html file is. In this case, just move the global.css into the same folder. 9. Ope n t h e file ch a pt e r _ 2

lin k e d_ pa ge .h t m l.

This lead st ory from Cosm oFarm er.com cont ains som e of t he sam e HTML t agsh1, h2, p, and so onas t he ot her Web page you've been working on.

Section 2.5. Tutorial: Creating Your First Styles

Click a ft e r t h e closin g < / t it le > t a g a n d pr e ss En t e r ( Re t u r n ) . You'll now link t o t he st yle sheet . 11. Type t h e sa m e < lin k > t a g you did in st e p 6 a bove . The Web page code should look like t his ( t he code you j ust t yped appears in bold) : Explaining Irrigation Problems To Your Downstairs Neighbors

12. Sa ve t h e pa ge a n d pr e vie w it in a W e b br ow se r . Ta- da! Just one line of code added t o t he Web page is enough t o inst ant ly t ransform it s appearance. To dem onst rat e how easy it is t o updat e an ext ernal st yle sheet , you'll do so by edit ing one st yle and adding anot her. 13. Ope n t h e globa l.css file a n d a dd t h e CSS de cla r a t ion m a r gin - le ft : 2 5 px ; a t t h e e n d of t h e p st yle . The code should look like t his ( t he bold t ext is what you've j ust added) : p { color: #003366; font-size: .9em; line-height: 150%; margin-top: 0; margin-left: 25px; }

Last but not least , creat e a new rule for t he h2 t ag. 14. Click a t t h e e n d of t h e p st yle 's closin g } , pr e ss En t e r ( Re t u r n ) , a n d a dd t h e follow in g r u le : h2 { color: #FFFFCC; margin-bottom: 0;

Section 2.5. Tutorial: Creating Your First Styles

padding: 5px 0px 3px 25px; background-color: #999999; }

Most of t hese CSS propert ies you've encount ered already. You'll learn about padding and backgrounds in Chapt er 7. 15. Sa ve t h e file globa l.css a n d pr e vie w bot h t h e ba sic.h t m l a n d lin k e d_ pa ge .h t m l file s in a W e b br ow se r . Figu r e 2 - 4 sh ow s t h e com ple t e d lin k e d_ pa ge .h t m l file . Not ice t hat t he appearance of bot h pages changes, based on t he sim ple edit s you m ade t o t he CSS file. Close your eyes and im agine t hat your Web sit e has a t housand pages. Aaaahhhhhhh, t he power.

Figu r e 2 - 4 . Usin g a n e x t e r n a l st yle sh e e t , you ca n u pda t e a n e n t ir e sit e 's w or t h of W e b pa ge s by e dit in g a sin gle CSS file . I n a ddit ion , by m ovin g a ll of t h e CSS code ou t of a n H TM L docu m e n t a n d in t o a se pa r a t e file , you cu t dow n on t h e file size of you r W e b pa ge s so t h e y loa d m u ch fa st e r .

Section 2.5. Tutorial: Creating Your First Styles

Chapter 3. Selector Basics: Identifying What to Style

Chapter 3. Selector Basics: Identifying What to Style Every CSS st yle has t wo basic part s: a select or and a declarat ion block. ( And if t hat 's news t o you, go back and read t he previous chapt er.) The declarat ion block carries t he form at t ing propert iest ext color, font size, and so onbut t hat 's j ust t he pret t y st uff. The m agic of CSS lies in t hose first few charact ers at t he beginning of every rulet he select or. By t elling CSS what you want it t o form at ( see Figure 3- 1) , t he select or gives you full cont rol of your page's appearance. I f you're int o sweeping generalizat ions, t hen you can use a select or t hat applies t o m any elem ent s on a page at once. But if you're a lit t le m ore det ail orient ed ( OK, a lot m ore) , ot her select ors let you single out one specific it em or a collect ion of sim ilar it em s. CSS select ors give you a lot of power: This chapt er shows you how t o use t hem .

Figu r e 3 - 1 . Th e fir st pa r t of a st yle , t h e se le ct or , in dica t e s t h e e le m e n t or e le m e n t s of a pa ge t o for m a t . I n t h is ca se , h 1 st a n ds for " e ve r y h e a din g 1 or < h 1 > t a g on t h is pa ge ."

Note: If you'd rather get some hands-on experience before studying the ins and outs of CSS selectors, then jump to the tutorial in Section 3.1.

Section 3.1. Tag Selectors: Page-Wide Styling

3.1. Tag Selectors: Page-Wide Styling Tag select orssom et im es called t ype select orsare ext rem ely efficient st yling t ools, since t hey apply t o every occurrence of an HTML t ag on a Web page. Wit h t hem , you can m ake sweeping design changes t o a page wit h very lit t le effort . For exam ple, when you want t o form at every paragraph of t ext on a page using t he sam e font , color, and size, you m erely creat e a st yle using p ( as in t he < p> t ag) as t he select or. I n essence, a t ag select or redefines how a browser displays a part icular t ag. Prior t o CSS, in order t o form at t ext , you had t o wrap t hat t ext in a < font > t ag. To add t he sam e look t o every paragraph on a page, you oft en had t o use t he < font > t ag m ult iple t im es. This process was a lot of work, and required a lot of HTML, m aking pages slower t o download and m ore t im e- consum ing t o updat e. Wit h t ag select ors you don't act ually have t o do anyt hing t o t he HTMLj ust creat e t he CSS rule, and let t he browser do t he rest . Tag select ors are easy t o spot in a CSS rule, since t hey bear t he exact sam e nam e as t he t ag t hey st ylep, h1, t able, im g, and so on. For exam ple, in Figure 3- 2, t he h2 select or ( t op) applies som e font st yling t o all < h2> t ags on a Web page ( bot t om ) .

Figu r e 3 - 2 . A t a g se le ct or a ffe ct s e ve r y in st a n ce of t h e t a g on t h e pa ge . Th is pa ge h a s t h r e e < h 2 > t a gs ( in dica t e d by t h e bla ck la be ls a t t h e le ft e dge of t h e br ow se r w in dow ) . A sin gle CSS st yle w it h a se le ct or of h 2 con t r ols t h e pr e se n t a t ion of e ve r y < h 2 > t a g on t h e pa ge .

Section 3.1. Tag Selectors: Page-Wide Styling

Note: As Figure 3-2 makes clear, tag selectors don't get the less than () symbols that surround HTML tags. So when you're writing a rule for the

tag, for example, just type the tag's namep.

Tag select ors have t heir downsides, however. What if you want som e paragraphs t o look different from ot her paragraphs? A sim ple t ag select or won't do, since it doesn't provide enough inform at ion for a Web browser t o ident ify t he difference bet ween t he < p> t ags you want t o highlight in purple, bold, and large t ype from t he < p> t ags you want t o leave wit h norm al, black t ext . Fort unat ely, CSS provides j ust such a t ool class select ors, described next .

Section 3.1. Tag Selectors: Page-Wide Styling

Section 3.2. Class Selectors: Pinpoint Control

3.2. Class Selectors: Pinpoint Control When you don't want every inst ance of a paragraph or heading t ag t o get t he sam e st yling, CSS let s you creat e a class select or wit h a nam e of your choosing, and t hen select ively apply it t o cert ain bit s of HTML on your page. For exam ple, you can creat e a class st yle nam ed .copyright and t hen apply it only t o a paragraph cont aining copyright inform at ion, wit hout affect ing any ot her paragraphs. Class select ors also let you pinpoint an exact elem ent on a page, regardless of it s t ag. Say you want t o form at a word or t wo inside of a paragraph, for exam ple. I n t his case, you don't want t he ent ire < p> t ag affect ed, j ust a single phrase inside it , so you can use a class select or t o indicat e j ust t hose words. You can even use a class select or t o apply t he sam e form at t ing t o m ult iple elem ent s t hat have different HTML t ags. For exam ple, you can give one paragraph and one second- level heading t he sam e st ylingperhaps a color and a font t hat you've select ed t o highlight special inform at ion, as shown in Figure 3- 3. Unlike t ag select ors which lim it you t o t he exist ing HTML t ags on t he page, you can creat e as m any class select ors as you like and put t hem anywhere you want .

Note: When you want to apply a class selector to just a few words contained inside another tag (like the middle paragraph in Figure 3-3), you need a little help from the tag (Section 1.2.1). See the box in Section 3.1 for more detail.

You've probably not iced t he period t hat st art s every class select or's nam esuch as .copyright and .special. I t 's one of a few rules t o keep in m ind when nam ing a class: ●

● ●



All class select or nam es m ust begin wit h a period. That 's how Web browsers spot a class select or in t he st yle sheet . CSS perm it s only let t ers, num bers, hyphens, and underscores in class nam es. Aft er t he period, t he nam e m ust always st art wit h a let t er. For exam ple, .9lives isn't a valid class nam e, but .crazy8 is. You can have classes nam ed .copy- right and .banner_im age, but not .- bad or . _as_bad. Class nam es are case sensit ive. For exam ple, CSS considers .SI DEBAR and .sidebar t wo different classes.

Figu r e 3 - 3 . Cla ss se le ct or s le t you m a k e h igh ly t a r ge t e d de sign ch a n ge s. For e x a m ple , you ca n st ylize on e in st a n ce of a n < h 2 > h e a din g ( " W e t Sod is H e a vy Sod" ) . Th e cla ss se le ct or .spe cia l t e lls t h e br ow se r t o a pply t h e st yle t o j u st t h a t sin gle < h 2 > t a g. On ce you 've cr e a t e d a cla ss se le ct or , you ca n u se it on ot h e r t a gs, lik e t h e t op pa r a gr a ph on t h is pa ge .

Section 3.2. Class Selectors: Pinpoint Control

Section 3.2. Class Selectors: Pinpoint Control

Apart from t he nam e, you creat e class st yles exact ly like t ag st yles. Aft er t he class nam e, sim ply slap on a declarat ion block cont aining all of t he st yling you desire: .special { color:#FF0000; font-family:"Monotype Corsiva"; }

Because t ag st yles apply across t he board t o all t ags on a Web page, you m erely have t o define t hem in t he head of t he page: t he HTML t ags t hat m ake t hem work are already in place. The ext ra freedom you get wit h class st yles, t hough, com es wit h a lit t le m ore work. Using class select ors is a t wo- st ep process. Aft er you creat e a class rule, you m ust t hen indicat e where you want t o apply t hat form at t ing. To do so, you add a class at t ribut e t o t he HTML t ag you wish t o st yle. Say you creat e a class .special t hat you'll use t o highlight part icular page elem ent s. To add t his st yle t o a paragraph, add a class at t ribut e t o t he < p> t ag, like so:



Note: In the HTML, as part of the class attribute, you don't put a period before the class name; the period's only required for the class selector name in a style sheet.

When a Web browser encount ers t his t ag, it knows t o apply t he form at t ing rules cont ained in t he .special st yle t o t he paragraph. You can also apply class form at t ing t o only part of a paragraph or heading by adding a < span> t ag as described in t he box below. Once you creat e a class st yle, you can apply it t o j ust about any t ag on t he page. Alt hough t hey give you alm ost lim it less form at t ing possibilit ies, classes aren't always t he right t ool when using CSS for laying out a page. Ent er t he I D select or, which let s you designat e a form at t ing rule for one specific use on a page, as described next .

GEM IN THE ROUGH Divs and Spans

Section 3.2. Class Selectors: Pinpoint Control

Chapt er 1 int roduced you t o < div> and < span> , t wo generic HTML t ags t hat you can bend t o your CSS wishes. When t here's no HTML t ag t hat exact ly delineat es where you want t o put a class or I D st yle you've creat ed, use a < div> or < span> t o fill in t he gaps. The div t ag ident ifies a logical division of t he page like a banner, navigat ion bar, sidebar, or foot er. You can also use it t o surround any elem ent t hat t akes up a chunk of t he page, including headings, bullet ed list s, or paragraphs. ( Program m er t ypes call t hese block- level elem ent s because t hey form a com plet e " block" of cont ent , wit h line breaks before and aft er t hem .) The < div> t ag works j ust like a paragraph t ag: t ype t he opening < div> , add som e t ext , a phot o, or som e ot her cont ent inside it , and t hen end it wit h t he closing < / div> . The div t ag has t he unique abilit y t o cont ain several block- level elem ent s, m aking it a great way t o group t ags t hat are logically relat ed such as t he logo and navigat ion bar in a page's banner, or a series of news st ories t hat com pose a sidebar. Once grouped in t his way, you can apply specific form at t ing t o j ust t he t ags inside t he part icular div, or m ove t he ent ire divt agged chunk of cont ent int o a part icular area, such as t he right side of t he browser window ( CSS can help you cont rol t he visual layout of your pages in t his m anner as described in Part 3 of t his book) . For exam ple, say you added a phot o t o a Web page; t he phot o also has a capt ion t hat accom panies it . You could wrap a < div> t ag ( wit h a class applied t o it ) around t he phot o and t he capt ion t o group bot h elem ent s t oget her:

Mom, dad and me on our yearly trip to Antarctica.



Depending on what you put in t he declarat ion block, t he .phot o class can add a decorat ive border, background color, and so on, t o bot h phot o and capt ion. Part 3 of t his book shows you even m ore powerful ways t o use < div> t agsincluding nest ed divs. A < span> t ag, on t he ot her hand, let s you apply a class or I D st yle t o j ust part of a t ag. You can place < span> t ags around individual words and phrases ( oft en called inline elem ent s) wit hin paragraphs t o form at t hem independent ly. Here, a class called .com panyNam e st yles t he inline elem ent s " Cosm oFarm er.com ," " Disney," and " ESPN" :

Welcome to CosmoFarmer.com, the parent company of such well-known corporations as Disney and ESPN…well, not really.



Section 3.2. Class Selectors: Pinpoint Control

Section 3.3. ID Selectors: Specific Page Elements

3.3. ID Selectors: Specific Page Elements CSS reserves t he I D select or for ident ifying a unique part of a page like a banner, navigat ion bar, or t he m ain cont ent area. Just like a class select or, you creat e an I D by giving it a nam e in CSS and t hen you apply it by adding t he I D t o your page's HTML code. So what 's t he difference? As explained in t he box in Sect ion 3.1, I D select ors have som e specific uses in JavaScript - based or very lengt hy Web pages. Ot herwise, com pelling reasons t o use I Ds over classes are few. When deciding whet her t o use a class or an I D, follow t hese rules of t hum b: ●





To use a st yle several t im es on a page, you m ust use classes. For exam ple, when you have m ore t han one phot o on your page, use a class select or t o apply st ylinglike a bordert o each of t hem . Use I Ds t o ident ify sect ions t hat occur only once per page. CSS- based layout s oft en rely on I D select ors t o ident ify t he unique part s of a Web page, like a sidebar or foot er. Part 3 shows you how t o use t his t echnique. Consider using an I D select or t o sidest ep st yle conflict s, since Web browsers give I D select ors priorit y over class select ors. For exam ple, when a browser encount ers t wo st yles t hat apply t o t he sam e t ag but specify different background colorst he I D's background color wins. ( See Sect ion 5.4.3 for m ore on t his t opic.)

Note: Although you should apply only a single ID to a single HTML tag, a browser won't blow up or set off alarm bells if you apply the same ID to two or more tags on the same page. In fact, most browsers will apply the CSS from an ID style correctly in this case. However, your HTML won't validate (see Section 1.2.4) and your Web designer friends may stop talking to you.

Should you decide t o use an I D select or, creat ing one is easy. Just as a period indicat es t he nam e of a class select or, a pound or hash sym bol ident ifies an I D st yle. Ot herwise, follow t he exact sam e nam ing rules used for classes ( Sect ion 3.1) . This exam ple provides background color and sizing: #banner { background: #CC0000; height: 300px; width: 720px; }

Applying I Ds in HTML is sim ilar t o applying classes, but uses a different at t ribut e nam ed, logically enough, id. For exam ple, t o indicat e t hat t he last paragraph of a page is t hat page's one and only copyright not ice, you can creat e an I D st yle nam ed # copyright and add it t o t hat paragraph's t ag:

A paragraph of importanttext.



You can t urn t he above HTML code int o a diagram , like Figure 3- 4, showing t he relat ionships bet ween t he page's t ags. First t here's t he < ht m l> t ag; it 's divided int o t wo sect ions represent ed by t he < head> and < body> t ags. Those t wo t ags cont ain ot her t ags t hat in t urn m ay cont ain ot her t ags. By seeing which t ags appear inside which ot her t ags, you can diagram any Web page.

Figu r e 3 - 4 . H TM L con sist s of n e st e d t a gst a gs w it h in t a gs w it h in e ve n m or e t a gs. Th e r e la t ion sh ip be t w e e n t h e se t a gsh ow t h e y'r e n e st e d w it h in e a ch ot h e r for m s a k in d of fa m ily tree.

Section 3.4. Styling Tags Within Tags

Tree diagram s help you figure out how CSS sees t he relat ionship of one elem ent on a page t o anot her. Many of t he select ors in t his chapt er, including descendent select ors, rely on t hese relat ionships. The m ost im port ant relat ionships are: ●









An ce st or . As explained at t he beginning of t his chapt er, an HTML t ag t hat wraps around anot her t ag is it s ancest or. I n Figure 3- 4, t he < ht m l> t ag is an ancest or of all ot her t ags, while t he < body> t ag is an ancest or for all of t he t ags inside of it t he < h1> , < p> , and < st rong> t ags. D e sce n de n t . A t ag inside one or m ore t ags is a descendent . I n Figure 3- 4, t he < body> t ag is a descendent of t he < ht m l> t ag, while t he < t it le> t ag is a descendent of bot h t he < head> and < ht m l> t ags. Pa r e n t . A parent t ag is t he closest ancest or of anot her t ag. I n Figure 3- 4, a parent is t he first t ag direct ly connect ed t o and above anot her t ag. Thus, t he < ht m l> t ag is t he parent of t he < head> and < body> t ags, but of no ot her t ags. And, in t his diagram , t he < p> t ag is t he parent of t he < st rong> t ag. Ch ild. A t ag t hat 's direct ly enclosed by anot her t ag is a child. I n Figure 3- 4, bot h t he < h1> and < p> t ags are children of t he < body> t ag, but t he < st rong> t ag isn't since t hat t ag is direct ly wrapped inside t he < p> t ag. Siblin g. Tags t hat are children of t he sam e t ag are called siblings, j ust like brot hers and sist ers. I n an HTML diagram , sibling t ags are next t o each ot her and connect ed t o t he sam e parent . I n Figure 3- 4, t he < head> and < body> t ags are siblings, as are t he < h1> and < p> t ags.

Thankfully, t hat 's where CSS 2.1 draws t he line wit h t his fam ily m et aphor, so you don't have t o worry about aunt s, uncles, or cousins. ( Though rum or has it CSS 10 will include in- laws.)

3.4.2. Building Descendent Selectors Descendent select ors let you t ake advant age of t he HTML fam ily t ree by form at t ing t ags different ly when t hey appear inside cert ain ot her t ags or st yles. For exam ple, say you have an < h1> t ag on your Web page, and you want t o em phasize a word wit hin t hat heading wit h t he < st rong> t ag. The t rouble is, m ost browsers display bot h heading t ags and t he < st rong> t ag in bold, so anyone viewing t he page can't see any difference bet ween t he em phasized word and t he ot her words in t he headline. Creat ing a t ag select or t o change t he < st rong> t ag's color and m ake it st and out from t he headline isn't m uch of a solut ion: you end up changing t he color of every < st rong> t ag on t he page, like it or not . A descendent select or let s you do what you really want change t he color of t he < st rong> t ag only when it appears inside of an < h1> t ag. The solut ion t o t he < h1> and < st rong> dilem m a looks like t his:

Section 3.4. Styling Tags Within Tags

h1 strong { color: red; }

Here any < st rong> t ag inside an h1 is red, but ot her inst ances of t he < st rong> t ag on t he page, aren't affect ed. Descendent select ors st yle elem ent s t hat are nest ed inside ot her elem ent s, following t he exact sam e pat t ern of ancest ors and descendent s as t he t ags in t he HTML fam ily t ree. You creat e a descendent select or by t acking t oget her select ors according t o t he part of t he fam ily t ree you want t o form at , wit h t he m ost senior ancest or on t he left , and t he act ual t ag you're t arget ing on t he far right . For exam ple, in Figure 3- 5 not ice t he t hree links ( t he < a> t ag) inside of bullet ed list it em s, and anot her link inside of a paragraph. To form at t he bullet ed links different ly t han t he ot her links on t he page, you can creat e t he following descendent select or: li a { font-family: Arial; }

Figu r e 3 - 5 . Th is sim ple t r e e dia gr a m ( r igh t ) r e pr e se n t s t h e st r u ct u r e of t h e W e b pa ge pict u r e d t o t h e le ft . Eve r y t a g on a W e b pa ge is a de sce n de n t of t h e < h t m l> t a g, sin ce < h t m l> w r a ps a r ou n d t h e m a ll. A t a g ca n de sce n d fr om m u lt iple t a gs. For e x a m ple , t h e fir st < a > t a g list e d in t h is dia gr a m is a de sce n de n t of t h e < st r on g> , < p> , < body> , a n d < h t m l> t a gs.

This rule says, " Form at all links ( a) t hat appear inside a list it em ( li) by using t he Arial font ." A descendent select or can cont ain m ore t han j ust t wo elem ent s. The following are all valid select ors for t he < a> t ags inside of t he bullet ed list s in Figure 3- 5:

Section 3.4. Styling Tags Within Tags

ul li a body li a html li a html body ul li a

Note: One reason you would tack on additional descendent selectors is if you've written several different rules that simultaneously format a tag. Formatting instructions from a long-winded descendent selector can override simple class or tag styles. More on that in the next chapter.

These four select orsall of which do t he sam e t hingdem onst rat e t hat you don't have t o describe t he ent ire lineage of t he t ag you want t o form at . For inst ance, in t he second exam plebody li aul isn't needed. This select or works as long as t here's an < a> t ag t hat 's a descendent ( som ewhere up t he line) of an < li> t ag ( which is also a descendent of t he < body> t ag) . This select or can j ust as easily apply t o an < a> t hat 's inside of an < em > t ag, t hat 's inside of a < st rong> t ag, t hat 's inside an < li> t ag, and so on. You're not lim it ed t o j ust t ag select ors, eit her. You can build com plex descendent select ors com bining different t ypes of select ors. For exam ple, suppose you want your links t o appear in yellow only when t hey're in int roduct ory paragraphs ( which you've designat ed wit h a class st yle nam ed int ro) . The following select or does t he t rick: p.intro a { color: yellow; }

Quick t ranslat ion: Apply t his st yle t o every link ( a) t hat 's a descendent of a paragraph ( p) t hat has t he int ro class applied t o it . Not e t hat t here's no space bet ween p and .int ro, which t ells CSS t hat t he int ro class applies specifically t o t he < p> t ag. I f you add a space, you get a different effect : p .intro a { color: yellow; }

This seem ingly slight variat ion select s an < a> t ag inside of any t ag st yled wit h t he .int ro class, t hat 's it self a descendent of a < p> t ag. Leaving off t he ancest or t ag nam e ( in t his case t he p) provides a m ore flexible st yle: .intro a {color: yellow; }

This select or indicat es any < a> t ag inside of any ot her t ag< div> , < h1> , < t able> , and so onwit h t he .int ro class applied t o it . Descendent select ors are a very powerful weapon in your CSS arsenal. You can find m any m ore powerful ways t o use t hem in Chapt er 14.

Section 3.5. Styling Groups of Tags

3.5. Styling Groups of Tags Som et im es you need a quick way t o apply t he sam e form at t ing t o several different elem ent s. For exam ple, m aybe you'd like all t he headers on a page t o share t he sam e color and font . Creat ing a separat e st yle for each headerh1, h2, h3, h4 and so onis way t oo m uch work, and if you lat er want t o change t he color of all of t he headers, t hen you have six different st yles t o updat e. A bet t er approach is t o use a group select or. Group select ors let you apply a st yle t o m ult iple select ors at t he sam e t im e.

3.5.1. Constructing Group Selectors To work wit h select ors as a group, sim ply creat e a list of select ors separat ed by com m as. So t o st yle all of t he heading t ags wit h t he sam e color, you can creat e t he following rule: h1, h2, h3, h4, h5, h6 { color: #F1CD33; }

This exam ple consist s of only t ag select ors, but you can use any valid select or ( or com binat ion of select or t ypes) in a group select or. For exam ple, here's a select or t hat applies t he sam e font color t o t he < h1> t ag, t he < p> t ag, any t ag st yled wit h t he .copyright class, and t he t ag wit h t he # banner I D. h1, p, .copyright, #banner { color: #F1CD33; }

Note: If you want a bunch of page elements to share some but not all of the same formatting properties, then you can create a group selector with the shared formatting options, and individual rules, with unique formatting, for each individual element. The ability to use multiple styles to format a single element is a powerful CSS feature. See Chapter 5 for details.

3.5.2. The Universal Selector (Asterisk) You can t hink of a group select or as short hand for applying t he sam e st yle propert ies t o several different page elem ent s. CSS also gives you a sort of über group select ort he universal select or. An ast erisk * is universal select or short hand for select ing every single t ag. For exam ple, say you want all t he t ags on your page t o appear in bold t ype. Your group select or m ight look som et hing like t he following: a, p, img, h1, h2, h3, h4, h5 …yadda yadda… { font-weight: bold; }

The ast erisk, however, is a m uch short er way t o t ell CSS t o select all HTML t ags on t he page:

Section 3.5. Styling Groups of Tags

* { font-weight: bold; }

You can even use t he universal select or as part of a descendent select or, so you can apply a st yle t o all of t he t ags t hat descend from a part icular page elem ent . For exam ple, # banner * select s every t ag inside t he page elem ent t o which you've applied t he # banner I D. Since t he universal select or doesn't specify any part icular t ype of t ag, it 's hard t o predict it s effect on an ent ire Web sit e's wort h of pages all com posed of a variet y of different HTML t ags. To form at m any different page elem ent s, Web page gurus rely on inherit ancea CSS t rait discussed in dept h in t he next chapt er.

Section 3.6. Pseudo-Classes and Pseudo-Elements

3.6. Pseudo-Classes and Pseudo-Elements Som et im es you need t o select part s of a Web page t hat don't have t ags per se, but are nonet heless easy t o ident ify, like t he first line of a paragraph, or a link as you m ove your m ouse over it . CSS gives you a handful of select ors for t hese doohickeyspseudo- classes and pseudo- elem ent s.

3.6.1. Styles for Links Four pseudo- classes let you form at links in four different st at es based on how a visit or has int eract ed wit h t hat link. They ident ify when a link's in one of t he following four st at es: ●





a :lin k select s any link t hat your guest hasn't visit ed yet , while t he m ouse isn't hovering over or clicking it . This st yle is your regular, unused Web link. a :visit e d is a link t hat your visit or has clicked before, according t o t he Web browser's hist ory. You can st yle t his t ype of link different ly t han a regular link t o t ell your visit or, " Hey, you've been t here already! " a :h ove r let s you change t he look of a link as your visit or passes t he m ouse over it . The rollover effect s you can creat e aren't j ust for funt hey can provide useful visual feedback for but t ons on a navigat ion bar. You can also use t he : hover pseudo- class on elem ent s ot her t han links. For exam ple, you can use it t o highlight t ext in a < p> or < div> when your guest s m ouse over it .

Note: In Internet Explorer 6 and earlier, :hover works only on links. For a JavaScript workaround, see the box in Section 3.6.2.4. ●

a :a ct ive let s you det erm ine how a link looks as your visit or clicks. I n ot her words, it covers t he brief nanosecond when som eone's pressing t he m ouse but t on, before releasing it .

Chapt er 9 shows you how t o design links using t hese select ors t o help your visit ors click t heir way around your sit e.

Tip: You can live a long, healthy, productive life without reading about the selectors in the next few sections. Many Web designers never use them. The selectors you've learned so fartag, class, ID, descendent, group, and so onlet you build absolutely beautiful, functional, and easily maintained Web sites. If you're ready for the fun stuffdesigning Web pagesthen skip to the tutorial in Section 3.1. You can always finish reading this discussion some cold, rainy night by the fire.

GEM IN THE ROUGH Styling Paragraph Parts

Section 3.6. Pseudo-Classes and Pseudo-Elements

The t ypographic feat ures t hat m ake books and m agazines look cool, elegant , and polished didn't exist in t he early Web era. ( Aft er all, when did scient ist s ever worry about looking cool?) CSS provides t wo pseudo- elem ent s: first - let t er and : first - linet hat give your Web pages t he design finesse t hat print has enj oyed for cent uries. The : first - let t er pseudo- elem ent let s you creat e a drop capan init ial let t er t hat j um ps out from t he rest of t he paragraph wit h bigger or bolder font form at t ing, as at t he beginning of a book chapt er. St yling t he : first - line of a paragraph in a different color keeps your reader's eye m oving and m akes t ext appear appealing and fresh. ( I f you're int rigued, Chapt er 6 is all about form at t ing t ext .)

3.6.2. More Pseudo-Classes and -Elements The CSS guidelines define several powerful pseudo- class and elem ent select ors beside t he ones covered so far. Unfort unat ely, t he m ost popular browser aroundI nt ernet Explorer 6 for Windowsdoesn't recognize t hem . So m ost Web surfers can't appreciat e any design elem ent s you creat e wit h t hese select ors ( at least unt il t hey upgrade t o I E 7 or swit ch t o Mozilla Firefoxor t rade in t heir PCs for Macs) . Meanwhile, you can work around t his problem using JavaScript , as described in t he box in Sect ion 3.6.2.4.

3.6.2.1. :before The : before pseudo- elem ent does som et hing no ot her select or can: I t let s you add cont ent preceding a given elem ent . For exam ple, say you want ed t o put " HOT TI P! " before cert ain paragraphs t o m ake t hem st and out , like t he boxes in t his book t hat say " UP TO SPEED" and " POWER USERS' CLI NI C." I nst ead of t yping t hat t ext in your page's HTML, you can let t he : before select or do it for you. This approach not only saves on code, but if you decide t o change t he m essage from " HOT TI P! " t o, say, " Things t o know," t hen you can change every page on your sit e wit h one quick change t o your st yle sheet . ( The downside is t hat t his special m essage is invisible t o browsers t hat don't underst and CSS or don't underst and t he : before select or.) First , creat e a class ( .t ip, say) and apply it t o t he paragraphs t hat you want t o precede wit h t he m essage, like so: < p class= " t ip" > . Then, add your m essage t ext t o t he st yle sheet : p.tip:before {content: "HOT TIP!" }

Whenever a browser encount ers t he .t ip class in a < p> t ag, it dut ifully insert s t he t ext " HOT TI P! " j ust before t he paragraph. The t echnical t erm for t ext you add wit h t his select or is generat ed cont ent , since Web browsers creat e ( generat e) it on t he fly. I n t he page's HTML source code, t his m at erial doesn't exist . Whet her you realize it or not , browsers generat e t heir own cont ent all t he t im e, like t he bullet s in bullet ed list s and num bers in ordered list s. I f you want , you can even use t he : before select or t o define how a browser displays it s bullet s and num bers for list s. Despit e it s pot ent ial, I nt ernet Explorer 6 and earlier versions ignore t he : before select or offhand. Even up-

Section 3.6. Pseudo-Classes and Pseudo-Elements

t o- dat e program s like Safari and Firefox don't apply generat ed cont ent consist ent ly. ( See t he cont ent propert y list ed in Appendix A in Sect ion A.1 for m ore inform at ion and a list of resources on t his t opic.)

3.6.2.2. :after Exact ly like t he : before select or, t he : aft er pseudo- elem ent adds generat ed cont ent but aft er t he elem ent , not before. You can use t his select or, for exam ple, t o add closing quot at ion m arks ( " ) aft er quot ed m at erial.

3.6.2.3. :first-child Going back t o t he HTML fam ily t ree analogy for a m om ent , recall what a child t ag is: any t ag direct ly enclosed by anot her t ag. ( I n Figure 3- 5, < h1> , < p> , < h2> , and < ul> are all children of t he < body> t ag.) The : first - child pseudo- elem ent let s you select and form at j ust t he first of however m any children an elem ent m ay have.

POWER USERS' CLINIC Getting Internet Explorer 6 Up to Speed I f you're a Web designer, you've probably got t he lat est version of Firefox, Opera, or Safari on your com put er. Unfort unat ely, m ost of t he world doesn't . The vast m aj orit y of Web surfers use I nt ernet Explorer 6 on Windows and I E 5.5 has a respect able num ber of holdout s as well. The fact is, m ost people resist upgrading t heir soft wareif t hey even know how t o do it . Even wit h t he release of I E 7, I E 6 will probably st ick around for quit e som e t im e. So, when you're designing a m ainst ream Web sit e ( not one for hardcore net izens) , you should st ill fact or I nt ernet Explorer 6 int o your designs. But t hat doesn't m ean giving up all t he cool select ors discussed on t hese pages, such as : before, : aft er, and : hover. Believe it or not , wit h a lit t le help from JavaScript and several pioneering and st ubborn program m ers before you, you can writ e script s t hat t each I E how t o handle t hese t ypes of select ors. For exam ple, CSSHOVER t eaches I nt ernet Explorer 6 for Windows what t o do wit h t he : focus ( below) and : hover select ors ( when applied t o elem ent s ot her t han links) . You can read about and download t his quick, sim ple script at www.xs4all.nl/ ~ pet erned/ csshover.ht m l . This cool bit of JavaScript sim plifies t he creat ion of CSS- based drop- down navigat ion m enus like t he ones you can read about at www.seoconsult ant s.com / css/ m enus/ t ut orial/ . An even m ore am bit ious proj ect , from JavaScript expert Dean Edwards, let s I nt ernet Explorer 5 and 6 for Windows t ake advant age of all CSS 2 select ors as well as m any space age select ors from t he not - yet - finalized CSS 3 st andard. Edwards' set of script snam ed I E7let s you use select ors like : before, : aft er, : first - child, and t he advanced select ors discussed in Sect ion 3.1. You can learn m ore about t his am azing proj ect at ht t p: / / dean.edwards.nam e/ I E7/ overview/ .

A < ul> t ag, for exam ple, which creat es a bullet ed list , can have m any list it em s as children. ( I n Figure 3- 5, t he < ul> t ag has t hree < li> children.) To form at j ust t he first list it em ( in boldface) , you can writ e t his rule:

Section 3.6. Pseudo-Classes and Pseudo-Elements

li:first-child { font-weight: bold; }

Because t he : first - child select or includes only t he nam e of t he child elem ent , never t he parent , t his st yle form at s any < li> t ag t hat 's t he first child of any ot her t ag, not j ust < ul> . List it em s always fall wit hin list s, so you know t he select or li: first - child affect s all list s on t he pageunordered or ordered. Wit h ot her t ags, however, t he : first - child select or get s a lit t le t ricky. For exam ple, in Figure 3- 5, t he select or p: first - child would have no effect at all, since t he < p> t ag is a child of t he < body> t ag, but it isn't t he first childt he < h1> t ag is. Since t he HTML parent - child relat ions can change each t im e you edit a Web page, it 's hard t o predict how t he : first - child select or will behave as you develop your Web sit e. Also, t his select or doesn't work at all in I nt ernet Explorer 6 or earlier versionsanot her reason t o avoid it unless absolut ely necessary.

3.6.2.4. :focus The : focus pseudo- class works m uch like t he : hover pseudo- class. While : hover applies when a visit or m ouses over a link, : focus applies when t he visit or does som et hing t o indicat e her at t ent ion t o a Web page elem ent usually by clicking or t abbing int o it . I n program m ery lingo, when a visit or clicks in a t ext box on a Web form , she put s t he focus on t hat t ext box. That click's a Web designer's only clue as t o where t he visit or's focusing her at t ent ion. The : focus select or is m ost ly useful for giving your visit or feedback, like changing t he background color of a t ext box t o indicat e where he's about t o t ype. ( Single- line t ext fields, password fields, and m ult i- line < t ext area> boxes are com m on t arget s for t he : focus select or.) This st yle, for exam ple, adds a light yellow color t o any t ext box a visit or clicks or t abs int o: input:focus { background-color: #FFFFCC; }

The : focus select or applies only while t he elem ent 's in focus. When a visit or t abs int o anot her t ext field or clicks anywhere else on t he page, she t akes t he focusand t he CSS propert iesaway from t he t ext box.

Tip: Learning how to write selectors can sometimes feel like learning hieroglyphics. To translate a selector into straightforward language, visit the Selectoracle at http://gallery.theopalgroup.com/selectoracle/. This great resource lets you type in a selector and spits out a clear description of which page elements on a page the style affects.

Section 3.7. Advanced Selectors

3.7. Advanced Selectors The CSS 2 guidelines provide a few m ore powerful select ors t hat give you even finer cont rol over Web page st yling. Like som e of t he select ors you've seen previously, t he select ors in t his sect ion don't work in Windows I nt ernet Explorer 6 and earlier. ( But you can t ry t he JavaScript workaround in t he box in Sect ion 3.6.2.4.)

3.7.1. Child Selectors Sim ilar t o t he descendent select ors described earlier in t his chapt er, CSS let s you form at t he children of anot her t ag wit h a child select or. The child select or uses an addit ional sym bolan angle bracket ( > ) t o indicat e t he relat ionship bet ween t he t wo elem ent s. For exam ple, t he select or body > h1 select s any < h1> t ag t hat 's a child of t he < body> t ag. Unlike a descendent select or, which applies t o all descendent s of a t ag ( children, grandchildren, and so on) , t he child select or let s you specify which child of which parent you m ean. For exam ple, in Figure 3- 6, t here are t wo < h2> t ags. Using a plain old descendent select orbody h2select s bot h < h2> t ags. Even t hough bot h < h2> t ags are inside of t he < body> t ag, t hough, only t he second one is a child of t he < body> t ag. The first < h2> is direct ly inside of a < div> t ag, so it s parent is < div> . Since t he t wo < h2> t ags have different parent s, you can use a child select or t o get at t hem individually. To select only t he second < h2> t ag, your child select or looks like t his: body > h2. I f you want t he first < h2> t ag, t hen you m ust use t his child select or inst ead: div > h2.

Figu r e 3 - 6 . Th e dia gr a m ( r igh t ) sh ow s t h e r e la t ion sh ip be t w e e n H TM L t a gs ( le ft ) .

Section 3.7. Advanced Selectors

FREQUENTLY ASKED QUESTION Making Lists Look Great

Section 3.7. Advanced Selectors

When would I ever use a child select or? Just from reading t his chapt er, I already know enough select ors t o get at j ust about any page elem ent , so why learn anot her? There's one design challenge where child select ors can't be beat and it com es up in m ore Web sit es t han you t hink. Any t im e you have an unordered list wit h one or m ore unordered list s nest ed inside ( as in Figure 3- 6) , you can use child select ors t o visually organize t hese cat egories and subcat egories of inform at ion. You can form at t he first level of list it em s one way, and t he second level of list it em s anot her way. Cont ent present ed in t his m anner looks neat , professional, and readable ( and your visit ors will love you for it ) . First , creat e a class st yle for t he out erm ost nest ed level in your list and call it , say, .m ainList . For t his t op level, you m ight use a sans- serif font , a lit t le larger t han your ot her t ext , perhaps in bold or a different color. Subsequent cat egories can be sm aller, in a serif font like Tim es for easiest reading. When you have a lot of t ext , st yling each subcat egory level a bit different ly helps visually orient your visit ors in t he m at erial. Apply t he .m ainList class st yle t o t he first < ul> t ag: < ul class= " m ainList " > . Then use a child select or ( ul.m ainList > li) t o select j ust t he first set of list it em s, and add your desired t ext st yling for t he first subcat egory. This st yling applies only t o t he < li> t ags t hat are children of t he < ul> t ag wit h t he .m ainList st yle applied t o it . The child < li> t ags of any subsequent nest ed < ul> t ags are unaffect ed, so you can st yle t hem independent ly wit h t he proper child select ors. For exam ple, t o st yle t he < li> t ags of t he first nest ed list , use t his select or ul. m ainList > li > ul > li. ( A descendent select or like ul li, by cont rast , select s t he list it em s of all unordered list s on t he pagenest ed ones and all.)

3.7.2. Adjacent Siblings Parent - child relat ionships aren't t he only ones in t he HTML fam ily t ree. Som et im es you need t o select a t ag based not on it s parent t ag, but on it s surrounding siblingst he t ags t hat share a com m on parent . A t ag t hat appears im m ediat ely aft er anot her t ag in HTML is called an adj acent sibling. I n Figure 3- 6, t he < div> t ag is t he adj acent sibling of t he < h1> t ag, t he < p> t ag is t he adj acent sibling of t he < h2> t ag, and so on. Using an adj acent sibling select or, you can, for exam ple, give t he first paragraph aft er each heading different form at t ing from t he paragraphs t hat follow. Suppose you want t o rem ove t he m argin t hat appears above t hat < p> t ag so t hat it sit s right below t he heading wit hout any gap. Or perhaps you want t o give t he paragraph a dist inct color and font size, like a lit t le int roduct ory st at em ent . The adj acent sibling select or uses a plus sign ( + ) t o j oin one elem ent t o t he next . So t o select every paragraph following each < h2> t ag, use t his select or: h2 + p. The last elem ent in t he select or ( p, in t his case) is what get s t he form at t ing, but only when it 's next t o it s brot her < h2> .

3.7.3. Attribute Selectors CSS provides a way t o form at a t ag based on any at t ribut es it has. For exam ple, say you want t o place borders around t he im ages on your pagebut only around t he im port ant phot os. You don't want t o include your logo, but t ons, and ot her lit t le doodads t hat also have an < im g> t ag. Fort unat ely, you realize t hat you've given all t he phot os descript ions using t he t it le at t ribut e, which m eans you can use an at t ribut e select or t o ident ify j ust t he im port ant im ages.

Section 3.7. Advanced Selectors

Tip: The HTML title attribute's a great way to add tooltips (pop-up messages) to links and images on a page. It's also one way to inform search engines about the useful information on a Web page. Learn more about it at http://webdesign.about. com/od/htmltags/a/aa101005.htm.

Wit h at t ribut e select ors, you can single out t ags t hat have a part icular propert y. For exam ple, here's how t o select all < im g> t ags wit h a t it le at t ribut e: img[title]

The first part of t he select or is t he nam e of t he t ag ( im g) while t he at t ribut e's nam e goes in bracket s: [ t it le] . CSS doesn't lim it at t ribut e select ors t o t ag nam es: You can com bine t hem wit h classes, t oo. For exam ple, . phot o[ t it le] select s every elem ent wit h t he .phot o class st yle and an HTML t it le at t ribut e. To get m ore specific, you can select elem ent s t hat not only share a part icular at t ribut e, but also have an exact value set for t hat at t ribut e. For exam ple, when you want t o highlight links t hat point t o a part icular URL, creat e an eye- cat ching at t ribut e select or, like so: a[href="http://www.cosmofarmer.com"]{ color:red; font-weight:bold; }

Adding a value t o an at t ribut e select or's very useful when working wit h form s. Many form elem ent s have t he sam e t ag, even if t hey look and act different ly. The checkbox, t ext box, Subm it but t on, and ot her form fields all share t he < input > t ag. The t ype at t ribut e's value is what gives t he field it s form and funct ion. For exam ple, < input t ype= " t ext " > creat es a t ext box, and < input t ype= " checkbox" > creat es a checkbox. To select j ust t ext boxes in a form , for exam ple, use t his select or: input[type="text"]

Note: The CSS 3 guidelines promise even more variations on the attribute selector.

Section 3.8. Tutorial: Selector Sampler

3.8. Tutorial: Selector Sampler I n t he rest of t his chapt er, you'll creat e a variet y of select or t ypes and see how each affect s a Web page. This t ut orial st art s wit h t he basic select or t ypes and t hen m oves on t o m ore advanced st yles. To get st art ed, you need t o download t he t ut orial files locat ed on t his book's com panion Web sit e at www. sawm ac.com / css/ . Click t he t ut orial link and download t he files. All of t he files are enclosed in a ZI P archive, so you'll need t o unzip t hem first . ( Det ailed inst ruct ions for unzipping t he files are on t he Web sit e.) The files for t his t ut orial are cont ained inside t he folder nam ed chapt er_03.

INDIGNANTLY ASKED QUESTION Keeping It Internal Hey, what 's up wit h t he int ernal st yle sheet in t his t ut orial? Chapt er 2 recom m ends using ext ernal st yle sheet s for a bunch of reasons. Think you're pret t y sm art , eh? Yes, ext ernal st yle sheet s usually m ake for fast er, m ore efficient Web sit es, for all t he reasons m ent ioned in Chapt er 2. However, int ernal st yle sheet s m ake your life easier when you're designing a single page at a t im e, as in t his t ut orial. You get t o work in j ust one Web page file inst ead of flipping back and fort h bet ween t he ext ernal st yle sheet file and t he Web page. Furt herm ore, you can preview your result s wit hout const ant ly refreshing your browser's cache; flip back t o t he box in Sect ion 2.5.1 for m ore on t hat quirkiness. Many hot shot Web designers like t o begin t heir designs wit h an int ernal st yle sheet , since it 's fast er and it avoids any problem s wit h all t hat cache nonsense. Here's t heir secret : Once t hey've perfect ed t heir design, t hey sim ply copy t he code from t he int ernal st yle sheet , past e it int o an ext ernal st yle sheet , and t hen link t he st yle sheet t o t heir sit e's pages as described in Sect ion 2.4.2.

1. Ope n se le ct or _ ba sics.h t m l in you r fa vor it e t e x t e dit or . This page is m ade of very basic HTML t ags. The m ost excit ing t hing about it is t he graphic banner ( see Figure 3- 7) . But you'll liven t hings up in t his t ut orial. You'll st art by adding an int ernal st yle sheet t o t his file.

Figu r e 3 - 7 . Pla in H TM L look s cold a n d m on ot on ou s in a W e b br ow se r . Bu t w it h a lit t le CSS, you ca n t u r n dr a b ( le ft ) in t o fa b ( Figu r e 3 - 1 0 ) in 3 1 e a sy st e ps.

Section 3.8. Tutorial: Selector Sampler

2. Click dir e ct ly a ft e r t h e closin g < / t it le > t a g, h it Re t u r n a n d t ype < st yle t ype = " t e x t / css" > . This is t he opening st yle t ag, which let s a Web browser know t hat t he inform at ion t hat follows is Cascading St yle Sheet inst ruct ions. The HTML should now look like t his ( t he st uff you added is in bold) : Selector Basics

Tip: Another way to fine-tune designs on a page-by-page basis is to use different ID names for the tag of different types of pagesfor example #review, #story, #homeand then create descendent selectors to change the way tags on these types of pages look. This technique's discussed in Section 9.1.1.

Section 5.3. Controlling the Cascade

Section 5.4. Tutorial: The Cascade in Action

5.4. Tutorial: The Cascade in Action I n t his t ut orial, you'll see how st yles int eract and how t hey can som et im es conflict t o creat e unexpect ed result s. First , you'll creat e t wo st yles and see how som e propert ies are inherit ed and how ot hers are overruled by t he cascade. Then you'll see how inherit ance affect s t ags on a page, and how a browser resolves any CSS conflict s. Finally, you'll learn how t o t roubleshoot problem s creat ed by t he cascade. To get st art ed, you need t o download t he t ut orial files locat ed on t his book's com panion Web sit e at www.sawm ac.com / css/ . Click t he t ut orial link and download t he files. All of t he files are enclosed in a ZI P archive, so you'll need t o unzip t hem first . ( Go t o t he Web sit e for det ailed inst ruct ions on unzipping t he files.) The files for t his t ut orial are cont ained inside t he folder nam ed chapt er_05.

5.4.1. Creating a Hybrid Style I n t his exam ple, you'll creat e t wo st yles. One st yle form at s all t he paragraphs of t he page; and anot her, m ore specific st yle, reform at s t wo paragraphs in a part icular spot on t he page. 1. Usin g you r fa vor it e t e x t or W e b pa ge e dit or , ope n t h e file ca sca de .h t m l loca t e d in t h e ch a pt e r _ 0 5 folde r . You'll st art by creat ing an int ernal st yle sheet . ( See Sect ions 11.7.2 and 3.8 for m ore on int ernal and ext ernal st yle sheet s and when t o use which.) 2. Click dir e ct ly a ft e r t h e closin g < / t it le > t a g. Pr e ss En t e r ( Re t u r n ) , a n d t h e n t ype < st yle t ype = " t e x t / css" > . I t 's a good idea t o writ e bot h t he opening and closing st yle t ags before you st art adding st yles. This will help you avoid t he som et im es com m on problem of forget t ing t o add t he closing st yle t aga m ist ake t hat leads t o all sort s of weird display problem s in Web browsers. 3. Pr e ss En t e r ( Re t u r n ) t w ice , a n d t h e n t ype < / st yle > . Now you'll add a basic t ag st yle t o form at t he paragraphs of t ext on t he page. 4. Pla ce you r cu r sor in t h e e m pt y lin e be t w e e n t h e ope n in g a n d closin g st yle t a gs. Type t h e follow in g st yle : p { font-family: Arial, Helvetica, sans-serif; font-size: .9em; line-height: 175%; color: #73AFB7; }

Section 5.4. Tutorial: The Cascade in Action

The CSS line- height propert y set s t he leading or space bet ween lines of t ext . ( See Sect ion 6.4 for m ore on t his propert y.) 5. Pr e vie w t h e pa ge in a W e b br ow se r . All of t he paragraphs should be form at t ed using Arial, and a light blue color. There should also be a great er- t hanusual am ount of space bet ween each line in a paragraph. That 's t he line- height propert y in act ion. Next , you'll creat e a st yle for t he paragraphs t hat appear inside a special area of t he pagea < div> t ag wit h an I D of not e. ( The < div> is already part of t he HTML of t his page.) 6. Re t u r n t o you r W e b pa ge e dit or , click dir e ct ly a ft e r t h e e n d of t h e n e w < p> t a g st yle , a n d pr e ss En t e r ( Re t u r n ) t o cr e a t e a n e m pt y lin e . Add t h e follow in g st yle : #note p { line-height: normal; color: #993366; }

You've j ust creat ed a descendent select or ( Sect ion 3.1) t hat form at s all < p> t ags t hat appear inside of a t ag wit h an I D of not e applied t o it . I n ot her words, only t he paragraphs t hat are inside t he < div> on t his page are affect ed by t hese inst ruct ions. Not ice t hat t his st yle has t wo propert iesline- height and colort hat conflict wit h t he inst ruct ions provided in t he p st yle you creat ed earlier. To see how a browser deals wit h t his conflict , you'll preview t he page. 7. Pr e vie w t h e pa ge on ce a ga in in a W e b br ow se r . You'll not ice t hat t he t wo paragraphs t hat appear below t he headline " Just Say No To Bam boo" are purple, and t hat t he paragraphs are less spaced out t han ot her paragraphs on t he page. Their line- height 's also sm aller t han t he ot her paragraphs. Because t he # not e p st yle is m ore specific, it s propert ies are m ore im port ant t han t he sim ple p st yle. So in t he case where t here's a conflict t he line- height and colort he # not e p propert ies win out . However, since # not e p doesn't assign values t o t he font - fam ily or font - size propert ies, t hose propert ies in t he p t ag st yle are applied t o t he t wo paragraphs. According t o t he rules of t he cascade, propert ies from m ult iple st ylest he p and # not e p st ylescom bine t o creat e a hybrid st yle.

5.4.2. Combining Cascading and Inheritance CSS propert ies can accum ulat e or add- up due t o inherit ance as well. I n ot her words, as a t ag inherit s propert ies from surrounding t ags ( it s ancest ors) , t hose propert ies m ix ( and perhaps conflict ) wit h st yles purposely applied t o t he t ag. You'll creat e a st yle t hat will be inherit ed by all t he t ags on t he page, and you'll see how, in t he case of conflict s, som e propert ies from t hat st yle are ignored. 1.

Section 5.4. Tutorial: The Cascade in Action

Re t u r n t o you r W e b pa ge e dit or a n d t h e ca sca de .h t m l file . You'll now add a new t ag st yle for t he < body> t ag. 2. Add t h e follow in g st yle t o t h e in t e r n a l st yle sh e e t be low t h e # n ot e p st yle you j u st a dde d: body { color: #000066; letter-spacing: 1px; }

This set s an overall t ext color for t he page, and adds one pixel of space bet ween each let t er, spreading t he let t ers out a lit t le on t he page. Bot h t hese propert ies are inherit ed, so any t ags inside t he < body> t ag will display t hese propert ies. 3. Pr e vie w t h e pa ge in a W e b br ow se r t o se e t h e e ffe ct ( se e Figu r e 5 - 5 ) . Not ice t hat t he let t ers t hat appear in t he headlines and paragraphs are spaced apart a sm all am ount , creat ing an airy qualit y t o t he t ext . That 's t he effect of all of t he t ags inherit ing t he let t er- spacing propert y. However, t he color propert y, alt hough inherit ed by t he paragraph t ags, isn't applied t o t hem because it conflict s wit h m ore specific rulest he color propert ies set in t he p and # not e p st yles.

Figu r e 5 - 5 . I n h e r it a n ce a lso a ffe ct s t h e ca sca de by pa ssin g on pr ope r t ie s t o de sce n de n t t a gs. W e b br ow se r s follow t h e r u le s of t h e ca sca de t o de t e r m in e w h ich pr ope r t ie s sh ou ld be a pplie d t o e a ch pa r t icu la r t a g.

Section 5.4. Tutorial: The Cascade in Action

As you can see, underst anding exact ly why a t ag is form at t ed t he way it is requires underst anding of t he cascade and inherit ance, as well as a lit t le bit of det ect ive work t o t race t he origin of each propert y t hat a Web browser applies t o a t ag on t he page. For exam ple, t he paragraphs inside t he < div> t ag are form at t ed using propert ies from t hree different st yles ( see Figure 5- 6) .

5.4.3. Overcoming Conflicts Because of how CSS propert ies som et im es conflict when several st yles apply t o t he sam e t ag, you'll som et im es find your pages don't look exact ly as you planned.

Figu r e 5 - 6 . D u e t o in h e r it a n ce a n d t h e ca sca de , a sin gle t a g on a pa ge ca n ge t it s pr ope r t ie s fr om m u lt iple CSS st yle s, cr e a t in g a h ybr id st yle . Th e fin a l a ppe a r a n ce of t h e t w o pa r a gr a ph s be low t h e h e a dlin e be gin n in g " Ju st Sa y N o" ( se e Figu r e 5 - 5 ) com e s fr om pr ope r t ie s of t h r e e st yle s list e d in t h is dia gr a m fr om le a st t o m ost spe cific ( t op t o bot t om ) . Th e cr osse d- ou t pr ope r t ie s a r e ove r r idde n by m or e spe cific st yle s.

Section 5.4. Tutorial: The Cascade in Action

When t hat happens you'll need t o do a lit t le work t o find out why, and rej igger your CSS select ors t o m ake sure t he Cascade is working t o produce t he result s you want . 1. Re t u r n t o you r W e b pa ge e dit or a n d t h e ca sca de .h t m l file . You'll now creat e a new st yle t hat you'll use t o highlight t he int roduct ory paragraph of t he # not e sect ion. 2. Add t h e follow in g st yle t o t h e in t e r n a l st yle sh e e t be low t h e body t a g st yle you cr e a t e d in Se ct ion 5 .4 .2 : .intro { font-weight: bold; color: #FF0000; }

Next , you'll apply t his class st yle t o a t ag. 3. Loca t e t h e < p> t a g t h a t a ppe a r s dir e ct ly be low < h 2 > Ju st Sa y N o To Ba m boo< / h 2 > , a n d t h e n a dd t h e follow in g cla ss a t t r ibu t e :



4. Pr e vie w t h e pa ge in a W e b br ow se r .

Section 5.4. Tutorial: The Cascade in Action

You'll not ice t hat t he paragraph t urns bold, but t he t ext color rem ains t he sam e as t he ot her paragraph inside t he < div> . What gives? Following t he rules of t he cascade, .int ro is a basic class select or, while t he # not e p is a descendent select or com posed of bot h an I D and a t ag nam e. These add up t o creat e a m ore specific st yle, so it s st yle propert ies overrule any conflict bet ween it and t he .int ro st yle. I n order t o m ake t he .int ro st yle work, you'll need t o give it a lit t le j uice by m aking it s select or m ore powerful. 5. Re t u r n t o t h e ca sca de .h t m l file in you r W e b pa ge e dit or a n d ch a n ge t h e n a m e of t h e st yle fr om .in t r o t o # n ot e p.in t r o. Now you have a descendent select or com posed of an I D, a t ag, and a class. This st yle's m ore specific t han # not e p and it s propert ies override t hose in any less specific st yle. 6. Pr e vie w t h e pa ge in a W e b br ow se r . Voila! The paragraph changes t o bright red. I f you didn't have a clear underst anding of t he cascade, you'd be scrat ching your head wondering why t he color propert y didn't work. I n t his and t he previous four chapt ers, you've covered t he basics of CSS. Now, in Part 2, it 's t im e t o t ake t hat knowledge and apply it t o real design challenges, m aking Web pages look great .

Part II: Applied CSS

Part II: Applied CSS Ch a pt e r 6 : For m a t t in g Te x t Ch a pt e r 7 : M a r gin s, Pa ddin g, a n d Bor de r s Ch a pt e r 8 : Addin g Gr a ph ics t o W e b Pa ge s Ch a pt e r 9 : Spr u cin g Up You r Sit e 's N a viga t ion Ch a pt e r 1 0 : For m a t t in g Ta ble s a n d For m s

Chapter 6. Formatting Text

Chapter 6. Formatting Text Most Web sit es st ill rely on words t o get t heir m essages across. Sure, people like t o look at phot os, m ovie clips, and Flash anim at ions, but it 's t he reading m at erial t hat keeps 'em com ing back. People are hungry for news, gossip, how- t o art icles, recipes, FAQs, j okes, inform at ion list s, and ot her writ t en cont ent . Wit h CSS, you canand shouldm ake your headlines and body t ext grab a visit or's at t ent ion as com pellingly as any phot o. CSS offers a powerful array of t ext - form at t ing opt ions, which let you assign font s, color, sizes, line- spacing and m any ot her propert ies t hat can add visual im pact t o headlines, bullet ed list s, and regular old paragraphs of t ext ( see Figure 6- 1) . This chapt er reveals all, and t hen finishes up wit h a t ut orial where you can pract ice assem bling CSS t ext st yles and put t hem t o work on an act ual Web page.

Section 6.1. Formatting Text

6.1. Formatting Text The first t hing you can do t o m ake t ext on your Web sit e look m ore excit ing is t o apply different font s t o headlines, paragraphs, and ot her writ t en elem ent s on your pages. To apply a font t o a CSS st yle, you use t he font - fam ily propert y:

font-family: Arial;

Note: In real life, when you put a CSS property into action, you must, of course, include all the other necessities of a complete style declaration block and style sheet, as described in Chapter 2: p { font-family: Arial; }, for example. When you see examples like font-family: Arial;, remember that's just the property in isolation, distilled down for your bookreading benefit.

Figu r e 6 - 1 . W h y se t t le for bor in g a n d dr a b t e x t ( t op) , w h e n you ca n m a k e you r h e a dlin e s scr e a m a n d you r t e x t sin g w it h a fe w sim ple CSS pr ope r t ie s ( bot t om ) ?

Section 6.1. Formatting Text

UP TO SPEED Know Your Font Types

Section 6.1. Formatting Text

You can find lit erally t ens of t housands of different font s t o express your every t hought : from bookish, st aid, and classical t ype faces t o rounded, cart oonish squiggles. But alm ost all font s fall int o one of t wo cat egories: serif and sans- serif. Serif font s are best for long passages of t ext , as it 's widely believed t hat t he serifst hose t iny " hands" and " feet " at t he end of a let t er's m ain st rokesgent ly lead t he eye from let t er t o let t er, m aking t ext easier t o read. Exam ples of serif font s are Tim es, Tim es New Rom an, Georgia, and t he font in t he m ain body paragraphs of t his book. Sans- serif font s, on t he ot her hand, are oft en used for headlines, t hanks t o t heir clean and sim ple appearance. Exam ples of sans- serif font s include Arial, Helvet ica, Verdana, and Form at a, which you're reading now. Som e people believe t hat you should use only sans- serif font s on Web pages because t hey t hink t he delicat e decorat ive st rokes of serif font s don't display well on t he coarse resolut ion of a com put er screen. I n t he end, your aest het ic j udgm ent is your best guide. Pick t he t ypes of font s you t hink look best .

6.1.1. Choosing a Font Choose a font t hat m akes your t ext eye- cat ching ( especially if it 's a headline) and readable ( especially if it 's m ain body t ext ) , as discussed in t he box above. Unfort unat ely, you can't use j ust any font you want . Well, act ually you can use any font you want , but it won't show up on a viewer's com put er unless she's inst alled t he sam e font on her syst em . So t hat handcraft ed font you purchased from t he sm all font bout ique in Nom e, Alaska, won't do you any good on t he Webunless each person viewing your sit e has also bought and inst alled t hat font . Ot herwise, your visit ors' Web browsers will show your t ext in a default font , which is usually som e version of Tim es for body t ext , and Arial or Helvet ica for headlines.

Tip: For one cutting edge method of using any font you'd like for headline text, there's a Flash-driven technique known as sIFR. Find out about it at http://wiki.novemberborn.net/sifr.

One solut ion's t o specify t he font you'd like t o use, as well as a couple of back- up choices. I f your viewer's com put er has your first - choice font , t hen t hat 's what she'll see. But when t he first font isn't inst alled, t he browser looks down t he list unt il it finds a font t hat is. The idea is t o specify a list of sim ilar- looking font s t hat are com m on t o a variet y of operat ing syst em s, like so: font-family: Arial, Helvetica, sans-serif;

I n t his exam ple, a Web browser first looks t o see if t he Arial font 's inst alled; if it is, t hen t hat font 's used; if not , t he browser next looks for Helvet ica, and if t hat isn't inst alled, t hen it finally set t les for a generic font sans- serif. ( For m ore inform at ion on com m on Mac and PC font s, see Figure 6- 2.) When you list a generic font t ype ( like sans- serif or serif) , t he viewer's browser get s t o choose t he act ual font . But at least you can define it s basic charact er. Here are som e com m only used com binat ions, including a generic font t ype at t he end of each list : ● ● ●

Arial, Helvet ica, sans- serif " Tim es New Rom an" , Tim es, serif " Courier New" , Courier, m onospace

Section 6.1. Formatting Text ● ● ● ● ● ● ●

Georgia, " Tim es New Rom an" , Tim es, serif Verdana, Arial, Helvet ica, sans- serif Geneva, Arial, Helvet ica, sans- serif Tahom a, " Lucida Grande" , Arial, sans- serif " Lucida Console" , Monaco, m onospace " Marker Felt " , " Com ic Sans MS" , fant asy " Cent ury Got hic" , " Gill Sans" , Arial, sans- serif

Note: When a font name's more than a single word, it must be enclosed by quotes like this: "Times New Roman".

6.1.2. Adding Color to Text Black and whit e's great for Casablanca and Woody Allen film s, but when it com es t o t ext , a nice skyline blue looks m uch sharper and classier t han drab black. Coloring your t ext wit h CSS is easy. I n fact , you've used t he color propert y in a few t ut orials already. You have several different ways t o define t he exact color you want , but t hey all follow t he sam e basic st ruct ure. You t ype color: followed by a color value: color: #3E8988;

I n t his exam ple, t he color value is a hexadecim al num ber indicat ing a m ut ed shade of t eal ( m ore in a m om ent on what hexadecim al is) . Every graphics program from Fireworks t o Phot oshop t o GI MP let s you select a color using hexadecim al or RGB values. Also, t he color pickers built int o Windows and Macs let you use a color wheel or palet t e t o select t he perfect color and t ranslat e it int o a hexadecim al or RGB value.

Tip: If your color design sense needs some help, you can find lots of attractive, coordinated collections of colors at www. colorschemer.com/schemes/.

6.1.2.1. Hexadecimal color notation The m ost com m on color syst em used by Web designers is hexadecim al not at ion. A color valuelike # 6600FFact ually cont ains 3 hexadecim al num bersin t his exam ple 66, 00, FFeach of which specify an am ount of red, green, and blue, respect ively. As in t he RGB color syst em described next , t he final color value is a blend of t he am ount s of red, green, and blue specified by t hese num bers.

Tip: You can shorten the hexadecimal numbers to just three characters if each set contains the same two numbers. For example, shorten #6600FF to #60F, or #FFFFFF to #FFF.

Figu r e 6 - 2 . W h ile M a c a n d W in dow s u se d t o com e w it h ve r y diffe r e n t se t s of

Section 6.1. Formatting Text

pr e in st a lle d fon t s, t h e r e 's be e n som e con ve r ge n ce in t h e pa st fe w ye a r s. Th e se da ys, you ca n cou n t on t h e a ve r a ge M a c or PC t o h a ve t h e follow in g fon t s: Ar ia l, Ar ia l Bla ck , Ar ia l N a r r ow , Com ic Sa n s M S, Cou r ie r N e w , Ge or gia , Tim e s N e w Rom a n , Tr e bu ch e t M S, Ve r da n a , a n d W e bdin gs. I f you r a u die n ce in clu de s Lin u x fa n s, t h e n a ll be t s a r e off, t h ou gh H e lve t ica , Tim e s, a n d Cou r ie r a r e sa fe be t s. For a con cise list in g of fon t s com m on t o t h e t w o ope r a t in g syst e m s, ch e ck ou t w w w .a m psoft .n e t / w e bde sign - l/ W in dow sM a cFon t s.h t m l.

Section 6.1. Formatting Text

6.1.2.2. RGB You can also use t he RGB red, green, bluem et hod fam iliar in com put er graphics program s. The color value consist s of t hree num bers represent ing eit her percent ages ( 0100 percent ) or num bers bet ween 0255 for each hue ( red, green and blue) . So when you want t o set t he t ext color t o whit e ( perhaps t o set it off from an om inous dark page background) , you can use t his: color: rgb(100%,100%,100%);

or color: rgb(255,255,255);

Tip: If all these numbers and digits have your head spinning, then you can always fall back on the classic HTML color keywords. (Just don't expect your site to win any awards for originality.) There are 17 colorsaqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow. In CSS, you add them to your style like so: color: fuchsia;.

Section 6.2. Changing Font Size

6.2. Changing Font Size Varying t he size of t ext on a Web page is a great way t o creat e visual int erest and direct your visit ors' at t ent ion t o im port ant areas of a page. Headlines in large t ype sizes capt ure your at t ent ion, while copyright not ices displayed in sm all t ype subt ly recede from prom inence. The font - size propert y set s t ext size. I t 's always followed by a unit of m easurem ent , like so: font-size: 1em;

The value and unit you specify for t he font size ( in t his exam ple, 1em ) det erm ine t he size of t he t ext . CSS offers a dizzying select ion of sizing unit s: keywords, em s, exs, pixels, percent ages, picas, point s, even inches, cent im et ers and m illim et ers. Unit s of m easurem ent com m only used wit h print ed m at erialspicas, point s, inches, and so ondon't work well on Web pages because you can't predict how t hey'll look from one m onit or t o t he next . But you m ay have occasion t o use point s when creat ing st yle sheet s for print er- friendly pages, as described in Chapt er 13 ( Sect ion 13.1) . Only a few of t he m easurem ent unit spixels, keywords, em s, and percent agesm ake sense when you're sizing t ext for a com put er m onit or. The rest of t his sect ion explains how t hey work.

6.2.1. Using Pixels Varying Pixel values are t he easiest t o underst and, since t hey're com plet ely independent from any browser set t ings. When you specify, for exam ple, a 36- pixel font size for an < h1> t ag, t he Web browser displays t ext t hat 's 36 pixels t all, period. Web designers cherish pixel values because t hey provide consist ent t ext sizes across different t ypes of com put ers and browsers. ( Well, not all Web designers. See t he box in Sect ion 6.2.2 for one lim it at ion of pixel sizing.) To set a pixel value for t he font - size propert y, t ype a num ber followed by t he abbreviat ion px: font-size: 36px;

Note: Don't include a space between the number and the unit type. For example, 36px is correct, but 36 px isn't.

FREQUENTLY ASKED QUESTION The Problem with Pixels

Section 6.2. Changing Font Size

I t sounds like pixel values give m e com plet e cont rol over t ext size. Why bot her using any ot her kind of t ext - sizing value? Unfort unat ely, in I nt ernet Explorer 6 ( and earlier) for Windows, t here's one serious lim it at ion t o pixel t ext sizes: The viewer get s no cont rol over t ext size. Som e peopleespecially t hose wit h Text Size com m and t o pum p up t ext t o a size t hat 's easier t o lim it ed eyesight use I E's View read. However, I E won't resize any t ext t hat 's sized wit h a pixel value. I E adheres t o what t he designer want s, wit h no concern for t he person behind t he wheel of t he browser. Whet her or not t o use pixel values is som et hing of a holy war in Web design circles. Many Web developers believe pixelsized t ext creat es an accessibilit y issue. That is, it pot ent ially lim it s access t o your sit e for people wit h disabilit ies. I nt ernet Explorer 7, like m ost ot her Web browsers current ly available, does let you resize pixelsized t ext . As I E 7 becom es m ore popular, you'll be able t o use pixel values wit hout worrying about t he lim it at ions of I E 6. Meanwhile, t he best you can do is consider your audience. I f you're creat ing a sit e t hat 's aim ed at older folks or dest ined for use in schools, t hen use one of t he resizable t ext opt ions like keywords, em s, or percent ages. Anywhere you're likely t o find a com binat ion of older com put ers and people wit h special needs, m ake accessibilit y m ore of a priorit y.

6.2.2. Using Keywords, Percentages, and Ems Three ways of sizing t ext wit h CSSkeywords, percent ages, and em swork by eit her adding t o or subt ract ing from t he t ext size already on t he viewer's browser screen. I n ot her words, if you don't specify a size for t ext using CSS, a Web browser falls back on it s pre- program m ed set t ings. I n m ost browsers, t ext inside a non- header t ag's displayed 16 pixels t allt hat 's called t he base t ext size. Web surfers can adj ust t heir browsers by pum ping up or dropping down t hat base size. I n I nt ernet Explorer, for Text Size and select an opt ion such as Larger or Sm aller t o adj ust t he t ext exam ple, you can choose View Text Size I ncrease ( or Decrease) ; and in Safari t he m enu size on t he screen; in Firefox, it 's View Make Text Sm aller and View Make Text Bigger. opt ions are View When you resize t ext wit h CSS, t he browser t akes t he base t ext size ( whet her it 's t he original 16 pixels or som e ot her size t he viewer ordered) and adj ust s it up or down according t o your keyword, em , or percent age value.

6.2.2.1. Keywords CSS provides seven keywords which let you assign a size t hat 's relat ive t o t he base t ext size: xx- sm all, x- sm all, sm all, m edium , large, x- large, and xx- large. The CSS looks like t his: font-size: large;

The m edium opt ion's t he sam e as t he browser's base font size. Each of t he ot her opt ions decreases or increases t he size by a fact or of 1.2. For exam ple, say t he base t ext size is 16 pixels. Set t ing t he font size t o large m akes t he t ext 19 pixels, while a set t ing of sm all set s it t o 13 pixels. I f your visit or adj ust s t he t ext size, large sim ply Text Size m ult iplies t hat size by 1.2, what ever it m ay be. Som e eagle- eyed nerdlingt on could choose View

Section 6.2. Changing Font Size

Sm aller t o really cram a lot of fine print on t he screen. Your large set t ing boost s his 13- point t ext t o a healt hy 16not exact ly large, but st ill bigger t han any base- sized t ext on t he sam e page. Keywords are pret t y lim it ed: You have only seven choices. When you want m ore cont rol over t he size of your t ext , t urn t o one of t he ot her font - sizing opt ions discussed next .

Note: Due to a bug in Internet Explorer 5 for Windows, using these keywords results in text that displays one size smaller than in other browsers. For example, small comes out as x-small in IE 5. (To defeat this bug, check out the section called "Setting the font size" on this Web page: http://simon.incutio.com/archive/2003/05/20/defeatingIE5.)

6.2.2.2. Percentages Like keywords, percent age values adj ust t ext in relat ionship t o t he font size defined by t he browser, but t hey give you m uch finer cont rol t han j ust large, x- large, and so on. Every browser has a pre- program m ed base t ext size, which in m ost browsers is 16 pixels. You can adj ust t his base size in your browser t hrough t he browser's Opt ions ( or Preferences) or via t he View m enu ( see Sect ion 6.2.2) . What ever set t ing's been chosen, t he base t ext size for a part icular browser's equivalent t o 100 percent . I n ot her words, for m ost browsers, set t ing t he CSS percent age t o 100 percent is t he sam e as set t ing it t o 16 pixels. Say you want t o m ake a part icular headline appear 2 t im es t he size of average t ext on a page. You sim ply set t he font size t o 200 percent , like so:

font-size: 200%;

Or, when you want t he t ext t o be slight ly sm aller t han t he default size, use a value like 90% t o shrink t he font size down a bit . The above exam ples are pret t y st raight forward, but here's where it get s a lit t le t ricky: Font size is an inherit ed propert y ( see Chapt er 4) , m eaning t hat any t ags inside of a t ag t hat has a font size specified inherit t hat font size. So t he exact size of 100 percent can change if a t ag inherit s a font - size value. For exam ple, at t he lower- left of Figure 6- 3, t here's a < div> t ag t hat has it s font size set t o 200 percent . That 's t wo t im es t he browser's base t ext size, or 32 pixels. All t ags inside t hat < div> inherit t hat t ext size and use it as t he basis for calculat ing t heir t ext sizes. I n ot her words, for t ags inside t hat < div> , 100 percent is 32 pixels. So t he < h1> t ag inside t he < div> t hat has a font size of 100 percent displays at t wo t im es t he base- t ext size for t he page, or 32 pixels.

Figu r e 6 - 3 . Th e t h r e e m ost com m on u n it s for sizin g t e x t : pix e ls, e m s, a n d pe r ce n t a ge s. W a t ch ou t for in h e r it e d t e x t size s w h e n u sin g e m s or pe r ce n t a ge s a s e x pla in e d on t h e opposit e pa ge . I f you n ot ice t h a t som e t e x t on a pa ge look s u n u su a lly la r ge or sm a ll, t h e n ch e ck t o se e if t h e offe n din g t e x t isn 't in side a t a g t h a t in h e r it s a fon t size fr om a n ot h e r t a g.

Section 6.2. Changing Font Size

6.2.2.3. Ems Once you underst and percent ages, you know everyt hing you need t o underst and em s. The t wo work exact ly t he sam e way, but m any Web designers use em s because of it s root s in t ypography. The word em com es from t he world of print ed ( as in paper) t ypography, where it refers t o t he size of a capit al

Section 6.2. Changing Font Size

let t er M for a part icular font . As it 's worked it s way int o t he Web world, an em in CSS no longer m eans t he sam e t hing as in t ypography. Think of it as referring t o t he base t ext size. That is, a value of 1em m eans t he sam e t hing as a value of 100 percent as described in t he previous sect ion. You can even say it t he opposit e way: A percent age value is j ust an em m ult iplied by 100: .5em is 50 percent , .75em is 75 percent , 3em is 300 percent and so on. For exam ple, t his CSS does t he exact sam e t hing as font - size: 200% ; ( opposit e page) . font-size: 2em;

Note: As with pixel values, there's no space between the number and the word em. Also, even if you specify more than one em, you never add an s to the end: 2.5em, never 2.5ems.

When it com es t o inherit ance, em s also work j ust like percent age values. See t he upper right of Figure 6- 3 for an exam ple. The bot t om paragraph's set t o .75em , which, since t he < p> t ag inherit s t he 2em ( 32 pixel) set t ing from t he < div> t ag, works out t o .75 x 32, or 24 pixels. I nside t he < p> t ag are t wo ot her t ags t hat also have a font - size set t ing of .75em . The innerm ost t ag, a < st rong> t ag is set t o .75em or, in essence, 75 percent of it s inherit ed size. There's a lot of m at h t o t his one: 32 pixels ( inherit ed from t he < div> t ag) x .75 ( inherit ed from t he < p> t ag) x .75 ( inherit ed from t he < em > t ag) x .75 ( t he < st rong> t ag's own font size) . The result of t his braint easer is a t ext size of roughly 14 pixels.

Note: Internet Explorer 6 and earlier sometimes has problems displaying text when only em units are used. You have two ways around this: Either stick with percentage values, or set the font size for the body of the page to a percentage and then use em units to size other text. For some mysterious reason, this trick seems to fix the bugs in IE.

WORKAROUND WORKSHOP Untangling the Nest I nherit ed font - size values can cause problem s for nest ed list s. ( See t he bot t om - right square of Figure 6- 3.) I f you creat e a st yle like ul { font - size: 75% } , t hen a nest ed list , which is a < ul> t ag inside of anot her < ul> t ag, is set t o 75 percent of 75 percent m aking t he t ext in t he nest ed list sm aller t han t he rest of t he list . To get around t his conundrum , creat e an addit ional descendent select or st yle ( Sect ion 3.1) like t his: ul ul { font size: 100% } . This st yle set s any ul t ag inside of a ul t o 100 percent ; in ot her words, 100 percent of t he surrounding ul t ag's font size. I n t his exam ple, it keeps any nest ed list s t o 75 percent .

Tip: You can make type stand out on a page in many different ways. Making certain words larger than others, or making some text darker, lighter, or brighter visually sets them apart from the surrounding text. Contrast is one of the most important principles to good graphic design; it can help highlight important messages, guide a reader's eye around a page, and generally

Section 6.2. Changing Font Size

make understanding a page easier. For a quick overview of typographic contrast, check out this page: www.creativepro.com/ story/feature/19877.html.

Section 6.3. Formatting Words and Letters

6.3. Formatting Words and Letters Alt hough you'll spend a lot of t im e fine- t uning t he color, size, and font s of t he t ext on your Web pages, CSS also let s you apply ot her com m on t ext form at t ing propert ies ( like bold and it alics) as well as som e less com m on ones ( like sm all caps and let t er spacing) .

Tip: CSS lets you combine multiple text properties, but don't get carried away. Too much busy formatting makes your page harder to read. Worst of all, your hard work loses its impact.

6.3.1. Italicizing and Bolding Web browsers display t ype inside t he < em > and < i> t ags in it alicized t ype, and t ext inside t he < st rong> , < b> , < t h> ( t able header) , and header t ags ( < h1> , and so on) in bold t ype. But you can cont rol t hese set t ings yourselfeit her t urn off bold for a headline, or it alicize t ext t hat norm ally isn't using t he font - st yle and font - weight propert ies. To it alicize t ext , add t his t o a st yle:

font-style: italic;

Alt ernat ively, you can m ake sure t ext isn't it alicized, like so: font-style: normal;

Note: The font-style property actually has a third option obliquewhich works identically to italic.

The font - weight propert y let s you m ake t ext bold or not . I n fact , according t o t he rules of CSS, you can act ually specify nine num eric values ( 100- 900) t o choose subt le gradat ions of boldness ( from super- ext ra- heavy [ 900] t o ult ra- nearlyinvisible- light [ 100] ) . Of course, t he font s you use m ust have 9 different weight s for t hese values t o have any visible effect for your Web sit e's visit ors. And since t here aren't any font s t hat work t his way wit h Web browsers yet , you have far fewer opt ions for t his propert y t o worry about . So, for now, t o m ake t ext bold: font-weight: bold;

And t o m ake t ext un- bold: font-weight: normal;

Tip: Since headlines are already displayed as bold type, you may want to find another way of highlighting a word or words that are strongly emphasized or bolded inside a headline. Here's one way:This descendent selector changes the color of any tags (usually displayed as bold) that appear inside a tag.

Section 6.3. Formatting Words and Letters

6.3.2. Capitalizing Capit alizing t ext is pret t y easyj ust hit t he caps lock key and st art t yping, right ? But what if you want t o capit alize every heading on a page, and t he t ext you've copied and past ed from a Word docum ent is lowercase? Rat her t han ret yping t he headline, t urn t o t he CSS t ext - t ransform propert y. Wit h it , you can m ake t ext all uppercase, all lowercase, or even capit alize t he first let t er of each word ( for t it les and headlines) . Here's an exam ple:

text-transform: uppercase;

For t he ot her t wo opt ions, j ust use lowercase; or capit alize; . Because t his propert y is inherit ed, a t ag t hat 's nest ed inside a t ag wit h t ext - t ransform applied t o it get s t he sam e uppercase, lowercase, or capit alized value. To t ell CSS not t o change t he case of t ext , use t he none value: text-transform: none;

6.3.2.1. Small caps For m ore t ypographic sophist icat ion, you can also t urn t o t he font - variant propert y, which let s you set t ype as sm all- caps. I n sm all cap st yle, lowercase let t ers appear as slight ly downsized capit al let t ers, like so: POMP AND CI RCUMSTANCE. While difficult t o read for long st ret ches of t ext , sm all caps lend your page an oldworld, bookish gravit as when used on headlines and capt ions. To creat e sm all- cap t ext :

font-variant: small-caps;

6.3.3. Decorating CSS also provides t he t ext - decorat ion propert y t o add various enhancem ent s t o t ext . Wit h it , you can add lines over, under, or t hrough t he t ext ( see Figure 6- 4) , or for real giggles you can m ake t he t ext blink like a No Vacancy sign. Use t he t ext decorat ion propert y by adding one or m ore of t he following keywords: underline, overline, line- t hrough, or blink. For exam ple, t o underline t ext :

text-decoration: underline;

You can also com bine m ult iple keywords for m ult iple effect s. Here's how t o add a line over and under som e t ext : text-decoration: underline overline;

But j ust because you can add t hese not - so- decorat ive decorat ions t o t ext , doesn't m ean you should. For one t hing, anyone who's used t he Web for any lengt h of t im e inst inct ively associat es any underlined t ext wit h a link and t ries t o click it . So it 's not a good idea t o underline words t hat aren't part of a link. And t he blink propert y is like a neon sign crying " Am at eur! Am at eur! Am at eur! "

Tip: You can get a similar effect to underlining and overlining by adding a border to the bottom or top of an element (see Section 7.3).

Section 6.3. Formatting Words and Letters

The big advantage of borders is that you can control their placement, size, and color to create a more attractive design that doesn't look like a link.

The overline opt ion sim ply draws a line above t ext , while line- t hrough draws a line right t hrough t he cent er of t ext . Som e designers use t his st rike- t hrough effect t o indicat e an edit on a page where t ext has been rem oved from t he original m anuscript . Coupled wit h t he a: visit ed select or, you can also creat e a cool effect where previously visit ed links are crossed out like a shopping list .

Figu r e 6 - 4 . Th e t e x t - de cor a t ion pr ope r t y in a ct ion . I f t h is is w h a t t h e pe ople a t CSS h e a dqu a r t e r s ca ll " de cor a t ion s," you 'd be st n ot a sk for t h e ir de sign h e lp on you r n e x t h om e r e m ode l.

Finally, you can t urn off all decorat ions by using t he none keyword like t his: text-decoration: none;

Why do you need a t ext - decorat ion propert y t hat rem oves decorat ions? The m ost com m on exam ple is rem oving t he line t hat appears under a link. ( See Sect ion 9.1.)

6.3.4. Letter and Word Spacing

Section 6.3. Formatting Words and Letters

Anot her way t o m ake t ext st and out from t he crowd is t o adj ust t he space t hat appears bet ween let t ers or words ( see Figure 6- 5) . Reducing t he space bet ween let t ers using t he CSS let t er- spacing propert y can t ight en up headlines m aking t hem seem even bolder and heavier while fit t ing m ore let t ers on a single line. Conversely, increasing t he space can give headlines a calm er, m ore m aj est ic qualit y. To reduce t he space bet ween let t ers, you use a negat ive value like t his:

letter-spacing: -1px;

A posit ive value adds space bet ween let t ers: letterspacing: 10px;

Likewise, you can open up space ( or rem ove space) bet ween words using t he wordspacing propert y. This propert y m akes t he space wider ( or narrower) wit hout act ually affect ing t he words t hem selves:

word-spacing: 2px;

Wit h eit her of t hese propert ies, you can use any t ype of m easurem ent you'd use for t ext sizingpixels, em s, percent ageswit h eit her posit ive or negat ive values.

Figu r e 6 - 5 . Use w or d a n d le t t e r spa cin g j u diciou sly. Too m u ch or t oo lit t le of e it h e r ca n m a k e t e x t difficu lt if n ot im possible t o r e a d.

Section 6.3. Formatting Words and Letters

Unless you're going for som e really far- out design effect in ot her words, t ot ally unreadable t ext keep your values sm all. Too high a negat ive value, and let t ers and words overlap. To keep t he m essage of your sit e clear and legible, use bot h let t er and word spacing wit h care.

Section 6.4. Formatting Entire Paragraphs

6.4. Formatting Entire Paragraphs Rat her t han individual words, som e CSS propert ies apply t o chunks of t ext . You can use t he propert ies in t his sect ion on com plet e paragraphs, headlines, and so on.

6.4.1. Adjusting the Space Between Lines I n addit ion t o changing t he space bet ween words and let t ers, CSS let s you adj ust t he space bet ween lines of t ext using t he line- height propert y. The bigger t he line height , t he m ore space t hat appears bet ween each line of t ext ( see Figure 6- 6) .

Figu r e 6 - 6 . Th e lin e - h e igh t pr ope r t y le t s you spr e a d a pa r a gr a ph 's lin e s a pa r t or br in g t h e m close r t oge t h e r . Th e n or m a l se t t in g is e qu iva le n t t o 1 2 0 pe r ce n t , so a sm a lle r pe r ce n t a ge t igh t e n s u p t h e lin e s ( t op) , w h ile a la r ge r pe r ce n t a ge pu sh e s t h e m a pa r t ( bot t om ) .

Section 6.4. Formatting Entire Paragraphs

6.4.1.1. Line spacing by pixel, em, or percentage Just as wit h t he font - size propert y, you can use pixels, em s, or percent ages t o set t he size of line height : line-height: 150%;

Section 6.4. Formatting Entire Paragraphs

I n general, percent ages or em s are bet t er t han pixels, because t hey change according t o, and along wit h, t he t ext 's font - size propert y. I f you set t he line height t o 10 pixels, and t hen lat er adj ust t he font size t o som et hing m uch larger ( like 36 pixels) , because t he line height rem ains at 10 pixels, t hen your lines overlap. However, using a percent age ( 150 percent , say) m eans t he line- height spacing adj ust s proport ionally whenever you change t he font - size value. The norm al line- height set t ing for a browser is 120 percent . So, when you want t o t ight en up t he line spacing, use a value less t han 120 percent . To spread lines apart , use a value great er t han 120 percent .

Note: To determine the amount of space that appears between lines of text, a Web browser subtracts the font size from the line height. The resultcalled leadingis the amount of space between lines in a paragraph. Say the font size is 12 pixels, and the line height (set to 150 percent) works out to 18 pixels. 18 minus 12 equals 6 pixels, so the browser adds 6 pixels of space between each line.

6.4.1.2. Line spacing by number CSS offers one ot her m easurem ent m et hod specific t o line height , which is sim ply a num ber. You writ e it like t his:

line-height: 1.5;

There's no unit ( like em or px) aft er t his value. The browser m ult iplies t his num ber by t he font size t o det erm ine t he line height . So if t he t ext is 1em and t he line- height value's 1.5, t hen t he calculat ed line height is 1.5em . I n m ost cases, t he effect 's no different from specifying a value of 1.5em or 150 percent . But som et im es t his m ult iplicat ion fact or com es in handy, especially since nest ed t ags inherit t he line- height value of t heir parent s. For exam ple, say you set t he line- height propert y of t he < body> t ag t o 150 percent . All t ags inside t he page would inherit t hat value. However, it 's not t he percent age t hat 's inherit ed; it 's t he calculat ed lineheight . So, say t he font size for t he page is set t o 10 pixels; 150 percent of 10 is 15 pixels. Every t ag would inherit a line- height of 15 pixels, not 150 percent . So if you happened t o have a paragraph wit h large, 36 pixel t ext , t hen it s line- height 15 pixelswould be m uch sm aller t han t he t ext , m aking t he lines squish t oget her in a hard- t o- read m ess. I n t his exam ple, inst ead of using a line- height of 150 percent applied t o t he < body> t ag, you could have all t ags share t he sam e basic proport ional line- height by set t ing t he line- height t o 1.5. Every t ag, inst ead of inherit ing a precise pixel value for line height , sim ply m ult iplies it s font size by 1.5. So in t he above exam ple of a paragraph wit h 36 pixel t ext , t he line- height would be 1.5 x 36 or 54 pixels.

6.4.2. Aligning Text One of t he quickest ways t o change t he look of a Web page is wit h paragraph alignm ent . Using t he t ext -

Section 6.4. Formatting Entire Paragraphs

align propert y, you can cent er a paragraph on a page, align t he t ext along it s left or right edge, or j ust ify bot h left and right edges ( like t he paragraphs in t his book) . Norm ally, t ext on a page is left aligned, but you m ay want t o cent er headlines t o give t hem a form al look. Languages t hat read from right t o left , like Hebrew and Arabic, require right - alignm ent . To change t he alignm ent of t ext , use any of t he following keywordsleft , right , j ust ify, cent er:

text-align: center;

Just ified t ext looks great on a print ed pagem ainly because t he fine resolut ion possible wit h print ing allows for sm all adj ust m ent s in spacing. This fine spacing prevent s large, unsight ly gaps or rivers of whit e space flowing t hrough t he paragraphs. Web pages are lim it ed t o m uch coarser spacing because of t he generally low- resolut ion of m onit ors. So when you use t he j ust ify opt ion, t he space bet ween words can vary significant ly from line t o line, m aking t he t ext harder t o read. When you want t o use t he j ust ify opt ion on your Web pages, t est it t horoughly t o m ake sure t he t ext is at t ract ive and readable.

POWER USERS' CLINIC A Shorthand Method for Text Formatting Writ ing one t ext propert y aft er anot her get s t iring, especially when you want t o use several different t ext propert ies at once. Fort unat ely, CSS offers a short hand propert y called font , which let s you com bine t he following propert ies int o a single line: font - st yle ( Sect ion 6.3.2) , font - variant ( Sect ion 6.3.2.1) , font - weight ( Sect ion 6.3.2) , font - size ( Sect ion 6.3.2) , lineheight ( Sect ion 6.4) and font - fam ily ( Sect ion 6.1.1) . For exam ple, t he declarat ion font : it alic bold sm all- caps 18px/ 150% Arial, Helvet ica, sans- serif; creat es bold, it alicized t ype in sm all caps, using 18px Arial ( or Helvet ica or sans- serif) wit h a line height of 150 percent . Keep t hese rules in m ind: ●







You don't have t o include every one of t hese propert ies, but you m ust include t he font size and font fam ily: font : 1.5em Georgia, Tim es, serif; . Use a single space bet ween each propert y value. You use a com m a only t o separat e font s in a list like t his: Arial, Helvet ica, sans- serif. When specifying t he line height , add a slash aft er t he font size followed by t he lineheight value, like t his: 1.5em / 150% or 24px/ 37px. The last t wo propert ies m ust be font - size ( or font size/ line- height ) followed by font fam ily, in t hat order. All t he ot her propert ies m ay be writ t en in any order. For exam ple bot h font : it alic bold sm all- caps 1.5em Arial; and font : bold sm all- caps it alic 1.5em Arial; are t he sam e.

Finally, om it t ing a value from t he list is t he sam e as set t ing t hat value t o norm al. Say you creat ed a < p> t ag st yle t hat form at t ed all paragraphs in bold, it alics, and sm all caps wit h a line height of 2000 percent ( not t hat you'd act ually do t hat ) . I f you t hen creat ed a class st yle nam ed, say, .special- Paragraph wit h t he following font declarat ion font : 1.5em Arial; and applied it t o one paragraph on t he page, t hen t hat paragraph would not inherit t he it alics, bold, sm all caps, or line- height . Om it t ing t hose four values in t he .specialParagraph st yle is t he sam e as writ ing t his: font : norm al norm al norm al 1.5em / norm al Arial/ ; .

6.4.3. Indenting the First Line and Removing Margins

Section 6.4. Formatting Entire Paragraphs

I n m any books, t he first line of each paragraph is indent ed. This first - line indent m arks t he beginning of a paragraph when t here are no spaces separat ing paragraphs. On t he Web, however, paragraphs don't have indent s but are inst ead separat ed by a bit of spacelike t he paragraphs in t his book. I f you have a hankering t o m ake your Web pages look less like ot her Web pages and m ore like a handsom ely print ed book, t ake advant age of t he CSS t ext - indent and m argin propert ies. Wit h t hem , you can add a first - line indent and rem ove ( or increase) t he m argins t hat appear at t he beginning and ends of paragraphs.

6.4.3.1. First-line indents You can use pixel and em values t o set t he first - line indent like t his:

text-indent: 25px;

or

text-indent: 5em;

A pixel value's an absolut e m easurem ent a precise num ber of pixelswhile an em value specifies t he num ber of let t ers ( based on t he current font size) you want t o indent .

Tip: You can use negative text-indent values to create what's called a hanging indent where the first line starts further to the left than the other lines in the paragraph. (Think of it as "hanging" off the left edge.)

You can also use a percent age value, but wit h t he t ext - indent propert y, percent ages t ake on a different m eaning t han you've seen before. I n t his case, percent ages aren't relat ed t o t he font size; t hey're relat ed t o t he widt h of t he elem ent cont aining t he paragraph. For exam ple, if t he t ext - indent is set t o 50 percent , and a paragraph spans t he ent ire widt h of t he Web browser window, t hen t he first - line of t he paragraph st art s half t he way across t he screen. I f you resize t he window, bot h t he widt h of t he paragraph and it s indent change. ( You'll learn m ore about percent ages and how t hey work wit h t he widt h of elem ent s in Sect ion 7.5.1.)

6.4.3.2. Controlling margins between paragraphs Many designers hat e t he space t hat every browser t hrows in bet ween paragraphs. Before CSS, t here was not hing you could do about it . Fort unat ely, you can now t ap int o t he m argin- t op and m argin- bot t om propert ies t o rem ove ( or, if you wish, expand) t hat gap. To t ot ally elim inat e a t op and bot t om m argin, writ e t his: margin-top: 0; margin-bottom: 0;

Section 6.4. Formatting Entire Paragraphs

To elim inat e t he gaps bet ween all paragraphs on a page, creat e a st yle like t his: p { margin-top: 0; margin-bottom: 0; }

As wit h t ext - indent , you can use pixel or em values t o set t he value of t he m argins. You can also use percent ages, but as wit h t ext - indent , t he percent age is relat ed t o t he widt h of t he paragraph's cont aining elem ent . Because it 's confusing t o calculat e t he space above and below a paragraph based on it s widt h, it 's easier t o st ick wit h eit her em or pixel values.

Tip: Because not all browsers treat the top and bottom margin of headlines and paragraphs consistently, it's often a good idea to simply zero out (that is, eliminate) all margins at the beginning of a style sheet. To see how this works, turn to Section 14.3.

For a special effect , you can assign a negat ive value t o a t op or bot t om m argin. For exam ple a - 10px t op m argin m oves t he paragraph up 10 pixels, perhaps even visually overlapping t he page elem ent above it . ( See t he m ain headline in Figure 6- 1 for an exam ple.)

6.4.4. Formatting the First Letter or First Line of a Paragraph CSS also provides a way of form at t ing j ust a part of a paragraph using t he : first - let t er and : first - line pseudo- elem ent s. Technically, t hese aren't CSS propert ies, but t ypes of select ors ( Sect ion 3.1) t hat det erm ine what part of a paragraph CSS propert ies should apply t o. Wit h t he : first - let t er pseudo- elem ent , you can creat e an init ial capit al let t er t o sim ulat e t he look of a hand- let t ered m anuscript . To m ake t he first let t er of each paragraph bold and red you could writ e t his st yle: p:first-letter { font-weight: bold; color: red; }

To be m ore select ive and form at j ust t he first let t er of a part icular paragraph, you can apply a class st yle t o t he paragraph.int ro, for exam pleand creat e a st yle wit h a nam e like t his: .int ro: first - let t er. The : first - line pseudo elem ent form at s t he init ial line of a paragraph ( see Figure 6- 7) . You can apply t his t o any block of t ext like a heading ( h2: first - line) or paragraph ( p: first - line) . As wit h : first - let t er, you can apply a class t o j ust one paragraph and form at only t he first line of t hat paragraph. Say you want ed t o capit alize every let t er in t he first line of t he first paragraph of a page. Apply a class t o t he HTML of t he first paragraph< p class= " int ro" > and t hen creat e a st yle like t his:

Section 6.4. Formatting Entire Paragraphs

.intro:first-line { text-transform: uppercase; }

Section 6.5. Styling Lists

6.5. Styling Lists The < ul> and < ol> t ags creat e bullet ed and num bered list s, like list s of relat ed it em s or num bered st eps. But you don't always want t o set t le for t he way Web browsers aut om at ically form at t hose list s. You m ay want t o swap in a m ore at t ract ive bullet , use let t ers inst ead of num bers, or even com plet ely elim inat e t he bullet s or num bers.

6.5.1. Types of Lists Most Web browsers display unordered list s ( < ul> t ags) using round bullet s, and num bered list s ( < ol> t ags) using…well…num bers. Wit h CSS, you can choose from am ong t hree t ypes of bullet s disc ( a solid round bullet ) , circle ( a hollow round bullet ) , or square ( a solid square) . There are also six different num bering schem esdecim al, decim al- leading- zero, upper- alpha, lower- alpha, upper- rom an, or lower- rom an ( see Figure 6- 8) . You select all t hese opt ions using t he list - st yle- t ype propert y, like so:

Figu r e 6 - 7 . Th e :fir st - le t t e r pse u do e le m e n t for m a t s t h e fir st le t t e r of t h e st yle d e le m e n t , lik e t h e " in it ia l ca ps" t o t h e le ft . Th e :fir st - lin e se le ct or , on t h e ot h e r h a n d, st yle s t h e fir st lin e of a pa r a gr a ph . Eve n if you r gu e st r e size s t h e w in dow ( bot t om ) , t h e br ow se r st ill st yle s e ve r y w or d t h a t a ppe a r s on a pa r a gr a ph 's fir st lin e .

Section 6.5. Styling Lists

list-style-type: square;

or

list-style-type: upper-alpha;

Figu r e 6 - 8 . M a n y W e b br ow se r s displa y t h e de cim a l a n d de cim a l- le a din g- ze r o opt ion s ide n t ica lly. Fir e fox a n d ot h e r M ozilla - ba se d br ow se r s lik e Ca m in o ( pict u r e d h e r e ) cor r e ct ly displa y t h e de cim a l- le a din g- ze r o se t t in g by a ddin g a 0 be for e sin gle digit - n u m be r s0 1 , for e x a m ple .

Section 6.5. Styling Lists

Tip: If you feel like rushing a fraternity or sorority, you can also replace numbers with Greek lettersα, β, γusing the lower-greek option.

Most of t he t im e, you use t his propert y on a st yle t hat 's form at t ing an < ol> or < ul> t ag. Typical exam ples include an ol or ul t ag st yleul { list - st yle- t ype: square; } or a class you're applying t o one of t hose t ags. However, you can also apply t he propert y t o an individual list it em ( < li> t ag) as well. You can even apply different t ypes of bullet st yles t o it em s wit hin t he sam e list . For exam ple, you can creat e a st yle for a < ul> t ag t hat set s t he bullet s t o square, but t hen creat e a class nam ed .circle t hat changes t he bullet t ype t o circle, like t his: .circle { list-style-type: circle; }

Section 6.5. Styling Lists

You can t hen apply t he class t o every ot her it em in t he list t o creat e an alt ernat ing pat t ern of square and circular bullet s:

  • Item 1
  • Item 2
  • Item 3
  • Item 4


At t im es you'll want t o com plet ely hide bullet s, like when you'd rat her use your own graphic bullet s ( Sect ion 6.5.3) . Also, when a sit e's navigat ion bar is a list of links, you can use an < ul> list , but hide it s bullet s ( see t he exam ple in Sect ion 9.1.1) . To t urn off t he bullet s, use t he keyword none:

list-style-type: none;

6.5.2. Positioning Bullets and Numbers Web browsers usually display bullet s or num bers hanging t o t he left of t he list it em 's t ext ( Figure 6- 9, left ) . Wit h CSS, you can cont rol t he posit ion of t he bullet ( som ewhat ) using t he list - st yle- posit ion propert y. You can eit her have t he bullet appear out side of t he t ext ( t he way browsers norm ally display bullet s) or inside t he t ext block it self ( Figure 6- 9, right ) : list-style-position: outside;

or list-style-position: inside;

Figu r e 6 - 9 . Usin g t h e list - st yle - posit ion pr ope r t y, you ca n con t r ol t h e posit ion of bu lle t s a n d n u m be r s in a list . Th e ou t side opt ion ( le ft ) e m ph a size s t h e " list n e ss" of you r list . Use t h e in side opt ion ( r igh t ) if you n e e d t o m a x im ize t h e w idt h of you r list .

Section 6.5. Styling Lists

Tip: You can adjust the space between the bullet and its textincrease or decrease that gapby using the padding-left property (see Section 7.2). To use it, you create a style that applies to the
  • tags. This technique works only if you set the list-styleposition property to the outside option (or don't use list-style-position at all).

    I n addit ion, if you don't like how Web browsers indent a list from t he left edge, t hen you can rem ove t hat space by set t ing bot h t he m argin- left and padding- left propert ies t o 0 for t he list . To rem ove t he indent from all list s, you could creat e t his group select or: ul, ol { padding-left: 0; margin-left: 0; }

    Or, you could creat e a class st yle wit h t hose propert ies and apply it t o a part icular < ul> or < ol> t ag. The reason you need t o set bot h t he padding and m argin propert ies is because som e browsers use padding ( Firefox, Mozilla,

    Section 6.5. Styling Lists

    Safari) and som e use m argin ( I nt ernet Explorer) t o cont rol t he indent . ( You'll learn m ore about t he m argin and padding propert ies in t he next chapt er.) Browsers norm ally display one bullet ed it em direct ly above anot her, but you can add space bet ween list it em s using t he m argin- t op or m argin- bot t om propert ies on t he part icular list it em s. These propert ies work for spacing list it em s exact ly as for spacing paragraphs, as explained in Sect ion 6.4.3.2. You j ust need t o m ake sure t hat t he st yle applies t o t he < li> t ags by creat ing a class st yle and applying it individually t o each < li> t ag. Or, bet t er yet , creat e an < li> t ag st yle or descendent select or. The st yle should not apply t o t he < ul> or < ol> t ag. Adding m argins t o t he t op or bot t om of t hose t ags sim ply increases t he space bet ween t he list and t he paragraphs above or below it not t he space bet ween each it em in t he list .

    6.5.3. Graphic Bullets I f you're not happy wit h squares and circles for your bullet s, creat e your own. Using an im age- edit ing program like Phot oshop or Fireworks, you can quickly creat e colorful and int erest ing bullet s. Clip art collect ions and m ost sym bol font s ( like Webdings) provide great inspirat ion.

    Tip: You can also find many examples of bullets on the Web. Go to www.stylegala.com/features/bulletmadness/ to find over 200 free bullet icons.

    The CSS list - st yle- im age propert y let s you specify a pat h t o a graphic on your sit e, m uch as you'd specify a file when adding an im age t o a page using t he src at t ribut e of t he HTML < im g> t ag. You use t he propert y like t his:

    list-style-image: url(images/bullet.gif);

    The t erm url and t he parent heses are required. The part inside t he parent hesesim ages/ bullet .gif in t his exam pleis t he pat h t o t he graphic. Not ice t hat , unlike HTML, you don't use quot at ion m arks around t he pat h.

    FREQUENTLY ASKED QUESTION Customizing List Bullets and Numbers I 'd like t he num bers in m y num bered list s t o be bold and red inst ead of boring old black. How do I cust om ize bullet s and num bers? CSS gives you a few ways t o cust om ize t he m arkers t hat appear before list it em s. For bullet s, you can use your own graphics as described in Sect ion 6.5.3. You have t wo ot her t echniques available: one t hat 's labor int ensive, but works on m ost browsers, and one t hat 's super geeky, cut t ingedge, and doesn't work on I nt ernet Explorer 6 for Windows or earlier. First , t he labor- int ensive way. Say you want t he num bers in an ordered list t o be red and bold, but t he t ext t o be plain, unbolded black. Creat e a st yle t hat applies t o t he list like a class st yle you apply t o t he < ol> or < li> t agswit h a t ext color of red, and t he font weight set t o bold. At t his point , everyt hing in t he list t ext includedis red and bold Next , creat e a class st yle.regularList , for exam plet hat set s t he font color t o black and font weight t o norm al ( t hat is, not bold) . Then ( and t his is t he t edious part ) , wrap a < span> t ag around t he

    Section 6.5. Styling Lists

    t ext in each list it em and apply t he class st yle t o it . For exam ple: < li> < span class= " regularList " > I t em 1< / span> < / li> . Now t he bullet s are bold and red and t he t ext is black and norm al. Unfort unat ely, you have t o add t hat < span> t o every list it em ! The cool, " I 'm so CSS- savvy," way is t o use what 's called generat ed cont ent . Basically, generat ed cont ent 's j ust st uff t hat isn't act ually t yped on t he page, but is added by t he Web browser when it displays t he page. A good exam ple is bullet s t hem selves. You don't t ype bullet charact ers when you creat e a list ; t he browser adds t hem for you. Wit h CSS, you can have a browser add cont ent and even st yle t hat cont ent , before each < li> t ag. For an int roduct ion t o generat ed cont ent , visit www.richinst yle.com / guides/ generat ed2.ht m l. The official ( read: t echnical and confusing descript ion) is at www.w3.org/ TR/ REC- CSS2/ generat e.ht m l.

    Note: When specifying a graphic in an external style sheet, the path to the image is relative to the style sheet file, not the Web page. You'll learn more about how this works in Section 8.2, as you start to use images with CSS.

    While t he list - st yle- im age propert y let s you use a graphic for a bullet , it doesn't provide any cont rol over it s placem ent . The bullet m ay appear t oo far above or below t he line, requiring you t o t weak t he bullet graphic unt il you get it j ust right . A bet t er approachone you'll learn in Chapt er 8is t o use t he background- im age propert y. That propert y let s you very accurat ely place a graphic for your bullet ed list s.

    Tip: As with the font property (see the box in Section 6.4.3), there's a shorthand method of specifying list properties. The liststyle property can include a value for each of the other list propertieslist-style-image, list-style-position, and list-style-type. For example, ul { list-style: circle inside; } would format unordered lists with the hollow circle bullet on the inside position. When you include both a style type and style imagelist-style: circle url(images/bullet.gif) inside;Web browsers use the style type circle in this exampleif the graphic can't be found.

    Section 6.6. Tutorial: Text Formatting in Action

    6.6. Tutorial: Text Formatting in Action I n t his t ut orial, you'll gussy up headlines, list s, and paragraphs of t ext using CSS's powerful form at t ing opt ions. To get st art ed, you need t o download t he t ut orial files locat ed on t his book's com panion Web sit e at www.sawm ac.com / css/ . Click t he t ut orial link and download t he files. All of t he files are enclosed in a ZI P archive, so you'll need t o unzip t hem first . ( Go t o t he Web sit e for det ailed inst ruct ions on unzipping t he files.) The files for t his t ut orial are cont ained inside t he folder nam ed chapt er_06.

    6.6.1. Setting Up the Page 1. La u n ch you r W e b br ow se r a n d ope n t h e file ch a pt e r _ 6

    t e x t .h t m l ( se e Figu r e 6 - 1 0 ) .

    As usual, you'll be working on a Web page from Cosm oFarm er.com . I n t his case, t here's already an ext ernal st yle sheet at t ached t o t he page, adding som e design and layout t ouches. I t 's a glim pse of som e of t he t hings you'll be learning in fut ure chapt ers. For now, concent rat e on im proving t he look of t he t ext on t his page.

    Figu r e 6 - 1 0 . Th e pa ge be gin s w it h som e ba sic la you t a n d for m a t t in g. You 'll m a k e t h e t e x t spa r k le !

    Section 6.6. Tutorial: Text Formatting in Action

    2. Ope n t h e file t e x t .h t m l in you r fa vor it e t e x t e dit or . St art by adding an int ernal st yle sheet t o t his file. ( Yes, ext ernal st yle sheet s are bet t er, but it 's perfect ly OK t o st art your design wit h an int ernal sheet . See t he box in Sect ion 3.1.) 3. I n t h e < h e a d> of t h e W e b pa ge , click dir e ct ly a ft e r t h e < lin k > t a g ( u se d t o a t t a ch t h e e x t e r n a l st yle sh e e t ) . H it En t e r ( Re t u r n ) , a n d t h e n t ype < st yle t ype = " t e x t / css" > . Now t hat you've creat ed t he opening st yle t ag, creat e a st yle t hat defines som e general propert ies for all t ext on t he page. 4. Pr e ss t h e En t e r ( Re t u r n ) k e y a n d t ype body { This is a basic t ag select or t hat applies t o t he < body> t ag. As discussed in Chapt er 4, ot her t ags inherit t he propert ies of t his t ag. You can set up som e basic t ext charact erist ics like font , color, and font size for lat er t ags t o use as t heir st art ing point . 5. Pr e ss En t e r ( Re t u r n ) a ga in , a n d t h e n a dd t h e follow in g t h r e e pr ope r t ie s: color: #102536; font-family: Tahoma, "Lucida Grande", Arial, sans-serif; font-size: 62.5%;

    These t hree inst ruct ions set t he color of t he t ext t o a dark blue, t he font t o Tahom a ( or one of 3 ot hers depending on which font is inst alledsee Sect ion 6.1.1) , and set s t he font size t o 62.5 percent .

    Note: Why set the page's base font to 62.5 percent? It just so happens that 62.5 percent times 16 pixels (the normal size of text in most Web browsers) equals 10 pixels. With 10 pixels as a starting point, it's easy to compute what other text sizes will look like on the screen. For example, 1.5em would be 1.5 x 10 or 15 pixels. 2em is 20 pixels, and so oneasy multiples of ten. For more on this interesting discovery and more font- sizing strategies, visit http://clagnut.com/blog/348/. 6. Com ple t e t h is st yle by pr e ssin g En t e r ( Re t u r n ) , a n d t ypin g a closin g br a ck e t t o m a r k t h e e n d of t h e st yle . At t his point , your com plet ed st yle should look like t his: body { color: #102536;

    Section 6.6. Tutorial: Text Formatting in Action

    font-family: Tahoma, "Lucida Grande", Arial, sans-serif; font-size: 62.5%; }

    Finally, add t he closing < st yle> t ag t o com plet e t he st yle sheet . 7. H it En t e r ( Re t u r n ) t o cr e a t e a n e w , bla n k lin e , a n d t h e n t ype < / st yle > . Your st yle sheet is com plet e. 8. Sa ve t h e pa ge , a n d ope n it in a W e b br ow se r t o pr e vie w you r w or k . The t ext on t he page changes color and font . You'll also not ice t hat t he headings aren't , proport ionally, as sm all as t he ot her t ext on t he page. ( The cascade you read about last chapt er rears it s ugly head.) Yes, t he < h1> and < h2> t ags inherit t he 62.5 percent font size set in t he < body> t ag st yle. However, every browser includes it s own st yle sheet wit h specific font - size set t ings for heading t ags, which overrule t he size specified in t he body. You'll fix t his problem next .

    6.6.2. Formatting the Headings and Paragraphs Now t hat t he basic t ext form at t ing is done, it 's t im e t o refine t he present at ion of t he headlines and paragraphs. 1. Re t u r n t o you r t e x t e dit or a n d t h e t e x t .h t m l file . Click a t t h e e n d of t h e closin g br a ce of t h e body t a g se le ct or , pr e ss En t e r ( Re t u r n ) t o cr e a t e a n e w lin e , a n d t h e n t ype h 1 { . This st yle form at s all < h1> t ags on t he page. 2. H it En t e r ( Re t u r n ) , a n d t h e n t ype t h e se t w o CSS pr ope r t ie s: font-size: 2.4em; color: #14556B;

    You've j ust changed t he color of t he < h1> t ags and set t heir size t o 2.4em , which for m ost browsers ( unless t he visit or has t weaked his browser's font set t ings) is 24 pixels t all. 3. Fin a lly, com ple t e t h is st yle by h it t in g En t e r ( Re t u r n ) a n d t ypin g t h e closin g br a ce . The com plet ed st yle should look like t his: h1 { font-size: 2.4em; color: #14556B; }

    Section 6.6. Tutorial: Text Formatting in Action

    4. Sa ve t h e file , a n d pr e vie w it in a W e b br ow se r . Next , spruce up t he appearance of t he ot her headings and paragraphs. 5. Re t u r n t o you r t e x t e dit or a n d t h e t e x t .h t m l file . Click a ft e r t h e closin g br a ce of t h e h 1 t a g st yle a n d a dd t h e follow in g t w o st yle s: h2 { font-size: 1.5em; color: #993; } p { font-size: 1.2em; text-indent: 2em; line-height: 150%; }

    The p st yle int roduces t he t ext - indent propert y, which indent s t he first line of a paragraph, and t he line- height propert y, which set s t he spacing bet ween lines. A percent age of 150 percent adds a lit t le m ore space bet ween lines in a paragraph t han you'd norm ally see in a Web browser. This ext ra breat hing room gives t he t ext a light er, airier qualit y and m akes t he sent ences a lit t le easier t o read ( but only if you speak Lat in) . 6. Sa ve t h e pa ge , a n d ope n it in a W e b br ow se r t o pr e vie w you r w or k . The page is com ing t oget her nicely, but t he space bet ween paragraphs and bet ween t he headings and t he paragraphs is t oo dist ract ing. You'll t ight en it up a bit next . 7. Re t u r n t o you r t e x t e dit or a n d t h e t e x t .h t m l file . Loca t e t h e h 2 t a g st yle you cr e a t e d e a r lie r , a n d a dd t h e m a r gin - bot t om pr ope r t y. The st yle now looks like t his: h2 { font-size: 1.5em; color: #993; margin-bottom: 5px; }

    This addit ion ( in bold) reduces t he gap bet ween t he bot t om of every < h2> t ag and t he next elem ent on t he page t o 5 pixels. I t also provides a consist ent value, since t he am ount of space added below < h2> t ags varies from browser t o browser. Next , you cont rol t he paragraphs. 8. Edit t h e < p> t a g st yle by a ddin g t h e follow in g t w o pr ope r t ie s t o t h e e n d of t h e st yle :

    Section 6.6. Tutorial: Text Formatting in Action

    margin-top: 0; margin-bottom: 5px;

    The m argin- t op propert y cont rols t he space above t he paragraphs. I n t his case, you've com plet ely elim inat ed t he space above each paragraph. To add a lit t le space bet ween each paragraph, use t he m argin- bot t om propert y. 9. Sa ve t h e pa ge , a n d ope n it in a W e b br ow se r t o pr e vie w you r w or k . At t his point , t he page should look like Figure 6- 11.

    Figu r e 6 - 1 1 . Th e pa ge is st a r t in g t o com e t oge t h e r . Th e h e a dlin e s, pa r a gr a ph s, a n d ba sic t e x t se t t in gs a r e in pla ce .

    Section 6.6. Tutorial: Text Formatting in Action

    6.6.3. Formatting Lists Not ice t hat t he page you're working on has t wo list s: a bullet ed list of t he different sect ions of t he sit e in t he left sidebar, and a bullet ed list of t hree it em s in t he m ain body copy. Use descendent select ors ( see Sect ion 3.1) t o t arget and form at each list different ly. 1. Re t u r n t o you r t e x t e dit or a n d t h e t e x t .h t m l file . Click a t t h e e n d of t h e closin g br a ce of t h e < p> t a g se le ct or , pr e ss En t e r ( Re t u r n ) t o cr e a t e a n e w lin e , a n d t h e n t ype # con t e n t u l { . The m ain cont ent of t he page is cont ained in a < div> t ag wit h an I D select or nam ed cont ent . You're now creat ing a rule t hat you want t o apply only t o bullet ed list s ( < ul> t ags) t hat appear inside t he m ain cont ent area. You can achieve t his wit h t he descendent select or # cont ent ul, which sim ply inst ruct s t he Web browser t o apply t his st yle t o any < ul> t ag t hat appears inside a page elem ent wit h an I D of cont ent . I n ot her words, bullet ed list s t hat appear elsewherelike t he one in t he left - hand sidebarwon't be affect ed by t his st yle. 2. Pr e ss En t e r ( Re t u r n ) , a n d t h e n t ype : font-size: 1.2em; list-style-type: square;

    This set s t he font size for t he t ext inside t he bullet ed list t o 1.2em . The second line set s t he bullet st yle t o squaredisplaying a square bullet icon inst ead of t he usual round bullet found in m ost Web browsers. 3. Pr e ss En t e r ( Re t u r n ) a n d t h e n t ype t h e closin g br a ce t o com ple t e t h e st yle . Th e fin ish e d r u le sh ou ld look lik e t h is: #content ul { font-size: 1.2em; list-style-type: square; }

    Finally, add a lit t le bit of space bet ween each bullet ed it em using t he < li> ( list it em ) t ag's bot t om - m argin propert y. 4. Pr e ss En t e r ( Re t u r n ) , a n d t h e n a dd t h e follow in g st yle : #content li { margin-bottom: 5px; }

    Again, you're using a descendent select or t o t arget j ust t he < li> t ags t hat appear inside t he m ain cont ent area of t he page. Next , work on t he list in t he sidebar. 5. Pr e ss En t e r ( Re t u r n ) t o cr e a t e a n e w bla n k lin e , a n d t h e n a dd t h e follow in g st yle :

    Section 6.6. Tutorial: Text Formatting in Action

    #mainNav ul { font-size: 1.2em; list-style-type: none; }

    Here, you're using a descendent select or t o t arget list s t hat appear inside t he sidebar ( a < div> t ag wit h t he I D of m ainNav) . The list - st yle- t ype propert y not only let s you change a bullet from a circle t o a square, but can also com plet ely elim inat e any bullet . 6. Sa ve t h e pa ge , a n d ope n it in a W e b br ow se r t o pr e vie w you r w or k . I f you look closely, you'll not ice t hat t he list in t he sidebar is indent ed quit e a bit on t he left . Web browsers norm ally indent list s, so you have t o add a couple of CSS propert ies t o elim inat e t hat ext ra space. 7. Re t u r n t o you r t e x t e dit or a n d t h e t e x t .h t m l pa ge . Add a lin e be low t h e list - st yle - t ype pr ope r t y you j u st a dde d, a n d t h e n t ype : margin-left: 0; padding-left: 0;

    Due t o a difference in t he way browsers display list s, you need t o set t he m argin and padding propert ies t o 0. ( See Sect ion 6.5.3 for det ails.) Last ly, cent er t he t ext , and t urn it all int o uppercase let t ers. 8. Add t h e la st t w o pr ope r t ie s h igh ligh t e d be low . Th e fin ish e d st yle sh ou ld look lik e t h is: #mainNav ul { font-size: 1.2em; list-style-type: none; margin-left: 0; padding-left: 0; text-transform: uppercase; text-align: center; }

    Finally, t o finish up, add a bit of space bet ween each it em in t he sidebar. 9. Add t h is st yle be low t h e # m a in N a v u l st yle you j u st cr e a t e d: #mainNav li { margin-bottom: 10px; }

    10.

    Section 6.6. Tutorial: Text Formatting in Action

    Sa ve t h e pa ge a n d pr e vie w it in a W e b br ow se r . The page should now look like Figure 6- 12.

    Figu r e 6 - 1 2 . CSS le t s you con t r ol t h e for m a t t in g of bu lle t e d list s, e ve n le t t in g you r e m ove t h e bu lle t s e n t ir e ly ( le ft ) . By u sin g de sce n de n t se le ct or s, you ca n for m a t list s diffe r e n t ly de pe n din g on w h e r e t h e y a ppe a r in t h e pa ge ( for e x a m ple t h e le ft side ba r , or m a in con t e n t a r e a on t h is pa ge ) .

    6.6.4. Adding the Finishing Touches For t he last bit of design, pull out all t he st ops and incorporat e several t ext form at t ing propert ies t o alt er t he look of t he aut hor's byline. 1. Re t u r n t o you r t e x t e dit or a n d t h e t e x t .h t m l file . First , you'll m ark up one of t he paragraphs wit h a class, so you can creat e a specific st yle for t he aut hors' credit s.

    Section 6.6. Tutorial: Text Formatting in Action

    2. Loca t e t h e pa r a gr a ph t a g w it h t h e bylin e < p> By Jean Graine de Pom m e < / p> . Add a cla ss a t t r ibu t e t o t h e < p> t a g:

    Now you can creat e a class st yle t o t arget t hat part icular paragraph. 3. Click a t t h e e n d of t h e closin g br a ce of t h e # m a in N a v li t a g se le ct or you j u st a dde d, pr e ss Re t u r n t o cr e a t e a n e w lin e , a n d t h e n t ype .bylin e { . This is t he beginning part of a class st yle. I t j ust needs a few propert ies and a closing brace. 4. Add t h e follow in g t h r e e pr ope r t ie s a n d t h e closin g br a ce t o cr e a t e t h e cla ss st yle by t ypin g t h e follow in g: color: #73afb7; font-size: 1.5em; margin-bottom: 10px; }

    By now, you should feel com fort able wit h t hese propert ies, which set t he size and color of t he paragraph, as well as adj ust t he space below it . Next , m ake t he t ext st and out in bold. 5. Add a n e w lin e be low t h e m a r gin - bot t om pr ope r t y of t h e .bylin e st yle , a n d t h e n t ype : font-weight: bold;

    Now form at t he st yle in sm all caps and spread out t he let t ers a lit t le t o give t he byline a form al and regal look t hat m akes it st and out from t he page. 6. Add a n ot h e r lin e a ft e r t h e fon t - w e igh t pr ope r t y you j u st a dde d a n d a dd t w o m or e pr ope r t ie s: letter-spacing: 1px; font-variant: small-caps;

    I f you preview t he page now, you'll not ice t hat t he byline's indent ed t he sam e am ount as t he ot her paragraphs. Due t o t he cascade, t he byline ( which is a < p> t ag) get s t hat form at t ing from t he < p> t ag st yle's t ext - indent propert y. To get rid of t hat indent , you need t o override t he set t ing in t he class st yle. 7. Add a t e x t - in de n t pr ope r t y t o t h e .bylin e st yle a n d se t it s va lu e t o 0 . Th e fin a l st yle sh ou ld look lik e t h is: .byline { color: #73afb7;

    Section 6.6. Tutorial: Text Formatting in Action

    font-size: 1.5em; margin-bottom: 10px; font-weight: bold; letter-spacing: 1px; font-variant: small-caps; text-indent: 0; }

    Tim e t o t est your hard work. 8. Sa ve t h e file a n d pr e vie w it in a W e b br ow se r . I t should look like Figure 6- 13. You can com pare your work t o t he finished t ext .ht m l page locat ed in t he chapt er_06_finished folder. Congrat ulat ions! You've explored m any of t he t ext - form at t ing propert ies offered by CSS, and t urned ho- hum HTML int o an at t ract ive, at t ent ion- get t ing design. I n t he next chapt er, you'll explore graphics, borders, m argins, and ot her powerful design opt ions offered by CSS.

    Figu r e 6 - 1 3 . W it h a lit t le CSS, you ca n t u r n pla in t e x t in t o a pow e r fu l de sign st a t e m e n t t h a t h e lps gu ide r e a de r s t h r ou gh t h e in for m a t ion on you r sit e .

    Section 6.6. Tutorial: Text Formatting in Action

    Chapter 7. Margins, Padding, and Borders

    Chapter 7. Margins, Padding, and Borders Every HTML t ag is surrounded by a world of propert ies t hat affect how t he t ag appears in a Web browser. Som e propert ieslike borders and background colorsare im m ediat ely obvious t o t he naked eye. Ot hers, t hough, are invisiblelike padding and m argin. They provide a bit of em pt y space on one or m ore sides of a t ag. By underst anding how t hese propert ies work, you can creat e at t ract ive colum ns, decorat ive sidebars, and cont rol t he space around t hem ( what designers call whit e space) so your pages look less clut t ered, light er, and m ore professional. Taken t oget her, t he CSS propert ies discussed in t his chapt er m ake up one of t he m ost im port ant concept s in CSSt he box m odel.

    Section 7.1. Understanding the Box Model

    7.1. Understanding the Box Model You probably t hink of let t ers, words, and sent ences when you t hink of a paragraph or headline. You also probably t hink of a phot o, logo, or ot her pict ure when you t hink of t he < im g> t ag. But a Web browser t reat s t hese ( and all ot her) t ags as lit t le boxes. To a browser, any t ag's a box wit h som et hing inside it t ext , an im age, or even ot her t ags cont aining ot her t hings, as illust rat ed in Figure 7- 1. Surrounding t he cont ent are different propert ies t hat m ake up t he box: ●



    ● ●

    Padding is t he space bet ween t he cont ent and t he cont ent 's border. Padding is what separat es a phot o from t he border t hat fram es t he phot o. Border is t he line t hat 's drawn around each edge of t he box. You can have a border around all four sides, on j ust a single side, or any com binat ion of sides. Background- color fills t he space inside t he border, including t he padding area. Margin is what separat es one t ag from anot her. The space t hat com m only appears bet ween t he t ops and bot t om s of paragraphs of t ext on a Web page, for exam ple, is t he m argin.

    For a given t ag, you can use any or all of t hese propert ies in com binat ion. You can set j ust a m argin for a t ag, or add a border, m argins, and padding. Or you can have a border and m argin but no padding, and so on. I f you don't adj ust any of t hese propert ies, t hen you'll end up wit h t he browser's default set t ings, which you m ay or m ay not like. For exam ple, while browsers usually don't apply eit her padding or borders t o any t ags on a page, som e t ags like headings and paragraphs have a preset t op and bot t om m argin. ( Throughout t his chapt er you'll learn about t hese default set t ings as well as how t o override t hem .)

    Figu r e 7 - 1 . Th e CSS box m ode l in clu de s t h e con t e n t in side a t a g ( for e x a m ple , se ve r a l se n t e n ce s of t e x t ) plu s pa ddin g, bor de r s, a n d m a r gin s. Th e a r e a w it h in t h e bor de r , w h ich in clu de s t h e con t e n t a n d pa ddin g, m a y a lso h a ve a ba ck gr ou n d color . Act u a lly, t h e ba ck gr ou n d color is dr a w n u n de r n e a t h t h e bor de r , so w h e n you a ssign a da sh e d or dot t e d bor de r , t h e ba ck gr ou n d color a ppe a r s in t h e ga ps be t w e e n t h e dot s or da sh e s ( Se ct ion 7 .4 ) .

    Section 7.1. Understanding the Box Model

    Section 7.2. Control Space with Margins and Padding

    7.2. Control Space with Margins and Padding Bot h m argins and padding add space around cont ent . You use t hese propert ies t o separat e one elem ent from anot herfor exam ple, t o add space bet ween a left - hand navigat ion m enu and t he m ain page cont ent on t he right or t o inj ect som e whit e space bet ween cont ent and a border. You m ay want t o m ove t he border away from t he edge of a phot o ( see Figure 7- 2) .

    Figu r e 7 - 2 . Ea ch ph ot o on t h is pa ge h a s a 1 0 - pix e l m a r gin , so t h e ga p se pa r a t in g t w o ph ot os is 2 0 pix e ls. Pa ddin g se pa r a t e s t h e im a ge s fr om t h e ir bor de r s a n d e x pose s a gr a y ba ck gr ou n d color . You ca n se t t h e bor de r , m a r gin , a n d pa ddin g in de pe n de n t ly for e a ch e dge . N ot ice t h e la r ge r pa ddin g a pplie d t o t h e bot t om e dge of e a ch ph ot o.

    Padding and m argin funct ion sim ilarly and unless you apply a border or background color, you can't really t ell whet her t he space bet ween t wo t ags is caused by padding or by a m argin. But if you have a border around an elem ent or a background behind it , t hen t he visual difference bet ween t he t wo propert ies is significant . Padding adds space bet ween t he cont ent and t he border and keeps t he cont ent from appearing cram ped inside t he box, while m argins add whit e space

    Section 7.2. Control Space with Margins and Padding

    ( oft en called a gut t er) bet ween elem ent s giving t he overall look of t he page a light er appearance. You can cont rol each side of t he m argin or padding for an elem ent independent ly. Four propert ies cont rol m argin edges: m argin- t op, m argin- right , m argin- bot t om , and m argin- left . Sim ilarly, four propert ies cont rol padding: padding- t op, padding- right , padding- bot t om , and padding- left . You can use any valid CSS m easurem ent t o define t he size of a m argin or padding, like so: margin-right: 20px; padding-top: 3em; margin-left: 10%;

    Pixels and em s are com m only used and act j ust as t hey do wit h t ext ( see Sect ion 6.2) . A 20- pixel m argin adds 20 pixels of space, and 3em s of padding adds space equal t o 3 t im es t he font size of t he st yled elem ent . You can also use percent age values, but t hey're t ricky. ( See t he box below for t he det ails.)

    Tip: To remove all the space for a margin or padding, use 0 (margin-top: 0 or padding-bottom: 0, for example). To remove space around all four edges of the browser windowto let a banner or logo or other page element butt right up to the edge without a gapgive the body tag a margin of 0, and a padding of 0: margin: 0; padding 0;. The margin property works for most browsers, except Opera. Opera requires that padding be set to 0 instead.

    POWER USERS' CLINIC Margins, Padding, and Percentages When you use percent ages, Web browsers calculat e t he am ount of space based on t he widt h of t he cont aining elem ent . On a sim ple Web page, t he cont aining elem ent is t he body of t he page, and it fills t he browser window. I n t his case, t he percent age value's based on t he widt h of t he browser window at any given t im e. Say t he window is 760 pixels wide. I n t hat case, a 10 percent left m argin adds 76 pixels of space t o t he left edge of t he st yled elem ent . But if you resize t he browser window, t hen t hat value changes. Narrowing t he browser window t o 600 pixels changes t he m argin t o 60 pixels ( 10 percent of 600) . However, t he cont aining elem ent isn't always t he widt h of t he browser window. As you'll see in lat er chapt ers, when you creat e m ore sophist icat ed layout s, you can int roduce new elem ent s t hat help organize your page. You m ay want t o add a < div> t ag t o a page in order t o group relat ed cont ent int o a sidebar area. ( You'll see an exam ple of t his in t he t ut orial in Sect ion 7.7.4.) That sidebar m ight have a specified widt h of 300 pixels. Tags inside t he sidebar consider t he < div> t ag t heir cont aining elem ent . So a t ag in t he sidebar wit h a right m argin of 10 percent will have 30 pixels of em pt y space t o it s right . To m ake m at t ers m ore confusing, t op and bot t om percent age values are calculat ed based on t he widt h of t he cont aining elem ent , not it s height . So a 20 percent t op m argin is 20 percent of t he widt h of t he st yled t ag's cont ainer.

    7.2.1. Margin and Padding Shorthand You'll frequent ly want t o set all four sides of a st yle's m argin or padding. But t yping out all four propert ies ( m argin- right , m argin- left , and so on) for each st yle get s t edious. Fear not : you can use t he short cut propert ies nam ed m argin and padding t o set all four propert ies quickly:

    Section 7.2. Control Space with Margins and Padding

    margin: 0 10px 10px 20px; padding: 10px 5px 5px 10px;

    Tip: If the value used in a CSS property is 0, then you don't need to add a unit of measurement. For example, just type margin: 0; instead of margin: 0px;.

    The order in which you specify t he four values is im port ant . I t m ust be t op, right , bot t om , and left . I f you get it wrong, you'll be in t rouble. I n fact , t he easiest way t o keep t he order st raight is t o rem em ber t o st ay out of TRou BLe t op, right , bot t om , and left . I f you want t o use t he sam e value for all four sides, it 's even easierj ust use a single value. I f you want t o rem ove m argins from all < h1> t ags, you can writ e t his st yle: h1 { margin: 0; }

    Sim ilarly, use short hand t o add t he sam e am ount of space bet ween som e cont ent and it s border:

    padding: 10px;

    Tip: When you're using the same value for both top and bottom and another value for both left and right, you can use two values. margin: 0 2em; sets the top and bottom margins to 0 and the left and right margins to 2ems.

    7.2.2. Colliding Margins When it com es t o CSS, t wo plus t wo doesn't always equal four. You could run int o som e bizarre m at h when t he bot t om m argin of one elem ent t ouches t he t op m argin of anot her. I nst ead of adding t he t wo m argins t oget her, a Web browser applies t he larger of t he t wo m argins ( Figure 7- 3, t op) . Say t he bot t om m argin of an unordered list is set t o 30 pixels and t he t op m argin of a paragraph following t he list is 20 pixels. I nst ead of adding t he t wo values t o creat e 50 pixels of space bet ween t he list and t he paragraph, a Web browser uses t he largest m arginin t his case 30 pixels. I f you don't want t his t o happen, t hen use t op or bot t om padding inst ead ( Figure 7- 3, bot t om ) .

    Figu r e 7 - 3 . W h e n t w o ve r t ica l m a r gin s m e e t , t h e sm a lle r on e colla pse s. Alt h ou gh t h e t op h e a dlin e h a s a bot t om m a r gin of 2 0 pix e ls a n d t h e pa r a gr a ph h a s a t op m a r gin of 1 5 pix e ls, a W e b br ow se r a dds on ly 2 0 pix e ls of spa ce be t w e e n t h e t w o e le m e n t s. To ge t t h e fu ll 3 5 pix e ls' w or t h of spa ce t h a t you w a n t , u se pa ddin g in st e a d of m a r gin s, a s sh ow n in t h e bot t om h e a dlin e . H e r e , t h e h e a din g h a s 2 0 pix e ls of bot t om pa ddin g. Th ose 2 0 pix e ls ge t a dde d t o t h e 1 5 - pix e l t op m a r gin of t h e pa r a gr a ph t o for m a 3 5 - pix e l ga p.

    Section 7.2. Control Space with Margins and Padding

    Things get even weirder when one elem ent 's inside anot her elem ent . This sit uat ion can lead t o som e head- scrat ching behavior. For exam ple, say you add a " warning" box t o a page ( like a < div> t ag t o hold a warning m essage inside it ) . You add a 20 pixel t op and bot t om m argin t o separat e t he warning box from t he heading above it and t he paragraph of t ext below it . So far so good. But say you insert a heading inside t he warning box, and t o put a lit t le room bet ween it and t he t op and bot t om of t he div, you set t he heading's m argin t o 10 pixels. You m ay t hink you're adding 10 pixels of space bet ween t he heading and t he t op and bot t om of t he div, but you'd be wrong ( Figure 7- 4, left ) . I nst ead, t he m argin appears above t he div. I n t his case, it doesn't m at t er how large a m argin you apply t o t he headlinet he m argin st ill appears above t he div.

    Note: In the lingo of CSS, this phenomenon's known as " collapsing margins," meaning two margins actually become one.

    You have t wo ways around t his problem : Eit her add a sm all am ount of padding around t he < div> t ag or add a border t o it . Since border and padding sit bet ween t he t wo m argins, t he m argins no longer t ouch, and t he headline has a lit t le breat hing room ( Figure 7- 4, right ) .

    Figu r e 7 - 4 . H oly sh r in k in g m a r gin s Ba t m a n ! Le ft : W h e n e ve r ve r t ica l m a r gin s t ou ch , e ve n w h e n on e e le m e n t is in side a n ot h e r e le m e n t , t h e m a r gin s colla pse . Righ t : To solve t h is dile m m a , a dd a lit t le pa ddin g or a bor de r a r ou n d t h e con t a in in g e le m e n t ( t h e < div> , in t h is ca se ) .

    Section 7.2. Control Space with Margins and Padding

    Note: Horizontal (left and right) margins and margins between floating elements (Section 7.6) don't collapse in this way. Absolutely and relatively positioned elementswhich you'll learn about in Chapter 12don't collapse either.

    7.2.3. Removing Space with Negative Margins Most m easurem ent s in CSS have t o be a posit ive valueaft er all what would t ext t hat 's negat ive 20 pixels t all ( or short ) look like? Padding also has t o be a posit ive value. But CSS allows for m any creat ive t echniques using negat ive m argins. I nst ead of adding space bet ween a t ag and elem ent s around it , a negat ive m argin rem oves space. So you can have a paragraph of t ext overlap a headline, poke out of it s cont aining elem ent ( a sidebar or ot her layout < div> ) , or even disappear off an edge of t he browser window. And, hey, you can even do som et hing useful wit h negat ive m argins. Even when you set t he m argins bet ween t wo headlines t o 0, t here's st ill a lit t le space bet ween t he t ext of t he headlines ( t hanks t o t he t ext 's line- height as described in Sect ion 6.4 in t he last chapt er) . That 's usually a good t hing, since it 's hard t o read sent ences t hat bunch t oget her and t ouch. But , used in m oderat ion, t ight ening t he space bet ween t wo headlines can produce som e int erest ing effect s. The second headline of Figure 7- 5 ( t he one t hat begins " Raise Tuna" ) has a t op m argin of - 10px applied t o it . This m oves t he headline up 10 pixels so it slight ly overlaps t he space occupied by t he headline above it . Also, t he left and right borders of t he " Ext ra! Ext ra! " headline act ually t ouch t he let t ers of t he larger headline. You can also use a negat ive m argin t o sim ulat e negat ive padding. I n t he t hird headline of Figure 7- 5, t he one t hat begins wit h " The Ext raordinary Technique," a line appears direct ly under t he t ext . This line is act ually t he t op border for t he paragraph t hat follows. ( You'll learn how t o add borders in Sect ion 7.3.) But because t hat paragraph has a negat ive t op m argin, t he border m oves up and under t he headline. Not ice how t he descending t ail for t he let t er Q in t he headline act ually hangs below t he border. Since paddingt he space bet ween cont ent ( like t hat let t er Q) and a bordercan't be negat ive, you can't m ove a bot t om border up over t ext or any ot her cont ent . But you get t he sam e effect by applying a border t o t he following elem ent and using a negat ive m argin t o m ove it up.

    Figu r e 7 - 5 . I n t h is e x a m ple , t o m a k e t h e la st pa r a gr a ph 's t op bor de r look lik e it 's a ct u a lly t h e bot t om bor de r for t h e h e a dlin e a bove it , a dd a lit t le pa ddin g t o t h e pa r a gr a ph . Ar ou n d 5 pix e ls of t op pa ddin g m ove s t h e pa r a gr a ph dow n fr om t h e bor de r , w h ile 4 e m s of le ft pa ddin g in de n t s t h e pa r a gr a ph 's t e x t , st ill a llow in g t h e t op bor de r t o e x t e n d t o t h e le ft e dge .

    Section 7.2. Control Space with Margins and Padding

    Tip: You can actually use a negative top margin on the paragraph, or a negative bottom margin on the headline. Both have the same effect of moving the paragraph up close to the headline.

    7.2.4. Displaying Inline and Block-Level Boxes Alt hough Web browsers t reat every t ag as a kind of box, not all boxes are alike. CSS has t wo different t ypes of boxesblock boxes and inline boxest hat correspond t o t he t wo t ypes of t ags inline and block- level t ags. A block- level t ag creat es a break before and aft er it . The < p> t ag, for exam ple, creat es a block t hat 's separat ed from t ags above and below. Headlines, < div> t ags, t ables and list s are ot her exam ples of block- level t ags. I nline t ags don't creat e a break before or aft er t hem . They appear on t he sam e line as cont ent and t ags beside t hem . The < st rong> t ag is an inline t ag. A word form at t ed wit h t his t ag happily sit s next t o ot her t ext even t ext wrapped in ot her inline t ags like < em > . I n fact , it would look pret t y weird if you em phasized a single word in t he m iddle of a paragraph wit h t he < st rong> t ag and t hat word suddenly appeared on it s own line by it self. Ot her inline t ags are < im g> for adding im ages, < a> for creat ing links, and t he various t ags used t o creat e form fields. I n m ost cases, CSS works t he sam e for inline boxes and block boxes. You can st yle t he font , color, and background and add borders t o bot h t ypes of boxes. However, when it com es t o m argins and padding, browsers t reat inline boxes different ly. While you can add space t o t he left or right of an inline elem ent using eit her left or right padding or left or right m argins, you can't increase t he height of t he inline elem ent wit h t op or bot t om padding or m argins. I n t he t op paragraph in Figure 7- 6, t he inline elem ent is st yled wit h borders, a background color, and 20 pixels of m argin on all four sides. But t he browser only adds space t o t he left and right sides of t he inline elem ent .

    Figu r e 7 - 6 . Addin g t op or bot t om m a r gin s a n d pa ddin g doe sn 't m a k e a n in lin e e le m e n t a n y t a lle r , so you ca n r u n in t o som e w e ir d for m a t t in g. I n t h e m iddle pa r a gr a ph , t h e ba ck gr ou n d a n d bor de r s of a lin k ove r la p t h e t e x t a bove a n d be low . Th e ba ck gr ou n d a ppe a r s on t op of

    Section 7.2. Control Space with Margins and Padding

    t h e lin e be for e t h e st yle d in lin e t e x t , bu t u n de r n e a t h t h e lin e follow in g it be ca u se t h e br ow se r t r e a t s e a ch lin e a s if it 's st a ck e d on t op of t h e pr e viou s lin e . N or m a lly, t h a t isn 't a pr oble m sin ce lin e s of t e x t don 't u su a lly ove r la p. To cr e a t e spa ce a bove a n d be low a n in lin e e le m e n t , a dd t h e lin e - h e igh t pr ope r t y t o t h e in lin e e le m e n t . ( Th e e x a ct a m ou n t de pe n ds on h ow la r ge t h e m a r gin a n d pa ddin g a r e . I n t h is ca se , a 4 0 0 pe r ce n t lin e h e igh t e x pa n ds t h e lin e e n ou gh so t h e ba ck gr ou n d a n d bor de r don 't ove r la p a n y t e x t .)

    Note: One exception to the rule that inline elements don't get taller when padding or margin are added is the tag (even though it's an inline tag). Web browsers correctly expand the height of the image's box to accommodate any padding and margins you add.

    At t im es, you m ay wish an inline elem ent behaved m ore like a block- level elem ent and vice versa. Bullet ed list s present each it em as it s own blockeach list it em 's st acked above t he next . But what if you want t o change t hat behavior so t he list it em s appear side by side, all on a single line ( as in a navigat ion bar, as you'll see in Sect ion 9.3.4 in Chapt er 9) ? Or you m ay want t o t reat an inline elem ent like a block- level elem ent . Maybe you want an im age em bedded in a paragraph t o be

    Section 7.2. Control Space with Margins and Padding

    on it s own line, wit h space above and below. Fort unat ely, CSS includes a propert y t hat let s you do j ust t hat t he display propert y. Wit h it , you can m ake a block- level elem ent act like an inline elem ent :

    display: inline;

    Or you can m ake an inline elem ent like an im age or link behave like a block- level elem ent : display: block;

    Note: The display property has a myriad of possible options, most of which aren't supported in today's browsers. However, one value, none, is supported by most browsers and has many uses. It does one simple thingcompletely hides the styled element so it doesn't appear in a Web browser. With a dab of Java-Script programming, you can make an element hidden in this way instantly become visible, simply by changing its display back to either inline or block. You can even make an element with a display of none suddenly appear using CSS.

    Section 7.3. Adding Borders

    7.3. Adding Borders A border is sim ply a line t hat runs around an elem ent . As shown back in Figure 7- 1, it sit s bet ween any padding and m argins you set . A border around every edge can fram e an im age or m ark t he boundaries of a banner or ot her page elem ent . But borders don't necessarily have t o creat e a full box around your cont ent . While you can add a border t o all four edges, you can j ust as easily add a border t o j ust t he bot t om or any com binat ion of sides. This flexibilit y let s you add design elem ent s t hat don't necessarily feel like a border. For exam ple, add a border t o t he left of an elem ent , m ake it around 1em t hick, and it looks like a square bullet . A single border under a paragraph can funct ion j ust like t he < hr> ( horizont al rule) by providing a visual separat or bet ween sect ions of a page. You cont rol t hree different propert ies of each border: color, widt h, and st yle. The color can be a hexadecim al num ber, a keyword or an RGB value, j ust like wit h t ext ( see Sect ion 6.1.2) . A border's widt h is t he t hickness of t he line used t o draw t he border. You can use any CSS m easurem ent t ype ( except percent ages) or t he keywords t hin, m edium , and t hick. The m ost com m on and easily underst ood m et hod is sim ply pixels. Finally, t he st yle cont rols t he t ype of line drawn. There are m any different st yles, and som e look very different from browser t o browser, as you can see in Figure 7- 7. You specify t he st yle wit h a keyword. For exam ple solid draws a solid line and dashed creat es a line m ade up of dashes. CSS offers t hese st yles: solid, dot t ed, dashed, double, groove, ridge, inset , out set , none, and hidden.

    Tip: None and hidden work the same way: they remove the border entirely. The none value's useful for turning off a single border. (See the example in Section 7.3.1.)

    Figu r e 7 - 7 . Th e a ppe a r a n ce of bor de r st yle s ca n va r y gr e a t ly fr om br ow se r t o br ow se r . Th e br ow se r s pict u r e d h e r e a r e I n t e r n e t Ex plor e r 6 for W in dow s ( t op le ft ) , Fir e fox for W in dow s ( t op r igh t ) , Ope r a 8 .5 for W in dow s ( bot t om le ft ) , a n d Sa fa r i 2 for M a c ( bot t om r igh t ) . I n t e r n e t Ex plor e r 7 displa ys bor de r s t h e sa m e a s I E 6 in t h is im a ge , a n d t h e M a c ve r sion of Fir e fox a n d Ca m in o look j u st lik e t h e Fir e fox e x a m ple pict u r e d h e r e .

    Section 7.3. Adding Borders

    Section 7.3. Adding Borders

    Note: In Windows' Internet Explorer version 6 and earlier, a 1 pixel dotted border looks just like a 1 pixel dashed border.

    7.3.1. Border Property Shorthand I f you've ever seen a list of t he different border propert ies available in CSS, you m ay t hink borders are really com plex. Aft er all, t here are 20 different border propert ies, which you'll m eet in t he following sect ions, plus a couple t hat apply t o t ables. But all t hese propert ies are m erely variat ions on a t hem e t hat provide different ways of cont rolling t he sam e t hree propert iescolor, widt h, and st ylefor each of t he four borders. The m ost basic and st raight forward propert y is border, which sim ply adds four borders: border: 4px solid #F00;

    The above st yle creat es a solid, red, 4- pixel border. You can use t his propert y t o creat e a basic fram e around a pict ure, navigat ion bar, or ot her it em t hat you want t o appear as a self- cont ained box.

    Note: The order in which you write the properties doesn't matter. border: 4px solid #F00; works as well as border: #F00 solid 4px;.

    7.3.2. Formatting Individual Borders You can cont rol each border individually using t he appropriat e propert y: border- t op, border- bot t om , borderleft , or border- right . These propert ies work j ust like t he regular border propert y, but t hey cont rol j ust one side. The following propert y declarat ion adds a 2- pixel, red, dashed line below t he st yle: border-bottom: 2px dashed red;

    You can com bine t he border propert y wit h one of t he edge- specific propert ies like border- left t o define t he basic box for t he ent ire st yle, but cust om ize a single border. Say you want t he t op, left , and right sides of a paragraph t o have t he sam e t ype of border but you want t he bot t om border t o look slight ly different . You can writ e four lines of CSS, like t his: border-top: 2px solid black; border-left: 2px solid black; border-right: 2px solid black; border-bottom: 4px dashed #333;

    Or, you can achieve t he sam e effect as t he previous four lines of CSS wit h j ust t wo lines: border: 2px solid black; border-bottom: 4px dashed #333;

    Section 7.3. Adding Borders

    The first line of code defines t he basic look of all four borders, and t he second line redefines j ust t he look of t he bot t om border. Not only is it easier t o writ e t wo lines of CSS inst ead of four but it also m akes changing t he st yle easier. I f you want t o change t he color of t he t op, left , and right borders t o red, t hen you only have t o edit a single line, inst ead of t hree: border: 2px solid red;

    When you use t his short cut m et hoddefining t he basic look of all four borders using t he border propert y and t hen overriding t he look of a single border wit h one of t he edge- specific propert ies like border- left it 's crucial t hat you writ e t he code in a specific order. The m ore general, global border set t ing m ust com e first , and t he edge- specific set t ing second, like so: border: 2px solid black; border-bottom: 4px dashed #333;

    Because t he border- bot t om propert y appears second, it overrides t he set t ing of t he border propert y. I f t he border- bot t om line cam e before t he border propert y, t hen it would be cancelled out by t he border propert y, and all four borders would be ident ical. The last propert y list ed can overrule any relat ed propert ies list ed above it . This is an exam ple of t he CSS Cascade t hat you read about in Chapt er 5. You can also use t his short cut m et hod t o t urn off t he display of a single border wit h t he none keyword. Say you want t o put a border around t hree sides of a st yle ( t op, left , and bot t om ) but no border on t he last side ( right ) . Just t wo lines of code get you t he look you're aft er: border: 2px inset #FFCC33; border-right: none;

    The abilit y t o subt ly t weak t he different sides of each border is t he reason t here are so m any different border propert ies. The rem aining 15 propert ies let you define individual colors, st yles, and widt hs for t he border and for each border side. For exam ple, you could rewrit e border: 2px double # FFCC33; like t his: border-width: 2px; border-style: double; border-color: #FFCC33;

    Since you're using t hree lines of code inst ead of one, you'll probably want t o avoid t his m et hod. However, each border edge has it s own set of t hree propert ies, which are helpful for overriding j ust one border propert y for a single border edge. The right border has t hese t hree propert ies: border- right - widt h, borderright - st yle, and border- right - color. The left , t op, and bot t om borders have sim ilarly nam ed propert iesborder- left - widt h, border- left - st yle, and so on. I m agine t hat you want t o have a t wo- pixel, dashed border around t he four edges of a st yle, but you want each border t o be a different color. ( Perhaps you're doing a Web sit e for kids.) Here's a quick way t o do t hat :

    Section 7.3. Adding Borders

    border: 2px dashed green; border-left-color: blue; border-right-color: yellow; border-bottom-color: red;

    This set of rules creat es a t wo- pixel dashed border around all four edges, while m aking t he t op edge green ( from t he first propert y declarat ion) , t he left edge blue, t he right edge yellow, and t he bot t om edge red. You can change t he widt h of j ust a single border like t his: border- right - widt h: 4px; . One nice t hing about t his approach is t hat if you lat er decide t he border should be solid, you need t o edit only t he generic border propert y by changing dashed t o solid.

    Tip: You usually add padding whenever you use borders. Padding provides space between the border and any content, such as text, images, or other tags. Without padding, borderlines usually sit too close to the content.

    Section 7.4. Coloring the Background

    7.4. Coloring the Background I t 's a cinch t o add a background t o an ent ire page, an individual headline, or any ot her page elem ent . Use t he background- color propert y followed by any of t he valid color choices described in Sect ion 6.1.2. I f you want , add a shockingly bright green t o t he background of a page wit h t his line of code: body { background-color: #6DDA3F; }

    Alt ernat ively, you can creat e a class st yle nam ed, say, .review wit h t he background- color propert y defined, and t hen apply t he class t o t he body t ag in t he HTML, like so: < body class= " review" > .

    Note: You can also place an image in the background of a page and control that image's placement in many different ways. You'll explore that in the next chapter.

    Background colors com e in handy for creat ing m any different visual effect s. You can creat e a bold- looking headline by set t ing it s background t o a dark color and it s t ext t o a light color. ( You'll see an exam ple of t his " reverse t ype" effect in t he t ut orial in Sect ion 7.7.3.) Background colors are also a great way t o set off part of a page like a navigat ion bar, banner, or sidebar.

    Tip: When you use background colors and borders, keep the following in mind: If the border style is either dotted or dashed (see Figure 7-7), the background color shows in the empty spaces between the dots or dashes. In other words, Web browsers actually paint the background color under the borderline.

    Section 7.5. Determining Height and Width

    7.5. Determining Height and Width Two ot her CSS propert ies t hat form part of t he CSS box m odel are useful for assigning dim ensions t o an obj ect , such as a t able, colum n, banner, or sidebar. The height and widt h propert ies assign a height and widt h t o t he cont ent area of a st yle. You'll use t hese propert ies oft en when building t he kinds of CSS layout s described in Part I I I of t his book, but t hey're also useful for m ore basic design chores like assigning t he widt h of a t able, creat ing a sim ple sidebar, or creat ing a gallery of t hum bnail im ages ( like t he one described in t he st eps in Sect ion 8.6) . Adding t hese propert ies t o a st yle is very easy. Just t ype t he propert y followed by any of t he CSS m easurem ent syst em s you've already encount ered. For exam ple: width: 300px; width: 30%; height: 20em;

    Pixels are, well, pixels. They're sim ple t o underst and and easy t o use. They also creat e an exact widt h or height t hat doesn't change. An em is t he sam e as t he t ext size for t he st yled elem ent . Say you set t he t ext size t o 24px; an em for t hat st yle is 24px, so if you set t he widt h t o 2em , t hen it would be 2x24 or 48 pixels. I f you don't set a t ext size in t he st yle, t he em is based on t he inherit ed t ext size ( see Sect ion 6.2.2.3) . For t he widt h propert y, percent age values are based on t he percent age of t he widt h of t he st yle's cont aining elem ent . I f you set t he widt h of a headline t o 75 percent and t hat headline isn't inside any ot her elem ent s wit h a set widt h, t hen t he headline will be 75 percent of t he widt h of t he browser window. I f t he visit or adj ust s t he size of his browser, t hen t he widt h of t he headline will change. However, if t he headline's cont ained inside a < div> ( m aybe t o creat e a colum n) , t hat 's 200 pixels wide, so t he widt h of t hat headline will be 150 pixels. Percent age values for t he height propert y work sim ilarly, but are based on t he cont aining elem ent 's height , inst ead of widt h.

    GEM IN THE ROUGH Minimum and Maximum CSS also support s a few ot her propert ies relat ed t o height and widt h: m in- height , m in- widt h, m ax- height , and m ax- widt h. These propert ies let you set a m inim um widt h or height m eaning t he elem ent m ust be at least t hat widt h or height or a m axim um widt h or height . The elem ent can't be wider or t aller t han a set am ount . These propert ies are useful in t he flexible layout s described in Sect ion 11.1, since t hey let you keep your design wit hin a reasonable space for eit her very sm all m onit ors or very large m onit ors. Unfort unat ely, I nt ernet Explorer 6 and earlier doesn't underst and t hese propert ies. C'est la guerre. You can read m ore about t hese propert ies in Sect ion 11.4.3.

    7.5.1. Calculating a Box's Actual Width and Height While t he widt h and height propert ies seem pret t y st raight forward, t here are a few nuances t hat oft en t hrow people for a loop. First of all, t here's a difference bet ween t he value you set for a st yle's widt h and height and t he am ount of space t hat a Web browser act ually uses t o display t he st yle's box. The widt h and height propert ies set t he widt h and height of t he cont ent area of t he st ylet he place where t he t ext , im ages, or ot her nest ed t ags sit . ( See Figure 7- 1 for a refresher on where t he cont ent area sit s wit hin t he overall box m odel.) The act ual widt ht hat is, t he am ount of screen real est at e given by t he Web browseris t he t ot al of t he widt hs of t he m argins, borders, padding, and widt h propert ies, as illust rat ed in Figure 7- 8. Say you've set t he following propert ies: margin: 10px; border-width: 5px; padding: 15px; width: 100px;

    When t he widt h propert y is set , you always know how m uch room is allocat ed j ust for your cont ent t he words and im ages t hat fill t he spaceregardless of any ot her propert ies you m ay set . You don't need t o do any m at h, because t he value of t he widt h propert y is t he room for your cont ent ( in t he above exam ple, 100 pixels) . Of course, you do have t o perform a lit t le m at h when you're t rying t o figure out exact ly how m uch space an elem ent will t ake up on a Web page. I n t he above exam ple, t he widt h t hat a Web browser allocat es for t he

    Section 7.5. Determining Height and Width

    st yle's box is 160 pixels: 20 pixels for t he left and right m argins, 10 pixels for t he left and right borders, 30 pixels for t he left and right padding, and 100 pixels for t he widt h. ( And versions of I nt ernet Explorer for Windows older t han version 6 get t he whole t hing wrongsee Sect ion 7.5.3forcing you t o do a lit t le ext ra work for t hose browsers.)

    Figu r e 7 - 8 . Ca lcu la t e t h e a ct u a l w idt h of a st yle d e le m e n t 's box by a ddin g u p it s m a r gin s, bor de r s, pa ddin g, a n d w idt h pr ope r t ie s. Th e h e igh t occu pie d on t h e scr e e n by t h e e le m e n t is ca lcu la t e d in t h e sa m e w a yt h e t ot a l of t h e h e igh t pr ope r t y, t h e t op a n d bot t om m a r gin s, t h e t op a n d bot t om bor de r s, a n d t h e t op a n d bot t om pa ddin g.

    Be careful when you specify height s for page elem ent s. Unless you're sure of t he exact dim ensions of t he cont ent of a t ag, it 's hard t o know exact ly how t all a box will be. Say you creat ed a st yle for a pull quot e t o highlight an int erest ing com m ent from an art icle and you set t he pull quot e box t o a widt h of 100px and a height of 100px. When you add t oo m uch t ext t o t he pull quot e, t he box will grow t aller t han 100 pixels and you'll run int o som e weird problem s ( see Figure 7- 9) . Even if t he t ext fit s wit hin t he 100- pixel height , a visit or t o your sit e m ay increase t he font size in her browser, m aking t he t ext larger t han t he height you specified.

    7.5.2. Controlling the Tap with the Overflow Property When t he cont ent inside a st yled t ag's larger t han t he st yle's defined widt h and height , som e weird t hings happen. As shown in Figure 7- 9, I E 6 and earlier j ust let t he box expand t o fit t he larger cont ent , while ot her browsers let t he cont ent spill out of t he box ( past t he borders and oft en over ot her cont ent ) .

    Figu r e 7 - 9 . D e pe n din g on t h e br ow se r you 'r e u sin g, t h e con t e n t in a box w ill displa y in on e of t w o w a ys if it 's t a lle r t h a n t h e box 's se t h e igh t . I n t e r n e t Ex plor e r 6 ( le ft ) a n d e a r lie r for W in dow s w ill sim ply e x pa n d t h e box t o fit t h e con t e n t . Bu t ot h e r br ow se r s, lik e Fir e fox ( r igh t ) a n d I n t e r n e t Ex plor e r 7 , k e e p t h e box t h e sa m e h e igh t a n d spill t h e con t e n t ou t a n d be low t h e e dge s.

    Section 7.5. Determining Height and Width

    Fort unat ely, you can cont rol what a browser should do in t his sit uat ion wit h t he overflow propert y. Overflow accept s four keywords t hat cont rol how cont ent t hat overflows t he edges of a box should be displayed: ● ●

    visible. This opt ion is what browsers do norm ally. I t 's t he sam e as not set t ing t he propert y at all ( Figure 7- 10, t op) . scroll. Let s you add scroll bars ( Figure 7- 10, m iddle) . I t creat es a kind of m ini- browser window in your page and looks sim ilar t o oldschool HTML fram es, or t he HTML < ifram e> t ag. You can use scroll t o provide a lot of cont ent in a sm all am ount of space. Unfort unat ely, scroll bars always appear when you use t his opt ion, even if t he cont ent fit s wit hin t he box.

    Figu r e 7 - 1 0 . Th e ove r flow pr ope r t y give s you t h r e e ba sic w a ys t o de a l w it h t e x t t h a t doe sn 't fit in side a box . Visible displa ys t h e con t e n t a n yw a y ( t op) ; scr oll a n d a u t o a dd scr oll ba r s ( m iddle ) ; a n d h idde n j u st doe sn 't sh ow a n yt h in g t h a t doe sn 't fit ( bot t om ) .

    Section 7.5. Determining Height and Width

    Section 7.5. Determining Height and Width ● ●

    aut o. To m ake scroll bars opt ional, use t he aut o opt ion. I t does t he sam e t hing as scroll, but adds scroll bars only when needed. hidden. Hides any cont ent t hat ext ends out side t he box ( Figure 7- 10, bot t om ) . This opt ion's a bit dangerous, since it can m ake som e cont ent disappear from t he page. But it com es in handy for solving som e I E browser bugs ( see Sect ion 11.1) .

    7.5.3. Fixing IE 5's Broken Box Model Here's a bit of bad news: Versions 5.5 and earlier of I nt ernet Explorer for Windows doesn't always calculat e widt h and height correct ly. Unlike ot her browsers, it doesn't set t he act ual area t aken up by an elem ent t o t he t ot al value of t he m argins, border, padding, and widt h ( or height ) propert y. I nst ead, I E 5.5and I E 6 in quirks m ode ( Sect ion 1.3) only uses t he m argin and widt h. I t includes padding and borders as part of t he widt h propert y value, m aking t he cont ent area sm aller t han in m ost browsers, as illust rat ed in Figure 7- 11.

    Figu r e 7 - 1 1 . I n t e r n e t Ex plor e r 5 for W in dow s doe sn 't ge t t h e CSS box m ode l. ( Th e e a r lie r ve r sion s don 't e it h e r .) I E 5 in clu de s a n y pa ddin g a n d bor de r s a s pa r t of a st yle 's w idt h a n dh e igh t pr ope r t ie s. Th is r e m ove s a r e a t h a t 's n or m a lly r e se r ve d for con t e n t . As a r e su lt , I E 5 ca n displa y a n e le m e n t m u ch t h in n e r ( or m u ch sh or t e r ) t h a n it sh ou ld.

    Here's how I E 5 would handle t he box in Figure 7- 8. All current browsers set aside 160 pixels for t he widt h of t he box. The t ot al widt h of t hat sam e st yled elem ent would be 10 + 10 ( left and right m argins) + 100 ( widt h propert y) for a grand t ot al of 120 pixels. But in Windows I E 5, t hat sidebar would look 40 pixels t hinner t han in ot her browsers. I n fact , t he act ual widt h dedicat ed t o t he cont ent is equal t o 100 ( t he widt h propert y) 30 ( left and right padding) 10 ( left and right border) . The t ext in a sidebar wit h t hese set t ings would be cram m ed int o 60 pixels, inst ead of t he appropriat e 100 pixels. The sam e's t rue for t he height propert y. I E 5 t reat s t he height value as t he t ot al of t he cont ent , t op and bot t om padding, and t op and bot t om border. So boxes also appear short er in I E 5 t han in ot her browsers. You have m any different ways around t his problem . Here are a few of t he m ost com m on: ●



    D on 't a pply pa ddin g or bor de r s t o t h e st yle con t a in in g t h e w idt h or h e igh t pr ope r t y. The problem crops up only when padding or borders are set , so avoiding t hese propert ies prevent s t he problem ent irely. But if you want t o add a decorat ive border, you can't very well avoid t he border propert y. Use t w o t a gson e t o se t t h e w idt h / h e igh t a n d a n ot h e r , n e st e d t a g, t o se t pa ddin g a n d bor de r s. Say you want t o have a 100 pixel wide pull quot e st yle, but you also want it t o have borders and padding ( and, of course, you want it t o work in I E 5) . You can creat e t he following HTML for t he pull quot e:

    This is the content of the pull quote.

    Section 7.5. Determining Height and Width



    Then, in your st yle sheet , add t he following t wo st yles: .pullquote { width: 100px; } .inner_pullquote { padding: 10px; background-color: #333; border: 1px dotted red; }



    The first st yle set s t he widt h for t he first < div> t agt he parent t ag t hat surrounds t he ot her part s of t he pull quot e. Since it has only a widt h specified, all browsers ( including I E 5) will display t he box at 100 pixels wide. The second, inner < div> has t he padding and border set , but no widt h, so once again t here's no I E 5 problem . This solut ion let s you use borders and padding and works in all browsers, but it requires ext ra HTML coding and an ext raneous < div> t ag j ust t o support one dying browser. Se n d I E 5 a diffe r e n t w idt h / h e igh t va lu e . Many Web developers prefer t his elegant solut ion, alt hough it requires a lit t le m at h. The basic idea is t o give I E 5.5 and earlier a special widt h value t hat 's equal t o t he widt h value you set for ot her browsers, plus t he com bined value of t he padding and borders. You have m any different ways t o specify a CSS propert y and value t o j ust one browser, like t he advanced m et hod discussed in Chapt er 14 ( Sect ion 14.5.2) . A sim ple m et hod is t he st ar ht m l hack ( see t he box in Sect ion 7.6) . Take t he exam ple in Figure 7- 8. The widt h value in t his case is 100 pixels: There are 15 pixels wort h of left padding and 15 pixels of right padding, as well as 10 pixels of t ot al border widt h ( bot h left and right borders) . Adding t hose t oget her you get 140 pixels. Now say you've creat ed a class st yle for t his page called .pullquot e. This st yle has all of t he basic set t ings you want : m argins, padding, borders, widt h, and so on. All you need t o do is feed I E 5.5 and earlier a different widt h. So below t he .pullquot e st yle, add t he following: * html .pullquote { width: 140px; w\idth: 100px; }



    This st yle m ust com e aft er t he original .pullquot e st yle, since it overrides t he widt h propert y for t hat st yle. Essent ially, t his new st yle's invisible t o every browser except I E 6 and earlier. ( I E 7 ignores it as well.) The first propert y set s t he widt h t o 140px ( t he correct value for I E 5) , but since I E 6 get s t his new value and handles t he box m odel correct ly, you have t o reset t he widt h t o 100 pixels in order for I E 6 t o display t he st yle correct ly. That 's where t hat second, weirdo propert yw\ idt hcom es in. I t 's act ually valid CSS, but it 's underst ood only by I E 6I E 5.5 t hrows it s hands up in disgust and ignores it . Thus, w\ idt h reset s t he widt h propert y t o 100 pixels for I E 6 and everyone's happy ( except for t he poor Web designers who have t o learn t hese crazy workarounds) . I gn or e I E 5 e n t ir e ly. This last opt ion m ay sound a lit t le discrim inat ory, but it 's wort h checking out your Web server's log file t o see if you even have any visit ors com ing t o your sit e wit h I E 5.5 or earlier. Alt hough t his ant iquat ed browser st ill has a few dedicat ed fans, t heir num bers are dwindling. And if your sit e t arget s a m ore t ech- savvy crowd, t hen you m ay not even need t o bot her designing wit h I E 5 in m ind. ( Lucky you.)

    BROWSER BUG Special Rules for IE 6 and Earlier Dealing wit h t he surprisingly inconsist ent ways different browsers display pages is t he bane of every Web designer. What looks great in I nt ernet Explorer m ay fall com plet ely apart in Firefox, or vice versa. Throughout t his book you'll find t ips on browser m anagem ent and ways t o overcom e t he worst browser bugs. Not surprisingly, I nt ernet Explorer 6, which is over half a decade old, is plagued by m any display problem s. I nt ernet Explorer 5 has even m ore. For exam ple, bot h I E 5 and 6 have t rouble displaying float - based layout s, as you'll see in Chapt er 11 ( Sect ion 11.1) . And I E 5 doesn't always calculat e t he widt h of a box correct ly ( Sect ion 7.5.3) . To overcom e t hese bugs, you frequent ly have t o send propert ies and values t o I E t hat are different t han t he ones used by ot her browsers. To t hat end, t here's an easy way t o creat e CSS st yles t hat apply only t o I E 6 and earliert he st ar ht m l hack. I n t his m et hod, you begin t he st yle wit h t he following: * ht m l. I f you want t o have an h1 t ag st yle t hat applies only t o I E 6 and earlier, t hen nam e t he st yle * ht m l h1. All ot her browsers see t he st yle as a descendent select or t hat doesn't m ake any sense, so t hey prom pt ly ignore it . You'll frequent ly use t he st ar ht m l hack t o override som e set t ing from a st yle t hat ot her ( bet t er) browsers display properly but I E get s wrong. I n t hat case, apply t he * ht m l hack aft er t he correct st yle. Say you creat e a class st yle nam ed .sidebar

    Section 7.5. Determining Height and Width

    t hat creat es an at t ract ive sidebar box for news and sit e navigat ion links. Due t o a weird bug in I E, t he sidebar m ay appear t hree pixels off t o t he left or right ( see Sect ion 11.1.1) . To count eract t his snafu, you can add t his I E only special fix aft er t he regular .sidebar st yle: * html .sidebar { margin-left: -3px }

    You'll see t he * ht m l hack in a couple of places in t his book ( like t his chapt er's t ut orial in Sect ion 7.7.5) . You'll learn ot her t echniques for m anaging I nt ernet Explorer in Chapt er 14 ( Sect ion 14.5.2) . I nt ernet Explorer 7 doesn't underst and t he * ht m l hack, so it 'll ignore t hese t ypes of st yles. Fort unat ely, I E 7 has fixed m any of t he bugs t hat plagued earlier versions of t he browser so t he fixes supplied by * ht m l st yles aren't usually needed for t hat browser.

    Section 7.6. Wrap Content with Floating Elements

    7.6. Wrap Content with Floating Elements HTML norm ally flows from t he t op of t he browser window down t o t he bot t om , one headline, paragraph, or block- level elem ent on t op of anot her. This word processorlike display is visually boring ( Figure 7- 12, t op) , but wit h CSS, you're far from st uck wit h it . You'll learn lot s of new m et hods for arranging it em s on a Web page in Part 3, but you can spice up your pages plent y wit h one lit t le CSS propert y float . The float propert y m oves an elem ent t o eit her t he left or right . I n t he process, cont ent below t he float ed elem ent m oves up and wraps around t he float ( Figure 7- 12, bot t om ) . Float ing elem ent s are ideal for m oving supplem ent al inform at ion out of t he way of t he m ain t ext of a page. I m ages can m ove t o eit her edge, let t ing t ext wrap elegant ly around t hem . Sim ilarly, you can shut t le a sidebar of relat ed inform at ion and links off t o one side.

    Figu r e 7 - 1 2 . Th e r e gu la r flow of H TM L is le ft t o r igh t , t op t o bot t om , w it h on e block - le ve l e le m e n t h e a dlin e , pa r a gr a ph , < div> , a n d so on st a ck e d on t op of t h e n e x t . By le t t in g you br e a k u p t h is u n ifor m it y, t h e floa t pr ope r t y is on e of t h e m ost pow e r fu l a n d u se fu l t ools t h a t CSS offe r s. I t s u se s r a n ge fr om sim ply m ovin g a n im a ge t o on e side of a pa r a gr a ph t o pr ovidin g com ple t e la you t con t r ol ove r ba n n e r s, side ba r s, n a viga t ion ba r s, a n d ot h e r pa ge e le m e n t s.

    Section 7.6. Wrap Content with Floating Elements

    While you can use float s in som e com plex ( and confusing) ways, as you'll see in Chapt er 11, t he basic propert y is very sim ple. I t t akes one of t hree keywords, left , right , or none, like so: float: left;

    ● ● ●

    left . Slides t he st yled elem ent t o t he left , while cont ent below wraps around t he right side of t he elem ent . right . Slides t he elem ent t o t he right . none. Turns off t he float and ret urns t he obj ect t o it s norm al posit ion.

    Note: Floating an image is similar to setting the tag's align attribute to either left or right. That little bit of HTML is deprecated (Section 3.3), so use the CSS float property instead.

    Float ed elem ent s m ove t o t he left or right edge of t he browser window, or of t heir cont aining elem ent , if t here is one. You m ay have a box on t he page t hat 's 300 pixels wide and is it self float ed t o t he right edge of t he browser window. I nside t hat box, you've got an im age t hat float s t o t he left . That im age slides t o t he left edge of t hat 300 pixel- wide boxnot t he left edge of t he browser window. You can even use t he float propert y wit h an inline elem ent ( see Sect ion 7.2.4) such as t he < im g> t ag. I n fact , float ing a phot o t o t he left or right using CSS is a very com m on use of t he float propert y. A Web browser t reat s a float ed inline elem ent j ust like a block- level elem ent , so you don't run int o t he problem s wit h padding and m argin t hat norm ally t rouble inline elem ent s ( see Sect ion 7.2.4) . You can also float a block- level elem ent like a headline or paragraph. A com m on t echnique's t o float a < div> t ag cont aining ot her HTML t ags and page cont ent t o creat e a kind of cont aining box. I n t his way, you can creat e sidebars, pull quot es, and ot her self- cont ained page elem ent s. ( You'll see an exam ple of t his in t his chapt er's t ut orial.) When you float block- level elem ent s, it 's a good idea t o set t he widt h propert y as well. This way, you can cont rol how m uch horizont al space t he block t akes up and how m uch space is available for t he cont ent below it t o m ove up and wrap around t he block.

    Note: The source orderthe order in which you write your HTMLhas a big impact on the display of floated elements. The HTML for the floated tag must appear before the HTML of any content that wraps around the floated element. Say you've created a Web page composed of an tag, followed by a

    tag. Toward the end of that

    tag, you've also inserted a photo using the tag. If you float that photo to the right, say, then the tag and most of the content inside that

    tag will still appear above the photo; only content that follows the tag will wrap around the left side of the image.

    7.6.1. Backgrounds, Borders, and Floats To t he const ernat ion of m any Web designers, backgrounds and borders don't float t he sam e way as ot her page elem ent s. Say you float an elem ent a sidebar for exam plet o t he right . The cont ent below t he sidebar m oves up and wraps around it , j ust as it should. But if t hat cont ent has a background or border set on it , t hen t hat background or border act ually appears underneat h t he float ed sidebar ( Figure 7- 13, left ) . I n essence, a Web browser wraps t he t ext around t he float , but not t he border or background. Believe it or not , t his is absolut ely kosher, and how ( according t o t he rules) it 's supposed t o work. Of course, you m ay not want t o follow t hese rules; you m ight want t o have t he border or background st op when it reaches t he float ed elem ent ( Figure 7- 13, right ) . Wit h a lit t le CSS m agic, you can do it .

    Section 7.6. Wrap Content with Floating Elements

    First , you need t o add one rule t o t he st yle t hat has background or borders running underneat h t he float . Once you locat e t he st yle, add t his line: overflow: hidden; . The overflow propert y ( discussed in m ore det ail in Sect ion 7.5.2) m akes any background or border t hat ext ends underneat h t he float disappear. Anot her approach is t o add a borderline around t he float ed elem ent ; when you m ake t he borderline t hick enough and m at ch it s color t o t he background color of t he page, t he border looks j ust like em pt y spaceeven t hough it 's covering and hiding t he background color and borderlines t hat are ext ending below it .

    Figu r e 7 - 1 3 . I n t h is e x a m ple , t h e r e 's a n < h 1 > t a g w it h a ba ck gr ou n d color a n d a n < h 2 > t a g w it h a bor de r ( le ft ) . Addin g ove r flow : h idde n ; t o t h e st yle for t h e < h 1 > t a g ( r igh t ) pr e ve n t s t h e h e a dlin e fr om a ppe a r in g u n de r t h e floa t in g e le m e n t ( side ba r ) .

    7.6.2. Stopping the Float Som et im es you need a way t o t ell a t ag t o ignore a float ed elem ent . You m ay have a copyright not ice t hat should always appear at t he bot t om of t he browser window. I f you have a part icularly t all sidebar t hat 's float ed t o t he left side of t he page, t he copyright not ice m ight act ually be drawn up t he page and wrap around t he float . I nst ead of appearing at t he bot t om of t he page, t he copyright is sit t ing up t he page next t o t he sidebar. You want t he copyright not ice part of your page t o refuse t o wrap around t he float ed elem ent and inst ead drop below it . Ot her problem s occur when you have several float ed it em s close t oget her. I f t he float ed it em s aren't very wide, t hey float up and next t o each ot her, and if t hey're of varying height s t hey can get int o an unat t ract ive logj am ( see Figure 7- 14, t op) . I n t his case, t he float ed elem ent s shouldn't float next t o each ot her. CSS provides t he clear propert y for j ust t hese t ypes of problem s.

    BROWSER BUG When overflow: hidden Fails

    Section 7.6. Wrap Content with Floating Elements

    The overflow: hidden propert y prevent s backgrounds and borders from awkwardly running under float ing elem ent s ( Figure 7- 13) . But not hing's ever t hat sim ple in t he world of Web browsers. While t his one line of code works for I nt ernet Explorer 7, Firefox, Cam ino, and Safari, it doesn't work reliably in Opera ( at least version 8.5) , and I nt ernet Explorer 5 and 6 for Windows j ust ignore it . Alas t here's no apparent fix for Opera, but t here's som et hing you can do for I E 5 and 6. For t hose browsers, you need t o add one addit ional rule: zoom : 1; . This is a Microsoft - only propert y t hat let s you enlarge an elem ent on a page. I n t his case, t hough, it 's j ust a weird way t o force I E 5 and 6 t o st op a border or background from ext ending underneat h t he float ed elem ent . ( For m ore det ail on why t his zoom t hing works, see " Got Layout ?" in Sect ion 11.1.) You m ay want t o put t he I E- specific zoom rule in an I E- only st yle ( see t he box in Sect ion 7.6) . You can even put it in a com plet ely separat e I E- only ext ernal st yle sheet ( Sect ion 14.5.2) . You'll also find an exam ple of t his problem and it s solut ion in t he t ut orial st art ing in Sect ion 7.7.5.

    The clear propert y inst ruct s an elem ent t o not wrap around a float ed it em . By clearing an elem ent , you essent ially force it t o drop down below t he float ed it em . Also, you can cont rol which t ype of float ( left or right ) is cleared or force a st yle t o sim ply ignore bot h t ypes of float s. The clear propert y accept s t he following opt ions: ● ● ● ●

    left . The st yle will drop below elem ent s t hat are float ed left but will st ill wrap around right - float ed obj ect s. right . Forces a drop below right - float ed obj ect s but st ill wraps around left - float ed obj ect s. bot h. Forces a drop below bot h left - and right - float ed elem ent s. none. Turns off clearing alt oget her. I n ot her words, it m akes an it em wrap around bot h left - and right - float ed obj ect s, which is how Web browsers norm ally work.

    I n t he case of a copyright not ice t hat m ust appear at t he bot t om of t he page, you'd want it t o clear bot h left - and right - float ed obj ect sit should always be below ot her cont ent and should never wrap t o t he left or right of any ot her it em . Here's a class st yle t hat would do j ust t hat : .copyright { clear: both; }

    Figure 7- 14 shows how t he clear propert y can prevent float ed it em s of varying height s from clum ping t oget her. All t hree phot os in t hat figure have a right float applied t o t hem . I n t he t op figure, t he phot o of t he t om at oes ( 1) is t he first im age on t he page and appears at t he far right edge. The second im age ( 2) obeys t he float set on t he first im age and wraps up t o t he left of it . The last phot o ( 3) isn't wide enough t o sit next t o t he second phot o ( 2) but st ill t ries t o wrap around bot h ( 1) and ( 2) . I t get s st uck in t he process. Using clear: right ; on t he im ages prevent s t he phot os from sit t ing next t o each ot her ( Figure 7- 14, bot t om ) . The clear applied t o t he second phot o prevent s it from wrapping up next t o t he first im age, while t he last im age's right clear propert y forces it t o appear below t he second im age.

    Figu r e 7 - 1 4 . Top: Som e t im e s you don 't w a n t a n e le m e n t t o w r a p a r ou n d a floa t e d obj e ct . Bot t om : Applyin g t h e cle a r pr ope r t y ( in t h is ca se cle a r : r igh t ;) t o e a ch im a ge pr e ve n t s t h e m fr om sit t in g n e x t t o e a ch ot h e r . Th e cle a r a pplie d t o ph ot o ( 2 ) pr e ve n t s it fr om w r a ppin g u p n e x t t o im a ge ( 1 ) . Applyin g cle a r : r igh t t o ph ot o ( 3 ) for ce s it t o a ppe a r be low ph ot o ( 2 ) .

    Section 7.6. Wrap Content with Floating Elements

    Tip: This business of left floats, right floats, and how to clear them sounds complicatedand it is. This section gives you a basic introduction. You'll see the

    Section 7.6. Wrap Content with Floating Elements

    subject again in Chapter 11 and eventually learn how to use floats in more sophisticated ways.

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    7.7. Tutorial: Margins, Backgrounds, and Borders I n t his t ut orial, you'll explore elem ent s of t he CSS box m odel, adj ust t he spacing around obj ect s on a page, add colorful borders t o it em s on a page, and cont rol t he size and flow of page elem ent s. To get st art ed, you need t o download t he t ut orial files locat ed on t his book's com panion Web sit e at www.sawm ac.com / css/ . Click t he t ut orial link and download t he files. ( All of t he files are enclosed in a ZI P archive. See det ailed inst ruct ions for unzipping t he files on t he Web sit e.) The files for t his t ut orial are cont ained inside t he chapt er_07 folder.

    7.7.1. Controlling Page Margins As usual, you'll be working on a Web page from Cosm oFarm er.com . You'll st art by cont rolling t he m argin around t he edges of t he Web page.

    Tip: For a sneak preview of the final result, check out Figure 7-18.

    1. La u n ch a W e b br ow se r a n d ope n t h e file ch a pt e r _ 0 7

    side ba r .h t m l.

    I n t his case, t here's already an ext ernal st yle sheet at t ached t o t he page t hat adds som e basic t ext form at t ing, as you can see in Figure 7- 15. 2. I n you r fa vor it e t e x t e dit or , ope n ch a pt e r _ 0 7

    side ba r .h t m l.

    St art by adding an int ernal st yle sheet t o t his file. 3. Click dir e ct ly a ft e r t h e closin g < / lin k > t a g ( u se d t o a t t a ch t h e e x t e r n a l st yle sh e e t ) , h it En t e r ( Re t u r n ) , a n d t h e n t ype < st yle t ype = " t e x t / css" > . You've j ust creat ed t he opening st yle t ag. Next , you'll creat e a st yle t hat set s t he m argin around t he edges of t he page and adds a color t o t he background. 4. Pr e ss t h e En t e r ( Re t u r n ) k e y, a n d t h e n t ype t h e follow in g st yle : body { margin-top: 15px; margin-left: 0; margin-right: 0; padding: 0; background-color: #f8faf1; }

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    This st yle m akes t he page's background a light gray- green. The m argin set t ings indent t he page cont ent 15 pixels from t he t op of t he window but rem ove all space from t he left and right edges. I n ot her words, cont ent but t s right up against t he left and right edges of t he browser window. You could have done t he sam e t hing wit h t he m argin short hand propert y ( Sect ion 7.2.1) like t his: m argin: 15px 0 0 0; .

    Figu r e 7 - 1 5 . Th is W e b pa ge h a s som e ba sic t e x t st ylin g, bu t it 'll look a lot be t t e r w it h a box m ode l m a k e ove r .

    Note: The padding property (padding: 0;) in this style accommodates the Opera browser, which uses padding instead of margin to define the space around the edges of the browser window.

    Finally you'll add t he closing < st yle> t ag t o com plet e t he st yle sheet .

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    H it En t e r ( Re t u r n ) t o cr e a t e a n e w , bla n k lin e , a n d t h e n t ype < / st yle > . Your st yle sheet 's com plet e and you're ready t o check t he page. 6. Sa ve t h e file a n d pr e vie w t h e pa ge in a W e b br ow se r . The t op line of t ext is placed a lit t le way down from t he t op of t he browser window, while t he left edge of each headline and paragraph t ouches t he left side of t he browser window. The t ype looks cram ped on t he left side like t hat , but you'll fix it lat er in t his t ut orial. Next , adj ust t he spacing around t he headlines and paragraphs.

    7.7.2. Adjusting the Space Around Tags Web browsers aut om at ically insert a bit of space above and below headlines, paragraphs, list s, form s, and ot her blocklevel HTML elem ent s. The exact am ount varies from browser t o browser, so you get m ore predict able result s by set t ing t his value yourself, as described in t he following st eps. 1. Re t u r n t o you r t e x t e dit or a n d t h e side ba r .h t m l file . Click a t t h e e n d of t h e closin g br a ce of t h e body t a g se le ct or , pr e ss En t e r ( Re t u r n ) t o cr e a t e a n e w lin e , a n d t h e n a dd t h e se t w o st yle s: h1 { margin: 0; } h2 { margin-top: 10px; margin-bottom: 0; }

    The first st yle rem oves all m argins from all < h1> t ags, and t he second rem oves t he bot t om m argin from all < h2> t ags and set s t heir t op m argins t o 10 pixels. I f you preview t he page now, you'll see t hat it act ually doesn't look any different . But you can det ect a gap above t he < h1> t ag at t he t op of t he page, as well as space above and below each < h2> t ag. That 's because t here are st ill m argins above and below t he paragraph t ags and t he < h3> t ag ( " I deas for Bet t er I ndoor Agricult ure" ) .

    Note: The gap between the and

    tags didn't change at all because the bottom margin of the tag and the top margin of the

    tag were already collapsed. (See Section 7.2.2 to learn more about the mystery of collapsing margins.)

    Next , rem ove t he space bet ween t he t ops of t he paragraphs and t he bot t om s of t he < h2> t ag. 2. Click a t t h e e n d of t h e closin g br a ce of t h e h 2 t a g se le ct or , pr e ss En t e r ( Re t u r n ) t o cr e a t e a n e w lin e , a n d t h e n a dd t h is st yle : p { margin-top: 0; margin-bottom: 10px;

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    }

    3. Sa ve t h e file a n d pr e vie w t h e pa ge in a W e b br ow se r . The gap bet ween t he headline and t he paragraphs below has gone away, but t here's st ill a 10- pixel space bet ween each paragraph t hanks t o t he m argin- bot t om set t ing ( Figure 7- 16) .

    Figu r e 7 - 1 6 . W it h j u st a fe w sh or t st yle s, you ca n a dd ba ck gr ou n d color s, con t r ol m a r gin s t h r ou gh ou t t h e pa ge , a n d t igh t e n u p t h e spa ce be t w e e n h e a dlin e s a n d pa r a gr a ph s.

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    7.7.3. Emphasizing Text with Backgrounds and Borders Backgrounds can colorize a page or highlight a sidebar, but you can use t hem for plent y of ot her purposeslike m aking headlines st and out . Borders, t oo, are m ore versat ile t han t hey get credit for. Sure, t hey're fine for fram ing im ages, adding lines around t ables, and drawing boxes on a Web page, but a single border can draw at t ent ion t o headlines, separat e paragraphs of t ext , and replace t he gray, clunky- looking HTML < hr> t ag. I n t his sect ion, you'll use backgrounds and borders t o em phasize t he page headings. 1. Re t u r n t o you r t e x t e dit or a n d t h e side ba r .h t m l file . I t 's t im e t o edit t he h1 st yle you already creat ed. 2. Add t w o pr ope r t ie s t o t h e h 1 st yle , so t h a t it look s lik e t h is: h1 { margin: 0; border-top: solid 2px #fbef99; border-bottom: solid 2px #fbef99; }

    These t wo propert ies add a yellow line above and below t he headline. I f you preview t he page now, you'll see t he t wo lines are t oo close t o t he t ext . There could also st and t o be a lit t le m ore breat hing room bet ween t he left edge of t he page and t he t ext in t he headline. You'll m ake t hose t wo adj ust m ent s next . 3. Add som e pa ddin g t o t h e h 1 st yle : h1 { margin: 0; border-top: solid 2px #fbef99; border-bottom: solid 2px #fbef99; padding: 5px 0 5px 25px; }

    Padding indent s t he t ext of t he headline from it s borders. This short hand m et hod of specifying t he padding propert ies ( Sect ion 7.2.1) indent s t he t ext 5 pixels from t he t op line, 0 from t he right edge, and 5 pixels from t he bot t om line while indent ing t he left edge 25 pixels. I f you preview t he page, you'll see t hat t he t wo lines ext end t he full lengt h of t he browser window, t ouching bot h t he left and right edges, while t he headline t ext is nicely indent ed. Now you can see t he reason for set t ing t he left and right m argins of t he body t o 0it allows t he heading's border lines t o ext end across t he browser window wit hout gaps on t he left or right side. I n a m om ent , you'll also indent t he h2 and p t ags, but first add a bit m ore punch t o t hat opening headline by adding a background color. 4. Add t w o m or e pr ope r t ie s t o t h e h 1 st yle a ba ck gr ou n d color a n d a t e x t color lik e so:

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    h1 { margin: 0; border-top: 2px solid #FBEF99; border-bottom: 2px solid #FBEF99; padding: 5px 0 5px 25px; background-color: #294e56; color: #fff; }

    Wit h t his adj ust m ent , t he whit e headline t ext j um ps out from a dark st ripe across t he page. Next , add a bot t om underline t o each < h2> t ag. 5. Edit t h e h 2 st yle by a ddin g a m a r gin a n d bot t om bor de r , a s follow s: h2 { margin-top: 10px; margin-bottom: 0px; margin-left: 25px; border-bottom: 1px solid #5f9794; }

    The left m argin indent s t he headline, m oving it away from t he left edge of t he browser window and aligning it wit h t he t ext in t he < h1> t ag. You need t o m ake t he sam e change t o t he paragraph t ags, in order t o line t hem up as well. 6. Add a 2 5 px le ft m a r gin t o t h e p st yle : p { margin-top: 0; margin-bottom: 10px; margin-left: 25px; }

    This st ep indent s t he paragraphs t o m at ch t he indent of t he ot her headlines. You can also rewrit e t hese t hree m argin set t ings using t he m argin short cut propert y: m argin: 0 0 10px 25px; . 7. Sa ve t h e file a n d pr e vie w t h e pa ge in a W e b br ow se r . The page should look like Figure 7- 17. The bullet ed list of it em s doesn't look very good yet . This sidebar elem ent needs t o look like a real sidebarplaced in it s own box and m oved t o t he side of t he page. You'll do t hat in t he next sect ion.

    7.7.4. Building a Sidebar Sidebars are com m on elem ent s in m ost t ypes of print publicat ions like m agazines, books, and newspapers. They com part m ent alize and highlight sm all chunks of inform at ion like a resource list , cont act inform at ion, or a relat ed anecdot e. But t o be effect ive, sidebars shouldn't int errupt t he flow of t he m ain st ory. They should, like t he nam e says, sit unobt rusively off t o one side, which you can easily m ake happen wit h CSS.

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    1. Re t u r n t o you r t e x t e dit or a n d t h e side ba r .h t m l file . First , you m ust isolat e t he region of t he page t hat m akes up t he sidebar. The < div> t ag ( Sect ion 3.1) is t he perfect t ool. You can enclose any am ount of HTML int o it s own self- cont ained chunk by wrapping it in a < div> t ag. 2. Click be for e t h e ope n in g < h 3 > t a g ( t h e on e w it h t h e " I de a s for Be t t e r I n door Agr icu lt u r e " h e a dlin e ) . Th e n t ype < div cla ss= " side ba r " > , a n d pr e ss En t e r ( Re t u r n ) . This CSS m arks t he beginning of t he sidebar and applies a class t o it . You'll creat e t he .sidebar class st yle in t he next st ep, but first you need t o indicat e t he end of t he sidebar by closing t he < div> . 3. Click a ft e r t h e closin g < / u l> t a g. ( Th is in dica t e s t h e e n d of a bu lle t e d list .) Pr e ss En t e r ( Re t u r n ) , a n d t h e n t ype < / div> . You've j ust wrapped a headline and bullet ed list inside a < div> t ag. Next , you'll creat e a st yle for it .

    Figu r e 7 - 1 7 . A da r k ba ck gr ou n d color ca n m a k e a h e a dlin e pop, lik e t h e t op h e a dlin e on t h is pa ge . Th e pa ddin g pr ope r t y ope n s u p t h e h e a dlin e by m ovin g t h e t e x t a w a y fr om t h e e dge s of t h e bor de r a n d m or e st r on gly h igh ligh t in g t h e ba ck gr ou n d. A sin gle bor de r a dds su bt le e m ph a sis t o se con d le ve l h e a dlin e s.

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    4. I n t h e pa ge 's st yle sh e e t , a dd t h e follow in g st yle be low t h e < p> st yle you cr e a t e d e a r lie r : .sidebar { width: 200px; float: right; margin: 10px; }

    This st yle set s t he widt h of t he cont ent area ( where t he t ext appears) t o 200 pixels, float s it t o t he right side of t he browser window, and adds 10 pixels of space around t he box. I f you preview t he page in a browser, you'll see t hat t he basic shape and placem ent of t he sidebar's set , but t here's one problem : The < h2> t ags appear under- neat h t he box. Even t hough t he float ed sidebar m oves t he t ext of t he headlines out of t he way, float s don't displace border or backgrounds. Those j ust appear right under t he

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    float ed sidebar ( see Sect ion 7.6.1) . You can easily adj ust for t his bit of CSS frailt y by edit ing t he < h2> t ag st yle you creat ed earlier.

    Note: If your site's audience includes a lot of Opera fans (the Web browser, not the musical extravaganza), then skip step 5 and just live with the border extending underneath the floated sidebar. This fix is more like a break for that browser. 5. Loca t e t h e h 2 st yle a n d a dd t h e ove r flow pr ope r t y, lik e so: h2 { margin-top: 10px; margin-bottom: 0px; margin-left: 25px; border-bottom: 1px solid #5F9794; overflow: hidden; }

    Set t ing t he overflow propert y t o hidden hides t he borders t hat pass beyond t he headline t ext and under t he float ing elem ent . ( Unfort unat ely, I nt ernet Explorer 6 and 5 don't get it and st ill display t he borders underneat h t he sidebar. But you'll fix t hat in t he next sect ion.) I n t he m eant im e, m ake t he sidebar st and out by adding a border and background color. 6. Add t h e follow in g t w o pr ope r t ie s t o t h e .side ba r st yle : border: solid 1px #fdd041; border-top-width: 5px;

    The first propert y, border, is a short hand m et hod of set t ing t he st yle, widt h, and color of all four borders. I n t his, case, it creat es a 1- pixel, solid yellow line around t he sidebar. The second propert y, border- t op- widt h, overrides t he 1- pixel widt h set by t he border propert y, creat ing a t hicker t op border for som e visual int erest . Finally, you'll add a lit t le padding t o indent t he t ext from t he inside edges of t he box, as well as a background color. 7. Add t w o m or e pr ope r t ie s t o t h e side ba r st yle , lik e so: .sidebar { width: 200px; float: right; margin: 10px; border: solid 1px #fdd041; border-top-width: 5px; padding: 10px; background-color: #fbef99; }

    The background- color propert y adds a light yellow color t o t he sidebar and covers t he borders of t he < h2> t ags.

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    To finish up t he sidebar, you'll creat e a few descendent select ors t o cont rol t he form at t ing for t he t ags inside t he sidebar. First , you'll address t he < h3> t ag, which in som e browsers ( not ably Firefox) has unnecessary space above it . 8. Add t h is st yle t o you r st yle sh e e t : .sidebar h3 { margin: 0; text-align: center; }

    This descendent select or st yle affect s only < h3> t ags t hat appear inside a t ag t hat has t he .sidebar class applied t o it . I t cent ers t he t ext and elim inat es any m argins around t he headline. Because Web browsers indent list s, you'll not ice t hat t he bullet ed list in t he narrow sidebar looks weird wit h such a large left indent . 9. Add on e m or e st yle t o t h e st yle sh e e t : .sidebar ul { padding: 0; margin: 10px 0 0 0; }

    Because som e browsers use t he left padding propert y and ot hers use t he left m argin propert y t o indent list s, you need t o m ake sure bot h are set t o 0 in order t o reliably elim inat e a left m argin from list s. I n t his case, we've added 10 pixels of t op m argin space above t he list t o separat e it a bit from t he headline above. I f you preview t he page now, you'll not ice one big error. The bullet s appear eit her out side of t he sidebar box, or not at all ( in t he case of I nt ernet Explorer) . Sim ply adding a lit t le indent t o t he list it em s brings t he bullet s back int o view. 10. Add t h e follow in g st yle t o in de n t e a ch bu lle t e d it e m : .sidebar li { margin-left: 1.5em; }

    This st yle adds enough space t o t he left of each list it em , m oving t he bullet s back int o view. Now it 's t im e t o preview your handiwork. 11. Sa ve t h e file a n d pr e vie w t h e W e b pa ge in a br ow se r . The page should look like Figure 7- 18. Unfort unat ely, t he page doesn't look like Figure 7- 18 in I nt ernet Explorer 6 or 5 for Windows. A couple of bugs in t hose

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    browser versions affect t he page's appearance for t he worse. Read on for t he fixes.

    7.7.5. Fixing the Browser Bugs While t he sidebar.ht m l file looks j ust fine in I nt ernet Explorer 7, earlier versions of t hat browser don't display t he page correct ly. I f you have access t o eit her of t hese browsers, check it out . You'll see t he problem s.

    Figu r e 7 - 1 8 . A h a n dfu l of CSS st yle s a dds de sign e le ga n ce t o h o- h u m H TM L. N ot ice h ow t h e floa t e d side ba r bot h a t t r a ct s a t t e n t ion a n d m ove s it ou t of t h e w a y of t h e m a in body of t e x t .

    For one t hing, t he border under t he t wo < h2> headlines t ravels underneat h t he sidebar. I n st ep 5 in Sect ion 7.7.4, you used t he overflow propert y t o fix t his problem in m ost browsers, but you need som et hing else t o get I E 5 and 6 st raight ened out . I n addit ion, t he m argin around t he sidebar is not iceably larger on t he right . And in I E 5, t he sidebar's m uch sm aller t han in ot her browsers.

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    Tip: If you don't have access to check for yourself, just trust that problems are there and use this section to learn how to fix them for the sake of your visitors who are stuck with IE 5 or 6.

    The first bug, t he overext ended borders, affect s bot h I E 5 and 6. You'll t ackle t his one first : 1. Re t u r n t o you r t e x t e dit or a n d t h e side ba r .h t m l file . You first need t o creat e a st yle t hat only I nt ernet Explorer 6 and earlier can read. 2. Add t h is n e w st yle t o t h e e n d of t h e side ba r .h t m l pa ge 's st yle sh e e t : * html h2 { }

    The * ht m l part of t he st yle is in fact an incorrect CSS select or. However, I E 6 and earlier consider it legit im at e, so by adding h2 t o creat e a descendent select or, I nt ernet Explorer 6 and earlier t reat s t his as a valid st yle for form at t ing any < h2> t ag. ( See Sect ion 7.6 for m ore on t his t echnique.) So far, you've j ust got an em pt y st yle. Tim e t o add som e propert ies. 3. Add t h e follow in g pr ope r t y t o t h e n e w st yle : * html h2 { zoom: 1; }

    Zoom isn't an official CSS propert y. I t 's a Microsoft - only propert y m eant t o enlarge an elem ent on a page. That 's not why you're using it here, t hough. I n t his case, t he zoom propert y prevent s t he border from ext ending under t he float in I E 5 and 6. I t fixes t he border bugalbeit in a com plet ely arcane way. ( See t he box in Sect ion 11.1 for m ore det ails on t his browser voodoo.) Next problem : The double- m argin bug t hat 's causing t hat ext ra space on t he right side of t he sidebar. Since t his bug affect s bot h I E 5 and 6, you'll creat e anot her * ht m l st yle for t he sidebar. ( Rem em ber, * ht m l hides t he rest of t his select or.sidebarfrom all browsers except I E 6 for Windows and earlier.) 4. Add t h is st yle t o you r st yle sh e e t : * html .sidebar { display: inline; }

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    This use of t he display propert y is anot her nonsensical bit of CSS. But it does t he j ob: I t t ricks I E int o rem oving t he ext ra right - hand m argin. ( See Sect ion 11.1 for a full explanat ion.) Two down, one t o go. I nt ernet Explorer 5 on Windows incorrect ly calculat es t he widt h of t he sidebar, so it looks t hinner t han in ot her browsers. Blam e it on t he old I E 5 box m odel bug ( see Sect ion 7.5.3) . 5. To fa t t e n u p t h e sk in n y side ba r , a dd t h is pr ope r t y t o t h e * h t m l .side ba r st yle : width: 222px;

    Why 222 pixels? The .sidebar st yle you creat ed in st ep 4 in Sect ion 7.7.4 has a widt h of 200 pixels. All ot her browsers dedicat e 200 pixels t o t he cont ent onlyt he headline and bullet ed list . I E 5, on t he ot her hand, includes t he widt hs of t he borders and padding as part of t his 200 pixels, m aking t he act ual area dedicat ed t o t he cont ent m uch sm aller in t hat browser. For I E 5 t o provide t he sam e room as ot her browsers for t he headline and bullet ed list , you need t o give a widt h value equal t o t he com bined widt h of t he cont ent , borders, and padding. So, 200 pixels ( t he widt h value for t he cont ent ) plus 2 pixels ( t he widt h of t he left and right borders) , plus 20 pixels ( t he widt hs of t he left and right padding) equals 222 pixels. At t his point , you've successfully t ricked I E 5 t o display t he sidebar at t he sam e widt h as all ot her browsers. But you're not off t he hook yet . Because I E 6 also get s t his widt h sent t o it , you m ust t ell I E 6 t o reset t he widt h propert y back t o 200 pixels. 6. Add on e fin a l pr ope r t y t o t h is st yle so t h a t it look s lik e t h is: * html .sidebar { display: inline; width: 222px; w\idth: 200px; }

    No, t hat backslash isn't a t ypo, nor is it t eenage t ext - m essaging slang for " your j eans are t oo t ight ." The backslash in t he propert y nam e w\ idt h is j ust anot her exam ple of st range- but - t rue browser t rickery. I E 5 ignores t he m isspelled propert y, while I E 6 underst ands t hat it 's t he widt h propert y and t hat you're set t ing it s value back t o 200px. ( See Sect ion 7.5.3 for all t he gruesom e det ails.) 7. Sa ve t h e file a n d pr e vie w t h e pa ge in I n t e r n e t Ex plor e r 5 or 6 on W in dow s. The page should now look like Figure 7- 18 in t hose browsers as well. Dealing wit h t hese browser bugs is an unfort unat e realit y for every Web developer. You'll learn solut ions ( also known as hacks) t o part icular bugs t hroughout t his book. Also, in Chapt er 14, you'll learn even m ore st rat egies for dealing wit h hacks used t o fix I nt ernet Explorer browser bugs.

    7.7.6. Going Further To t ry out your newfound skills, t ry t his exercise on your own: Creat e a class st yle for form at t ing t he copyright not ice t hat appears at t he bot t om of t he sidebar.ht m l page ( called, say, .copyright ) . I n t his st yle, add a border above t he copyright not ice, change it s t ext color, shrink it s font size, and change t he t ype t o uppercase. ( Hint : Use t he t ext - t ransform

    Section 7.7. Tutorial: Margins, Backgrounds, and Borders

    propert y discussed in Sect ion 6.3.2.) Aft er you've creat ed t he st yle, apply it t o t he paragraph wit h t he copyright not ice. The solut ion's in t he sidebar_finished.ht m l file inside t he ch07_finished folder.

    Chapter 8. Adding Graphics to Web Pages

    Chapter 8. Adding Graphics to Web Pages No m at t er how m uch you gussy up your t ext or fiddle wit h borders and m argins, not hing affect s t he appearance of your sit e m ore t han t he im ages you add t o it . And once again, CSS gives you m ore im age cont rol t han HTML ever dream ed of. You can work wit h graphics in CSS on t wo front s: t he < im g> t ag and t he background- im age propert y ( which you can at t ach t o any num ber of t ags) . This chapt er delves int o som e of t he creat ive ways you can deploy im ages wit h CSS. The best way t o learn how t o use graphics in CSS is t o see t hem in act ion, so t his chapt er has t wocount 'em , t wot ut orials. By creat ing a phot o gallery Web page and using im ages for overall page st yling, you'll be an im age- slinging pro in no t im e.

    Section 8.1. CSS and the Tag

    8.1. CSS and the Tag The venerable < im g> t ag has been t he workhorse of phot o- heavy Web sit es since t he beginning of t he World Wide Web. Even sit es wit hout phot os use it t o add logos, navigat ion but t ons, and illust rat ions. While CSS doesn't have any propert ies specifically aim ed at form at t ing im ages, you can t ake advant age of t he CSS propert ies you've already learned t o enhance your sit e's graphics. For exam ple, t he border propert y's a quick and sim ple way t o fram e an im age or unify t he look of a gallery of phot os. Here's a rundown of t he CSS propert ies m ost com m only used wit h im ages: ●







    Bor de r s. Use one of t he m any border propert ies ( Sect ion 7.3) t o fram e an im age. You'll see an exam ple of t his in t he t ut orial in Sect ion 8.6.1. Since each border side can be a different color, st yle, and widt h, you've got lot s of creat ive opt ions here. Pa ddin g . The padding propert y ( Sect ion 7.2) adds space bet ween a border and an im age. By put t ing a lit t le breat hing room bet ween a phot o and it s fram e, padding sim ulat es t he fiberboard m at t hat 's used in t radit ional pict ure fram es t o surround and offset t he im age. And by set t ing a background color ( Sect ion 7.4) , you can even change t he color of t he " m at ." Floa t . Float ing an im age m oves it t o eit her t he left or right edge of t he page, orif t he im age is cont ained in anot her layout elem ent such as a sidebart he im age's cont aining elem ent ( Sect ion 7.2.1) . Text and ot her page elem ent s t hen wrap around t he im age. You can even float m ult iple im ages t o creat e a flexible, m ult i- row im age gallery. You'll see an exam ple of t his in t he t ut orial in Sect ion 8.6.3. M a r gin s. To add space bet ween an im age and ot her page cont ent , use t he m argin propert y ( Sect ion 7.2) . When you float an im age, t he t ext t hat wraps around it is usually uncom fort ably close t o t he im age. Adding a left m argin ( for right - float ed im ages) or right m argin ( for left - float ed im ages) adds space bet ween t ext and t he graphic.

    I n m ost cases, you won't creat e a st yle for t he < im g> t ag it self. Form at t ing t his t ag's t oo broad a brush, since it form at s all im ages on your pageeven t hose wit h very different funct ions such as t he logo, navigat ion but t ons, phot os, and even graphic ads. You wouldn't , aft er all, want t he sam e black fram e around all of t hose im ages. I nst ead, you should use a class st yle, such as .galleryI m age, or .logo t o apply t he st yle select ively. Anot her approach is t o use a descendent select or ( Sect ion 3.1) t o t arget im ages grouped t oget her in one sect ion of a page. I f you have a gallery of phot os, you can place all of t he phot os inside a < div> t ag wit h an I D nam e of gallery, and t hen creat e a st yle for j ust t he im ages inside t hat < div> , like t his: # gallery im g.

    Section 8.2. Background Images

    8.2. Background Images The background- im age propert y is t he key t o m aking visually st unning Web sit es. Learn how t o use it and it s cousin propert ies, and you can m ake your sit e st and head and shoulders above t he rest . For an exam ple of t he power of background im ages, check out www.csszengarden.com ( Figure 8- 1) . The HTML for bot h t he pages shown here is exact ly t he sam e; t he visual differences are accom plished by using different background im ages. How's t hat for CSS power? I f you've built a few Web sit es, you've probably used an im age for t he background of a pageperhaps a sm all graphic t hat repeat s in t he background of t he browser window creat ing a ( hopefully) subt le pat t ern. That t im e- honored HTML m et hod used t he < body> t ag's background at t ribut e. But CSS does t he sam e j ob bet t er.

    Note: In the next few pages, you'll meet three background image properties by learning the individual CSS code for each one. Later in the chapter you'll learn a shorthand method that'll save you a lot of typing.

    Figu r e 8 - 1 . CSSze n ga r de n .com sh ow ca se s t h e pow e r of Ca sca din g St yle Sh e e t s by de m on st r a t in g h ow you ca n t r a n sfor m a sin gle H TM L file in t o t w o u t t e r ly diffe r e n t look in g pa ge s w it h t h e h e lp of CSS. Th e r e a l se cr e t t o m a k in g e a ch of t h e w on de r fu l de sign s look u n iqu e is t h e e x t e n sive u se of ba ck gr ou n d im a ge s. ( I n fa ct , w h e n you look a t t h e se pa ge s' H TM L code , you 'll se e t h e r e isn 't a sin gle < im g> t a g in it .)

    Section 8.2. Background Images

    Section 8.2. Background Images

    The background- im age propert y adds a graphic t o t he background of an elem ent . To put an im age in t he background of a Web page, you can creat e a st yle for t he < body> t ag: body { background-image: url(images/bg.gif); }

    The propert y t akes one value: t he keyword url, followed by a pat h t o t he graphic file enclosed in parent heses. You can use an absolut e URL like t hisurl( ht t p: / / www.cosm ofarm er.com / im age/ bg.gif) or a docum ent - or root - relat ive pat h like t hese: url(../ images/bg.gif) /* document-relative */ url(/images/bg.gif) /* root-relative */

    As explained in t he box in Sect ion 8.3, docum ent - relat ive pat hs provide direct ions in relat ion t o t he st yle sheet file, not t he HTML page you're st yling. These will be one and t he sam e, of course, if you're using an int ernal st yle sheet , but you need t o keep t his point in m ind if you're using an ext ernal st yle sheet . Say you've got a folder nam ed st yles( cont aining t he sit e's st yle sheet s) and a folder nam ed im ages ( holding t he sit e's im ages) . Bot h t hese folders are locat ed in t he sit e's m ain folder along wit h t he hom e page ( Figure 82) . When a visit or views t he hom e page, t he ext ernal st yle sheet 's also loaded ( st ep 1 in Figure 8- 2) . Now, say t he ext ernal st yle sheet includes a st yle for t he < body> t ag wit h t he background im age propert y set t o use t he graphic file bg.gif in t he im ages folder. The docum ent - relat ive pat h would lead from t he st yle sheet t o t he graphic ( st ep 2 in Figure 8- 2) . I n ot her words, t he st yle would look like t his: body { background-image: url(../images/bg.gif);

    This pat h breaks down like t his: ../ m eans " go up one level" ( t hat is, up t o t he folder cont aining t he st yles folder) ; im ages/ m eans " go t o t he im ages folder" ; and bg.gif specifies t hat file.

    Figu r e 8 - 2 . D ocu m e n t - r e la t ive pa t h s a r e ca lcu la t e d in r e la t ion t o t h e st yle sh e e t ,

    Section 8.2. Background Images

    n ot t h e W e b pa ge be in g st yle d.

    I n t he exam ples so far, t he pat h isn't enclosed in quot es as in HTML but quot es are fine, t oo. I n CSS, all t hree of t he following code lines are kosher:

    background-image: url(images/bg.gif); background-image: url("images/bg.gif"); background-image: url('images/bg.gif');

    Note: Internet Explorer 5 for Mac doesn't recognize URLs that are specified inside of single quotes like this: url(' images/ bg.gif').

    Section 8.2. Background Images

    UP TO SPEED URL Types I n CSS, you need t o specify an URL when you add a background im age or at t ach an ext ernal st yle sheet using t he @im port m et hod ( Sect ion 2.4.2) . An URL or Uniform Resource Locat or is a pat h t o a file locat ed on t he Web. There are t hree t ypes of pat hs: absolut e pat h, root relat ive pat h, and docum ent - relat ive pat h. All t hree sim ply indicat e where a Web browser can find a part icular file ( like anot her Web page, a graphic, or an ext ernal st yle sheet ) . An absolut e pat h is like a post al addressit cont ains all t he inform at ion needed for a Web browser locat ed anywhere in t he world t o find t he file. An absolut e pat h includes ht t p: / / , t he host nam e, and t he folder and nam e of t he file. For exam ple: ht t p: / / www.cosm ofarm er.com / im ages/ bluegrass.j pg. A root - relat ive pat h indicat es where a file's locat ed relat ive t o a sit e's t op- level foldert he sit e's root folder. A root - relat ive pat h doesn't include ht t p: / / or t he dom ain nam e. I t begins wit h a / ( slash) indicat ing t he root folder of t he sit e ( t he folder t he hom e page is in) . For exam ple / im ages/ bluegrass.j pg indicat es t hat t he file bluegrass.j pg is locat ed inside a folder nam ed im ages, which is it self locat ed in t he sit e's t op- level folder. An easy way t o creat e a root - relat ive pat h is t o t ake an absolut e pat h and st rip off t he ht t p: / / and t he host nam e. A docum ent - relat ive pat h specifies t he pat h from t he current docum ent t o t he file. When it com es t o a st yle sheet , t his m eans t he pat h from t he st yle sheet t o t he specified file, not t he pat h from t he current Web page t o t he file. Here are som e t ips on which t ype t o use: ●





    I f you're point ing t o a file t hat 's not on t he sam e server as t he st yle sheet , you m ust use an absolut e pat h. I t 's t he only t ype t hat can point t o anot her Web sit e. Root - relat ive pat hs are good for im ages st ored on your own sit e. Since t hey always st art at t he root folder, you can m ove t he st yle sheet around wit hout affect ing t he pat h from t he root t o t he im age on t he sit e. However, t hey're difficult t o use when first building your designs: you can't preview root - relat ive pat hs unless you're viewing your Web pages t hrough a Web servereit her your Web server out on t he I nt ernet , or a Web server you've set up on your own com put er for t est ing purposes. I n ot her words, if you're j ust opening a Web page off your com put er using t he browser's File Open com m and, t hen you won't see any im ages placed using root - relat ive pat hs. Docum ent - relat ive pat hs are t he best when you're designing on your own com put er wit hout t he aid of a Web server. You can creat e your CSS files and t hen review t hem in a Web browser sim ply by opening a Web page st ored on your hard drive. These pages will work fine when you m ove t hem t o your act ual, living, breat hing Web sit e on t he I nt ernet , but you'll have t o re- writ e t he URLs t o t he im ages if you m ove t he st yle sheet t o anot her locat ion on t he server.

    Section 8.3. Controlling Repetition

    8.3. Controlling Repetition One problem wit h t he old HTML background at t ribut e is t hat t he graphic always t iles, filling up t he ent ire background of a Web page. ( Not only t hat , it 's being phased out from current HTML st andards.) Fort unat ely, CSS gives you far great er cont rol. Using t he background- repeat propert y you can specify how ( or if at all) an im age t iles:

    background-repeat: no-repeat;

    The propert y accept s four values: repeat , no- repeat , repeat - x, and repeat - y: ●

    repeat is t he norm al set t ing for background im ages t hat you want t o display from left t o right and t op t o bot t om unt il t he ent ire space is filled wit h a graphic ( Figure 8- 3) .

    Figu r e 8 - 3 . Be ca r e fu l w h e n t ilin g im a ge s in t h e ba ck gr ou n d of a W e b pa ge . Ch oose a n im a ge w it h ou t a lot of con t r a st t h a t t ile s se a m le ssly ( le ft ) . An im a ge w it h t oo m u ch con t r a st ( r igh t ) , m a k e s t e x t h a r d t o r e a d.







    no- repeat displays t he im age a single t im e, wit hout t iling or repet it ion. I t 's a very com m on opt ion, and you'll frequent ly use it when placing im ages int o t he background of t ags ot her t han t he body. You can use it t o place a logo in t he upper corner of a page or for using cust om graphics for bullet s in list s, t o nam e a couple. ( You'll see t he bullet exam ple in act ion in t he t ut orial in Sect ion 8.7.3.) I n anot her exam ple, you'll use it at t he t op of a < div> t ag t o creat e a rounded edge at t he t op of a box ( Sect ion 8.7.4) . repeat - x repeat s an im age horizont ally along t he x- axis ( t he horizont al widt h of t he page, if your geom et ry's rust y) . I t 's perfect for adding a graphical banner t o t he t op of a Web page ( Figure 8- 4, left ) or a decorat ive border along t he t op or bot t om of a headline. ( See Sect ion 8.7.2 in t he t ut orial for an exam ple of t his effect .) repeat - y repeat s an im age vert ically along t he y- axis ( t he vert ical lengt h of t he page) . You can use t his set t ing t o add a graphic sidebar t o a page ( Figure 8- 4, right ) or t o add a repeat ing drop shadow t o eit her side of a page elem ent ( like a

    Section 8.3. Controlling Repetition

    sidebar) .

    Section 8.4. Positioning a Background Image

    8.4. Positioning a Background Image Placing and t iling a background im age is j ust half t he fun. Wit h t he background- posit ion propert y, CSS let s you cont rol t he exact placem ent of an im age in a num ber of ways. You can specify bot h t he horizont al and vert ical st art ing point s for a graphic in t hree wayskeywords, exact values, and percent ages.

    Figu r e 8 - 4 . Add gr a ph ic ba ck gr ou n ds t o t h e ba n n e r s a n d side ba r s of a pa ge by t a k in g a dva n t a ge of t h e t ilin g con t r ol offe r e d by t h e r e pe a t - x ( le ft ) a n d r e pe a t - y ( r igh t ) opt ion s.

    8.4.1. Keywords You get t wo set s of keywords t o work wit h. One cont rols t he t hree horizont al posit ionsleft , cent er, right and t he ot her cont rols t he t hree vert ical posit ionst op, cent er, bot t om ( Figure 8- 5) . Suppose you want t o place a graphic direct ly in t he m iddle of a Web page. You can creat e a st yle like t his: body { background-image: url(bg_page.jpg); background-repeat: no-repeat; background-position: center center; }

    To m ove t hat graphic t o t he t op- right corner, j ust change t he background posit ion t o t his: background-position: right top;

    Note: If you've decided to tile an image (by setting background-repeat to one of the values listed in the previous section), then the background-position property controls the starting point of the first tile. So, for example, if you use the repeat option, you'll still see the entire background filled by the image. It's just that the position of the first tile changes based on which background-position setting you used.

    Section 8.4. Positioning a Background Image

    Keywords are really useful when you want t o creat e vert ical or horizont al banners. I f you want ed a graphic t hat 's cent ered on a page and t iled downwards in order t o creat e a backdrop for cont ent ( Figure 8- 6, left ) , t hen you'd creat e a st yle like t his: body { background-image: url(background.jpg); background-repeat: repeat-y; background-position: center top; }

    Figu r e 8 - 5 . You ca n u se k e yw or ds t o posit ion a n im a ge in t h e ba ck gr ou n d. Th e or de r in w h ich you spe cify t h e k e yw or ds doe sn 't m a t t e r t op ce n t e r a n d ce n t e r t op bot h h a ve t h e sa m e e ffe ct .

    Likewise, using t he bot t om , cent er, or t op keywords you can posit ion a horizont ally repeat ing im age using repeat - x ( Sect ion 8.3) in a part icular place on t he page ( or wit hin a st yled elem ent ) . Use t he t echnique shown on t he right side of Figure 8- 6, t o posit ion a line under headlines in t he t ut orial in Sect ion 8.7.2.

    Figu r e 8 - 6 . Use t h e ba ck gr ou n d- posit ion pr ope r t y w h e n t ilin g a n im a ge e it h e r ve r t ica lly ( le ft ) or h or izon t a lly ( r igh t ) . I n t h e le ft im a ge , t h e gr a ph ic is a w ide w h it e box w it h dr op sh a dow s on t h e le ft a n d r igh t e dge s. Th e pa ge 's ba ck gr ou n d color is gr a y, so t h e t e x t of t h e pa ge look s lik e it 's on a w h it e pie ce of pa pe r floa t in g a bove t h e scr e e n .

    Section 8.4. Positioning a Background Image

    BROWSER BUG Bottoming Out in Firefox When displaying an im age in t he background of a Web page, Firefox doesn't always vert ically posit ion t he im age in t he way you'd expect . For exam ple, if you set t he vert ical posit ion t o bot t om , t he im age doesn't always appear at t he bot t om of t he browser window. This happens when t he cont ent on a page is short er t han t he browser window is t all. I f t he Web page has only a couple of paragraphs of t ext and it 's displayed on a really large m onit or, Firefox t reat s t he " bot t om " as t he bot t om of t he last paragraph, not t he bot t om of t he browser window. I f you run int o t his annoyance, t hen j ust add t his st yle t o your st yle sheet : ht m l { height : 100% ; } .

    8.4.2. Precise Values You can also posit ion background im ages using pixel values or em s. You use t wo values: one t o indicat e t he dist ance bet ween t he im age's left edge and t he cont ainer's left edge, and anot her t o specify t he dist ance bet ween t he im age's t op edge and t he st yle's t op edge. ( Put anot her way, t he first value cont rols t he horizont al posit ion, t he second value cont rols t he vert ical posit ion.) Say you want cust om bullet s for a list . I f you add a background im age t o t he < li> t ag, t he bullet s oft en don't line up exact ly ( see Figure 87, t op) . So you can j ust nudge t he bullet s int o place using t he background- posit ion propert y ( Figure 8- 7, bot t om ) . I f t he list would look bet t er wit h, say, t he bullet s five pixels fart her t o t he right and eight pixels fart her down, t hen add t his declarat ion t o t he st yle defining t he background im age: background-position:5px 8px;

    Figu r e 8 - 7 . Usin g cu st om im a ge s for bu lle t s som e t im e s r e qu ir e s ca r e fu l posit ion in g, so t h a t t h e bu lle t gr a ph ic a ppe a r s t h e cor r e ct dist a n ce fr om , a n d pe r fe ct ly ce n t e r e d on , t h e list it e m 's t e x t .

    Section 8.4. Positioning a Background Image

    You can't specify dist ances from t he bot t om or right using pixel or em m easurem ent s, so if you want t o m ake sure an im age is placed in t he exact bot t om right corner of t he page or a st yled elem ent , t hen use keywords ( bot t om right ) or percent ages, as discussed next . However, you can use negat ive values t o m ove an im age off t he right edge or above t he t op edge, hiding t hat port ion of t he im age from view. You m ay want t o use negat ive values t o crop out part of a pict ure. Or, if t he background im age has lot s of ext ra whit e space at t he t op or left edge, you can use negat ive values t o elim inat e t hat ext ra space.

    8.4.3. Percentage Values Finally, you can use percent age values t o posit ion a background im age. Using percent ages in t his m anner is t ricky, and if you can achieve t he effect you're aft er wit h t he keyword or precise values discussed previously, t hen use t hem . But you have t o use percent ages t o posit ion an elem ent in a spot t hat 's proport ional t o t he widt h of an elem ent . For exam ple, if you want t o place a graphic t hree- quart ers of t he way across a headline, and you don't know t he widt h of t he elem ent .

    Note: Percentage values are also useful for a little trick often used with float-based layouts to give left and right sidebars background colors or graphics that span the entire height of a Web page (see the Note in Section 11.1.1).

    As wit h pixel or em values, you supply t wo percent ages: one t o indicat e t he horizont al posit ion and t he second t o indicat e t he vert ical posit ion. What t he percent age is m easuring is a lit t le t ricky. I n a nut shell, a percent age value aligns t he specified percent age of t he im age wit h t he sam e percent age of t he st yled elem ent . What ? The best way t o underst and how percent age values work is t o look at a few exam ples. To posit ion an im age in t he m iddle of a page ( like t he one shown in t he cent er of Figure 8- 8) you'd writ e t his:

    background-position:50% 50%;

    This declarat ion places t he point on t he im age t hat 's 50 percent from it s left edge direct ly on t op of t he point t hat 's 50 percent from t he left edge of t he page ( or what ever elem ent you've st yled wit h t he background im age) . The declarat ion also aligns t he point on t he im age t hat 's 50 percent from it s t op wit h t he point t hat 's 50 percent from t he t op edge of t he page or st yled elem ent . I n ot her words, t he cent er of t he im age is aligned wit h t he cent er of t he elem ent . This m eans t hat , when using percent ages, t he exact point on t he im age t hat 's being aligned can be a m oving t arget . ( That 's because your st yled elem ent 's posit ioning percent ages can change if your visit ors resize t heir browsers.) As wit h pixel and em values, you can specify negat ive percent age values, t hough t he result s can be hard t o predict . You can also m ix and m at ch pixel/ em values wit h percent age values. For exam ple, t o place an im age t hat 's 5 pixels from t he elem ent 's left edge, but placed in t he m iddle of t he elem ent 's height , you could use t his: background-position: 5px 50%;

    Section 8.4. Positioning a Background Image

    Due t o poor browser support , don't m ix and m at ch percent ages or pixels/ em s wit h keywords: t op 50px, for exam ple. Som e browsers can handle t his com binat ion, but som e can't .

    Note: Although background images can raise the visual quality of your Web pages, they usually don't show up if your visitor prints the page. Most browsers can print out the backgrounds, but it usually requires extra work on your visitor's part. If you plan to have your visitors print pages from your site, then you may want to keep using the tag to insert mission-critical images like your site logo, or a map to your store.

    Figu r e 8 - 8 . Ea ch of t h e fou r im a ge s pict u r e d h e r e h a ve be e n posit ion e d on t h is W e b pa ge ( r e pr e se n t e d by t h e la r ge bla ck box ) u sin g pe r ce n t a ge va lu e s. W h e n u sin g pe r ce n t a ge va lu e s, fir st ide n t ify t h e " a n ch or poin t " on t h e im a ge : 5 0 pe r ce n t 5 0 pe r ce n t , for e x a m ple , is t h e ce n t e r of t h e m iddle im a ge . N e x t , ide n t ify t h e 5 0 / 5 0 poin t on t h e pa ge it se lf: a ga in , t h a t w ou ld be dir e ct ly in t h e ce n t e r of t h e pa ge . Th a t spot 's w h e r e t h e im a ge 's a n ch or poin t ge t s pla ce d. Th e t h r e e ot h e r im a ge s a r e a ll posit ion e d in t h e sa m e w a y.

    8.4.4. Fixing an Image in Place Norm ally, if t here's a background im age on a Web page and t he visit or has t o scroll down t o see m ore of t he page, t he background im age scrolls as well. As a result , any pat t ern in t he background of t he page appears t o m ove along wit h t he t ext . Furt herm ore, when you have a non- repeat ing im age in t he background, it can pot ent ially scroll off t he t op of t he page out of view. I f you've placed t he sit e's logo or a wat erm ark graphic in t he background of t he page, t hen you m ay not want it t o disappear when visit ors scroll.

    Section 8.4. Positioning a Background Image

    The CSS solut ion t o such dilem m as is t he background- at t achm ent propert y. I t has t wo opt ionsscroll and fixed. Scroll is t he norm al Web browser behavior; t hat is, it scrolls t he background im age along wit h t he t ext and ot her page cont ent . Fixed, however, keeps t he im age in place in t he background ( see Figure 8- 9) . So if you want t o place your com pany's logo in t he upper left corner of t he Web page, and keep it t here even if t he viewer scrolls, t hen you can creat e a st yle like t his: body { background-image: url(images/logo.gif); background-repeat: no-repeat; background-attachment: fixed; }

    The fixed opt ion's also very nice when using a repeat ing, t iled background. When you have t o scroll, t he page's t ext disappears off t he t op, but t he background doesn't m ove: t he page cont ent appears t o float gracefully above t he background.

    Figu r e 8 - 9 . Look in g for a w a y t o n a il dow n a sit e logo ( lik e t h e Cosm oFa r m e r 2 .0 im a ge ) so t h a t w h e n vie w e r s scr oll dow n t h e pa ge t h e logo st a ys in pla ce ? Usin g t h e fix e d opt ion for t h e ba ck gr ou n da t t a ch m e n t pr ope r t y, you ca n lock a ba ck gr ou n d im a ge in pla ce . Th a t w a y, e ve n if t h e pa ge is ve r y lon g a n d t h e visit or h a s t o scr oll dow n , t h e im a ge r e m a in s visible on t h e W e b pa ge ( bot t om ) .

    Section 8.4. Positioning a Background Image

    Note: CSS lets you "fix" the background image for a style applied to any element, not just the tag. However, the Windows versions of Internet Explorer 6 and earlier only understand the background-attachment property when used with a style applied to the tag.

    Section 8.5. Using Background Property Shorthand

    8.5. Using Background Property Shorthand As you can see from t he exam ples above, t o really t ake cont rol of background im ages you need t o harness t he power of several different background propert ies. But t yping out background- im age, backgroundat t achm ent , and so on again and again can really t ake it s t oll on your hands. But t here's an easier wayt he background short hand propert y. You can act ually bundle all t he background propert ies ( including t he background- color propert y you learned about last chapt er) int o a single line of st ream lined CSS. Sim ply t ype background followed by t he values for background- color, background- im age, background- at t achm ent , and background- posit ion. The following st yle set s t he background t o whit e, and adds a non- repeat ing fixed background im age sm ack dab in t he m iddle of t he page:

    FREQUENTLY ASKED QUESTION Finding Free Imagery I 'm not an art ist . I can't draw, can't paint , don't even own a digit al cam era. Where can I find art work for m y sit e? Thank goodness for t he Web. I t 's t he one- st op shop for creat ive geniuses who couldn't paint t hem selves int o a corner if t hey t ried. There are plent y of pay- t o- download sit es for st ock phot os and illust rat ions, but t here are also quit e a few com plet ely free opt ions. For phot os, check out Morgue File ( www.m orguefile.com ) , which despit e t he grisly nam e has m any wonderful phot os supplied free of charge by people who love t o t ake pict ures. The Creat ive Com m ons sit e provides opt ions as well: ht t p: / / creat ivecom m ons.org/ im age/ . Open Phot o ( ht t p: / / openphot o.net / gallery/ browse.ht m l) also supplies im ages based on Creat ive Com m ons licenses. ( Alt hough t hey don't cost m oney, not all phot os on t hese sit es can be used in com m ercial proj ect s. Make sure you read t he fine print for any phot o you wish t o use.) I f you're looking for bullet s t o add t o list s, icons t o supercharge your navigat ion bar, or pat t erns t o fill t he screen, t here are plent y of sit es t o choose from . Bullet Madness ( www. st ylegala.com / feat ures/ bullet m adness/ ) offers 200 bullet s including variat ions on t he com m on arrow, circle and square as well as m ore det ailed bullet s represent ing soft ware icons, iPods, folders, and m ore. Som e Random Dude ( no, really; t hat 's t he nam e of t he Web sit e) offers a set of 121 icons free of charge: www.som erandom dude.net / srdproj ect s/ sanscons. And if you're looking for int erest ing t iling pat t erns, check out t he pat t erns on t hese sit es: Kaliber10000 ( www.k10k.net / fram es.aspx?sect ion= pat t erns) , Pat t ern4u ( www. kollerm edia.at / index.php/ pat t ern4u/ ) , and Squidfingers ( ht t p: / / squidfingers.com / pat t erns/ ) .

    body { background: #FFF url(bullseye.gif) scroll center center no-repeat; }

    You don't need t o specify all of t he propert y values eit her. You can use one or any com binat ion of t hem . For

    Section 8.5. Using Background Property Shorthand

    exam ple: background: yellow is t he equivalent of background- color: yellow. Any propert y value you leave out sim ply revert s t o it s norm al behavior, so say you specified only an im age: background: url(image/bullseye.gif)

    That 's t he equivalent of t his: background: url(image/bullseye.gif) fixed left top repeat;

    Because t he background propert y is so m uch fast er t o t ype, and it achieves all t he sam e ends as it s longwinded siblings, use it liberally when adding background im ages ( and colors) t o your st yles.

    Section 8.6. Tutorial: Creating a Photo Gallery

    8.6. Tutorial: Creating a Photo Gallery A phot o gallery's a perfect exam ple of an eye- cat ching Web page. This t ut orial brings t oget her a variet y of im age st yling t echniques. You'll form at im ages wit h fram es and capt ions, creat e a phot o gallery t hat 's flexible enough t o look great in a variet y of window sizes, and use background im ages t o creat e professional- looking drop shadows. To get st art ed, you need t o download t he t ut orial files locat ed on t his book's com panion Web sit e at www.sawm ac.com / css/ . Click t he t ut orial link and download t he files. All of t he files are enclosed in a ZI P archive, so you need t o unzip t hem first . ( There are det ailed inst ruct ions on t he Web sit e.) The files for t his t ut orial are in t he chapt er_08 folder.

    8.6.1. Framing an Image 1. La u n ch a W e b br ow se r a n d ope n t h e file ch a pt e r _ 0 8

    im a ge _ e x

    im a ge .h t m l.

    As usual, you'll be working on a Web page from Cosm oFarm er.com ( Figure 8- 10) . I n t his case, t here's already an ext ernal st yle sheet at t ached t o t he page, adding som e basic t ext form at t ing.

    Figu r e 8 - 1 0 . Be for e a n d a ft e r CSS, t h a t is. I f you r e ly j u st on H TM L, im a ge s t a k e u p lot s of spa ce ( le ft ) . W it h a lit t le CSS ( r igh t ) you ca n n ice ly fr a m e a n im a ge a n d m ove it ou t of t h e w a y.

    2. Ope n t h e file im a ge .h t m l in you r fa vor it e t e x t e dit or . St art by adding an int ernal st yle sheet and an em pt y class st yle.

    Section 8.6. Tutorial: Creating a Photo Gallery

    Note: The same caveat that you've read in previous tutorials about creating internal style sheets applies here. (See the box in Section 3.1.) In the final tutorial in this chapter, you'll go through the process of converting an internal style sheet into an external style sheet. 3. Click dir e ct ly a ft e r t h e < lin k > t a g ( u se d t o a t t a ch t h e e x t e r n a l st yle sh e e t ) , h it Re t u r n , a n d t h e n t ype t h e follow in g:

    This CSS adds a new int ernal st yle sheet j ust above t he closing < / head> t ag. The select or im g.figure t arget s any < im g> t ag wit h t he figure class applied t o it . You'll use t his t o select ively form at only t he im ages you want . 4. Add floa t a n d m a r gin pr ope r t ie s t o t h e st yle you j u st cr e a t e d, lik e so: float: right; margin-left: 10px; margin-bottom: 10px;

    The right float m oves t he im age t o t he right side of t he page, let t ing t he t ext m ove up and wrap around t he phot o's left edge. The left and bot t om m argins give t he phot o a lit t le breat hing room and m ove it away from t he t ext . Next , you'll add a border and som e padding t o m ake t he im age look m ore like a real snapshot . 5. Add bor de r a n d pa ddin g, so t h a t t h e fin ish e d st yle look s lik e t h is: img.figure { float: right; margin-left: 10px; margin-bottom: 10px; border: 1px solid #666; padding: 10px; }

    I f you preview t he page right now, you won't see a change, since t he class st yle has no effect unt il you've added t he class t o a t ag. 6. Loca t e t h e < im g> t a g a n d a dd cla ss= " figu r e " so t h a t t h e t a g look s lik e t h is:

    Now t hat im age t akes on all of t he form at t ing propert ies you defined for t he .figure class st yle. 7. Pr e vie w t h e pa ge in a W e b br ow se r . I t sh ou ld look lik e t h e r igh t im a ge in Figu r e 8 - 1 0 . You can find t he com plet ed version of t his exercise, im age_finished.ht m l in t he chapt er_08_finishe

    im age_ex folder.

    A pict ure m ay be wort h a t housand words, but som et im es you st ill need a few words t o explain a pict ure. So in t he next part of t his t ut orial, you'll add a capt ion below t he phot o.

    Note: Internet Explorer 5 for Windows doesn't display the padding between the photo and its border. D'oh!

    Section 8.6. Tutorial: Creating a Photo Gallery

    8.6.2. Adding a Caption You'll frequent ly want t o add a capt ion t o an im age or phot o t o provide m ore inform at ion about t he subj ect , where t he phot o was t aken, and so on. I nst ead of j ust float ing t he im age, as you did in t he previous exercise, you want t he capt ion t ext t o float as well. The best way t o float bot h is t o wrap t he im age and t he t ext in a cont ainera < div> t agt hat 's float ed as a single unit . This m et hod keeps t he phot o and it s relat ed t ext t oget her. I f you decide lat er t hat you want t o change t heir layout perhaps float t hem t o t he left no problem : You sim ply change t he form at t ing for t he ent ire cont ainer. 1. I n a t e x t e dit or , ope n t h e file ch a pt e r _ 0 8

    ca pt ion _ e x

    ca pt ion .h t m l folde r .

    Begin by adding a lit t le HTML t o creat e t he cont ainer. 2. Loca t e t h e < im g> t a g in t h e code , a n d a dd < div cla ss= " figu r e " > be for e t h a t t a g. This m arks t he beginning of t he cont ainer. Now close t he < div> t o indicat e t he end of t he cont ainer. 3. Fin d t h e closin g < / p> t a g of t h e pa r a gr a ph dir e ct ly a ft e r t h e im a ge a n d t ype < / div> . Th e code sh ou ld n ow look lik e t h is:

    Figure 1: Creeping Bentgrass is best suited for outdoor use and should be avoided by the indoor farmer.



    I n previous t ut orials you creat ed a new, int ernal st yle sheet . I n t his exercise, you'll edit t he exist ing ext ernal st yle sheet ( st yles.css) t hat 's linked t o t his Web page. 4. Ope n t h e file ch a pt e r _ 0 8

    ca pt ion _ e x

    st yle s.css.

    Because t his is an ext ernal st yle sheet , you'll not ice t here's no < st yle> t ag. That t ag's necessary only for int ernal st yle sheet s. 5. Scr oll t o t h e bot t om of t h e file a n d a dd t h e follow in g st yle t o t h e e n d: .figure img { border: 1px solid #666; padding: 10px; }

    This descendent select or ( Sect ion 3.1) affect s any < im g> t ag inside any ot her t ag wit h t he figure class applied t o it in t his case, t he < div> you j ust added. Since you're using a descendent select or here ( and in st ep 7) , you don't need t o add a class t o t he < im g> t ag. As a result , you save a lit t le t yping, cut down on HTML code, and m ake t he page load fast er for your sit e's visit ors. Next , you'll form at t he < div> so t hat it float s t he phot o and capt ion t ext t o t he right edge of t he page. 6. Add t h is st yle t o t h e st yle s.css file : div.figure { float: right;

    Section 8.6. Tutorial: Creating a Photo Gallery

    width: 222px; margin: 15px 10px 5px 10px; }

    You've already used t he float : right propert y in t his t ut orial, and t he m argin adds a lit t le whit e space around all four edges of t he < div> . But what 's t he widt h for, you ask? Alt hough t he phot o has a set widt h ( 200 pixels; see st ep 3) t he capt ion paragraph doesn't . When you don't set a widt h, t he paragraph m akes t he < div> expand wider t han t he phot o. I n t his case, you want t he capt ion t o be j ust as wide as t he phot o and it s fram e. The 222 pixels com es from a lit t le m at h used t o calculat e t he ent ire area t aken up by t he phot o on t he page: while t he phot o is only 200 pixels wide, t he 10 pixels of left and right padding as well as t he im age's 1- pixel left border and 1- pixel right border, m ake t he ent ire widt h of t he phot o equal t o 222 pixels, from border t o border. Next , spruce up t he look of t he capt ion t ext . 7. Add t h e follow in g st yle t o t h e st yle s.css st yle sh e e t : .figure p { font: bold 1em/normal Verdana, Arial, Helvetica, sans-serif; color: #333; text-align: center; }

    This st yle uses som e of t he propert ies you learned about in Chapt er 6 t o creat e a cent er- aligned, bold, and gray capt ion using t he Verdana font . Fort unat ely, t he font short hand propert y ( see Sect ion 6.4.3) in t he first line let s you roll four different propert ies int o a single st yle declarat ion. Again, you're t aking advant age of a descendent select or ( .figure p) t o t arget j ust t he capt ion paragraph. To m ake t he capt ion st and out even m ore, add a background color and border. 8. Add t h r e e pr ope r t ie s t o t h e .figu r e p st yle , lik e so: .figure p { font: bold 1em/normal Verdana, Arial, Helvetica, sans-serif; color: #333; text-align: center; background-color: #e6f3ff; border: 1px dashed #666; padding: 5px; }

    The purpose of t he background- color, border, and padding propert ies should be cleart o creat e a colored box around t he capt ion. Now it 's t im e t o preview your work. 9. Sa ve bot h t h e ca pt ion .h t m l a n d st yle s.css file s a n d pr e vie w t h e ca pt ion .h t m l file in a W e b br ow se r . ( Now you see one reason why it 's easier t o develop a design using an int ernal st yle sheet you need t o work in and save only one file inst ead of t wo.) The page looks great : The phot o and capt ion float t o t he right , and t he capt ion st ands out boldly. There's one sm all problem , t hough: I f you look at t he left and right edges of t he paragraph, you'll not ice t hey're indent ed slight ly and aren't as wide as t he phot o. Here's an exam ple of one of t he m any head- scrat ching sit uat ions you'll find as you work wit h CSS. I n t his case, you've run int o a problem wit h t he cascade. The capt ion t ext is inside a < p> t ag, and, as it happens, < p> t ag in t he st yles.css file. When you look at t hat st yle, you see it set s m argins10 pixels on t he t op and bot t om and right . You want t o override t hose m argins, and you can do so by adding new m argins t o a m ore specific st yle. discussion of specificit y and t he cascade.) Fort unat ely, you already have a m ore specific st yle.figure pso you need st yle t o override t he m argins from t he m ore generic p st yle. 10.

    t here's a t ag st yle for t he and 8 pixels on t he left ( See Sect ion 5.2 for a only add m argins t o t hat

    Section 8.6. Tutorial: Creating a Photo Gallery

    Add a m a r gin pr ope r t y t o t h e .figu r e p st yle , lik e so: .figure p { font: bold 1em/normal Verdana, Arial, Helvetica, sans-serif; color: #333; text-align: center; background-color: #e6f3ff; border: 1px dashed #666; padding: 5px; margin: 10px 0 0 0; }

    This rem oves m argins on all sides of t he capt ion except t he t op, which adds 10 pixels of space bet ween t he capt ion and t he phot o above. 11. Sa ve t h e ca pt ion .h t m l a n d st yle s.css file s. Pr e vie w ca pt ion .h t m l file in a W e b br ow se r . The page should now look like Figure 8- 11. ( You can find a com plet ed version of t his page in t he chapt er_08_finished folder.)

    capt ion_ex

    8.6.3. Building a Photo Gallery Folks used t o rely on t he HTML < t able> t ag t o creat e rows and colum ns for holding t he pict ures in a phot o gallery. But you can achieve t he sam e effect wit h a lit t le CSS and far less HTML.

    Figu r e 8 - 1 1 . W it h t h e u se of a con t a in in g < div> , a r igh t floa t , a n d a lit t le st yle , it 's e a sy t o a dd ca pt ion s t o ph ot os.

    Section 8.6. Tutorial: Creating a Photo Gallery

    Ope n t h e file ch a pt e r _ 0 8

    ga lle r y_ e x

    ga lle r y.h t m l.

    First , a quick review of t he HTML used t o const ruct t he phot o gallery. The page cont ains nine phot os and phot o capt ions. Each phot o and capt ion is cont ained in a < div> wit h a class nam ed figure applied t o it . This < div> funct ions j ust like t he sim ilar < div> used in t he previous exercise for adding a capt ion. The phot o it self is cont ained in anot her < div> wit h a class of phot o:



    Figure 6: The dandelion: scourge of the apartment farmer.



    Note: That second will come in handy for the next exercise, when you learn to add drop shadows to the photos. 2. Loca t e t h e < lin k > t a g n e a r t h e t op of t h e file , pla ce you r cu r sor a ft e r t h a t t a g, a n d t h e n pr e ss En t e r ( Re t u r n ) t o cr e a t e a n e w bla n k lin e . The < link> t ag at t aches an ext ernal st yle sheet cont aining som e basic form at t ing. 3. Add a n in t e r n a l st yle sh e e t . Th e n a dd t w o n e w st yle s, a s follow s:

    These t wo st yles add a border t o each im age in t he gallery, and set t he font , alignm ent , and m argins of t he capt ions. They use descendent select ors t o t arget j ust t he im ages and paragraphs inside t he gallery. All of t he im ages and capt ions are t hem selves wrapped in one < div> wit h an I D of gallery, since enclosing t he group of phot os in anot her < div> provides even m ore form at t ing opt ions. You could set a specific widt h for t he gallery or add a border around it . But t hat enclosing < div> also provides anot her way t o t arget t he phot os and paragraphs using descendent select ors. For exam ple, # gallery im g and # gallery p are also valid descendent select ors in t his case. The m ain difference bet ween t he t wo approaches is t he specificit y of t he st yles ( see Sect ion 5.2) . Because # gallery im g is m ore specific t han .phot o im g, it s form at t ing opt ions override t he .phot o im g st yle. Next , place t he phot os side by side.

    Note: When you insert the internal style sheet, make sure to place it in the page's head section, between the link tag and the closing tag. 4. Add t h e follow in g st yle t o t h e in t e r n a l st yle sh e e t you j u st cr e a t e d: .figure { float: left; width: 210px; margin: 0 10px 10px 10px;

    Section 8.6. Tutorial: Creating a Photo Gallery

    }

    This st yle float s each phot o/ capt ion pair t o t he left . I n effect , it places t he phot os side- by- side unt il t here's no m ore room in t he row. The browser t hen drops t he next phot os down a row, unt il all of t he phot os are displayed one row on t op of t he next . The widt h is t he t ot al widt h of t he phot o plus padding and borders. I n t his exam ple, it 's 200 pixels for t he phot o, 8 pixels for left and right padding, and 2 pixels for left and right borders.

    Tip: In this fictitious photo gallery, each picture's the same width. In the real world, you may have pictures of varying sizes. See the box below for a trick that lets you arrange rows of pictures of different widths. Using different height images won't work (as you'll see in step 5). When you've got images with differing heights, stick with HTML tables.

    POW ER USERS' CLI N I C W h e n On e W idt h D oe sn 't Fit All I t 's a breeze t o set up a phot o gallerylike t he Cosm oFarm er onewhen t he phot os are convenient ly all t he sam e widt h. But what if you have phot os of differing widt hs? One solut ion's t o creat e a st yle for each different widt h and apply t he st yle t o t he < div> wit h t he figure class. ( That 's t ons of work, so it would pay t o do som e phot o edit ing work t o st andardize your phot os t o j ust a handful of different widt hs first .) You can t ake advant age of CSS's abilit y t o apply t wo classes t o one t ag like t his: < div class= " figure w300" > . This < div> t ag has bot h t he figure and w300 class st yles applied t o it . Then creat e a class st yle, for exam ple .w300, and set t he widt h t o t he widt h of t he im age ( in t his case, 300) plus 10 t o cover t he padding and borders: .w300 { widt h: 310 } . For t his t rick t o work, you m ust eit her rem ove t he widt h set t ing on t he .figure st yle or add t he .w300 st yle aft er t he .figure st yle in t he st yle sheet . Here's why: The t wo widt h definit ions conflict ( one's 210 t he ot her's 300) , so t he browser has t o break t he t ie using t he cascade ( see Chapt er 5) . Since .figure and .w300 have t he sam e specificit y, t he one t hat 's defined last in t he st yle sheet wins.

    5. Sa ve t h e file a n d pr e vie w t h e ga lle r y.h t m l pa ge in a W e b br ow se r . I t sh ou ld look lik e t h e le ft im a ge in Figu r e 8 - 1 2 . Adj ust t he widt h of your browser window t o m ake it t hinner and wider and wat ch how t he im ages reflow int o t he space. Ahasom et hing's not quit e right . The second row of im ages has t wo em pt y spaces where phot os should be. This problem occurs because t he capt ion for t he second im age on t he first line is t aller t han t he ot her capt ions on t he line. I m ages t hat j um p down t o anot her row bum p int o t hat capt ion and can't get by it . ( You can read m ore about t his float propert y snafu in Sect ion 7.6.2.) Fort unat ely, t here's a sim ple fix t o t his dilem m a. 6. Re t u r n t o you r t e x t e dit or a n d t h e ga lle r y.h t m l file . Loca t e t h e .figu r e p st yle a n d a dd a h e igh t t o it . Th e fin ish e d st yle sh ou ld look lik e t h is: .figure p { font: 1.1em/normal Arial, Helvetica, sans-serif; text-align: center; margin: 10px 0 0 0; height: 5em; }

    Adding t his propert y set s a uniform height for each capt ion. I n t his case, it 's t all enough t o support t he lines of capt ion t ext . ( I f you needed m ore t ext , you'd j ust increase t he height .)

    Note: You don't need the height property if you're sure each floated element is the same height. This could happen if you don't have captions and all of the photos are the same height, or each caption has the same number of lines of text. 7. Sa ve t h e file a n d pr e vie w t h e pa ge in a W e b br ow se r . Se e t h e r igh t side of Figu r e 8 - 1 2 .

    Section 8.6. Tutorial: Creating a Photo Gallery

    I f you resize t he browser window, t he gallery reform at s it self. Wit h a wider window you can fit four or even five im ages on a row, but if you m ake it sm aller you'll see only one or t wo im ages per row. The gallery looks good, but if you're using I nt ernet Explorer you m ay have not iced anot her problem . I f you resize t he browser window, t he dashed border on t he left edge of t he page disappears. There's a fix for t his crazy bug, t oo.

    Figu r e 8 - 1 2 . Floa t in g e le m e n t s n e x t t o e a ch ot h e r is on e w a y t o sim u la t e t h e colu m n a n d r ow a ppe a r a n ce of a t a ble . Bu t it doe sn 't w or k w e ll if t h e e le m e n t s a r e of va r yin g h e igh t s ( le ft ) . Usin g t h e h e igh t pr ope r t y ca n h e lp you e n for ce e qu a l h e igh t s a n d m a k e su r e e le m e n t s lin e u p cor r e ct ly ( r igh t ) .

    8. At t h e e n d of t h e in t e r n a l st yle sh e e t ( a ft e r a ll ot h e r st yle s) , a dd t h e follow in g: /* IE 5/6 border erase bug */ * html #gallery { width: 100%; }

    As always, when adding st yles t o an int ernal st yle sheet , be sure t o put t he CSS code in bet ween t he opening < st yle> t ag and it s m at ching closing < / st yle> t ag. This st yle uses t he * ht m l hack ( see Sect ion 7.6) t o t arget j ust I E 6 and earlier and apply a propert y t hat m iraculously fixes t he problem . The first line of code/ * I E 5/ 6 border erase bug * / is a CSS com m ent . I t 's j ust a not e t hat let s you know t he purpose of t he following st yle.

    Tip: The end of a style sheet is a good place to group any styles like this one that fix browser bugs. This way, you can quickly identify and remove these

    Section 8.6. Tutorial: Creating a Photo Gallery

    weird styles when the buggy browser finally falls into disuse. Another good idea is to put browser hacks like this into their own external style sheet, as discussed in Section 14.5.2. 9. Sa ve t h e file . You'll im prove on t he gallery's look in t he next exercise.

    8.6.4. Adding Drop Shadows Your gallery looks good, but you can m ake it even m ore im pressive. Adding drop shadows under each phot o lends t he page an illusion of dept h and a realist ic 3- D qualit y. But before you fire up Phot oshop, you'll be glad t o know t here's no need t o add individual drop shadows. I nst ead, you can m ake CSS aut om at ically add a shadow t o any im age you want . gallery_ex folder, First you need a drop shadow graphicj ust an im age wit h fuzzy right and bot t om black edges. There's one in t he chapt er_08 but you can m ake your own in Phot oshop, Fireworks, or any ot her im age edit ing program t hat has a blur or drop shadow filt er. ( I n Fireworks, for exam ple, you'd creat e a whit e box and apply t he drop shadow filt er t o it . Then save t he file in GI F form at .) 1. I n a t e x t e dit or , ope n t h e ga lle r y.h t m l file you com ple t e d in t h e pr e viou s e x e r cise . First , add a background im age t o t he < div> t ag t hat surrounds each im age. 2. Add t h is st yle t o t h e ga lle r y pa ge 's st yle sh e e t : .photo { background: url(drop_shadow.gif) right bottom no-repeat; }

    This .phot o st yle adds a background im agedrop_shadow.gift o t he lower- right corner of t he phot o < div> . The no- repeat value m eans t he graphic won't t ile. I f you preview t he page now, you won't see m uch. That 's because t he drop shadow appears in t he background. On t op is t he phot o it self, which you st yled in st ep 3 in Sect ion 8.6.3 t o have a whit e background, a black border, and four pixels of padding. What you need is a way t o reveal t hat background im age. One clever t echnique pioneered by Richard Rut t er ( www.clagnut .com ) is t o m ove t he im age up and t o t he left a lit t leessent ially m oving it out side of it s cont aining < div> t ag. CSS provides a m echanism known as posit ioning t hat let s you cont rol t he exact placem ent of an elem ent . You'll learn m ore about posit ioning in Chapt er 12, but for now you need t o add only t hree propert ies t o t he .phot o im g st yle you creat ed in st ep 3 in Sect ion 8.6.3 t o reveal t he drop shadow.

    Note: Negative margins are another way to achieve the drop shadow shift. For details, see http://1976design.com/blog/archive/2003/11/14/shadows/. 3. Loca t e t h e . ph ot o im g st yle , a n d a dd t h r e e posit ion in g pr ope r t ie s lik e so: .photo img { border: 1px solid #666; background-color: #FFF; padding: 4px; position: relative; top: -5px; left:-5px; }

    I n a nut shell, t hese t hree propert ies sim ply m ove t he phot o up and t o t he left five pixels, exposing t he underlying drop shadow graphic of t he < div> . I n fact , t he very reason for using a < div> here is t o provide an elem ent t o hold a background im age.

    Section 8.6. Tutorial: Creating a Photo Gallery

    4. Sa ve t h e file a n d pr e vie w t h e pa ge . I t sh ou ld look lik e Figu r e 8 - 1 3 . Each im age has it s own drop- shadow, and you didn't even have t o open Phot oshop!

    Note: The graphic you used here is around 375x375 pixels, so it accommodates images only up to that size. You can use this same technique for larger images, but you'll need to create your own drop shadow.

    Of course, you're not com plet ely doneunless you don't care about support ing I nt ernet Explorer 5. That browser doesn't place t he shadow correct ly. 5. To fix t h e displa y pr oble m in I E 5 , a dd on e la st st yle t o t h e e n d of t h e in t e r n a l st yle sh e e t : /* IE 5 placement bug */ * html #gallery img { width: 100%; }

    You can use t his drop- shadow m et hod on any graphic, not j ust t hose inside a gallery. The key is surrounding t he < im g> t ag wit h a cont ainer < div> , applying a drop shadow graphic t o t hat < div> and offset t ing t he < im g> t ag wit h negat ive t op and left placem ent . Use t his sam e effect t o add a drop shadow t o any box elem ent , such as a sidebar or pull- quot e. You can find a com plet ed version of t his t ut orial in t he chapt er_08_finished

    gallery_ex folder.

    Figu r e 8 - 1 3 . Addin g dr op sh a dow s t o ph ot os give s a pa ge a 3 - D look , a n d in cr e a se s t h e visu a l a ppe a l of a n y ph ot o ga lle r y. For t u n a t e ly, u sin g CSS you ca n e a sily a dd a dr op sh a dow t o a n y pict u r e w it h ou t e ve n t ou ch in g Ph ot osh op.

    Section 8.6. Tutorial: Creating a Photo Gallery

    Note: You may have noticed that the drop shadows you just created have abrupt left and top endings. They don't fade like actual drop shadows. To learn how to create more sophisticated drop shadows, check out www.alistapart.com/articles/cssdrop2/ and www.ploughdeep.com/onionskin/.

    Section 8.7. Tutorial: Using Background Images

    8.7. Tutorial: Using Background Images The CSS background- im age propert y is t he secret weapon of m odern Web design. I t can t urn a ho- hum t ext - heavy Web page int o a dazzling swirl of im agery. Since you can use it t o add an im age t o t he background of any HTML t ag, t he designs you can creat e are lim it ed only by your im aginat ion. The drop shadow exam ple in t he previous t ut orial is j ust one exam ple of creat ive background im age use. Ot her com m on background im age frills include applying a page background and adding cust om bullet s t o unordered list s. You'll explore som e of t hese com m on t asks in t his t ut orial.

    8.7.1. Adding an Image to the Page Background Whet her it 's an int ricat e pat t ern, a logo, or a full- screen phot ograph, im ages appear in t he background of m any a Web page. I n fact , adding an im age t o t he background of a page is probably t he m ost com m on applicat ion of t he back- ground- im age propert y. 1. I n you r t e x t e dit or , ope n t h e file ch a pt e r _ 0 8

    bg_ e x

    side ba r .h t m l.

    This page is sim ilar t o t he one you creat ed in t he last chapt er's t ut orial. I t has a float ed sidebar and uses background colors t o highlight port ions of t he page ( Figure 8- 14, t op) .

    Figu r e 8 - 1 4 . Usin g ba ck gr ou n d im a ge s, you ca n m a k e a n a lr e a dy w e ll- or ga n ize d pa ge ( t op) look m u ch spiffie r ( bot t om ) . Sin ce you ca n a dd im a ge s t o t h e ba ck gr ou n d of a n y t a g on a pa ge , t h e possible pla ce m e n t of gr a ph ics on a pa ge a r e n e a r ly lim it le ss.

    Section 8.7. Tutorial: Using Background Images

    To st art , you'll add a < div> t ag t o creat e a cont ainer for t he page's cont ent . For a change of pace from t he previous exercises, where t he cont ent on t he page always fit t he browser window's widt h, you'll creat e a design t hat 's a set widt h and is cent ered in t he m iddle of t he browser window. 2. Loca t e t h e ope n in g < body> t a g a n d, dir e ct ly be low it , a dd t h e follow in g t a g:

    This opening < div> t ag m arks t he beginning of t he cont ainer. You need t o add a closing < / div> t ag next . 3. N e a r t h e bot t om of t h e file , loca t e t h e closin g < / body> t a g. Add t h is < / div> t a g dir e ct ly a bove it :

    You've wrapped all of t he page's cont ent in a single cont ainer. Now you'll add a st yle defining a widt h for t he cont ainer and cent ering it in t he browser window. This file already has an int ernal st yle sheet t hat provides som e basic form at t ing. You'll add t his new st yle t o t hat st yle sheet . 4. I n se r t t h e follow in g st yle be t w e e n t h e body a n d h 1 t a g st yle s: #wrapper { width: 760px; margin: 15px auto 0 auto; text-align: left; }

    This I D st yle defines how t he < div> you j ust insert ed should look. The 760pixel widt h m eans t he ent ire widt h should fit inside m onit ors t hat have a resolut ion of at least 800x600 pixels ( a safe bet for t he vast m aj orit y of m onit ors out t here t oday) . The m argin propert y uses t he keyword aut o for bot h t he left and right m argins, which t ells a Web browser t o split t he difference bet ween eit her side of t he cont ainer, effect ively cent ering t he cont ainer inside t he browser window. So, if t he browser window of t he visit or viewing t his page is 900 pixels wide, t hen t here'll be 70 pixels of space on bot h t he left and right sides ( 900760= 140; 140 divided by t he t wo sides equals 70 pixels on eit her side) .

    Section 8.7. Tutorial: Using Background Images

    The last st yle declarat iont ext - align: left sim ply aligns all t ext t o t he left edge. Left - alignm ent is how t ext usually appears, but in t his case, you're using t he declarat ion t o help solve a problem in I E 5 for Windows. ( More on t hat in st ep 6.) First , you'll add an im age t o t he page's background. 5. Loca t e t h e body t a g st yle . ( I t 's t h e fir st on e in t h e in t e r n a l st yle sh e e t .) Add t h e follow in g t h r e e lin e s of CSS t o it :

    background-image: url( images/page_bg.jpg); background-repeat: repeat-x; background-position: left top;

    The first line of code point s t o t he im agepage_bg.j pgyou want t o display on t he page. This graphic's a gradient t hat st art s as a vibrant green at t he t op and fades t o whit e at t he bot t om . The graphic isn't as t all as t he page cont ent , so wit hout furt her inst ruct ions, it would t ile over and over across and down t he page. At a cert ain point down t he page, t hat vibrant green would reappear and fade once again downward t o whit e. To prevent t his unsight ly snafu, you've set t he background- repeat propert y so t hat t he im age t iles from left t o right in order t o fit any widt h of browser window, but doesn't t ile down t he page. The last line posit ions t he im age t o st art at t he t op left edge of t he page.

    Note: Using background property shorthand (Section 8.5), you can condense the three lines of code from step 5 (and the background-color property already defined in the body style) into a single line of CSS: background: white url(images/page_bg.jpg) left top repeat-x.

    Finally, com plet e t his st yle by fixing an I E 5 for Windows bug. That browser doesn't underst and t he aut o m argins you set in st ep 4, so it won't cent er t he cont ainer < div> . You need t o add one m ore propert y t o t he st yle for I E 5's benefit . 6. Edit t h e body st yle by a ddin g t h e t e x t - a lign CSS pr ope r t y. Th e com ple t e d st yle sh ou ld look lik e t h is: body { font-family: Tahoma, "Lucida Grande", Arial, sans-serif; font-size: 62.5%; margin: 0; padding: 0; background-color: white; background-image: url(images/page_bg.jpg); background-repeat: repeat-x; background-position: center top; text-align: center; }

    Note: Centering the text on the page using the text-align property forces Internet Explorer 5 to center the container . (IE 6 and 7 don't need this extra help since those browsers understand the auto value used for the left and right margins in step 4.) However, all of the text inside the is aligned in the center as well. Fortunately, you fixed that problem in step 4 when you set the text-align to left, restoring normal alignment to the text inside the . 7. Sa ve t h e file a n d pr e vie w it in a W e b br ow se r . The background graphic's bright green gradient drips down t he page. Unfort unat ely, t he graphic is also in t he t ext 's background, m aking som e part s difficult t o read. You'll t ake care of t hat by adding a background color and graphic t o t he < div> t ag.

    Section 8.7. Tutorial: Using Background Images

    8. Re t u r n t o you r t e x t e dit or a n d t h e side ba r .h t m l file . Edit t h e # w r a ppe r st yle lik e so: #wrapper { width: 760px; margin: 15px auto 0 auto; background: #FFF url( images/wrapper_bg.gif) center top no-repeat; text-align: left; }

    This background propert y short hand set s t he background of t he < div> t o whit e, adds an im age nam ed wrapper_bg.gif t o t he background, cent ers t hat graphic at t he t op of t he < div> , and set s it t o display only once ( no repeat ing) . I f you preview t he page now, you'll see t he area where t he t ext sit s is whit e. You'll also not ice reddish lines on eit her side of t he < div> t hat fade at t he bot t om . The effect 's subt le, but not iceable ( Figure 8- 15) .

    Figu r e 8 - 1 5 . CSS le t s you com bin e a ba ck gr ou n d color a n d a ba ck gr ou n d im a ge , w h ich com e s in r e a lly h a n dy in t h is e x a m ple . Th e m a in t e x t a r e a h a s a w h it e ba ck gr ou n d color t h a t h e lps se pa r a t e t h e t e x t fr om t h e fa din g gr a da t ion in t h e pa ge 's ba ck gr ou n d. I n a ddit ion , a sim ple gr a ph ic of t w o fa din g lin e s on e it h e r side of t h e t e x t a dds a su bt le de t a il t o t h e de sign .

    Section 8.7. Tutorial: Using Background Images

    8.7.2. Replacing Borders with Graphics The border propert y ( Sect ion 7.3) is a useful t ool in your design arsenal, but t he lim it ed num ber of border st yles CSS offers can get boring. A hand- drawn line wit h t he t ext ure of charcoal on rough paper would cat ch your visit ors' at t ent ion bet t er t han a plain, st raight one. You can skip t he border propert y and add any kind of line you want as a background im ageeasy as pie. I n t his t ut orial, you'll replace t he underline below each < h2> t ag wit h a cust om graphic t hat looks like a hand- drawn line. 1. Re t u r n t o you r t e x t e dit or a n d t h e side ba r .h t m l file . Loca t e t h e h 2 t a g st yle , r e m ove t h e bor de r - bot t om pr ope r t y, a n d t h e n a dd t w o ba ck gr ou n d pr ope r t ie s, so t h a t t h e st yle look s lik e t h is: h2 { font-size: 1.8em; color: #7BA505; margin: 10px 5px 0 25px; overflow: hidden; background-image: url( images/underline.gif); background-repeat: repeat-x; }

    The background- im age propert y specifies which graphic t o use in t he background of every < h2> t ag on t he page, while t he repeat - x value m akes sure t hat t he graphic online t iles horizont ally. I n ot her words, no m at t er how long t he < h2> t ag is, t he graphic repeat s, giving t he illusion of one solid line. I f you preview t he file now, you'll see t hat t he underline doesn't exact ly line up. I n fact , it isn't under at all. I t 's above t he headlines! 2. Add t h e follow in g st yle de cla r a t ion t o t h e h 2 st yle be low t h e ba ck gr ou n d- r e pe a t pr ope r t y: background-position: left bottom;

    You've changed t he graphic's st art ing locat ion so it appears at t he left edge and bot t om of t he < h2> t ags. I f you preview t he page now, t hough, you m ay not not ice m uch im provem ent . The underline runs int o t he headline t ext . But t here's an easy fix. Since t he bot t om value used here put s t he graphic at t he bot t om of t he block creat ed by t he < h2> t ag, you need only t o increase t he overall height of t he block t o m ove t he line down a bit . You'll do t his wit h a lit t le bot t om padding. 3. Edit t h e h 2 st yle on e la st t im e , so t h a t it look s lik e t h is: h2 { font-size: 1.8em; color: #7BA505; margin: 10px 5px 0 25px; overflow: hidden; background-image: url( images/underline.gif); background-repeat: repeat-x; background-position: left bottom; padding-bottom: 7px; }

    Section 8.7. Tutorial: Using Background Images

    Padding, as you'll recall from Sect ion 7.2, is t he space bet ween t he border and t he cont ent . I t also increases t he overall height of t he boxin t his case by adding seven pixels of bot t om padding. Now, t he line graphic is placed at t he bot t om of t he h2 block, but in t he em pt y space creat ed by t he bot t om padding. 4. Sa ve t h e file a n d pr e vie w t h e pa ge in a W e b br ow se r . Each < h2> t ag has t he hand- drawn underline. Next you'll t ackle t he sidebar box, m aking it look a lit t le less boxy and j azzing up t he bullet ed list s.

    8.7.3. Using Graphics for Bulleted Lists The average bullet used for unordered list s is a black dot not very inspiring. But you can use t he background- im age propert y t o replace t hose drab bullet s wit h any im age you want . The first st ep's t o hide t he bullet s t hat norm ally appear beside list it em s. 1. Re t u r n t o you r t e x t e dit or a n d t h e side ba r .h t m l pa ge . Loca t e t h e .side ba r li st yle n e a r t h e e n d of t h e in t e r n a l st yle sh e e t . This descendent select or t arget s any < li> t ag t hat appears inside anot her t ag wit h a class of sidebar. 2. Re pla ce t h e t w o CSS pr ope r t ie s in t h e .side ba r li st yle w it h list - st yle : n on e ; t h e st yle sh ou ld n ow look lik e t h is: .sidebar li { list-style: none; }

    This rem oves t he bullet . Now add t he graphic.

    Note: You can just as well apply list-style: none; to a style affecting the
      or tags to remove bullets from each list item. 3. Add t h e follow in g t w o pr ope r t ie s t o t h e .side ba r li st yle : background-image: url(images/flower_bullet.gif); background-repeat: no-repeat;

      You've seen t hese t wo propert ies before. They add an im age t o t he background and t urn off repeat ing so t hat t he graphic appears only once. I f you preview t he page, you'll see t hat t he bullet s current ly overlap t he list t ext and t he list it em s are a lit t le j am m ed t oget her ( Figure 8- 16, left ) . A lit t le padding and m argin will fix t his. 4. Add t w o m or e pr ope r t ie s t o t h e .side ba r li st yle :

      padding-left: 18px; margin-bottom: 6px;

      Section 8.7. Tutorial: Using Background Images

      The left padding adds em pt y space, effect ively m oving t he t ext out of t he way in order t o display t he new bullet icon. The bot t om m argin adds j ust a bit of breat hing room bet ween each list it em ( Figure 8- 16, m iddle) . There's j ust one final flaw. The bullet im age is a t ad t oo high on t he line, causing t he t ip of t he icon t o st ick out t oo far above t he t ext . But you can easily fix t hat wit h t he background- posit ion propert y. 5. Fin ish t h is st yle by a ddin g ba ck gr ou n d- posit ion : 0 px 2 px ; Th e com ple t e d st yle sh ou ld look lik e t h is: .sidebar li { list-style: none; background-image: url( images/flower_bullet.gif); background-repeat: no-repeat; background-position: 0px 2px; padding-left: 18px; margin-bottom: 6px; }

      This last st yle declarat ion posit ions t he bullet icon t o t he far left , t wo pixels from t he t op of t he list it em . I t m oves t he icon down j ust a sm idgen, enough t o m ake t he bullet look perfect .

      Note: As discussed in Section 6.6, this kind of exact positioning is precisely why you should use the background property instead of the liststyle-image property for adding graphic bullets to your lists. 6. Sa ve t h e file a n d pr e vie w t h e pa ge in you r br ow se r . The list should now have fanciful flower icons inst ead of dreary black circles ( Figure 8- 16, right ) .

      Figu r e 8 - 1 6 . Re pla cin g r e gu la r bla ck bu lle t s w it h you r ow n gr a ph ics is e a sy. Ju st a fe w e x t r a st e ps e n su r e t h e bu lle t s a n d t e x t a r e pla ce d in t h e cor r e ct loca t ion .

      8.7.4. Adding Rounded Corners to the Sidebar

      Section 8.7. Tutorial: Using Background Images

      At t his point , t he sidebar, like m uch of t he page, is rat her boxy. To add visual variet y, soft en t he sidebar's appearance wit h som e rounded corners. I n a nut shell, you'll first add a background im age wit h rounded corners t o t he bot t om of t he sidebar. Then, for t he rounded corners at t he t op of t he box, you'll add a background im age t o t he first t ag in t he sidebar ( t he < h3> t ag) . 1. Re t u r n t o you r t e x t e dit or a n d t h e side ba r .h t m l file t h a t you 've be e n w or k in g on . The graphic you'll place in t he bot t om of t he sidebar has a decorat ive phot o and t wo rounded lower corners. 2. Loca t e t h e .side ba r st yle in t h e file 's in t e r n a l st yle sh e e t . Re pla ce t h e ba ck gr ou n d- color de cla r a t ion ba ck gr ou n dcolor : # CBF6 2 2 ;w it h t h is: background: #CBF622 url( images/bg_bottom.gif) center bottom no-repeat;

      This short hand propert y includes t he sam e background color you j ust replaced plus inst ruct ions for adding a graphic t o t he cent er and bot t om of t he sidebar. Preview t he page now, and you'll see t he graphic, but a few t hings aren't quit e right , as shown at left in Figure 8- 17. There's space on bot h t he left and right side of t he im age, so it doesn't look like it 's act ually t he bot t om of t he sidebarit j ust looks like a phot o inside t he sidebar. Also, you can't read all of t he t ext since som e of it overlaps t he im age. Finally, t he border around t he sidebar appears out side of t he graphic, m aking t he sidebar appear t o st ill have a square bot t om . You'll t ackle t hese problem s one by one. 3. I n t h e .side ba r st yle , r e m ove t h e follow in g pr ope r t y de cla r a t ion : pa ddin g: 1 0 px ; The graphic is 220 pixels wide, and t he widt h of t he sidebar is also set t o 220 pixels. However, t he 10 pixels of padding adds 10 pixels of space around t he sidebar, and 20 pixels ( left and right ) t o t he overall widt h of t he sidebar. Rem oving t he padding propert y m akes t he sidebar shrink down t o t he widt h of t he graphic.

      Note: The rounded corners technique used here is for a fixed-width box. That means if you change the width of the sidebar, you'll need to recreate the graphics at the same width to match. For a few techniques that let you create rounded corners with more flexibilityand require more CSS and HTML codevisit these pages:

      To add som e room at t he bot t om of t he sidebar, so t hat t he pict ure doesn't int erfere wit h t he t ext , t urn t o t he padding- bot t om propert y. 4. Add t h e st yle de cla r a t ion pa ddin g- bot t om : 7 5 px ; t o t h e .side ba r st yle . Padding is t he space bet ween t he borders of an elem ent and t he cont ent . By adding 75 pixels of bot t om padding, you ensure t hat t here's plent y of room for t he background im age, so t hat t ext can never overlap it . There's one final problem t o fix: The border around t he sidebar appears around t he background graphic ( Figure 8- 17, m iddle) . Sim ply rem oving t he border does t he t rick.

      Figu r e 8 - 1 7 . I t t a k e s a fe w st e ps t o pla ce t h e im a ge a n d t w e a k t h e displa y of t h e side ba r t o

      Section 8.7. Tutorial: Using Background Images

      a ch ie ve con vin cin g r ou n de d bot t om cor n e r s.

      5. Re m ove t h e bor de r pr ope r t y fr om .side ba r , so t h a t t h e fin a l ve r sion of t h e st yle look s lik e t h is: .sidebar { width: 220px; float: right; margin: 10px; background: #CBF622 url( images/bg_bottom.gif) center bottom no-repeat; padding-bottom: 75px; }

      6. Sa ve t h e file a n d pr e vie w it in a W e b br ow se r . The sidebar should look like Figure 8- 17, right . Not ice t hat even t hough you elim inat ed t he border, t here's st ill a borderline around t he bot t om , curved corners, and sides of t he base of t he sidebar. That line isn't creat ed wit h CSS; it 's j ust a line drawn direct ly on t he graphic. You'll next insert a graphic t o m ake t he t op of t he sidebar box rounded as well. I t would be really cool if you could add a background im age t o t he t op of t he sidebar and a different background im age t o t he bot t om of t he sidebar. This way you'd have rounded corners on bot h t he t op and bot t om , but t he sidebar it self could expand t o fit what ever cont ent was added t o it . Unfort unat ely, CSS 2.1 let s you add only one background im age per st yle, so you m ust find som et hing else t o " hook" t he second background im age on, like a t ag som ewhere in t he sidebar. I n t his case, since t he im age adds rounded corners t o t he t op of t he sidebar box, you can apply t he st yle t o t he first t ag inside t he sidebar. You'll use a descendent select or t o do t hat .

      Note: Future versions of CSS will allow multiple background images for a single style. So far, only one browserSafarirecognizes them. 7.

      Section 8.7. Tutorial: Using Background Images

      Loca t e t h e .side ba r h 3 st yle in t h e e x t e r n a l st yle sh e e t . ( I t 's dir e ct ly be low t h e .side ba r st yle you j u st m odifie d.) Th e n a dd t h e follow in g lin e of code t o t h e st yle : background: url(images/top_bg.gif) center top no-repeat;

      By now, t his kind of short cut st yle should look fam iliar. I t adds a graphic t o t he t op and cent er of t he st yle. I n t his case, it 'll appear in t he background of t he < h3> t ag inside t he sidebar. At t his point , t he rounded corners are in place, and t he box is, well, a lit t le less boxy. You'll j ust add a few final t ouches t o t he headline by m aking t he t ext whit e so it st ands out from t he newly added graphic and adding a lit t le padding above and below t he headline so it isn't so cram ped. 8. Add t w o a ddit ion a l pr ope r t ie s t o t h e .side ba r h 3 st yle so t h a t it look s lik e t h is: .sidebar h3 { font-size: 1.4em; margin: 0; text-align: center; text-transform: uppercase; background: url(images/top_bg.gif) center top no-repeat; color: #FFF; padding: 5px; }

      I f you preview t he page now, t he sidebar looks finished…alm ost . Look closely at t he left and right edges and you'll not ice t hat while t here's an out line around t he bot t om graphic, t hat line doesn't appear on eit her side of t he sidebar where t he bullet ed list appears ( Figure 8- 18, left ) . One solut ion would be t o sim ply m ake t he bot t om graphic a solid background color wit hout an out line, but t hat wouldn't be m uch fun. I nst ead, you'll add left and right borders t o t he bullet ed list . The lines from t he border overlap t he out line on t he graphic, giving t he appearance of one unified line running around t he ent ire sidebar. 9. Fin d t h e .side ba r u l st yle . Th e n a dd t w o bor de r de cla r a t ion s so t h e fin a l st yle look s lik e t h is: .sidebar ul { color: #666; font-size: 1.2em; margin: 0; padding: 10px 5px 0 5px; border-left: 1px solid #E73A10; border-right: 1px solid #E73A10; }

      Now t he unordered list has t wo borders on eit her side. Because t here's no padding on t he sidebar it self, t hose borders ext end t o t he very edges, m aking t hem appear t o act ually be bordering t he sidebar ( Figure 8- 18, right ) . 10. Sa ve t h e file a n d pr e vie w t h e pa ge in a W e b br ow se r . The final page m akes use of background im ages in ways t hat m ay not feel im m ediat ely like im ages at allt o creat e t he curved sidebar corners and com plet e it s borders. Creat ive use of background im ages adds dept h t o your Web page designs, and m akes your Web sit e look richer and m ore professional.

      Figu r e 8 - 1 8 . Alt h ou gh t h e gr a ph ic a t t h e bot t om of t h e side ba r h a s a lin e dr a w n a r ou n d it s e dge , t h e u n or de r e d list doe sn 't ( le ft ) . By a ddin g bor de r s t o t h e list , it a ppe a r s t h a t on e u n ifie d bor de r is dr a w n a r ou n d t h e cu r ve d side ba r ( r igh t .)

      Section 8.7. Tutorial: Using Background Images

      8.7.5. Creating an External Style Sheet There's one final t ask t o perform . I t 's one t hat you'll probably do t im e and t im e again in your CSS career. Aft er you've finalized your design using an int ernal st yle sheet , it 's t im e t o t ake t hose st yles and place t hem in an ext ernal st yle sheet for use by all of t he pages of your sit e. 1. I n you r t e x t e dit or , cr e a t e a n e w file . Sa ve it a s st yle s.css in t h e sa m e folde r a s t h e side ba r .h t m l file . This docum ent is your ext ernal st yle sheet . You'll copy t he st yles you em bedded in t he sidebar.ht m l file and past e t hem int o t his file. 2. Re t u r n t o t h e side ba r .h t m l file , a n d se le ct a ll of t h e code be t w e e n t h e ope n in g < st yle > a n d closin g < / st yle > t a gs. Don't select t he st yle t ags t hem selves. Those are HTML code, and an ext ernal st yle sheet m ust cont ain only CSS code. 3. Cu t t h e code fr om t h e file by ch oosin g Edit

      Cu t .

      You're rem oving t he code from t his page, since you'll link t o t he ext ernal st yle sheet in a m om ent . 4. Re t u r n t o t h e e m pt y st yle s.css file , a n d pa st e t h e code by ch oosin g Edit

      Pa st e . Sa ve t h e file .

      Now all of t he CSS code is in it s own file. You can link any page in your sit e t o t his file and your pages can share t he sam e form at t ing inst ruct ions.

      Section 8.7. Tutorial: Using Background Images

      Now you j ust need t o at t ach t he st yle sheet t o t he HTML page. 5. Re t u r n t o t h e side ba r .h t m l file . M a k e su r e t h e < st yle > t a gs a r e st ill in pla ce , a n d t h e n a dd on e lin e of code be t w e e n t h e se t a gs:

      Note: The other way to attach an external style sheet is with a link tag (Section 2.4.2). To use this tag, first remove the opening and closing

      This descendent select or changes t he color of all < a> t ags t hat are inside t ags t hat have an I D of # m ain. The m ain body t ext on t he page is wrapped in a < div> t ag wit h an I D of # m ain. Adding and nam ing a < div> like t his m akes it easy t o creat e st yles t hat t arget j ust t he HTML cont aining t he page's m ain t ext . This st yle changes t he color of t he t ext for links, but only t hose inside t his m ain body < div> . I f you preview t he page now, you'll see t hat t he color of t he link at t he bot t om of t he pagewhich is cont ained in a separat e < div> wit h a different I Disn't affect ed. Now, t im e t o rem ove t hat boring old underline beneat h t he link. 4. Add t e x t - de cor a t ion : n on e ; t o t h e # m a in a st yle you j u st cr e a t e d. This rem oves t he underline, but also m akes t he link less visible on t he page. Rem em ber you should always do som et hing t o m ake links st and out and seem clickable t o your sit e's visit ors.

      Figu r e 9 - 1 1 . H e r e 's a ba sic W e b pa ge w it h lin k s in t h e ir st a n da r d br ow se r con figu r a t ion u n de r lin e d a n d blu e . I n t h is ca se , som e lin k s poin t t o ot h e r pa ge s on t h e sit e , som e poin t t o ot h e r sit e s, a n d on e is a n e m a il a ddr e ss. I n t h is t u t or ia l, you 'll st yle e a ch of t h e se lin k s diffe r e n t ly.

      Section 9.5. Tutorial: Styling Links

      5. Add fon t - w e igh t : bold; t o t h e # m a in a st yle . Now links appear in bold ( ot her t ext m ay appear bold, t oo) . Next you'll replace t he underline, but you'll do it a bit m ore creat ively, using a border inst ead of t he t ext - decorat ion propert y. 6. Add a bor de r de cla r a t ion t o t h e st yle , so it look s lik e t h is: #main a { color: #8C1919; text-decoration: none; font-weight: bold; border-bottom: 2px dotted #A5E410; }

      The links really st and out , and using a border inst ead of t he norm al underline applied t o links let s you change t he line's color, size, and st yle ( Figure 9- 12, left ) . Tim e t o t ake it a st ep furt her by adding a rollover effect , so t he link's background changes color when t he m ouse

      Section 9.5. Tutorial: Styling Links

      m oves over it . 7. Add a :h ove r pse u do- cla ss st yle t o t h e st yle sh e e t : #main a:hover { background-color: #FCC423; }

      This pseudo- class applies only when t he m ouse is over t he link. The int eract ive qualit y of rollovers let s visit ors know t he link does som et hing ( Figure 9- 12, right ) .

      Figu r e 9 - 1 2 . W it h a cou ple of st yle s, you ca n ch a n ge t h e look of a n y lin k . W it h t h e :h ove r pse u do- cla ss, you ca n e ve n sw it ch t o a diffe r e n t st yle w h e n t h e m ou se m ove s ove r t h e lin k ( r igh t ) .

      9.5.2. Adding a Background Image to a Link The em ail link at t he bot t om of t he page rem ains unaffect ed by t he st yles you've creat ed so far ( Figure 9- 13, t op) . That 's fineyou have ot her plans for t hat m ailt o link. Since it point s t o an em ail address, clicking it doesn't t ake a visit or t o anot her page, but inst ead launches an em ail program . To provide a visual cue em phasizing t his point , you'll add a cut e lit t le em ail icon. 1. Add a n ot h e r de sce n de n t se le ct or t o t h e in t e r n a l st yle sh e e t of t h e ba t h t u b.h t m l file : #legal a { color: #666666; background: url(images/email.gif) no-repeat left center; }

      The em ail link's inside a < div> t ag wit h an I D of legal, so t his st yle affect s only t his link, and t he color declarat ion m akes it gray. The background propert y adds an im age on t he left edge of t he link. Finally, t he no- repeat value forces t he graphic t o appear j ust a single t im e. Trouble is, t he graphic lies direct ly underneat h t he link, so it 's hard t o read t he t ext ( Figure 9- 13, m iddle) . 2.

      Section 9.5. Tutorial: Styling Links

      Add 2 0 pix e ls of le ft pa ddin g t o t h e # le ga l a st yle you j u st cr e a t e d: padding-left: 20px;

      Rem em ber t hat padding adj ust s t he space bet ween cont ent and it s border. So adding som e left padding m oves t he t ext over 20 pixels but leaves t he background in place. One last t ouch: m ove t he ent ire link a lit t le away from t he copyright not ice. 3. Add 1 0 pix e ls of le ft m a r gin t o t h e st yle , so it fin a lly e n ds u p lik e t h is: #legal a { color: #666666; background: url(images/email.gif) no-repeat left center; padding-left: 20px; margin-left: 10px; }

      This sm all visual adj ust m ent m akes it clear t hat t he icon's relat ed t o t he link and not part of t he copyright not ice ( Figure 9- 13, bot t om ) .

      Figu r e 9 - 1 3 . Ju st a fe w su bt le t ou ch e s ca n h e lp m a k e a lin k 's pu r pose obviou s. I n t h is ca se , a pla in lin k ( t op) be com e s cle a r ly ide n t ifia ble a s a n e m a il lin k ( bot t om ) .

      9.5.3. Highlighting External Links

      Section 9.5. Tutorial: Styling Links

      At t im es you m ay want t o indicat e t hat a link point s t o anot her Web sit e. I n t his way, you can give your visit ors a visual clue t hat t here's addit ional inform at ion elsewhere on t he I nt ernet , or warn t hem t hat t hey'll exit your sit e if t hey click t he link. I n t he next few st eps, you'll creat e a special st yle for ext ernal links. 1. Add t h is st yle t o t h e ba t h t u b.h t m l in t e r n a l st yle sh e e t : #main a.external { background-image: url(images/globe.png); background-repeat: no-repeat; background-position: right top; padding-right: 18px; border-bottom: none; }

      As wit h t he em ail link st yle you j ust creat ed, t his st yle adds a background im age. I t places t he im age at t he right side of t he link. Set t ing t he border- bot t om propert y t o none elim inat es t he green, dashed border t hat appears under links point ing t o ot her pages on t he Cosm oFarm er sit e. None of t he ext ernal links on t he page have changed yet . Now t hat you've got your new class st yle.ext ernalyou should apply it t o any ext ernal links you want t o form at . 2. I n t h e pa ge 's H TM L code , loca t e t h e t h r e e e x t e r n a l lin k s. ( H in t : Th e y'r e in a n u n or de r e d list a bou t t w o- t h ir ds of t h e w a y dow n t h e pa ge .) Add cla ss= " e x t e r n a l" t o e a ch of t h e < a > t a gs:
    • American Standard Bathtubs
    • Cast-iron tub buying guide
    • Vintage Tubs


    • I f you preview t he page in a Web browser, you'll see t hose t hree links have a sm all globe icon at t heir right ( Figure 9- 14, t op) . The links higher up on t he page are globe- free. They point t o ot her Cosm oFarm er pages, so you didn't apply t he ext ernal class t o t hem .

      Tip: You've been learning about the rules for CSS 2.1 (the most widely supported version of CSS). But you can use a CSS 3 selector to automatically target any link beginning with http://. Just change the name of the selector in step 1 above from #main a.external to #main a[href^='http://']. When you use this selector, you don't have to apply classes to individual links as in step 2. The downside: Only Internet Explorer 7, Safari, Firefox, and Opera 9 recognize the selector. IE 6 folks won't see the style at all.

      Next , give t hese links a rollover effect using t he Pixy m et hod described in Sect ion 9.1.1. As a m at t er of fact , t he background graphic you added in st ep 1globe.pngact ually cont ains t wo im ages. Current ly, only t he t op im age is visible, and you want t he graphic's posit ion t o shift when a visit or m ouses over t he link. 3. I m m e dia t e ly a ft e r t h e st yle you cr e a t e d in st e p 1 , a dd t h e follow in g st yle : #main a.external:hover { background-position: right -24px; color: #152D6A; }

      This st yle bot h changes t he color of t he t ext and adj ust s t he posit ion of t he background im age. I t m oves t he graphic up - 24 pixels, essent ially m oving t he globe im age out of view and exposing a new rollover im age. There's one problem , however. The background color from t he # m ain a: hover st yle ( creat ed in st ep 7 in Sect ion 9.1.1) also appears. As you can see Figure 9- 14, m iddle, t he graphic obscures part of t he background. I t 'll look bet t er when you rem ove t hat background color.

      Section 9.5. Tutorial: Styling Links

      4. Edit t h e st yle you j u st cr e a t e d by a ddin g a ba ck gr ou n d- color pr ope r t y: #main a.external:hover { background-position: right -24px; color: #152D6A; background-image: url(images/globe_highlight.png); background-color: #FFF; }

      This declarat ion set s t he background color t o whit e, m at ching t he whit e background of t he page ( Figure 9- 14, bot t om ) .

      Figu r e 9 - 1 4 . Usin g a cla ss st yle , you ca n for m a t e x t e r n a l lin k s diffe r e n t ly t h a n ot h e r lin k s on t h e pa ge . A globe icon is on e w a y t o in dica t e t h a t a lin k le a ds ou t in t o t h e gr e a t e r W e b ( t op) . You m a y h a ve t o t w e a k a st yle t o ove r com e pr ope r t ie s in h e r it e d fr om ot h e r st yle s, lik e t h e ba ck gr ou n d color in h e r it e d fr om a m or e ge n e r ic st yle ( m iddle ) . H e r e , t h e fix is r e m ovin g a ba ck gr ou n d color fr om t h e lin k 's :h ove r st yle ( bot t om ) .

      9.5.4. Marking Visited Pages To round out t he look of t he links on t his page, you'll add one m ore st yle. This one applies only in one cert ain casewhen a link's been visit ed. Using t he : visit ed pseudo- class, it 's easy t o add a graphic m arker indicat ing pages som eone has already been t o. 1. Add on e la st st yle t o t h e st yle sh e e t : #main a:visited { color: #999; }

      Now, when t he Web browser has already visit ed one of t he pages linked t o from t his page, it m akes t hat link gray. By m aking t he color duller and light er t han ot her links, you m ake t he link visually recede from t he page ( Figure 9- 15, t op) . But j ust in case t hat 's not enough inform at ion t o let people know t hey've been t o t he linked page before, you'll m ake it even m ore obvious wit h a checkm ark. 2. Edit t h e st yle you j u st cr e a t e d by a ddin g a ba ck gr ou n d pr ope r t y a n d som e pa ddin g: #main a:visited {

      Section 9.5. Tutorial: Styling Links

      color: #999; background: url(images/check.gif) no-repeat right center; padding-right: 18px; }

      Preview t he page, click one of t he links, and t hen hit your browser's back but t on t o see how t he link changes appearance once visit ed ( Figure 9- 15, bot t om ) .

      A finished version of t his t ut orial is in t he chapt er_09_finished

      links folder.

      9.5.5. Creating a Vertical Navigation Bar I n t his exercise you'll t urn a plain old list of links int o a spect acular navigat ion bar com plet e wit h rollover effect s and a " You are here" but t on effect . 1. I n a t e x t e dit or , ope n ch a pt e r _ 0 9

      n a v_ ba r

      n a v_ ba r .h t m l.

      As you can see, t here's not m uch t o t his file yet . There's an int ernal st yle sheet wit h one rule set t ing up som e basic propert ies for t he < body> t ag, and an unordered list consist ing of six links. I t looks like exam ple one in Figure 9- 16. Your first st ep is t o add som e HTML so you can t arget your CSS t o form at t he links in t his list . 2. Loca t e t h e ope n in g < u l> t a g a n d a dd id= " m a in N a v" t o it , so it look s lik e t h is: