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
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 :
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;
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:
Section 3.3. ID Selectors: Specific Page Elements
Note: As with class styles, you use the # symbol only when naming the style in the style sheet. You leave the # off when using the ID's name as part of an HTML tag: .
POWER USERS' CLINIC Proper IDs I D select ors have a few powers t hat class select ors lack. These benefit s act ually have not hing t o do wit h CSS, so you m ay never need an I D. But if you're curious: ●
●
JavaScript program m ing ut ilizes I D select ors t o locat e and m anipulat e part s of a page. For exam ple, program m ers oft en apply an I D t o a form elem ent like a t ext box for collect ing a visit or's nam e. The I D let s JavaScript access t hat form elem ent and work it s m agiclike m aking sure t he field isn't em pt y when t he visit or clicks Subm it . I Ds also let you link t o a specific part of a page, m aking long Web pages quicker t o navigat e. I f you have an alphabet ic glossary of t erm s, t hen you can use an I D select or t o creat e links t o t he let t ers of t he alphabet . When your visit ors click " R" , t hey j um p im m ediat ely t o all t he " R" words on t he page. First , creat e an I D for each let t er of t he alphabet ( # R) . When you creat e t he link in HTML, add t he pound sym bol and t he I D nam e t o t he end of t he URL followed by t he I D nam eindex.ht m l# R. This link point s direct ly t o an elem ent wit h t he I D of # R on t he page index. ht m l. ( When used t his way, t he I D behaves j ust like a nam ed anchor< a nam e= " sect ion1" > Sect ion 1< / a> in HTML.)
Section 3.4. Styling Tags Within Tags
3.4. Styling Tags Within Tags Choosing whet her t o st yle your page wit h t ag select ors or class select ors is a t radeoff. Tag select ors are fast and easy, but t hey m ake every occurrence of a t ag look t he sam e, which is fineif you want every < h1> on your page t o look exact ly like all t he rest . Class and I D select ors give you t he flexibilit y t o st yle individual page elem ent s independent ly, but creat ing a new CSS st yle j ust t o change one heading's font t akes a heck of a lot m ore workand HTML code. What you need is a way t o com bine t he ease of t ag select ors wit h t he precision of classes and I Ds. CSS has j ust t he t hing descendent select ors. You use descendent select ors t o form at a whole bunch of t ags in a sim ilar m anner ( j ust like t ag select ors) , but only when t hey're in a part icular part of a Web page. I t 's like saying, " Hey you < a> t ags in t he navigat ion bar, list en up. I 've got som e form at t ing for you. All you ot her < a> t ags, j ust m ove along; t here's not hing t o see here." Descendent select ors let you form at a t ag based on it s relat ionship t o ot her t ags. To underst and how it works, you need t o delve a lit t le bit m ore deeply int o HTML. On t he bright side, t he concept s underlying descendent select ors help you underst and several ot her select or t ypes, t oo, as discussed lat er in t his chapt er.
Note: Descendent selectors were called contextual selectors in CSS 1.
3.4.1. The HTML Family Tree The HTML t hat form s any Web page is akin t o a fam ily t ree, where t he HTML t ags represent various fam ily m em bers. The first HTML t ag you use on a paget he < ht m l> t agis like t he grandpappy of all ot her t ags. The < ht m l> t ag surrounds t he < head> t ag and t he < body> t ag, which m akes < ht m l> t he ancest or of bot h. Sim ilarly, a t ag inside of anot her t ag is a descendent . The < t it le> t ag in t he following exam ple is t he < head> t ag's descendent :
A Simple Document
Header
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;
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:
By Jean Graine de Pomme
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;
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
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 :
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
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:
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:
The I D at t ribut e ident ifies t his list as t he m ain navigat ion area. Use t his I D t o build descendent select ors t o form at only t hese links ( and not j ust any old link on t he page) . ( See Sect ion 3.1 for t he st ory on descendent select ors.)
Figu r e 9 - 1 5 . Le t folk s k n ow t h e y've click e d a lin k by e m ployin g t h e :visit e d pse u do- cla ss. You ca n su bt ly ide n t ify visit e d lin k s by m a k in g t h e ir color r e ce de in t o t h e ba ck gr ou n d ( t op) , or give t h e m a se n se of com ple t ion by a ddin g a ch e ck m a r k gr a ph ic ( bot t om ) .
Section 9.5. Tutorial: Styling Links
Figu r e 9 - 1 6 . W h ile it m a y fe e l lik e a lot of st e ps, t r a n sfor m in g a pla in u n or de r e d list of lin k s in t o a soph ist ica t e d n a viga t ion ba r r e qu ir e s on ly a fe w st yle s.
Section 9.5. Tutorial: Styling Links
3. Be low t h e body st yle in t h e in t e r n a l st yle sh e e t , a dd a n e w st yle : ul#mainNav { margin: 0; padding: 0; list-style: none; }
This st yle applies only t o a < ul> t ag wit h an I D of m ainNav. I t rem oves t he indent and bullet s t hat browsers apply t o unordered list s, as shown in # 2 in Figure 9- 16. Next , you'll st art form at t ing t he links. 4. Add a de sce n de n t se le ct or t o for m a t t h e lin k s in t h e list : #mainNav a { color: #000; font-size: 1.1em; text-transform: uppercase; text-decoration: none; }
This st yle defines t he basic t ext form at t ing for t he links. I t set s t he color and font size, m akes all let t ers uppercase, and rem oves t he line usually found underneat h links ( # 3 in Figure 9- 16) . Now st art m aking t he links look like but t ons. 5. To t h e # m a in N a v a st yle , a dd t h e follow in g bor de r a n d pa ddin g pr ope r t ie s: border: 1px dashed #999; padding: 7px 5px;
Section 9.5. Tutorial: Styling Links
I f you preview t he file now, you'll see a few problem s ( # 4 in Figure 9- 16) : The borders overlap and t he boxes aren't t he sam e widt h. That 's because t he < a> t ag is an inline elem ent , so t he widt h of t he box is j ust as wide as t he t ext in t he link. I n addit ion, t op and bot t om padding don't add any height t o inline boxes, so t he borders overlap. ( See Sect ion 7.2.4 for a discussion of inline boxes.) You can fix t hese problem s by changing how a browser displays t hese links. 6. To t h e # m a in N a v a st yle , a dd displa y: block ;. You've changed t he basic display of t he < a> t ag so t hat it act s like a paragraph or ot her block- level elem ent , wit h t he links neat ly st acked one on t op of t he ot her. The only problem now is t hat t hey also ext end t he full lengt h of t he browser windowa lit t le t oo wide for a but t on. You can fix t his by const raining t he widt h of t he < ul> t ag's st yle.
Note: If you preview the page in Internet Explorer 6 or earlier, you'll notice a gap between each nav button. Remain calm. You'll fix this bug in step 1 in Section 9.1.1. 7. I n t h e in t e r n a l st yle sh e e t , loca t e t h e u l# m a in N a v st yle a n d a dd w idt h : 1 7 5 px ; t o it . Wit h t he list 's widt h now set t o 175 pixels, t he links st ill expand, but t hey're lim it ed t o t he widt h of t heir cont ainer ( t he < ul> t ag) . I n m any cases, you'll have a list of links inside som e layout elem ent ( like a sidebar) t hat already has a set widt h, so you'll be able t o skip t his st ep. ( You'll learn how t o add sidebars in Part 3.) Now for t he fun part . 8. Add ba ck gr ou n d pr ope r t ie s t o t h e # m a in N a v a st yle , lik e so: #mainNav a { color: #000; font-size: 1.1em; text-transform: uppercase; text-decoration: none; border: 1px dashed #999; padding: 7px 5px; display: block; background-color: #E7E7E7; background-image: url(images/link.png); background-repeat: no-repeat; background-position: left center; }
These lines add a gray background color t o t he links and a non- repeat ing im age at t he left edge of each but t on ( # 5 in Figure 9- 16) . You st ill have a couple of t hings t o fix: The link t ext overlaps t he icon, and t he border bet ween each but t on is 2 pixels t hick. ( Technically, t he borders are st ill j ust 1 pixel t hick, but t he bot t om and t op borders of adj oining links are creat ing a 2- pixel line.)
Note: Using the background shorthand property you can write the code in step 8 like this: background: #E7E7E7 url(images/link.png) no-repeat left center;. See Chapter 8 (Section 8.5) for the details. 9. Re m ove t h e t op bor de r a n d a dj u st t h e pa ddin g for t h e # m a in N a v a st yle , so it look s lik e t h is: #mainNav a { text-decoration: none; color: #000000; font-size: 1.1em; text-transform: uppercase; border: 1px dashed #999999; border-bottom: none; padding: 7px 5px 7px 30px; display: block;
Section 9.5. Tutorial: Styling Links
background-color: #E7E7E7; background-image: url(images/link.png); background-repeat: no-repeat; background-position: left center; }
The t ext of each link sit s clear of t he icon and t he borders look great …except for one t hing. The last link's bot t om border is now gone. ( Som et im es CSS feels like t wo st eps forward, one st ep back! ) But you have a few ways t o fix t his snafu. One way is t o creat e a class st yle wit h t he proper border- bot t om set t ing, and t hen apply it t o j ust t hat first link. But it would be easier t o apply a bot t om border t o t he < ul> t ag cont aining t he list of links. ( Since t here's no padding on t hat t ag, t here's no space separat ing t he t op of t he < ul> from t he t op of t hat first link.) 10. Add a t op bor de r t o t h e u l# m a in N a v st yle so t h a t it look s lik e t h is: ul#mainNav { margin: 0; padding: 0; list-style: none; width: 175px; border-bottom: 1px dashed #999; }
There you have it : A basic navigat ion bar using borders, padding, background color and im ages ( # 6 in Figure 9- 16) .
9.5.6. Adding Rollovers and Creating "You Are Here" Links Now it 's t im e t o add som e int eract ive and advanced feat ures t o t his nav bar. First , you'll add a rollover effect t o t he but t ons in your m ain navigat ion bar. That way, t he but t ons change t o show your visit or which but t on she's about t o click. I t 's also considerat e t o let your visit or know which page of your sit e she's on. Using t he sam e HTML nav bar you already have, you can m ake t his bit of int eract ivit y happen aut om at ically. You sim ply m ake t he but t on's form at change t o m at ch t he page's sect ion. Sounds sim ple, but it does require a lit t le planning and set up, as you'll see in t he following st eps. The rollover effect is easy, so get t hat out of t he way first : 1. I n t h e n a v_ ba r .h t m l file , a dd t h e follow in g st yle t o t h e e n d of t h e st yle sh e e t : #mainNav a:hover { font-weight: bold; background: #B2F511 url(images/go.png) no-repeat 5px 50%; }
This st yle set s t he but t on's hover st at e. I t m akes t he t ext inside t he but t on bold, and ( using t he background short hand propert y) changes t he background color and im age ( Figure 9- 17) . Now, m oving t he m ouse over any of t he but t ons inst ant ly changes it s look. ( Open t he page in your Web browser and t ry it yourself.)
Figu r e 9 - 1 7 . W it h som e ba sic CSS, it 's e a sy t o cr e a t e in t e r a ct ive r ollove r e ffe ct s for n a viga t ion bu t t on s. You ca n e ve n a u t om a t ica lly h igh ligh t t h e se ct ion of t h e sit e in w h ich t h e cu r r e n t pa ge is loca t e d.
Section 9.5. Tutorial: Styling Links
Note: You can also use the Pixy method, as in step 3 in Section 9.1.1, to create the same rollover effect using just one graphics file. That approach has the added benefit of avoiding the slight delay that appears when a visitor first rolls over one of the links.
Next , m ake your navigat ion bar m ore inform at ive by highlight ing t he but t on t hat m at ches t he sect ion in which t he page is locat ed. To do so, you need t o ident ify t wo t hings in t he nav bar's HTML: 1) t he sect ion a page belongs t o, and 2) t he sect ion each link point s t o. For t his exam ple, assum e t hat t he page you're working on belongs t o t he Feat ures sect ion.
Note: Alternatively, you can create a class style that changes the appearance of a link, and apply it to the link representing the page's section. For a horoscope page, you'd apply the class to the Horoscope link in the nav bar: Horoscopes. 2. Loca t e t h e < body> t a g, a n d t h e n a dd id= " fe a t u r e " , lik e so:
Now t hat you know what sect ion t his page belongs t o, you can use a descendent select or t o creat e special CSS rules t hat apply only t o t ags on pages wit hin t he Feat ures sect ion. Next , you need t o ident ify t he sect ion each link applies t o, which you accom plish by adding som e I Ds t o t hose links. 3. I n t h e n a v ba r 's H TM L code , loca t e t h e Fe a t u r e s lin k , a n d t h e n a dd id= " fe a - t u r e Lin k " so t h e t a g look s lik e t h is: Features
This I D uniquely ident ifies t his link, providing t he inform at ion you need t o creat e a st yle t hat applies only t o t hat link. You need t o I D t he ot her links in t he navigat ion bar as well. 4. Re pe a t st e p 4 for e a ch of t h e ot h e r lin k s u sin g t h e follow in g I D s: h om e Lin k , e x pe r t Lin k , qu izLin k , pr oj e ct Lin k , a n d h or oscope Lin k . You're done wit h t he HTML part of t his exercise. Now it 's t im e t o creat e som e CSS. Because you've I D'd t he page and t he link, it 's easy t o creat e a descendent select or t o highlight t he Feat ures link. 5. Add a n ot h e r st yle t o t h e pa ge 's st yle sh e e t : body#feature a#featureLink { background: #FFFFFF url(images/bg_here.png) no-repeat 95% 50%; padding-right: 15px; padding-left: 30px; font-weight: bold; }
You've seen all t hese propert ies before. The int erest ing part 's t he select orbody# feat ure a# feat urelink. This is a very specific select or t hat applies only t o a link wit h an I D of feat ureLink t hat 's also inside a < body> t ag wit h an I D of feat ure. I f you change t he I D of t he page t o hom e, for exam ple, t he link t o t he Feat ures sect ion's no longer highlight ed. Preview t he page in a browser t o see t he effect : The Feat ures link now has a whit e background and a paperclip icon. To m ake t his work for t he ot her links, you need t o expand t his select or a lit t le…OK, m ake t hat a lot . 6.
Section 9.5. Tutorial: Styling Links
Edit t h e se le ct or for t h e st yle you j u st a dde d, lik e so: body#home a#homeLink, body#feature a#featureLink, body#expert a#experLink, body#quiz a#quizLink, body#project a#projectLink, body#horoscope a#horoscopeLink { background: #FFFFFF url(images/bg_here.png) no-repeat 95% 50%; padding-right: 15px; padding-left: 30px; font-weight: bold; }
Yes, t hat 's a lot of CSS. But your set - up work here has a big payoff. This st yle now applies t o every link in t he nav bar, but only under cert ain condit ions, which is exact ly how you want it t o behave. When you change t he id at t ribut e of t he < body> t ag t o quiz, t he link t o t he Quiz get s highlight ed inst ead of t he link t o t he Feat ures sect ion. Tim e t o t ake your work for a t est drive. 7. Ch a n ge t h e id a t t r ibu t e of t h e < body> t a g t o qu iz lik e t h is:
Preview t he page, and wham ! The Quiz link's now highlight ed wit h a whit e background and a paperclip icon ( Figure 9- 17) . The secret at t his point is t o j ust change t he I D in t he < body> t ag t o indicat e which sect ion of t he sit e a page belongs t o. For a horoscope page, change t he id t o id= " horoscope" in t he < body> t ag.
Note: Ready to take this design further? Try adding a rollover effect to complement the style you created in step 6. (Hint: Use the :hover pseudo-class as part of the selector like this: body#quiz a #quizLink:hover.) Also try adding a different graphic for the Home link. (You have a home.png file in the images folder to use.)
9.5.7. Fixing the IE Bugs What would a CSS t ut orial be if t here weren't any I nt ernet Explorer bugs t o fix? Unfort unat ely, t he navigat ion bar doesn't work quit e right in t hat browser. First , an annoying gap appears bet ween each but t on ( even in I E 7, as of t his writ ing) . I n addit ion, I E 6 and earlier t reat only t he t ext not t he ent ire area of t he but t onas clickable ( Figure 9- 18) . I n ot her browsers, m oving t he m ouse over any part of t he background ( including t he em pt y space t o t he right of t he link t ext ) highlight s t he link.
Figu r e 9 - 1 8 . I n t e r n e t Ex plor e r h a s som e pr oble m s w it h t h e n a viga t ion ba r a t t h is poin t . I t a dds spa ce be t w e e n e a ch lin k a n d w ill h igh ligh t a lin k on ly if t h e cu r sor ( cir cle d) is dir e ct ly ove r t h e t e x t lin k ..
Section 9.5. Tutorial: Styling Links
1. At t h e bot t om of t h e st yle sh e e t , a dd t h e follow in g: #mainNav li { display: inline; }
This bit of CSS changes t he nat ural behavior of list it em s from block- level elem ent s t o inline elem ent s. This workaround doesn't m ake m uch sense t heoret ically, but it at least rem oves t he space bet ween each link in t he navigat ion bar wit hout negat ively affect ing ot her browsers. The next st yle m akes I E 6 and earlier t reat t he ent ire area of t he but t on as clickable. 2. Aft e r t h e st yle you j u st a dde d, in se r t t h is I E- on ly st yle : * html #mainNav a { height: 1px; }
This st yle uses t he * ht m l hack t o apply CSS propert ies t o j ust I E 6 and earlier. I E 7 com plet ely ignores t his rule, as do all ot her browsers. The st yle declarat ion it self is nonsense: I t at t em pt s t o set t he height of t he link t o 1 pixel, som et hing t hat I E ignores, but which forces t hat browser t o see t he background of t he but t on as part of t he link. ( See t he box in Sect ion 11.1 for t he geeky det ails.) 3. Pr e vie w t h e pa ge in I n t e r n e t Ex plor e r on W in dow s. The navigat ion bar should now work as well in t hat browser as it does in m ore savvy browsers like Firefox, Opera, and Safari. To see t he com plet ed version of t his navigat ion bar, see t he file chapt er_09_finished
nav_bar
nav_bar_vert ical_finished.ht m l.
Section 9.5. Tutorial: Styling Links
Note: When creating specific styles targeted to just Internet Explorer, it's a good idea to isolate them from your other styles. Not that they're contagious, but they usually include nonsense CSS that for weird reasons smoothes out IE kinks. You don't want to read your style sheet later and get confused about why you included some bizarre CSS. In fact, the preferred method is to put IE-only styles in external style sheets and attach them using Microsoft's conditional comments feature. Get the full story in Section 14.5.2.
9.5.8. From Vertical to Horizontal Suppose you want a horizont al navigat ion bar t hat sit s at t he t op of t he page. No problem you did m ost of t he hard work in t he last part of t his t ut orial. Just m odify t hat page a lit t le t o spread t he but t ons along a single line. ( You'll use t he nav_bar.ht m l file you j ust com plet ed, so if you want t o keep t he vert ical nav bar, t hen save a copy of t he file before proceeding.) 1. M a k e su r e you 've com ple t e d a ll t h e st e ps a bove t o cr e a t e t h e ve r t ica l n a viga t ion ba r , a n d h a ve t h e file n a v_ ba r .h t m l ope n in you r t e x t e dit or . Now you'll see how easy it is t o change t he orient at ion of a navigat ion bar. St art by cleaning up som e of t he work you already did. 2. I n t h e n a v_ ba r .h t m l file 's st yle sh e e t , r e m ove t h e # m a in N a v li st yle you cr e a t e d in st e p 1 in Se ct ion 9 .1 .1 . That st yle was necessary only t o rem ove t he gap I E insert s bet ween links when but t ons are st acked one on t op of t he ot her, and t hat 's no longer an issue when t he but t ons appear side by side.
Tip: Cleaning up a style sheet by removing unnecessary styles is a good habit to get into. If you don't, you can end up with unused styles in your style sheets, causing unnecessary file size and potential confusion down the line. And here's another reason to put IE-specific styles either together at the bottom of a style sheet or in their own external style sheets: When you no longer have to support a particular version of IE, you can clean up your CSS by simply removing those styles.
You also need t o rem ove t he widt h you set for t he < ul> t ag in st ep 7 in Sect ion 9.5.5. That widt h prevent ed t he nav but t ons from spanning t he ent ire lengt h of t he page. But since t he < ul> needs t o spread out m uch wider t o cont ain t he side- by- side but t ons, t his widt h has t o go. 3. Fin d t h e u l# m a in N a v st yle , a n d t h e n r e m ove t h e w idt h : 1 7 5 px ; de cla r a t ion . And now it 's t im e for t he big secret of vert ical nav barsplacing t he but t ons side by side. 4. Add a n e w st yle t o you r st yle sh e e t ( dir e ct ly be low t h e u l# m a in N a v st yle is a good spot ) : #mainNav li { float: left; width: 12em; }
This st yle applies t o t he < li> t ag ( t he list it em s t hat hold each link) . The first declarat ion float s t he t ag t o t he left . I n t his way, each < li> t ag at t em pt s t o wrap around t o t he right side of t he previous < li> t ag. ( You saw t he sam e effect in t he phot o gallery t ut orial in Sect ion 8.6.3.) Also, set t ing t he widt h of t he < li> t ag defines t he widt h of each but t on. Here, a value of 12em s provides enough space t o cont ain t he longest link nam eHoroscopes. When you're working wit h longer links, you need t o increase t his value.
Tip: Using an em value instead of a pixel value for the width of the buttons makes the width adjust to the visitor's browser. If the buttons' widths were set to pixels, and a visitor increased the browser's font size, then the text in the button might get wider than the button itself. When you use ems, the button simply gets wider as the font gets larger.
Section 9.5. Tutorial: Styling Links
I f you preview t he page now, you'll see t he basics are com plet e. All t hat 's left are som e cosm et ic enhancem ent s ( see t he circled areas of # 1 in Figure 9- 19) . First , t he bot t om border you creat ed in st ep 10 in Sect ion 9.1.1 runs t he ent ire lengt h of t he < ul> t agwider t han t he navigat ion but t ons t hem selves. Even st ranger, t hat bot t om border's no longer on t he bot t om it 's on t op of t he navigat ion but t ons! I n addit ion, since t he but t ons sit side by side, t heir left and right borders com bine t o m ake a 2- pixel border bet ween each but t on. You'll fix t hat problem now.
Figu r e 9 - 1 9 . Ch a n gin g a ve r t ica l st a ck of n a viga t ion bu t t on s in t o t h e m u ch sh or t e r , side - by- side for m a t of a h or izon t a l n a viga t ion ba r on ly t a k e s a cou ple of st e ps. M ost of you r e ffor t in volve s t w e a k in g st yle s for cosm e t ic con side r a t ion s su ch a s bor de r s a n d ba ck gr ou n d im a ge pla ce m e n t .
5. I n t h e # m a in N a v a st yle ch a n ge bor de r - bot t om : n on e ; t o bor de r - le ft : n on e ;. This change rem oves t he left border so t hat t he borders don't double up bet ween but t ons, and at t he sam e t im e adds a border t o t he bot t om of each but t on. But t hat < ul> t ag's bot t om border is st ill on t op of t he but t ons, and now t he nav bar is m issing a border on t he far left but t on ( see circled areas of # 2 in Figure 9- 19) . No problem j ust change t he border on t he < ul> t ag. 6. Loca t e t h e u l# m a in N a v st yle a n d ch a n ge bor de r - bot t om : 1 px da sh e d # 9 9 9 9 9 9 ; t o bor de r - le ft : 1 px da sh e d # 9 9 9 9 9 9 ;. I f you preview t he page now, you'll see t hat t he border above t he but t ons is gone, but t here's st ill no left border ( # 3 in Figure 9- 19) . You're wit nessing one of t he com plicat ions of using float s. That is, float ing t he list it em s rem oves t hem from t he norm al flow of t he docum ent , so Web browsers no longer see t hem as part of t he < ul> t ag, and t he < ul> t ag shrinks down t o nearly no height t hat 's t he reason t he ul's bot t om border appeared on t op as well. ( I f t his whole scenario sounds confusing, it is. That 's why t here's an ent ire sect ion of Chapt er 11 dedicat ed t o dealing wit h t he issuesee Sect ion 11.1.1 for t he det ails.) Fort unat ely, while t he problem is com plex, t he solut ion is sim ple. Just float t he < ul> t ag as well. 7. Add floa t : le ft ; t o t h e u l# m a in N a v st yle . Th e com ple t e d st yle sh ou ld look lik e t h is: ul#mainNav { margin: 0; padding: 0; list-style: none; border-left: 1px dashed #999999; float: left; }
Section 9.5. Tutorial: Styling Links
Finally, t hat paperclip aligned t o t he right edge of t he " You are here" but t on looks funny ( # 4 in Figure 9- 19) . You'll swit ch it s posit ion t o t he left edge of t he but t on.
Note: Since the
tag is floated, other page elements try to wrap around it. It's a good idea to set the clear property on the next element immediately after the navigation bar as described in Section 7.6.2. That property forces whatever's following the navigation bar to sit below it rather than try to wrap to the nav bar's right side. 8. Loca t e t h e " You a r e h e r e " st yle you cr e a t e d in st e p 6 in Se ct ion 9 .5 .6 . ( I t 's t h e on e w it h t h e cr a zy, lon g- w in de d se le ct or .) Ch a n ge it s ba ck gr ou n d posit ion fr om 9 5 % 5 0 % t o 5 px 5 0 % . Th e st yle sh ou ld n ow look lik e t h is: body#home a#homeLink, body#feature a#featureLink, body#expert a#experLink, body#quiz a#quizLink, body#project a#projectLink, body#horoscope a#horoscopeLink { background: #FFFFFF url(images/bg_here.png) no-repeat 5px 50%; padding-right: 15px; padding-left: 30px; font-weight: bold; }
Preview t he page, and you'll find a fully funct ional horizont al navigat ion bar ( # 5 in Figure 9- 19) . And guess what ? I t works perfect ly even in I nt ernet Explorer. To see t he finished version, open t he file chapt er_09_finished
nav_bar
nav_ bar_horizont al_finished.ht m l.
Note: You may want to center the text inside each button. If so, you need to do two things: Add text-align: center; to the #mainNav a style, and adjust that style's leftpadding until the text looks absolutely centered.
Chapter 10. Formatting Tables and Forms
Chapter 10. Formatting Tables and Forms The form at t ing powers of CSS go way beyond t ext , im ages, and links. You can m ake t ables of inform at ion like schedules, sport s scores, and m usic playlist s easier t o read by adding borders, backgrounds, and ot her visual enhancem ent s. Sim ilarly, you can use CSS t o organize t he elem ent s of a form t o help your visit ors t hrough t he process of ordering it em s, signing up for your newslet t er, or using your lat est Web applicat ion. This chapt er shows you how t o display t ables and form s wit h HTML and how t o lay out and st yle t hem using CSS. I n t wo t ut orials at t he end of t he chapt er, you'll creat e a t able and a form , using t he t ricks you've learned along t he way.
Section 10.1. Using Tables the Right Way
10.1. Using Tables the Right Way HTML t ables have seen a lot of use in t he short hist ory of t he Web. Originally creat ed t o display dat a in a spreadsheet - like form at , t ables becam e a popular layout t ool. Faced wit h HTML's lim it at ions, designers got creat ive and used t able rows and colum ns t o posit ion page elem ent s like banner headlines and sidebars. As you'll see in Part I I I of t his book, CSS does a m uch bet t er j ob of laying out Web pages. You can concent rat e on using ( and form at t ing) t ables for t heir original purposedisplaying dat a ( Figure 10- 1) .
Figu r e 1 0 - 1 . You ca n do a ll of you r pa ge la you t a n d de sign w it h CSS, a n d u se t a ble s for w h a t t h e y w e r e in t e n de ddispla yin g r ow s a n d colu m n s of in for m a t ion . CSS cr e a t e d t h e a t t r a ct ive fon t s, bor de r s, a n d ba ck gr ou n d color s in t h is t a ble a bou t in door la w n m ow e r s, bu t t h e u n de r lyin g st r u ct u r e is a ll t h a n k s t o H TM L.
HTML ( and XHTML) has a surprising num ber of t ags dedicat ed t o t able building. This chunk of HTML creat es t he very sim ple t able pict ured in Figure 10- 2.
Section 10.1. Using Tables the Right Way
Table 1: CosmoFarmer.com's Indoor Mower Roundup
Brand
Price
Power Source
Chinook Push-o-matic Indoor Mower
$247.00
Mechanical
Sampson Deluxe Apartment Mower
$370.00
Mechanical
Even wit h only t hree rows and t hree colum ns, t he t able uses nine unique HTML t ags: < t able> , < capt ion> , < colgroup> , < col> , < t head> , < t body> < t r> , < t h> , and < t d> . I n general, m ore HTML isn't a good t hing, but a t able's various t ags give you lot s of useful hooks t o hang CSS st yles on. The headers of each colum nt he < t h> t agscan look different from ot her t able cells if you creat e a < t h> t ag st yle. This saves you t he hassle of having t o creat e lot s of classeslike .t ableHeaderand applying t hem by hand t o individual t able cells. I n t he next sect ion, you'll see exam ples of how you can use t hese different t ags t o your advant age.
Figu r e 1 0 - 2 . D a t a t a ble s, lik e t h is on e , u su a lly h a ve h e a de r s cr e a t e d w it h t h e < t h > t a g. H e a de r ce lls a n n ou n ce w h a t t ype of in for m a t ion a ppe a r s in a r ow or colu m n . Pr ice t e lls you t h a t you 'll fin d t h e cost of e a ch la w n m ow e r list e d in t h e ce lls be low . Th e a ct u a l da t a pr e se n t e d in a t a ble is e n close d in < t d> t a gs.
Note: For an in-depth article on the HTML used to create tables, visit www.456bereastreet.com/archive/200410/bring_on_the_tables/.
Section 10.1. Using Tables the Right Way
Section 10.2. Styling Tables
10.2. Styling Tables You can use m any of t he CSS propert ies you've read about t o dress up t he appearance of a t able and it s cont ent s. The color propert y, for exam ple, set s a t able's t ext color, j ust like anywhere else. You'll find a few propert ies, however, t hat are part icularly useful wit h t ables, as well as a couple aim ed specifically at form at t ing t ables. Because t ables are com posed of several HTML t ags, it helps t o know which t ag t o apply a part icular CSS propert y t o. Applying padding t o a < t able> t ag has no effect . The next few sect ions cover CSS propert ies for form at t ing t ables and which HTML t ags t hey get along wit h.
10.2.1. Adding Padding As you read in Sect ion 7.2, padding is t he space bet ween an elem ent 's border and it s cont ent . You can use padding t o provide a lit t le space bet ween t he edges of a paragraph's t ext and it s border. When it com es t o t ables, t he borders are t he edges of a cell, so padding adds space around any cont ent you've placed inside of a t able cell ( see Figure 10- 2) . I t works a lot like t he < t able> t ag's cellpadding at t ribut e, wit h t he added benefit t hat you can individually cont rol space bet ween a cell's cont ent and each of it s four edges. You apply padding t o eit her a t able header or a t able cell t ag, but not t o t he < t able> t ag it self. So, t o add 10 pixels of space t o t he inside of all t able cells, you'd use t his st yle: td, th { padding: 10px; }
You can also cont rol t he spacing separat ely for each edge. To add 10 pixels of space t o t he t op of each t able dat a cell, 3 pixels t o t he bot t om of t hat cell, and 5 pixels on bot h t he left and right sides, creat e t his st yle: td { padding-top: 10px; padding-right: 5px; padding-bottom: 3px; padding-left: 5px; }
Tip: If you place an image into a table cell using the tag, and notice that there's unwanted space below the image, then set its display property to block (see Section 7.2.4). For more information, see http://developer.mozilla.org/en/docs/Images,_Tables,_and_Mysterious_Gaps .
10.2.2. Adjusting Vertical and Horizontal Alignment To cont rol where cont ent is posit ioned wit hin a t able cell, use t he t ext - align and vert ical- align propert ies. Text - align cont rols horizont al posit ioning, and can be set t o left , right , cent er, and j ust ify ( see Figure 10- 3) . I t 's an inherit ed propert y. ( See Chapt er 4 for m ore on inherit ance.) When you want t o right align t he cont ent s of all t able cells, creat e a st yle like t his: table { text-align: right; }
This propert y com es in handy wit h < t h> t ags, since browsers usually cent er align t hem . A sim ple st yle like t h { t ext - align: left ; } m akes t able headers align wit h t able cells.
Figu r e 1 0 - 3 . W h e n a pplie d t o t a ble ce lls, t h e CSS t e x t - a lign pr ope r t y w or k s lik e t h e < t d> t a g's a lign a t t r ibu t e . Use t h e CSS a ppr oa ch , h ow e ve r , sin ce it le t s you st or e t h e st yle in for m a t ion in a n e x t e r n a l st yle sh e e t . Th a t w a y, if you de cide you n e e d t o ch a n ge a lign m e n t in you r t a ble ce lls fr om r igh t t o le ft , t h e n you n e e d t o u pda t e on ly t h e e x t e r n a l st yle sh e e t , n ot 1 0 ,0 0 0 in dividu a l < t d> t a gs.
Section 10.2. Styling Tables
Table cells have a height as well. Web browsers norm ally align cont ent vert ically in t he m iddle of a t able cell ( see " m iddle" exam ple in Figure 10- 4) . You can cont rol t his behavior using t he vert ical- align propert y. Use one of t hese four values: t op, baseline, m iddle, or bot t om . Top pushes cont ent t o t he t op of t he cell, m iddle cent ers cont ent , and bot t om pushes t he bot t om of t he cont ent t o t he bot t om of t he cell. Baseline works j ust like t op, except t he browser aligns t he baseline of t he first line of t ext in each cell in a row ( Figure 10- 4) . ( Unless you're a real perfect ionist , you won't even not ice t he subt let y of t he baseline opt ion. More im port ant ly, neit her will your visit ors.) Unlike t ext - align, t he vert ical- align propert y isn't inherit ed, so you can use it only on st yles t hat apply direct ly t o < t h> and < t d> t ags.
Figu r e 1 0 - 4 . Th e ve r t ica l- a lign pr ope r t y is t h e CSS e qu iva le n t of t h e < t d> t a g's a lign a t t r ibu t e . W h e n pa ddin g is a pplie d t o a ce ll, t h e con t e n t n e ve r a ct u a lly a lign s t o t h e bot t om or t op bor de r lin e s: Th e r e 's a lw a ys a ga p e qu a l t o t h e pa ddin g se t t in g. You ca n con t r ol t h e size of t h e pa ddin g ( se e Se ct ion 1 0 .2 .1 ) .
Section 10.2. Styling Tables
Tip: So far, the table formatting you've learned applies to all your tables. When you want to style individual tables (or table cells), change the selector you use. To apply a special design to a certain table, give it a class name
and create descendent selectors like .stocks td, or stocks th to uniquely format individual cells. If you want to style a particular cell differently than other cells in a table, then apply a class to the tag
and create a class style to format that cell.
10.2.3. Creating Borders The CSS border propert y ( Sect ion 7.3) works pret t y m uch t he sam e wit h t ables as wit h ot her elem ent s, but you need t o keep a couple of t hings in m ind. First , applying a border t o a st yle t hat form at s t he < t able> t ag out lines j ust t he t able, not any of t he individual cells. Second, applying borders t o cells ( t d { border: 1px solid black; } ) leaves you wit h a visual gap bet ween cells, as shown in Figure 10- 5, t op. To gain cont rol of how borders appear, you need t o underst and t he < t able> t ag's cellspacing at t ribut e and t he CSS border- collapse propert y. ●
●
Con t r ollin g t h e spa ce be t w e e n t a ble ce lls. Unless inst ruct ed ot herwise, browsers separat e t able cells by a couple of pixels. This gap's really not iceable when you apply a border t o t able cells. CSS 2.1 gives you t he border- spacing propert y t o cont rol t his space, but since I nt ernet Explorer ( including I E 7) doesn't support border- spacing, you're bet t er off using t he < t able> t ag's cellspacing at t ribut e. Here's t he HTML t o insert 10 pixels of space bet ween each cell: < t able cellspacing= " 10px" > . ( Set t ing t he value t o 0 elim inat es t he space ent irely, but if you want t o do t hat , t hen use t he CSS border- collapse propert y, discussed next .) Elim in a t in g dou ble bor de r s. Even if you elim inat e t he cell spacing of a t able, borders applied t o t able cells double up. That is, t he bot t om border of one cell adds t o t he t op border of t he underhanging cell, creat ing a line t hat 's t wice as t hick as t he border set t ing ( Figure 10- 5, m iddle) . The best way t o elim inat e t his ( and elim inat e cell- spacing at t he sam e t im e) is t o use t he border- collapse propert y. I t accept s t wo valuesseparat e and collapse. The separat e opt ion is norm ally how t ables are displayed, wit h t he cell spaces and doubled borders. Collapsing a t able's borders elim inat es t he gaps and doubled borders ( Figure 10- 5, bot t om ) . Apply t he collapse value t o a st yle form at t ing a t able, like so:
Section 10.2. Styling Tables
table { border-collapse: collapse; }
Note: HTML tags that are used to build tables include attributes that accomplish a lot of the same tasks as CSS. The border attribute can add a border to the table and each cell. In general, you should avoid these attributes: CSS can do a much better job with less code.
10.2.4. Styling Rows and Columns Adding st ripes, like t he ones in Figure 10- 6, is a com m on t able design t echnique. By alt ernat ing t he appearance of every ot her row of dat a, you m ake it easier for people t o spot t he dat a in each row. Unfort unat ely, CSS ( at least at t his point ) doesn't offer a way t o say, " Hey browser, m ake every ot her row look t his way! " The basic solut ion's t o apply a class ( like < t r class= " odd" > ) t o every ot her row, and t hen creat e a st yle t o form at t hat row: tr.odd { background-color: red; }
Figu r e 1 0 - 5 . Br ow se r s n or m a lly in se r t spa ce be t w e e n e a ch t a ble ce ll. ( You pr oba bly w on 't n ot ice t h is e x t r a spa ce u n le ss you 've a dde d a bor de r , a s sh ow n h e r e , a t t op.) I f you u se t h e < t a ble > t a g's ce llspa cin g a t t r ibu t e t o r e m ove t h e e x t r a spa ce , you 'r e le ft w it h dou ble bor de r lin e s w h e r e a dj oin in g bor de r s t ou ch ( m iddle ) . Th e bor de r - colla pse pr ope r t y solve s bot h dile m m a s ( bot t om ) .
Section 10.2. Styling Tables
You're not lim it ed t o colors eit her. You can use background im ages ( see Sect ion 8.2) t o creat e m ore sophist icat ed looks like t he slight gradat ion in t he t able header row of Figure 10- 6. ( You'll see a sim ilar exam ple of t his in t he t ut orial in Sect ion 10.4.) You can use a descendent select or t o t arget cells in t hat row as well. This t echnique's great for when you st yle all of t he cells in one colum n wit h t heir own class and look: < t d class= " price" > , for exam ple. To creat e a unique look for t hat cell when it appears in an odd row, creat e a st yle wit h t his select or: t r.odd t d.price.
Tip: For a quicker, JavaScript-driven approach to striping tables, check out www.alistapart.com/articles/zebratables/ .
Form at t ing colum ns is a bit t rickier. HTML provides t he < colgroup> and < col> t ags t o indicat e groups of colum ns and individual colum ns, respect ively. You include one < col> t ag for each colum n in t he t able and can ident ify t hem wit h eit her a class or I D. ( See t he HTML code in Sect ion 10.1.) Only t wo set s of propert ies work on t hese t ags: widt h and t he background propert ies ( background- color, background- im age, and so on) . But t hey can com e in m ight y handy. When you want t o set t he widt h of all of t he rows in a colum n, you can skip any HTML at t ribut es and j ust st yle t he colum ns using t he < col> t ag: col#price { width: 200px; }
Figu r e 1 0 - 6 . Alt e r n a t in g t h e ba ck gr ou n d color fr om r ow t o r ow in a t a ble m a k e s it e a sie r t o qu ick ly ide n t ify t h e da t a for e a ch r ow .
Section 10.2. Styling Tables
Of course, don't forget t o add a class or I D t o t he < col> t ag, like # price in t his exam ple. Likewise, t he < colgroup> t ag groups several colum ns t oget her. When you set a widt h for t hat t ag, a Web browser aut om at ically applies t he specified widt h t o each colum n in t he group. A t able displaying airline schedules m ight have several colum ns displaying t he different dat es a plane t ravels from Bost on t o Chicago. You can use < colgroup> t o organize t hose colum ns and apply an I D t o t he t ag t o ident ify it : < colgroup id= " dat es" > . Then, t o set each dat e colum n t o a set widt h of 10em s, you can creat e t his st yle: colgroup#dates{ width: 10em; }
Even t hough t he widt h propert y here applies t o t he < colgroup> t ag, a browser act ually applies t he value10em t o each colum n in t he group. To highlight a colum n, you can use t he background propert ies: col#price { background-color: #F33; }
Keep in m ind, however, t hat backgrounds for colum ns appear under t able cells, so if you set a background color or im age for < t d> or < t h>
Section 10.2. Styling Tables
t ags, t hen a colum n's background won't be visible.
Section 10.3. Styling Forms
10.3. Styling Forms Web form s are t he prim ary way visit ors int eract wit h a Web sit e. By supplying inform at ion on a form , you can j oin a m ailing list , search a dat abase of product s, updat e your personal profile on MySpace, or order t hat St ar Wars collect or's plat e you've had your eye on. There's no reason your form s need t o look like all t he ot hers on t he I nt ernet . Wit h a lit t le CSS, you can st yle form fields t o share t he sam e form at t ing as ot her sit e elem ent s like font s, background colors, and m argins. There aren't any CSS propert ies specific t o form s, but you can apply j ust about any propert y in t his book t o a form elem ent . The result s, however, can be m ixed ( see Figure 10- 7) . Browser support for st yling form elem ent s varies great ly. Safari 2 and earlier lim it s st yling t o only a few form elem ent s like t ext fields and t he < fieldset > and < legend> t ags. I t won't let you change t he look of but t ons, checkboxes, radio but t ons, or pull- down m enus. Even I nt ernet Explorer and Firefox m ay display t he sam e form elem ent s different ly. The next sect ion t ells you which propert ies work best wit h which form t ags, and also list s which browsers int erpret t hem properly.
UP TO SPEED Staying True to Form Even wit hout t he varying browser support for CSS- st yled form s ( Sect ion 10.3.1) , t here are good reasons t o t read light ly when alt ering t he look of universally recognized int erface elem ent s like Subm it but t ons and pull- down m enus. Most Web surfers are already very fam iliar wit h how form s look and work. The generic look of a Subm it but t on's t he sam e from sit e t o sit e. When people see it , t hey inst ant ly know what t hat but t on does and how t o use it . I f you alt er t he look of a form t oo m uch, you m ay m ake it harder for visit ors t o fill out your form correct ly. Adding a dot t ed border t o a form field can t urn an easily recognizable t ext field int o an easily skipped box. ( See t he exam ples at bot t om right and bot t om cent er of Figure 10- 7.) I f t hat t ext box is int ended t o capt ure em ail addresses for your newslet t er, you m ay lose a few visit ors who skip right over it . At t he very least , m ake sure people can recognize t he form s on your sit es as form s.
10.3.1. HTML Form Elements A variet y of HTML t ags help you build form s. You can form at som e of t hem ( like t ext fields) m ore successfully t han ot hers ( subm it but t ons.) Here are a few com m on form t ags and t he t ypes of propert ies t hey get along wit h: ●
Fie ldse t . The < fieldset > t ag groups relat ed form quest ions. Most browsers do a good j ob of displaying background colors, background im ages, and borders for t his t ag. However, I nt ernet Explorer let s t he background flow up and over t he t op line of t he fieldset . ( Look at t he t op of t he m iddle im age in Figure 10- 7, left colum n.) Padding places space from t he edges of t he fieldset t o t he cont ent inside it . ( Alt hough I nt ernet Explorer unfort unat ely ignores t op padding, you can sim ulat e it by adding a t op m argin t o t he first elem ent inside t he fieldset .)
Tip: Matt Heerema has found a way to prevent Internet Explorer from adding a background above a fieldset's top borderline. Read about it at www. mattheerema.com/archive/getting-fieldset-backgrounds-and-legends-to-behave-in-ie . ●
●
●
●
Le ge n d. The < legend> t ag follows t he HTML for t he < fieldset > t ag and provides a label for t he group of fields. The legend appears vert ically cent ered on t he t op borderline of a fieldset . I f t he form elem ent s for collect ing a shipping address appear inside t he fieldset , you m ight add a legend like t his: < legend> Shipping Address< / legend> . You can use CSS t o change t he < legend> t ag's font propert ies, add background colors and im ages, and add your own borders. Te x t fie lds. The < input t ype= " t ext " > ( < input t ype= " t ext " / > in XHTML) , < input t ype= " password" > ( < input t ype= " password" / > ) and t he < t ext area> t ags creat e t ext boxes on a form . These t ags give you t he m ost consist ent crossbrowser CSS cont rol. You can change t he font size, font fam ily, color, and ot her t ext propert ies for t ext boxes, as well as add borders and background colors. I E, Firefox, and Opera also let you add background im ages t o t ext boxes; Safari 2.0 doesn't . You can set t he widt h of t hese fields using t he CSS widt h propert y. However, only t he < t ext area> t ag obeys t he height propert y. Bu t t on s. Form but t onslike < input t ype= " subm it " > ( < input t ype= " subm it " / > ) let your visit ors subm it a form , reset it s cont ent s, or set off som e ot her act ion t o occur. While Safari 2.0 and earlier doesn't recognize form at t ing of t hese elem ent s, ot her browsers let you go wild wit h t ext form at t ing, borders, and backgrounds. You can also align t he but t on's t ext t o left , m iddle, or right using t he t ext - align propert y ( Sect ion 6.4.1.2) . D r op- dow n m e n u s. Drop- down m enus creat ed by t he < select > t ag also give you a fair am ount of st yling cont rol. Safari 2.0 lim it s you t o font fam ily, color, and size, while m ost ot her browsers also let you set background color, im age, and borders.
Figu r e 1 0 - 7 . Br ow se r su ppor t for st ylin g for m fie lds va r ie s. Sa fa r i 2 .0 ( r igh t ) h a s t h e st r on ge st
Section 10.3. Styling Forms
" k e e p you r h a n ds off m y u se r in t e r fa ce " policy. I n t e r n e t Ex plor e r ( le ft ) a n d Fir e fox ( ce n t e r ) a r e m or e t ole r a n t , bu t t h e r e a r e sign ifica n t diffe r e n ce s be t w e e n t h e m . I n t e r n e t Ex plor e r a pplie s ba ck gr ou n d color s a n d bor de r s t o ch e ck box e s a n d r a dio bu t t on s, w h ile Fir e fox doe sn 't . Th e be st you ca n do is de sign you r for m s ca r e fu lly a n d don 't e x pe ct t h e m t o look t h e sa m e on e ve r y br ow se r .
Note: For more on the wide variety of browser results you get when applying CSS to form elements, visit www.456bereastreet.com/archive/200409/ styling_form_controls/ and www.456bereastreet.com/archive/200410/styling_even_more_form_controls/.
Section 10.3. Styling Forms
●
Ch e ck box e s a n d r a dio bu t t on s. Most browsers don't allow form at t ing of t hese elem ent s. Opera, however, let s you set a background color t hat appears inside t he box or but t on. I nt ernet Explorer adds a background color around t he box or but t on. Because browsers vary widely in how t hey t reat t hese elem ent s, it 's best t o leave t hem alone.
POWER USERS' CLINIC Attribute: The Selector of the Future When it com es t o st yling form s, t ag st yles j ust don't cut t he m ust ard. Aft er all, t ext boxes, radio but t ons, checkboxes, password fields, and but t ons all share t he sam e HTML t ag< input > . While a widt h of 200 pixels m akes sense for a t ext box, you probably don't want your checkboxes t o be t hat big, so you can't use t he < input > t ag t o form at widt h. For now, t he m ost reliable way of form at t ing j ust t ext fields would be t o add a class nam e t o each t ext fieldlike < input t ype= " t ext " class= " t ext field" nam e= " em ail" / > and t hen use t he class st yle t o st yle it . Before long, you'll have a m ore advanced CSS select ort he at t ribut e select or. An at t ribut e select or t arget s an HTML t ag based on one of t he t ag's at t ribut es. The t ype at t ribut e is responsible for det erm ining what kind of form elem ent t he < input > t ag produces. The t ype value for a form t ext field is t ext . To creat e a st yle t hat m akes t he background color of all single- line t ext fields blue, you'd creat e t his select or and st yle: input[type="text"] { background-color: blue; }
Changing t ext in t he above exam ple t o subm it creat es a st yle for subm it but t ons only, and so on. Since I nt ernet Explorer 7, Firefox, Safari, and Opera already underst and at t ribut e select ors, it won't be long before you can st art using t hem full force. They're not j ust for form elem ent s eit her. You can use an at t ribut e select or t o st yle any t ag wit h a part icular at t ribut e. Here's t he select or for st yling links t hat point t o ht t p: / / www.cosm ofarm er.com / : a[ href= " ht t p: / / www.cosm ofarm er.com " ] . CSS 3 prom ises even m ore elaborat e at t ribut e select ors, including t he abilit y t o select at t ribut es t hat st art wit h a part icular value ( like ht t p: / / ) or which end wit h a part icular value ( like .j pg or .pdf) .
10.3.2. Laying Out Forms Using CSS All it t akes t o creat e a form is adding a bunch of labels and ot her form elem ent s t o a Web page. Visually, t hough, you m ay end up wit h a chaot ic m ess ( see Figure 10- 8, left ) . Form s usually look best when t he quest ions and form fields are organized int o colum ns ( Figure 10- 8, right ) .
Figu r e 1 0 - 8 . Th e diffe r e n t sh a pe s a n d size s of t e x t box e s, r a dio bu t t on s, a n d ot h e r for m obj e ct s don 't n a t u r a lly a lign w e ll w it h t e x t , oft e n ca u sin g a n u n ga in ly zigza g pa t t e r n . Th is for m isn 't j u st u gly, it 's h a r d t o r e a d ( le ft ) . Th e solu t ion 's t o or ga n ize you r for m s in t o colu m n s ( r igh t ) , u sin g e it h e r a n H TM L t a ble or CSS st yle s.
Section 10.3. Styling Forms
You can achieve t his effect in a couple of ways. The easiest approach is wit h an HTML t able. Alt hough form labels and fields aren't st rict ly t able dat a, t hey lend t hem selves beaut ifully t o a row/ colum n form at . Just put your labels ( " First Nam e," " Phone Num ber," and so on) in one colum n, and form fields in a second colum n. Using CSS, you can also creat e a t wo- colum n form like Figure 10- 8 ( wit h t he added benefit of less HTML code.) Here's t he basic approach: 1. W r a p e a ch la be l in a t a g. The obvious choice for a t ag is < label> , since it 's designed t o ident ify form labels. But you can't always use < label> t ags for all labels. Radio but t ons usually have a quest ion like " What 's your favorit e color?" followed by separat e < label> t ags for each but t on. So what t ag do you use for t he quest ion? I n t his case, you m ust resort t o wrapping t he quest ion in a < span> t ag: < span> What 's your favorit e color?< / span> . Then add a class t o each of t hese t ags: < span class= " label" > .
Note: Visit www.htmldog.com/guides/htmladvanced/forms/ for a quick overview on the tag. 2. Floa t a n d se t a w idt h for t h e la be ls. The secret t o t his t echnique lies in creat ing a st yle t hat float s t he labels t o t he left and set s a widt h for t hem . The widt h value should provide enough space t o accom m odat e t he ent ire label on one line if possible. You can creat e a class st yle t hat looks som et hing like t his: .label { float: left;
Section 10.3. Styling Forms
width: 20em; }
The widt h and float t urn t he labels int o lit t le evenly- sized blocks and let t he cont ent t hat followst he form fieldwrap on t he right side of t he label. 3. Adj u st t h e st yle . Just a couple m ore enhancem ent s com plet e t he j ob. You want t o align t he label t ext t o t he right , so each label appears next t o each form field. Also, adding a clear: left propert y clears t he float s ( Sect ion 7.6) , so t hat t he labels fall one below t he ot her inst ead of wrapping cont inuously. Finally, by adding a lit t le bit of right m argin, you can creat e a nice gut t er of whit e space bet ween t he labels and form fields. .label { float: left; width: 20em; text-align: right; clear: left; margin-right; 15px; }
At t his point , you've got yourself a sim ple, neat form . You can m ake ot her enhancem ent s if you wish, like m aking t he labels bold and a different color. The t ut orial t hat st art s in Sect ion 10.1 provides a st ep- by- st ep exam ple of t his t echnique.
Note: For a sophisticated demonstration of an all-CSS form layout, visit http://jeffhowden.com/code/css/forms/ .
Section 10.4. Tutorial: Styling a Table
10.4. Tutorial: Styling a Table HTML is great for building t ables, but you need CSS t o give t hem st yle. As you can see in Sect ion 10.1, it t akes quit e a bit of HTML t o const ruct a sim ple t able. Lucky for you, t his book com es wit h a prebuilt HTML t able for you t o pract ice your CSS on. I n t his t ut orial, you'll form at t he t able's rows, colum ns, and cells, and give it an at t ract ive font and background color. To get st art ed, 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 t he files are enclosed in a ZI P archive, so you need t o unzip t hem first . ( Go t o t he Web sit e for det ailed inst ruct ions.) The t able folder. files for t his t ut orial are in t he chapt er_10 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 _ 1 0
t a ble
t a ble .h t m l.
This Cosm oFarm er.com page cont ains a sim ple HTML t able t hat rat es t his season's indoor lawn m owers. The t able has a capt ion, a row of t able headers, and eight rows of dat a cont ained in t able cells ( Figure 10- 9) .
Figu r e 1 0 - 9 . For m a t t in g a t a ble w it h bor de r s, ba ck gr ou n d color s, a n d ot h e r CSS pr ope r t ie s n ot on ly m a k e s a dr a b H TM L t a ble ( t op) look gr e a t , bu t a lso m a k e s t h e t a ble 's da t a e a sie r t o r e a d ( bot t om ) .
2. Ope n t a ble .h t m l in a t e x t e dit or . You'll st art by creat ing a st yle t hat set s t he t able's widt h and t ext font .
Section 10.4. Tutorial: Styling a Table
Note: There are already a couple of external style sheets attached to this page, but you'll add your new styles to an internal style sheet. 3. Click be t w e e n t h e ope n in g a n d closin g < st yle > t a gs, a n d t h e n a dd t h e follow in g st yle : table { width: 100%; font-family: "Century Gothic", "Gill Sans", Arial, sans-serif; }
Unless you set t he widt h of a t able, it grows and shrinks t o fit t he size of t he cont ent inside it . I n t his case, you've set a 100 percent widt h, so t he t able st ret ches t o fit t he ent ire widt h of it s cont aining < div> . ( I n t his case, it 's t he area of t he page cont aining t he headline " Feat ure: I ndoor Mower Roundup" and t he t able it self.) Set t ing t he font fam ily in t he < t able> uses inherit ance t o give all of t he t ags inside t he t able t he sam e font < capt ion> , t able headers ( < t h> ) , t able cells ( < t d> ) , and so on. Next you'll st yle t he t able's capt ion. 4. Add a n ot h e r st yle be low t h e t a ble st yle you j u st cr e a t e d: caption { text-align: right; font-size: .75em; }
A < capt ion> t ag indicat es what a t able is about . I n t his case, it shouldn't be t he focus of at t ent ion, so you've shrunk t he t ext and m oved it t o t he right edge, out of t he way. When you read inform at ion across a t able row, it 's easy t o lose t rack of which row you're looking at . Good visual guides are essent ial. Adding borders around t he cells, which you'll do next , visually delineat es t he inform at ion. 5. Add t h e follow in g gr ou p st yle t o t h e in t e r n a l st yle sh e e t : td,th { font-size: .8em; border: 1px solid #73afb7; }
This group select or form at s t he t able header ( < t h> ) and t able cell ( < t d> ) t ags wit h sm aller t ype and draws a border around each header and each cell. Browsers norm ally insert space bet ween each cell, so at t his point t here are sm all gaps bet ween t he borders ( Figure 10- 10, circled) . Bet ween t he gaps and t he borders, t he whole t able looks t oo boxy. You'll fix t hat next . 6. Add t h e bor de r - colla pse pr ope r t y t o t h e t a ble st yle you cr e a t e d in st e p 3 so t h a t it look s lik e t h is: table { width: 100%; font-family: "Century Gothic", "Gill Sans", Arial, sans-serif; border-collapse: collapse; }
The border- collapse propert y rem oves t he spacing bet ween cells. I t also m erges borders t hat t ouch, which prevent s t hick, unat t ract ive borders. Wit hout border- collapse, t he bot t om border of a t able header and t he t op border of t he t able cell would double up t o m ake a 2pixel border. I f you preview t he t able now, you'll see t he dat a's bet t er organized visually, but t he inform at ion in each cell looks a lit t le cram ped. Add som e padding t o fix t hat .
Section 10.4. Tutorial: Styling a Table
7. Add pa ddin g t o t h e gr ou p se le ct or you cr e a t e d in st e p 5 : td,th { border: 1px solid #73afb7; padding: 3px 5px 2px 5px; font-size: .8em; }
While t he t op, t able- header row st ands out because of it s boldface t ext , t here are a few t hings you can do t o m ake it st and out even m ore and approve it s appearance. 8. Cr e a t e a n e w st yle be low t h e t d, t h st yle for for m a t t in g j u st t a ble h e a d ce lls: th { text-align: left; border-color: #14556b; }
This st yle's a perfect exam ple of effect ive cascading. The group select or t d, t h defines com m on form at t ing propert ies bet ween t he t wo t ypes of cells. By int roducing t his t h- only st yle, you can furt her t weak t he look of j ust t he t able headers. Not ice t hat t he basic border propert ies, such as line st yle and t hickness, com e from t he group select or, but t he t h st yle overrides t he border color. That 's why you m ust put t his st yle aft er t he t d,t h st yle in your code. Ot herwise, t his new border color has no effect . The t able headers st ill don't have enough oom ph, and t he t able seem s t o recede int o t he background of t he page. A background graphic can provide t he necessary boost .
Figu r e 1 0 - 1 0 . A br ow se r 's n or m a l displa y of a t a ble in se r t s spa ce be t w e e n e a ch ce ll ( t op) . I t a lso le t s bor de r s dou ble u p w h e r e ce lls t ou ch . Se t t in g t h e bor de r - colla pse pr ope r t y t o colla pse solve s bot h pr oble m s ( bot t om ) .
Section 10.4. Tutorial: Styling a Table
9. Edit t h e t h st yle by a ddin g a ba ck gr ou n d im a ge , a n d ch a n gin g t h e t e x t color : th { background: url(images/th_bg.png) no-repeat left top; color: white; text-align: left; border-color: #14556b; }
I n t his case, t he graphic int roduces a subt le t op- down gradient while a whit e borderline at t he t op and left edges of t he im age cont rast s nicely wit h t he darker t op and left borders around t he cells, giving t he cells a 3- D look.
Tip: By the way, you could just as easily set the background color of these cells to achieve a similar effect.
When t ables have lot s of dat a st uffed int o m any rows and colum ns, it 's som et im es hard t o quickly ident ify which dat a belongs t o each row. One solut ion designers use is t o alt ernat e t he color of every ot her row in a t able. You creat e t his effect wit h a class st yle t hat you apply t o every ot her t able row. 10. Add on e la st st yle t o t h e W e b pa ge 's in t e r n a l st yle sh e e t : tr.alt td { background: url(images/td_bg.png) no-repeat left top; }
This select or places a background im age int o every t able cell ( < t d> t ag) , but only when t hat < t d> t ag is nest ed inside a t able row ( < t r> t ag) wit h a class of alt applied t o it . So, next you have t o apply t he class t o every ot her row for t his st yle t o have any effect . 11. I n t h e pa ge 's H TM L, look for t h e < t r > t a g t h a t pr e ce de s t h e < t d> con t a in in g " Sa m pson D e lu x e Apa r t m e n t M ow e r ." Add cla ss= " a lt " t o t h a t < t r > t a g, lik e so:
Sampson Deluxe Apartment Mower
You'll need t o do t his wit h every second row aft er t his one as well. ( Manually t agging each alt ernat ing row can be t edious, especially if you frequent ly add or reorder t able rows. For an aut om at ed approach t o st riping t able rows using a lit t le JavaScript program m ing, see t he Tip in Sect ion 10.2.1.) 12. Re pe a t st e p 1 1 for t h e < t r > t a gs t h a t pr e ce de t a ble ce lls w it h t h e follow in g t e x t : Ur ba n M ow - m a ch in e , Th e Lor e m I psu m D olor 3 0 0 , a n d Gr a ss M a st e r V9 . Preview t he page in a Web browser t o see t he result s. Your page should look like t he bot t om im age in Figure 10- 9. You'll also find t he com plet ed exercise in t he chapt er_10_finished
t able folder.
Section 10.5. Tutorial: Styling a Form
10.5. Tutorial: Styling a Form This t ut orial gives you som e pract ice using CSS t o organize a form and m ake it m ore at t ract ive. I f you open form form .ht m l in a Web browser, t hen you'll see it cont ains a sim ple form for chapt er_10 subscribing t o Cosm oFarm er.com ( Figure 10- 11) . The form asks several quest ions and uses a variet y of form elem ent s for input , including t ext boxes, radio but t ons, and pull- down m enus. As subscript ion form s go, it looks fine, but a lit t le bland. I n t he st eps on t he following pages, you'll Cosm oFarm er- ize t he font s, line up t he quest ions and boxes bet t er, and add a few ot her im provem ent s. 1. Ope n t h e file for m .h t m l in a t e x t e dit or . There's already an ext ernal st yle sheet at t ached t o t his page, but you'll add your new st yles t o an int ernal st yle sheet . St art by bringing down t he size of t he t ype in t he form . 2. Click be t w e e n t h e ope n in g a n d closin g < st yle > t a gs, a n d t h e n a dd t h e follow in g st yle : #subForm { font-size: .8em; }
The subscript ion form has an I D of subForm applied t o it , so t his st yle set s t he t ext size for all t ext bet ween t he < form > t ags.
Figu r e 1 0 - 1 1 . H TM L's < t a ble > t a g is a com m on w a y t o or ga n ize t h e qu e st ion s of a for m . Bu t you ca n a lso u se CSS ( a n d a lot le ss H TM L) t o m a k e t h e for m 's la you t cle a r e r a n d m or e a t t r a ct ive .
Section 10.5. Tutorial: Styling a Form
Tim e t o work on t he layout . To bet t er align t he form elem ent s, you'll creat e t he appearance of t wo colum ns, one for t he quest ions ( labels) and anot her for t he answers ( form fields) . 3. Add a n ot h e r st yle t o t h e in t e r n a l st yle sh e e t : #subForm .label { float: left; width: 230px; }
This descendent select or ident ifies any elem ent wit h a class of .label wit hin t his form . The st yle set s a widt h of 230 pixels and float s t he elem ent t o t he left . Rem em ber t he float propert y let s you m ove elem ent s t o one side or t he ot her of a cont aining block. I t has t he added benefit of let t ing you set a
Section 10.5. Tutorial: Styling a Form
widt h and force elem ent s t hat follow t he st yle t o wrap around it . As a result , when you apply t his st yle t o each of t he quest ions in t he form , you creat e an even- widt h colum n. But in order t o see t he effect , you m ust first apply t he class t o t he appropriat e page elem ent s. 4. I n t h e pa ge 's H TM L, loca t e t h is code < la be l for = " n a m e " > a n d a dd cla ss= " la be l" , so t h e t a g look s lik e t h is:
You m ust do t he sam e for each quest ion in t he form , so… 5. Re pe a t st e p 5 for t h e follow in g pie ce s of H TM L code : < la be l for = " e m a il" > , < la be l for = " r e fe r " > , < la be l for = " com m e n t s" > . There's one addit ional quest ion on t he form " Rat e your apart m ent farm ing skills." I t isn't inside a label t ag, since it s purpose is t o int roduce a series of radio but t ons, each of which has it s own label. You need t o add a < span> t ag t o t his t ext so you can apply t he label st yle t o it . 6. Fin d t h e t e x t Ra t e you r a pa r t m e n t fa r m in g sk ills, a n d t h e n w r a p it in a < spa n > t a g w it h a cla ss of la be l, lik e so: Rate your apartment farming skills
Now t he quest ions appear t o be in a single colum n ( Figure 10- 12, t op) . But t hey'd look bet t er if t hey st ood out m ore and lined up wit h t he corresponding form fields. 7. Edit t h e # su bFor m .la be l st yle you cr e a t e d in st e p 4 , so it look s lik e t h is: #subForm .label { float: left; width: 230px; margin-right: 10px; text-align: right; font-weight: bold; }
Preview t he page in a Web browser. The form should look like t he bot t om im age in Figure 10- 12. There's one last st ep for t hese labels. Because t hey're float ed t o t he left , if t he t ext runs m ore t han one line, t he quest ion t hat follows will also t ry t o wrap around t o t he right . Fix t hat by applying t he clear
Section 10.5. Tutorial: Styling a Form
propert y.
Note: You can see a similar problem illustrated in Figure 7-12. See "Stopping the Float" in Section 7.6.2 for more detail on clearing floats. 8. Add a cle a r pr ope r t y t o t h e # su bFor m .la be l st yle : #subForm .label { float: left; width: 230px; margin-right: 10px; text-align: right; font-weight: bold; clear: left; }
The form 's shaping up, but t hat Subscribe but t on looks out of place over at t he left edge. You'll align it wit h t he ot her form elem ent s next .
Figu r e 1 0 - 1 2 . Som e t im e s sm a ll a n d su bt le ch a n ge s ca n m a k e a for m m or e r e a da ble . M a k in g t h e qu e st ion s on t h e for m bold, a n d a lign in g t h e m w it h t h e ir cor r e spon din g for m e le m e n t s ( bot t om figu r e ) im m e dia t e ly im pr ove s t h e look of t h e for m .
Section 10.5. Tutorial: Styling a Form
9. Add a n ot h e r st yle t o t h e in t e r n a l st yle sh e e t . input#subscribe { margin-left: 240px; }
Section 10.5. Tutorial: Styling a Form
The < input > t ag t hat creat es t his Subscribe but t on has an I D of subscribe already applied t o it , so t his st yle indent s t he but t on 240 pixels t o m at ch t he widt h and right m argin of t he # subForm .label st yle. Most browsers let you st yle but t ons in ot her ways, t oo, so… 10. Edit t h e Su bscr ibe bu t t on st yle by a ddin g a ba ck gr ou n d color a n d fon t t o t h e st yle you j u st cr e a t e d: input#subscribe { margin-left: 240px; background-color: #CBD893; font-family: "Century Gothic", "Gill Sans", Arial, sans-serif; }
You can even change t he font used in a pull- down m enu. 11. Add a st yle for t h e for m 's se le ct m e n u : select#refer { font-family: "Century Gothic", "Gill Sans", Arial, sans-serif; }
Note: You can style submit buttons and pull-down menus in Internet Explorer, Firefox, and Opera. Safari 2.0, as of this writing, doesn't let you change these basic form elements.
There! You've got t he t ext labels and Subscribe but t on looking great , but why st op t here? Tim e t o j azz up t he form fields. Begin by changing t heir font and background colors. 12. Cr e a t e a n e w gr ou p se le ct or for st ylin g t h e t h r e e t e x t box e s in t h e for m : input#name, input#email, textarea#comments { background-color: #FBEF99; font-family: "Lucida Console", Monaco, monospace; font-size: .9em; }
This st yle gives t he t ext boxes a light yellow background color and set s a new size and font for t ext visit ors t o t ype int o t hem . The boxes look a lit t le narrow, and t hey also appear a lit t le low com pared t o t heir labels at right . Fixing t hese t wo problem s wit h CSS is a snap:
Section 10.5. Tutorial: Styling a Form
Edit t h e st yle you j u st cr e a t e d by se t t in g a w idt h , a n d a lt e r in g t h e t op m a r gin : input#name, input#email, textarea#comments { background-color: #FBEF99; font-family: "Lucida Console", Monaco, monospace; font-size: .9em; width: 300px; margin-top: -2px; }
You can m ake your form easier for your visit ors t o fill out by highlight ing t he act ive form elem ent wit h t he special : focus pseudo- class ( Sect ion 9.1) . You'll add t hat in t he next st ep. 14. 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 dd on e la st st yle for t h e pu ll- dow n m e n u a n d t h e t h r e e t e x t fie lds: input#name:focus, input#email:focus, textarea#comments:focus, select#refer:focus { background-color: #FDD041; }
The : focus pseudo- class works only in Firefox, Safari, and Opera at t his writ ing, but since it doesn't do I E people any harm , adding a : focus st yle is a fun enhancem ent . Preview t he page in a Web browser. I t should now look like Figure 10- 13. You can find a com plet ed version of t his t ut orial in t he chapt er_10_finished
form folder.
Figu r e 1 0 - 1 3 . Usin g t h e :focu s pse u do- cla ss, you ca n m a k e you r for m s m or e in t e r a ct ive by h igh ligh t in g for m fie lds t h e visit or u se s. H e r e , you ca n se e you 'r e a bou t t o t ype in t o t h e Com m e n t s fie ld be ca u se of it s da r k e r ba ck gr ou n d color .
Section 10.5. Tutorial: Styling a Form
Part III: CSS Page Layout
Part III: CSS Page Layout Ch a pt e r 1 1 : Bu ildin g Floa t - Ba se d La you t s Ch a pt e r 1 2 : Posit ion in g Ele m e n t s on a W e b Pa ge
Chapter 11. Building Float-Based Layouts
Chapter 11. Building Float-Based Layouts CSS leads a double life. As great as it is for form at t ing t ext , navigat ion bars, im ages, and ot her bit s of a Web page, it s t ruly awesom e power com es when you're ready t o lay out ent ire Web pages. CSS layout com es in t wo flavors absolut e posit ioning and float s. Absolut e posit ioning let s you posit ion an elem ent anywhere on t he page wit h pixel- level accuracyor so t he t heory goes. This kind of t ot al cont rol is excit ing, as you'll see in t he next chapt er, but act ually very difficult t o achieve. That 's why t he vast m aj orit y of Web pages use float - based layout s, which are t he subj ect of t his chapt er.
Section 11.1. How CSS Layout Works
11.1. How CSS Layout Works As discussed in Chapt er 1, t he lim it at ions of HTML forced designers t o develop clever ways t o m ake t heir Web sit es look good. The m ost com m on t ool was t he < t able> t ag, which was originally supposed t o be used t o creat e a spreadsheet - like display of inform at ion com posed of rows and colum ns of dat a. I nst ead, designers used HTML t ables t o build a kind of scaffolding for organizing a page's cont ent s ( see Figure 11- 1) . But because t he < t able> t ag wasn't m eant for layout , designers oft en had t o m anipulat e t he t ag in unusual wayslike placing a t able inside t he cell of anot her t ablej ust t o get t he effect t hey want ed. This m et hod was a lot of work, added a bunch of ext ra HTML code, and m ade it very difficult t o m odify t he design lat er. But before CSS, t hat 's all Web designers had. I f you're a longt im e < t able> t ag j ockey, you need t o develop a new m indset when you begin t o use CSS for layout . First , forget about rows and colum ns ( a not ion t hat 's im port ant when working wit h t ables) . There are no colum n spans or row spans, and t he grid- like st ruct ure of a t able is nowhere t o be found in CSS. You can, however, t hink of a < div> t ag as a t able cell. As wit h t able cells, a < div> t ag is t he logical place t o put cont ent t hat you want t o posit ion in one area of t he page. I n addit ion, as you'll see, CSS designs oft en nest a div inside anot her div, m uch like you'd nest t ables wit hin t ables t o get cert ain effect sbut , fort unat ely, t he CSS m et hod uses a lot less HTML code.
Figu r e 1 1 - 1 . Bu ildin g a com ple x pa ge de sign ( le ft ) u sin g t h e < t a ble > t a g in volve s t r ick s lik e n e st in g t a ble s w it h in t a ble s, m e r gin g a dj a ce n t ce lls, a n d pr oppin g ope n ce lls w it h in visible spa ce r im a ge s. I t 's lik e bu ildin g a r igid sca ffoldin g ( r igh t ) , a n d ch a n gin g t h e de sign of a pa ge r e qu ir e s t e a r in g dow n t h e sca ffoldin g a n d bu ildin g a n e w on e .
11.1.1. The Mighty Tag Whet her you're using t ables or CSS, Web page layout involves put t ing chunks of cont ent int o different regions of t he page. Wit h CSS, t he elem ent m ost com m only used for organizing cont ent is t he < div> t ag. As you read in Sect ion 1.2.1, t he < div> t ag is an HTML elem ent t hat has no inherent form at t ing propert ies ( besides t he fact t hat browsers t reat t he t ag as a block wit h a line break before and aft er it ) ; inst ead, it 's used t o m ark a logical grouping of elem ent s or a division on t he page. You'll t ypically wrap a < div> t ag around a chunk of HTML t hat belongs t oget her. The elem ent s com prising t he logo and navigat ion bar in Figure 11- 1 occupy t he t op of t he page, so it m akes sense t o wrap a < div> t ag around t hem . At t he very least , you would include < div> t ags for all t he m aj or regions of your page, such as t he banner, m ain cont ent area, sidebar, foot er, and so on. But it 's also possible t o wrap a < div> t ag around one or m ore addit ional divs. One com m on t echnique is t o wrap t he HTML inside t he < body> t ag in a < div> . Then you can set som e basic page propert ies by applying CSS t o t hat wrapper < div> . You can set an overall widt h for t he page's cont ent , set left and
Section 11.1. How CSS Layout Works
right m argins, or cent er all of t he page's cont ent in t he m iddle of t he screen. ( You'll get a chance t o work wit h a wrapper < div> in t he t ut orial in Sect ion 11.1.1.) Once you've got your < div> t ags in place, add eit her a class or I D t o each one, which becom es your handle for st yling each < div> separat ely. For part s of t he page t hat appear only once and form t he basic building blocks of t he page, designers usually use an I D. The < div> t ag for a page's banner area m ight look like t his: < div id= " banner" > . You can use an I D only once per page, so when you have an elem ent t hat appears m ult iple t im es, use a class inst ead. I f you have several divs t hat posit ion phot os and t heir capt ions, t hen you can creat e a st yle like t his: < div class= " phot o" > . Wit h st yles like t hese, you can posit ion t he various page elem ent s. Using t he CSS float propert y, you can posit ion different blocks of cont ent t o t he left or right of a page ( or left or right edge of a cont aining block like anot her < div> ) .
WORD TO THE WISE When More Isn't Better Alt hough divs are crit ical t o CSS layout , don't go crazy pelt ing your page wit h divs. A com m on t rap is t o believe you m ust wrap everyt hing on a Web page in a < div> t ag. Say your m ain navigat ion bar is an unordered list of links ( like t he one described in Sect ion 9.1.1) . Because it 's an im port ant elem ent , you m ay be t em pt ed t o wrap a < div> around it : < div id= " m ainNav" > < ul> …< / ul> < / div> . But t here's no reason t o add a < div> when t he < ul> t ag's j ust as handy. As long as t he < ul> cont ains t he m ain navigat ion bar links, you can sim ply add your I D st yle t o t hat t ag: < ul id= " m ainNav" > . An addit ional < div> is j ust unnecessary code.
Section 11.2. Types of Web Page Layouts
11.2. Types of Web Page Layouts Being a Web designer m eans dealing wit h t he unknown. What kind of browsers do your visit ors use? Do t hey have t he lat est Flash Player plug- in inst alled? Perhaps t he biggest issue designers face is creat ing at t ract ive designs for different display sizes. Monit ors vary in size and resolut ion: from pet it e 15- inch 640 x 480 pixel displays t o 30- inch m onst rosit ies displaying, oh, about 5,000,000 x 4,300,000 pixels. Float - based layout s offer t hree basic approaches t o t his problem . Nearly every page design you see falls int o one of t wo t ypesfixed widt h, or liquid. A fixed widt h gives you t he m ost cont rol over how your design looks, but can inconvenience som e of your visit ors. Folks wit h really sm all m onit ors have t o scroll t o t he right t o see everyt hing, and t hose wit h large m onit ors have wast ed space t hat could be showing m ore of your excellent cont ent . Liquid designs m ake cont rolling t he design of t he page m ore challenging, but m ake t he m ost effect ive use of t he browser window. An elast ic design com bines som e advant ages of bot h. ●
Fix e d W idt h . Many designers prefer t he consist ency of a set widt h, like t he page in Figure 11- 2, t op. Regardless of t he browser window's widt h, t he page con- t ent 's widt h rem ains t he sam e. I n som e cases, t he design clings t o t he left edge of t he browser window, or, m ore com m only, it 's cent ered in t he m iddle. Wit h t he fixed- widt h approach, you don't have t o worry about what happens t o your design on a very wide ( or sm all) m onit or. Many fixed- widt h designs are about 760 pixels widea good size for 800 x 600 screens ( since you need t o leave a lit t le room for scrollbars and ot her part s of t he browsers " chrom e" ) . However, m ore and m ore sit es ( especially ones aim ed at a m ore t ech- savvy crowd) are about 950 pixels wide, on t he assum pt ion t hat visit ors have at least 1024 x 768 m onit ors.
Note: For examples of fixed-width designs aimed at larger monitors, visit www.alistapart.com, www.espn.com, or www.nytimes.com. ●
Liqu id. Som et im es it 's easier t o roll wit h t he t ide inst ead of fight ing it . A liquid design adj ust s t o fit t he browser's widt hwhat ever it m ay be. Your page get s wider or narrower as your visit or resizes t he window ( Figure 11- 2, m iddle) . While t his t ype of design m akes t he best use of t he available browser window real est at e, it 's m ore work t o m ake sure your design looks good at different window sizes. On very large m onit ors, t hese t ypes of designs can look ridiculously wide.
Note: The max-width and min-width properties offer a compromise between fixed and liquid designs. See Section 11.4.3. ●
Ela st ic. An elast ic design is really j ust a fixed- widt h design wit h a t wist t ype size flexibilit y. Wit h t his kind of design, you define t he page's widt h using em values. An em changes size when t he browser's font size changes, so t he design's widt h is ult im at ely based on t he browser's base font size ( see Sect ion 6.2.2) . I f a visit or increases t he size of t he browser's display font ( by pressing Ct rl+ in Firefox, for exam ple) , t hen t he page's widt h grows as well. Figure 11- 2, bot t om , shows an elast ic page wit h t he browser's norm al font size ( left ) and several font sizes larger ( right ) . I ncreasing t he font size m akes all page elem ent s wider as well. Elast ic
Section 11.2. Types of Web Page Layouts
designs keep everyt hing on your page in t he sam e relat ive proport ions, and m ake sure t hat when som eone wit h poor vision has t o pum p up t he t ext size, t he colum ns holding t he t ext grow as well. I n t he t ut orials at t he end of t his chapt er, you'll creat e a fixed- widt h design and a liquid design.
Section 11.3. Float Layout Basics
11.3. Float Layout Basics Float - based layout s t ake advant age of t he float propert y t o posit ion elem ent s side by side and creat e colum ns on a Web page. As described in Chapt er 7 ( Sect ion 7.6) , you can use t his propert y t o creat e a wrap- around effect for, say, a phot ograph, but when you apply it t o a < div> t ag, float becom es a powerful page- layout t ool. The float propert y m oves a page elem ent t o one side of t he page ( or ot her cont aining block) . Any HTML t hat appears below t he float ed elem ent m oves up on t he page and wraps around t he float .
Figu r e 1 1 - 2 . You h a ve se ve r a l w a ys t o de a l w it h t h e u n ce r t a in w idt h s of W e b br ow se r w in dow s a n d br ow se r fon t size s. You ca n sim ply ign or e t h e fa ct t h a t you r sit e 's visit or s h a ve diffe r e n t r e solu t ion m on it or s a n d for ce a sin gle , u n ch a n gin g w idt h for you r pa ge ( t op) , or cr e a t e a liqu id de sign t h a t flow s t o fill w h a t e ve r w idt h w in dow it e n cou n t e r s ( m iddle ) . An e la st ic de sign ( bot t om ) ch a n ge s w idt h on ly w h e n t h e fon t size n ot t h e w in dow w idt h ch a n ge s.
Section 11.3. Float Layout Basics
The float propert y accept s one of t hree different valuesleft , right , and none. To m ove an im age t o t he right side of t he page, you could creat e t his class st yle and apply it t o t he < im g> t ag: . floatRight { float: right; }
The sam e propert y applied t o a < div> t ag full of cont ent can also creat e a sidebar: #sidebar { float: left; width: 170px; }
Figure 11- 3 shows t hese t wo st yles in act ion.
Note: The none value turns off any floating and positions the element like a normal, unfloated element. It's useful only for overriding a float that's already applied to an element. You may have an element with a particular class such as "sidebar" applied to it and that element floats to the right. But on one page you may want an element with that class to not float, but to be placed within the flow of the page, like this Note box. By creating a more specific CSS selector (see Section 5.3) with float: none, you can prevent that element from floating.
Figu r e 1 1 - 3 . You ca n u se t h e floa t pr ope r t y t o la y ou t a W e b pa ge w it h m u lt iple colu m n s. On t h is pa ge , a block of con t e n t is floa t e d t o t h e le ft e dge . Th e side ba r h a s a se t w idt h , bu t t h e m a in con t e n t doe sn 't , w h ich m a k e s t h is de sign a liqu id la you t ( Se ct ion 1 1 .1 ) . Th e m a in se ct ion of t h e pa ge sim ply e x pa n ds t o fill t h e w idt h of t h e br ow se r w in dow . I n t h e u ppe r r igh t , t h e ba t h t u b ph ot o is floa t e d t o t h e r igh t .
Section 11.3. Float Layout Basics
A sim ple t wo- colum n design like Figure 11- 3 requires j ust a few st eps: 1.
Section 11.3. Float Layout Basics
W r a p e a ch colu m n in a < div> t a g w it h a n I D or cla ss a t t r ibu t e . I n Figure 11- 3, t he news it em s list ed in t he left sidebar are wrapped in one < div> < div id= " news" > and t he m ain cont ent in anot her div< div id= " m ain" > . 2. Floa t t h e side ba r < div> e it h e r r igh t or le ft . When you work wit h float s, t he source order ( t he order in which you add HTML t o a file) is im port ant . The HTML for t he float ed elem ent m ust appear before t he HTML for t he elem ent t hat wraps around it . Figure 11- 4 shows t hree t wo- colum n layout s. The diagram s on t he left side show t he page's HTML source order: A < div> for t he banner, followed by a < div> for t he sidebar and, last ly, a < div> for t he m ain cont ent . On t he right side, you see t he act ual page layout . The sidebar com es before t he m ain cont ent in t he HTML so it can float eit her left ( t op, bot t om ) or right ( m iddle) .
Figu r e 1 1 - 4 . Cr e a t in g a t w o- colu m n la you t 's a sim ple m a t t e r of floa t in g a < div> t a g t o t h e le ft ( t op) . To m a k e a side ba r m ove fr om t h e le ft t o r igh t side of t h e pa ge ( m iddle ) , j u st ch a n ge t h e side ba r 's CSS st ylin g t o floa t : r igh t . You don 't n e e d t o m a k e a n y ot h e r ch a n ge s t o you r CSS or H TM L.
Section 11.3. Float Layout Basics
3. Se t a w idt h for t h e floa t e d side ba r . Unless you're float ing an im age wit h a predefined widt h, you should always give your float s a widt h. I n t his way, you creat e a set size for t he float ed elem ent , let t ing t he browser m ake room for ot her cont ent t o wrap int o posit ion. The widt h could be a fixed size like 170px or 10em . You can also use percent ages for a flexible design t hat 's based on t he widt h of t he browser window. ( See Sect ion 11.1 for m ore about t he pros and cons of t he different m easurem ent unit s.) I f t he sidebar is 20 percent wide and t he browser window is 700 pixels wide, t hen t he sidebar will be 140 pixels wide. But if your visit or resizes t he window t o 1000 pixels, t hen t he sidebar grows t o 200 pixels. Fixed- widt h sidebars are easier t o design for, since you don't have t o consider all t he different widt hs t he sidebar m ight st ret ch t o. However, percent ages let you m aint ain t he sam e proport ions bet ween t he t wo colum ns, which can
Section 11.3. Float Layout Basics
be m ore visually pleasing.
Note: When the overall page design is a fixed width (as described in Section 11.1), percentage width values for the sidebar are based on the fixed-width containing element. The width isn't based on the window size and won't change when the browser window changes size. 4. Add a le ft m a r gin t o t h e m a in con t e n t . I f t he sidebar's short er t han t he ot her cont ent on t he page, t he t ext from t he m ain colum n wraps underneat h t he sidebar, ruining t he look of t wo side- by- side colum ns ( see Figure 11- 18 for an exam ple) . Adding a left m argin t hat 's equal t o or great er t han t he widt h of t he sidebar indent s t he m ain cont ent of t he page, creat ing t he illusion of a second colum n: #main { margin-left: 180px ; }
By t he way, it 's usually a good idea t o m ake t he left m argin a lit t le bigger t han t he widt h of t he sidebar: This creat es som e em pt y spacea whit e gut t erbet ween t he t wo elem ent s. So, when you use percent ages t o set t he widt h of t he sidebar, use a slight ly larger percent age value for t he left m argin. Avoid set t ing a widt h for t he m ain cont ent div. I t 's not necessary, since browsers sim ply expand it t o fit t he available space. Even if you want a fixed- widt h design, you don't need t o set a widt h for t he m ain cont ent div, as you'll see in t he next sect ion.
Section 11.4. Applying Floats to Your Layouts
11.4. Applying Floats to Your Layouts Now t hat you've learned a basic t wo- colum n liquid layout , you can adapt it in count less ways. Convert ing it int o a fixed- widt h layout is a snap. Sim ply wrap all t he t ags wit hin t he page's body inside anot her < div> ( like < div id= " wrapper" > ) . Then, creat e a st yle for t hat new cont ainer elem ent t hat has a set widt h such as 760 pixels ( see Figure 11- 4, bot t om ) . That widt h set t ing const rains everyt hing inside t he cont ainer box. Expanding it int o a t hree- colum n design isn't difficult , eit her ( Figure 11- 5) . First , add anot her < div> bet ween t he t wo colum ns and float it t o t he right . Then add a right m argin t o t he m iddle colum n, so t hat if t he t ext in t he m iddle colum n runs longer t han t he new right sidebar, it won't wrap underneat h t he sidebar. The rest of t his sect ion explores m ore CSS layout t echniques t hat use float - based layout s.
Figu r e 1 1 - 5 . A t h r e e - colu m n de sign u se s t h e sa m e con ce pt s u se d t o cr e a t e a t w o- colu m n de sign . I n t h is ca se , you floa t bot h t h e le ft a n d r igh t side ba r s a n d a dd bot h le ft a n d r igh t m a r gin s t o t h e ce n t e r colu m n . Th e le ft - h a n d dia gr a m sh ow s t h e or de r of t h e H TM L; t h e r igh t side sh ow s w h a t t h e W e b pa ge look s lik e .
Section 11.4. Applying Floats to Your Layouts
UP TO SPEED Don't Reinvent the Wheel I f t erm s like liquid layout and cont aining elem ent sound a lit t le int im idat ing, don't give up. First of all, t he t ut orials beginning in Sect ion 11.1 walk you st ep by st ep t hrough t he process of laying out Web pages wit h CSS. But t here's no law saying you have t o creat e your own CSS layout s from scrat ch. On t he Web you'll find plent y of pre- built and t est ed designs you can m ake your own. The Layout Gala sit e offers 40 different CSS designs t hat work in m ost com m on browsers, including I nt ernet Explorer 5 ( ht t p: / / blog.ht m l.it / layout gala/ ) . The designs are j ust basic skelet ons consist ing of < div> t ags and t he CSS t hat posit ions t hem . All you need t o do is fill t hem wit h your own design t ouches like font st yling and im agery. For a sophist icat ed design including m ult iple t em plat es, drop- down m enus, and preform at t ed t ext and link st yles, check out t he Mollio t em plat es at www.m ollio.org . The sit e includes a st yle guide explaining how t o use t he t em plat es, as well as t he original Phot oshop files so you can t weak t he graphics' appearance t o your liking. Finally, for a t ot al sm orgasbord of CSS designs, check out Open Source Web Design ( www. oswd.org ) . This sit e includes lit erally t housands of Web page designs t hat you can freely download and reuse.
11.4.1. Floating All Columns I t 's perfect ly possible t o float every colum n, not j ust t he left and right sidebars. You could float t he first sidebar t o t he left , t he m iddle colum n t o t he left , and t he right sidebar t o t he right , as shown in Figure 116, t op. This approach let s you put m ore t han t hree colum ns in your design. You can float four or m ore colum ns, as long as t here's room for all t he float s t o fit side by side. When you float all colum ns in a design, you need t o pay close at t ent ion t o t he widt hs of each colum n. I f t he t ot al widt h of all t he colum ns is less t han t he space availablefor exam ple, if t he browser window is sm aller, or t he colum ns are placed inside anot her < div> wit h a set widt ht hen t he last colum n drops down, below t he ot hers. ( You can read a solut ion t o t his dropping float problem in Sect ion 11.1.1.) I n addit ion, float ing m ore t han j ust t he sidebars let s you change t he order of your divs in t he HTML. Take, for exam ple, t he left diagram in Figure 11- 5, which shows t he order of t he < div> t ags for t hat page. Because of t he way float ed elem ent s work, t hey m ust appear before any cont ent t hat wraps around t hem , so in t his exam ple, t he m ain cont ent area m ust go aft er t he sidebars. The order of t he < div> t ags in t he HTML m ay not seem like a big deal unt il you t ry t o browse t he Web page wit hout CSS, which is t he case for m any alt ernat ive browsers, including screen readers which read a page's cont ent aloud t o visually im paired visit ors. Wit hout CSS, all t he sidebar m at erial ( which oft en includes navigat ional elem ent s, ads, or ot her inform at ion t hat 's not relevant t o t he m ain t opic of t he page) appears before t he cont ent t he visit or cam e t o read in t he first place. The inconvenience of having t o scroll past t he sam e sidebar cont ent on each page will t urn off som e visit ors. Furt herm ore, your page is less accessible t o vision- im paired visit ors, who have t o list en t o t heir screen readers read off a long list of links and ads before com ing t o any real inform at ion.
Section 11.4. Applying Floats to Your Layouts
And if t hat doesn't sway you, you've got t he search engines t o worry about . Most search engines lim it t he am ount of HTML t hey read when searching a sit e. On a part icularly long Web page, t hey sim ply st op at a cert ain point possibly m issing im port ant cont ent t hat should be indexed by t he search engine. Also, m ost search engines give great er value t o t he HTML near t he beginning of t he file. So if you're worried about get t ing good placem ent in search engine result s, it 's in your best int erest t o m ake sure t he im port ant cont ent s as close as possible t o t he t op of t he page's HTML code. Finally, float ing every colum n also avoids a 3- pixel bug t hat affect s I nt ernet Explorer 6 and earlier ( see Sect ion 11.1.1) . I n t he t op- left diagram in Figure 11- 6, t he m ain cont ent 's HTML is bet ween t he left and right sidebars, which is bet t er t han having it aft er bot h sidebars. You can even put t he m ain cont ent before bot h sidebars' HTML by wrapping t he m ain cont ent and left sidebar in one < div> , float ing t hat < div> left , and t hen float ing t he m ain cont ent right and t he left sidebar right wit hin t hat < div> ( Figure 11- 6, bot t om ) . Voilàt he m ain colum n's HTML falls before t he ot her < div> t ags.
11.4.2. Floats Within Floats The bot t om diagram in Figure 11- 6 illust rat es anot her useful t echniquefloat ing elem ent s wit hin float s. I m agine t hat t he m ain cont ent ( 3) and t he left sidebar ( 4) divs didn't exist , and only t he colum n wrapper ( 2) and t he right sidebar ( 5) were left . You'd have j ust a basic t wo- colum n design wit h one colum n float ed left and anot her float ed right . I n fact , it 's st ill a 2- colum n design even wit h t he t wo divs ( 3 and 4) placed back inside t he colum n wrapper div. The difference is t hat t he left colum n is it self divided int o t wo colum ns. Alt hough t his arrangem ent 's a bit confusing, it 's also helpful in a num ber of inst ances. First , it let s you add colum ns wit hin a colum n. The t hree- colum n layout at t he t op of Figure 11- 7 shows a sm all Tips box in t he m iddle colum n t hat also has t wo colum ns inside it . By nest ing float s inside float s, you can creat e som e very com plex designs.
Figu r e 1 1 - 6 . Th e r e 's m or e t h a n on e w a y t o floa t a pa ge . CSS's fle x ibilit y pr ovide s m a n y w a ys t o cr e a t e a m u lt i- colu m n la you t . Usin g diffe r e n t m e t h ods of floa t in g, you ca n e a sily ch a n ge t h e sou r ce or de r of t h e H TM L for t h e pa ge , a s you ca n se e in t h e dia gr a m s a t le ft . Righ t - side dia gr a m s r e pr e se n t fin a l W e b pa ge la you t .
Section 11.4. Applying Floats to Your Layouts
I n addit ion, when you have j ust a couple of float ed elem ent s divided int o colum ns wit h addit ional float ed elem ent s, it 's easier t o calculat e t he widt hs of page elem ent s. That 's a good t hing when you need t o cont rol float drops ( Sect ion 11.1.1) and ot her problem s t hat occur when colum ns get t oo wide.
11.4.3. Using Negative Margins to Position Elements While t he last sect ion provided a few t echniques t hat let you reorder t he HTML for each colum n in a design,
Section 11.4. Applying Floats to Your Layouts
t here's an even m ore advanced t echnique t hat gives you com plet e cont rol over t he placem ent of your colum ns. By using negat ive m argins, you can put your < div> t ags in any order you wish in your HTML, and t hen posit ion t hem in a different order onscreent hereby keeping your pages accessible t o screen readers, t ext browsers, and search engines as described on t he opposit e page. I n addit ion, since you don't need t o worry about t he source order, you can always change t he design of a pagem aybe float t he m ain colum n t o t he far right , and t he t wo sidebars t o t he left wit hout having t o change t he HTML of t he page. Be warned, t hough, t his m et hod involves m at h and som e m ind- bending uses of CSS. You can live a healt hy, happy life using j ust t he float m et hods present ed earlier in t his chapt er. But if you're up for som e advent ure, read on. ( The t ut orial also present s a hands- on dem onst rat ion of t his m et hod, st art ing in Sect ion 11.1.)
Figu r e 1 1 - 7 . Top: cr e a t e colu m n s w it h in colu m n s by floa t in g e le m e n t s in side a n ot h e r floa t e d e le m e n t . I n t h e m iddle colu m n , t h e Tips box pr ovide s a sim ple t w o- colu m n n ot e t h a t a dds visu a l in t e r e st t o t h e pa ge . Bot t om : it doe sn 't m a t t e r w h ich dir e ct ion t h e con t a in e r is floa t e d ( in t h is in st a n ce , t o t h e r igh t ) you sim ply floa t t h e t w o a ddit ion a l colu m n s le ft a n d r igh t .
Section 11.4. Applying Floats to Your Layouts
POWER USERS' CLINIC Finding the Middle Ground The t wo t ypes of layout s fixed- widt h and liquidhave t heir pluses and m inuses. A fixed- widt h design gives you a lot of cont rol and let s you m ake sure t hat your layout looks exact ly t he sam e even on different sized m onit ors. However, on a part icularly sm all m onit or, a fixedwidt h page m ay force your visit or t o scroll horizont ally t o view t he whole page. On a really wide m onit or, your lovely fixed- widt h design m ay look like a sm all sliver in a sea of em pt y space. Liquid layout s solve t hese problem s, but have t heir own lim it at ions as well. On a sm all screen, a liquid layout m ay cont ract so m uch t hat t he design falls apart . And on a really wide screen, your design m ay st ret ch so far t hat your visit ors get eye cram ps t rying t o read 30inch- wide lines of t ext . Several CSS propert ies aim t o solve t his problem : m in- widt h, m in- height , m ax- widt h, and m ax- height . The m in- propert ies inst ruct a browser t o m ake an elem ent at least as wide or t all as t he specified value. You can apply m in- widt h t o t he < body> t ag t o cont rol t he t ot al widt h of t he page's cont ent , like so: body { m in- widt h: 760px; } . I f a visit or expands his browser window t o 1000 pixels, t he page cont ent st ret ches t o fit t he space. However, if he m akes t he window 500 pixels, t hen t he cont ent rem ains 760 pixels wide and t he browser adds horizont al scrollbars. The m in- height propert y does t he sam e t hing, but for an elem ent 's height . On t he ot her hand, t he m ax- propert ies lim it an elem ent t o a m axim um size. The st yled
Section 11.4. Applying Floats to Your Layouts
elem ent can get sm aller t han t hat value, but never larger. Wit h t hem , you can m ake sure your pages don't get t oo wide t o be unreadable. Say you creat e a st yle for t he < body> t ag wit h t his propert y: m ax- widt h: 1200px. Now, if a visit or expands her browser window t o 1800 pixels wide ( on her unbelievably expensive 30- inch m onit or) , t he page cont ent doesn't sprawl all over t he screen, but rem ains 1200 pixels wide. Max- height does t he sam e t hing, but for t he height of a st yle. By com bining t he t wo propert ies, you can creat e a st yle t hat expands and cont ract s only wit hin set dim ensions, so your design never get s t oo sm all or t oo big: body { min-width: 760px; max-width: 1200px; }
The only problem wit h t hese ot herwise useful propert ies: I nt ernet Explorer 6 and earlier ignores t hem com plet ely. I f you're feeling advent urous, t ry one of t he workarounds at www. cssplay.co.uk/ boxes/ widt h3.ht m l or www.ant ix.co.uk/ code/ css/ im posing_m inim um _widt h/ . Bot h workarounds are experim ent al, but t hey work fairly well. There's also a JavaScript t echnique t hat dynam ically changes t he dim ensions of Web page elem ent s based on t he size of t he browser window: www.doxdesk.com / soft ware/ j s/ m inm ax.ht m l .
Note: The technique described on these pages works only for fixed-width layouts, where you know the exact width of each column. For another method that achieves the same results with a liquid layout (where you don't know the exact width of the middle column), visit www.alistapart.com/articles/holygrail/.
Here's how t o lay out a page using negat ive m argins: 1. Add a w r a ppe r < div> a r ou n d a ll of t h e pa ge con t e n t . This st ep provides a cont ainer for set t ing a fixed widt h for all of t he cont ent on t he page, and gives you an easy way t o m ake t he banner, colum ns, and foot er t he sam e widt h. 2. Se t a w idt h for t h e w r a ppe r < div> . Creat e a st yle for t he wrapper div t hat gives it a set widt h. For exam ple, 760 pixels is a t ypical size t hat accom m odat es visit ors wit h 800 x 600 pixel m onit ors. 3.
Section 11.4. Applying Floats to Your Layouts
W r a p e a ch colu m n in a < div> t a g w it h a n I D or cla ss a t t r ibu t e . This part of t he process is t he sam e as creat ing any float - based layout . I t defines t he basic layout blocks ( Figure 11- 8, t op left ) . 4. Floa t t h e divs for e a ch colu m n . You m ust float each of t he colum ns in your design. When you float t hem all t o t he left , t hey sit sideby- side. Anot her opt ion's t o float t he left sidebar and m ain cont ent left and t he right sidebar right . ( Since all colum ns are enclosed in t he wrapper < div> from st ep 1, t he right sidebar st ays close t o t he cent ral colum n.)
Note: If you're not using a wrapper div as described in step 1, then you must float the right sidebar left. Otherwise, it clings to the right edge of the browser window, potentially creating a large empty space between the right sidebar and the main content. 5. Se t w idt h s for e a ch colu m n . You should always specify a widt h for a float ed elem ent . Depending on your design, you can also add padding, m argins, and borders. Keep in m ind, t hough, t hat t he t ot al widt h of t he t hree colum ns in t he browser window is t he sum of t he CSS widt h propert y values and t he left and right m argins, padding, and borders for each colum n. ( And rem em ber t hat , as described in Sect ion 7.5.3, I nt ernet Explorer 5 on Windows has it s own ideas about what widt h m eans.) Yep, here's where t he m at h com es in. I f you're not careful, t he t ot al widt h of t he colum ns m ay exceed t he widt h provided by t he wrapper < div> , causing t he dreaded float drop ( see Sect ion 11.1.1) .
Note: The width property doesn't define the total width that an element takes up onscreen. Margins, padding, and borders count, too. If this stuff doesn't sound familiar, then read Section 7.1 to brush up on the CSS box model theory. 6. Add a le ft m a r gin t o t h e m a in colu m n . Here's where t he negat ive m argin t echnique differs from t he layout m et hods described earlier in t his chapt er. The left m argin should equal t he space required for t he left sidebar. I f t he left sidebar is 160 pixels wide, t hen set t he left m argin of t he m ain colum n t o 160 pixels: m argin- left : 160px. The t op- right diagram in Figure 11- 8 shows t he page so far. The crosshat ched area t o t he left of t he m ain colum n ( 3) represent s t hat colum n's left m argin. Or, say t he left sidebar is 160 pixels wide and you want 10 pixels of space bet ween it and t he m ain
Section 11.4. Applying Floats to Your Layouts
cont ent . I n t hat case, add 10 pixels t o t he m ain colum n's left m argin: m argin- left : 170px.
Figu r e 1 1 - 8 . Ye s, Vir gin ia , you ca n pu t t h r e e divs in t o a n y or de r in you r H TM L ( t op le ft ) a n d posit ion t h e m in a n y or de r on t h e scr e e n ( bot t om ) . Th e se cr e t is u sin g n e ga t ive m a r gin s t o pu ll a n e le m e n t t h a t a ppe a r s la t e r in t h e H TM L ove r a n d pa st a n e le m e n t t h a t pr e ce de s it . I n t h e t op r igh t dia gr a m , n ot ice t h a t t h e le ft side ba r ( # 4 ) floa t s n e x t t o t h e m a in con t e n t colu m n ( # 3 ) ; a ddin g a n e ga t ive m a r gin t o t h e le ft side ba r pu lls it in t o posit ion on t h e le ft e dge of t h e pa ge . To m a k e r oom for t h a t le ft side ba r , you a lso a dd a posit ive le ft m a r gin t o t h e m iddle colu m n s ( in dica t e d by t h e cr ossh a t ch e d box on t h e t op- r igh t dia gr a m ) .
Section 11.4. Applying Floats to Your Layouts
Finally, when t he left sidebar has padding and borders, you need t o fact or t hose in as well. Suppose t he left sidebar is 160 pixels wide, has a 2- pixel right border and 10 pixels of left and right padding, and you want 10 pixels of space bet ween it and t he m ain colum n. Add all of t hese t oget her t o get t he left m argin value for t he m ain colum n. So, 160 ( widt h value) + 2 ( right border) + 10 ( left padding) + 10 ( right padding) + 10 ( gut t er bet ween sidebar and m ain colum n) = 192 pixels ( m argin- left : 192px) . 7. Apply a n e ga t ive m a r gin t o t h e le ft side ba r < div> . At t his point , t he left sidebar's float ed t o t he left , but since it com es aft er t he m ain colum n in t he HTML's source order, it appears on t he right edge of t he m ain colum n ( Figure 11- 8, t op right ) . To get it int o posit ion, use a negat ive m argin, whichbelieve it or not pulls t he sidebar clear across t he m ain colum n t o t he left edge of t he page. The only t rick is figuring out what t hat negat ive m argin value should be t o m ove t he sidebar t he exact dist ance required t o posit ion it at t he left side of t he page. I n ot her words, t he left m argin m ust equal t he dist ance from t he right edge of t he m ain colum n t o t he left edge of t he wrapper < div> . To det erm ine t hat value, add t he m ain colum n's widt h, left and right m argins, left and right padding, and left and right borders. Say t he m ain colum n is 400 pixels wide, has a 1 pixel border around it , has 10 pixels of left padding and 15 pixels of right padding, and has a 160 pixels left m argin t o accom m odat e t he left sidebar. Just add t he values t oget her t o get t he left sidebar's left m argin value: 400+ 1+ 1+ 10+ 15+ 160= 587. Then add a left m argin t o t he st yle form at t ing t he left sidebar, but m ake it s value negat ive: left - m argin: - 587px; . The m inus sign is t he crit ical piece t hat m akes t he whole t hing work.
Section 11.4. Applying Floats to Your Layouts
8. Fix t h e I n t e r n e t Ex plor e r bu gs. When you use negat ive m argins, I nt ernet Explorer 6 and earlier exhibit s a weird bugt he doublem argin bug. I n t his case, I E doubles t he left m argin applied t o t he m ain colum n, t ot ally disrupt ing t he design. The fix is t o add display: inline t o t he st yle form at t ing t he m ain colum n. ( Read m ore about t he double- m argin bug in Sect ion 11.1.) Once you get past t he m at h, t he negat ive m argin approach rewards you wit h flexibilit y. I f you want t o swap t he sidebars so t he left sidebar m oves t o t he right and right sidebar m oves t o t he left , t hen sim ply swap t he st yles for t hose t wo divs. I n ot her words, set t he first sidebar t o float right , and t he second sidebar t o float left using a negat ive left m argin. You'll see negat ive m argins in act ion in t he t ut orial in Sect ion 11.1.
Section 11.5. Overcoming Float Problems
11.5. Overcoming Float Problems As you get m ore advent urous wit h CSS, you'll probably encount erlike m any Web designers before yousom e of t he weird int ricacies of working wit h float s. This sect ion describes a few com m on problem s and t heir solut ions. ( And if you ever st um ble upon a problem not list ed here, you can always t ake it t o one of t he online forum s or discussion list s in Appendix C.)
Note: When it comes to designing pages that work in Internet Explorer, there are even more potential pitfalls. So many, in fact, that this chapter has a separate section dedicated to dealing with that one browser. See Section 11.1.
11.5.1. Clearing and Containing Floats Float s are powerful design t ools because t hey let cont ent flow around t hem . Float ing a phot o let s t ext below it m ove up and wrap around t he im age ( Figure 11- 3) . When you're creat ing float - based colum n designs, t hough, som et im es you don't want cont ent t o m ove up and next t o a float ed elem ent . For exam ple, you frequent ly want t o keep copyright not ices, cont act inform at ion, or ot her housekeeping det ails at t he bot t om of your Web page, below all ot her cont ent . I n t he t wo- and t hree- colum n designs you've seen so far, if t he m ain colum n is short er t han eit her of t he float ed sidebar colum ns, a foot er can m ove up and around t he left float ed colum n ( Figure 11- 9, left ) . To m ake t he foot er st ay down below t he sidebars, you can use t he clear propert y ( Sect ion 7.6.2) . This propert y prevent s an elem ent from wrapping around float s. You can m ake an elem ent drop below a left float ed obj ect ( clear: left ; ) , or a right float ed obj ect ( clear: right ; ) . For foot ers and ot her it em s t hat need t o appear at t he bot t om of t he page, you should clear bot h left and right float s, like t his: #footer { clear: both; }
Figu r e 1 1 - 9 . You don 't a lw a ys w a n t a n it e m t o w r a p a r ou n d a floa t e d e le m e n t ( le ft ) . Copyr igh t n ot ice s a n d ot h e r m a t e r ia l t h a t be lon gs a t t h e bot t om of a pa ge u su a lly n e e d t o cle a r a n y floa t s t h e y e n cou n t e r . To a ch ie ve t h is, u se t h e cle a r pr ope r t y for t h e copyr igh t n ot ice t o for ce it t o t h e bot t om of t h e pa ge be low a n y floa t e d e le m e n t s.
Section 11.5. Overcoming Float Problems
Anot her problem occurs when you float one or m ore elem ent s inside a non- float ed cont aining t ag like a < div> t ag. When t he float ed elem ent is t aller t han t he ot her cont ent inside t he div, it st icks out of t he bot t om of t he enclosing elem ent . This snafu is especially not iceable if t hat t ag has a background or border. The t op of t he web page in Figure 11- 10 shows a < div> t ag t hat has an < h1> t ag ( " Bat ht ub Hydroponics Tips" ) and t wo colum ns creat ed by float ing t wo divs. The background and border, which appear only around t he < h1> t ag, are act ually applied t o t he ent ire enclosing < div> , including t he area where t he t wo colum ns are. However, since t he colum ns are float ed, t hey pop out of t he bot t om inst ead of expanding t he borders of t he box.
Note: For a good explanation of why floated elements can break outside of their containing blocks, read www.complexspiral.com/publications/containingfloats/ .
Figu r e 1 1 - 1 0 . A floa t e d e le m e n t ca n e sca pe it s con t a in in g < div> if it 's t a lle r t h a n t h e con t a in e r it se lf. I f t h e con t a in in g t a g in clu de s a ba ck gr ou n d or bor de r , t h e n t h e e sca pin g e le m e n t s ca n look lik e t h e y'r e n ot e ve n pa r t of t h e con t a in e r ( t op of pa ge ) . I n a ddit ion , a floa t e d e le m e n t ca n bu m p in t o ot h e r e le m e n t sin clu din g ot h e r floa t s, t h e r e by cr e a t in g a " st a ir - st e ppe d" e ffe ct ( bot t om of pa ge ) in st e a d of t h e n ice ly st a ck e d box e s in Figu r e 1 1 - 1 1 .
Section 11.5. Overcoming Float Problems
A sim ilar problem happens in t he bot t om exam ple in Figure 11- 10. I n t his case, each im age is float ed left inside a cont aining < div> t hat has a border. Because t he im ages are t aller t han t heir boxes, t hey pop out of t he bot t om . Unfort unat ely, t his exam ple's even worse t han t he previous one, because each im age causes t he im age below it t o wrap t o t he right , creat ing an ugly st aggered effect . You have t hree ways t o t ackle t he problem of t hese renegade float ing elem ent s: ●
Add a cle a r in g e le m e n t a t t h e bot t om of t h e con t a in in g div. This solut ion's t he m ost st raight forward, alt hough it adds ext ra HTML code. Sim ply add a t aglike a line break or horizont al ruleas t he last it em in t he < div> cont aining t he float ed elem ent ( t hat is, right before t he closing < / div> t ag) . Then use t he clear propert y t o force t hat ext ra t ag below t he float . This t rick m akes t he enclosing div expand, revealing it s background and border. You can add a line break< br> ( HTML) or < br / > ( XHTML) before t he closing < / div> t ag and add a class t o it : < br class= " clear" / > . Then creat e a st yle for it , like t his: br.clear { clear: both; }
●
●
Floa t t h e con t a in in g e le m e n t . An easier way is t o j ust float t he < div> cont aining t he float ed elem ent s as well. A float ed cont ainer < div> expands t o fully cont ain any float ed elem ent s inside it . I n Figure 11- 11, t op, t he < div> cont aining t he heading and t wo float ed colum ns is float ed t o t he left of t he page. I n t he process, it s ent ire boxbackground and bordersexpands t o fit everyt hing inside it , including t he float ed elem ent s. St range, but t rue. Use t h e " e a sy cle a r in g m e t h od." Wit h t his t echnique, creat ed by Tony Aslet t of CssCreat or.com , you add j ust a few st yles and a class nam e t o t he < div> t ag cont aining t he float ed elem ent . Of course, t he nam e " easy clearing m et hod" is a bit of a m isnom er, since t he CSS behind it is anyt hing but easy. You m ust add t hree different st yles t o your st yle sheet : One applies t o Firefox, Safari, Opera and ot her m odern browsers; anot her st yle applies t o I E 7 ( which doesn't yet underst and t he first st yle) ; and t he last st yle m akes I E 6 and I E 5 behave. The whole shebang looks like t his: .clear:after { content: ".";
The last t wo st yles m ake I E 5, 6, and 7 " have layout " as described in t he box in Sect ion 11.1. Once you've added t hese st yles t o a st yle sheet , you sim ply add t he class nam e t o t he div cont aining t he escaping float s: < div class= " clear" > . See t he bot t om of Figure 11- 11.
Tip: You can simplify this code by replacing the last two styles with this CSS: .clear { zoom: 1; }. This single style knocks all versions of IE into shape, but since it uses the non-standard zoom property, it makes your page flunk the CSS validator check. To get around that, you can put this rule (along with any other IE-only styles) into an external style sheet and attach it to your Web pages using any of the tricks described in Chapter 14 (Section 14.5.2).
Figu r e 1 1 - 1 1 . D on 't le t a floa t e sca pe ! You h a ve se ve r a l w a ys t o m a k e floa t e d e le m e n t s st a y in side t h e bor de r s a n d ba ck gr ou n ds of t h e ir con t a in in g t a g. Floa t in g t h e con t a in e r w or k s ( t op) , a s doe s a spe cia l com bin a t ion of CSSa ffe ct ion a t e ly ca lle d t h e " e a sy cle a r in g m e t h od" ( bot t om ) . Bot h m e t h ods r e su lt in bor de r s a n d ba ck gr ou n ds t h a t su r r ou n d t h e con t a in e r a n d t h e floa t s in side .
Section 11.5. Overcoming Float Problems
11.5.2. Creating Full-Height Columns HTML t ables aren't great for Web page layout for several reasons. They add lot s of code, are difficult t o updat e, and don't work well on alt ernat ive browsers like t hose used by cellphones. But t ables have one t hing going for t hem in t he layout depart m ent t he abilit y t o creat e colum ns of equal height . Equal- height colum ns let you add a background color or graphic t o one colum n and have it fill t he ent ire height of t he page. The backgrounds of t he t wo sidebars in t he t op im age of Figure 11- 12 fill t he screen height , creat ing solid, bold st ripes on eit her side of t he page. CSS float s, on t he ot her hand, fall a bit short in t his regard. Table cells in a row are always t he sam e height , which isn't t rue of divs. The height of a float is usually dict at ed by t he cont ent inside it . When t here's not a lot of cont ent , t he float 's not very t all. Since a background im age or background color fills only t he float , you can end up wit h solid- colored colum ns t hat st op short of t he page bot t om , as in t he circled areas in Figure 11- 12, bot t om . As wit h m ost problem s relat ed t o CSS, t here's a workaround. The secret 's t o add background im ages t o a t ag t hat wraps around t he st ubby sidebar and t he ot her colum ns on t he page. Say your HTML has t wo < div> t ags t hat cont ain t he cont ent for a left sidebar and t he page's m ain cont ent : Sidebar content here Main content for page, this column has a lot of text and is much taller than the sidebar.
The sidebar < div> is float ed t o t he left edge of t he page and has a widt h of 170 pixels. Because t here's less cont ent in t he sidebar, it 's short er t han t he m ain t ext . Suppose you wrap t hat HTML in a wrapper < div> t ag, like so: is 390 pixels wide, wit h a 1- pixel border and 15 pixels of left and right m argin for a t ot al widt h of 422 pixels. ( You m ay need a calculat or for t his one: 390 + 1 [ left border] + 1 [ right border] + 15 [ left m argin] + 15 [ right m argin] .) Side ba r 2 ( r igh t side ) . This elem ent has a widt h propert y set t o 150 pixels, wit h 10 pixels of left and 10 pixels of right padding: 170 pixels, j ust like Sidebar 1.
The act ual widt hs of each elem ent add up t o a grand t ot al of 762 pixels. That 's t wo pixels m ore t han t he widt h of t he wrapper < div> . The m iddle im age of Figure 11- 14 shows an out line around t he m ain cont ent < div> indicat ing it s t ot al widt h plus m argins. Just t hose m easly t wo ext ra pixels of widt h ( circled) are enough t o cause a colum n t o drop down. The solut ion: Rem ove t wo pixels of space from any of t he elem ent s. Changing t he m ain cont ent div's left and right m argins from 15 t o 14 pixels buys you t he ext ra room needed for all t hree colum ns t o fit side by side ( bot t om ) .
Figu r e 1 1 - 1 4 . I t t a k e s on ly a sin gle pix e l or t w o t o r u in a de sign . W h e n t h e w idt h of floa t e d e le m e n t s a r e j u st a h a ir w ide r t h a n t h e ir con t a in in g block ( lik e a < div> w it h a se t w idt h , or e ve n t h e br ow se r w in dow it se lf) , t h e la st floa t e d e le m e n t dr ops be low t h e ot h e r s ( t op) . Th e a ct u a l w idt h of a n e le m e n t com bin e s
Section 11.5. Overcoming Float Problems
m a n y CSS pr ope r t ie s. I n t h e m iddle im a ge , t h e ou t lin e a r ou n d t h e m a in con t e n t a r e a sh ow s t h a t it 's a t a d t oo w ide t o a llow t h e r igh t side ba r t o fit ( cir cle d) . Adj u st in g a n y of t h e e le m e n t s by r e m ovin g a bit of w idt h , pa ddin g, or m a r gin s ca n solve t h e pr oble m ( bot t om ) .
While m iscalculat ed colum n widt hs are t he m ost com m on cause of dropping float s, t hey're not t he only cause. Here are a few ot her culprit s: ●
●
Rou n din g e r r or s in pe r ce n t a ge w idt h s. Be careful when set t ing widt hs in percent ages. Browsers som et im es m ake m ist akes when calculat ing t he act ual num ber of pixels needed t o display som et hing on t he screen. That is, t hey can round num bers up, m aking elem ent s slight ly t oo large for t he available space. So err on t he side of caut ion and m ake your percent age widt hs t ot al slight ly less t han 100 percent . I n t e r n e t Ex plor e r 's dou ble - m a r gin bu g. Under som e condit ions, I nt ernet Explorer 6 and earlier doubles t he m argin applied t o a
Section 11.5. Overcoming Float Problems
●
●
float ed elem ent , m aking t he elem ent wider t han in ot her browsers. When you have a float drop occurring only in I E 6 or earlier, t his bug m ay be t he culprit . See Sect ion 11.1 for a solut ion. I n t e r n e t Ex plor e r 's 3 - pix e l ga p. Som et im es I E 6 and earlier adds an ext ra 3 pixels t o t he side of a float . Again, if you see a float drop only in I E, t hen t his bug could be t he reason. See Sect ion 11.1.1 for an explanat ion and solut ion. I t a lic t e x t . I E st rikes again. I f a float ed elem ent cont ains it alicized t ext , t hen I E 6 som et im es m akes t he float wider. When t here's a float drop and it alics inside t he float , check t o see if t he problem 's happening in all browsers or only I E. For a solut ion, you can rem ove any it alics from t he sidebar, or add overflow: hidden t o t he st yle form at t ing t he sidebar.
Tip: For the definitive treatise on dropping floats (and how to solve them), visit http://nemesis1.f2o.org/aarchive?id=11.
Bot t om line: Float drops are always caused by not enough room t o hold all of t he colum ns. Rat her t han st riving t o use every last pixel of onscreen space, give all your elem ent s a lit t le m ore wiggle room . Get in t he habit of m aking t he overall colum n widt hs a bit sm aller t han necessary, and you'll spend less t im e t roubleshoot ing float drops.
Section 11.6. Handling Internet Explorer Bugs
11.6. Handling Internet Explorer Bugs The Windows version of I nt ernet Explorer has a long hist ory of CSS bugs, especially ( and unfort unat ely) when it com es t o float - based layout s. These bugs can affect t he placem ent of float s and t he overall widt h allot t ed t o float ed elem ent s. I f you're lucky, you m ay j ust get a slight ly annoying difference in how your Web page looks in I nt ernet Explorer versus ot her browsers. At worst , t hese bugs can cause significant display problem s like t he float drops discussed in t he previous sect ion. This sect ion t ells you t he m ost com m on problem s and how t o get around t hem .
Tip: When a floated element has padding or a border, it appears thinner in IE 5 than in other browsers. There's more detail on this IE 5 bugand its solutionin Section 7.5.3.
11.6.1. Double-Margin Bug I nt ernet Explorer 6 and earlier som et im es doubles t he size of a m argin you've applied t o a float ed elem ent . The problem occurs only when t he m argin's in t he sam e direct ion as t he float a left m argin on a left - float ed elem ent or a right m argin on a right - float ed elem ent . I n Figure 11- 15, t here's a left - float ed sidebar holding t he sit e's navigat ion. To add a bit of space bet ween it and t he left edge of t he browser window, t he sidebar has a left m argin of 10 pixels.
Figu r e 1 1 - 1 5 . A 1 0 - pix e l le ft m a r gin a pplie d t o a le ft - floa t e d e le m e n t sh ou ld, in t h e or y a n yw a y, in de n t t h e floa t 1 0 pix e ls fr om t h e le ft e dge of t h e pa ge . Fir e fox ( a bove ) ge t s it r igh t . Bu t I E 6 ( bot t om ) in cor r e ct ly dou ble s t h a t m a r gin . By a ddin g 2 0 pix e ls t o t h e le ft e dge of t h e side ba r , I E 6 sign ifica n t ly ch a n ge s t h e pa ge 's a ppe a r a n ce .
Section 11.6. Handling Internet Explorer Bugs
Most browsers, including I nt ernet Explorer 7, Safari, and Firefox ( Figure 11- 15, t op) add t he request ed 10 pixels of space. However, I nt ernet Explorer 6 ( bot t om ) doubles t hat m argin t o 20 pixels. Even wit h relat ively sm all m argins like 10 pixels, t he visual difference is significant . Furt herm ore, if t he layout 's very t ight , wit h precisely m easured float ed elem ent s sit t ing side by side, t hen t he doubled m argin can easily t rigger a float drop ( Sect ion 11.1.1) .
Note: This margin doubling happens only when the element's margin touches the edge of its containing block, so when an element is floated left against another left-floated element, its left margin won't double.
The solut ion's sim ple: Add display: inline; t o t he CSS st yle for t he float ed elem ent : #sidebar { float: left; margin-left: 10px; width: 160px; display: inline; }
I n t his case, t he display propert y doesn't do anyt hing except fix I E's bug. Float ed elem ent s are always block- level elem ent s, and changing a st yle's display t o inline won't alt er t hat . ( See Sect ion 7.2.4 for m ore on t he display propert y.) However, even t hough t his added st yle declarat ion doesn't adversely affect any ot her browsers, you m ay want t o put it in an I E- only st yle using t he * ht m l hack: #sidebar { float: left; margin-left: 10px; width: 160px; } * html #sidebar { display: inline; }
Tip: Internet Explorer's conditional comments feature provides an even better way to isolate IE-only styles than the * html hack. An external style sheet attached to a page using a conditional comment is read only by Internet Explorer; it's ignored by all other browsers. See Section 14.5.2 for the details.
11.6.2. 3-Pixel Gaps
Section 11.6. Handling Internet Explorer Bugs
I nt ernet Explorer 6 and earlier insert s an addit ional t hree pixels of space bet ween a float ed colum n and a non- float ed colum n. The exact placem ent of t hat gap depends on a couple of condit ions: ●
Th e n on - floa t e d colu m n doe sn 't h a ve a se t w idt h or h e igh t . I f t he colum n next t o t he float doesn't have any dim ensions defined, t hen you'll see a 3- pixel indent bet ween t he edge of t he colum n and t he t ext inside t hat colum n. This space appears only along t he float , so when t he float ends, t he t ext m oves back t o t he left edge of t he colum n ( Figure 11- 16) . I n t his case, t he best solut ion's t o live wit h it . The ext ra indent isn't t erribly dist ract ing and doesn't do anyt hing else weird t o t he page. But if t he perfect ionist in you can't let go of t his bug, you can fix it by doing what 's known as " adding layout " t o t he nonfloat ed elem ent , as described in t he box in Sect ion 11.1. Add an I E6- only st yle for t hat colum n: * html #mainColumn { height; 1px; }
The downside t o fixing t his bug is t hat it t riggers t he bug discussed next . ( See what you get for being a perfect ionist ?)
Figu r e 1 1 - 1 6 . On t h is pa ge , t h e le ft - h a n d side ba r is floa t e d le ft , w h ile t h e ce n t r a l colu m n isn 't floa t e d a t a ll. A le ft m a r gin on t h e ce n t r a l colu m n in de n t s it fa r e n ou gh t o t h e le ft so t h a t it w on 't w r a p a r ou n d t h e bot t om of t h e side ba r . ( Th is t e ch n iqu e is de scr ibe d in Se ct ion 1 1 .1 .) Un for t u n a t e ly, I n t e r n e t Ex plor e r 6 a n d e a r lie r a lso a dds a sm a ll in de n t t o t h e t e x t in t h e n on floa t e d colu m n .
Section 11.6. Handling Internet Explorer Bugs
●
Th e n on - floa t e d colu m n h a s a se t w idt h or h e igh t . When t he colum n next t o t he float has a set layout dim ension ( like height in t he previous exam ple) , anot her 3- pixel error appearsa sm all gap bet ween t he t wo colum ns ( Figure 11- 17, left ) . This bug is m ore serious t han t he one in Figure 11- 16, since t his 3- pixel gap can force t he second colum n t o drop below t he float ed elem ent ( Figure 11- 17, right ) . The solut ion t o t his problem is t wo- fold. First , you m ust elim inat e t he left m argin of t he non- float ed colum n ( but for I E 6 and earlier only) : * html #mainColumn { margin-left: 0; }
Then, you m ust set t he right m argin for t he float ed colum n t o - 3 pixels. This pulls t he non- float ed colum n back int o posit ion: * html #sidebar { margin-right: -3px; }
I n any norm al browser, t hese st yles m ake no sense. Som e det erm ined CSS expert s ( wit h t im e on t heir hands, apparent ly) cam e up wit h t hem t o m ake I E behave. For m ore info on t his phenom enon, check out www.posit ioniseveryt hing.net / explorer/ t hreepxt est . ht m l .
Figu r e 1 1 - 1 7 . I n t e r n e t Ex plor e r 6 oft e n h a s t r ou ble w it h floa t s. I f, for e x a m ple , a sin gle colu m n is floa t e d le ft a n d a n ot h e r n on - floa t e d colu m n w it h a se t w idt h w r a ps a r ou n d t h e floa t , I E 6 a n d e a r lie r in j e ct a 3 - pix e l ga p be t w e e n t h e t w o colu m n s ( le ft ) . For de sign s t h a t h a ve pr e cise ly de t e r m in e d w idt h s, t h a t ga p ca n a dd j u st e n ou gh spa ce t o for ce a colu m n t o dr op be low t h e floa t e d e le m e n t ( r igh t ) .
Section 11.6. Handling Internet Explorer Bugs
Anot her opt ion is t o float all of t he colum ns. I n t he exam ples pict ured in Figure 11- 16 and Figure 11- 17, rem oving any left m argins from t he non- float ed colum n and float ing it eit her left or right elim inat es bot h 3- pixel problem s: #mainColumn { float: left; }
This solut ion seem s quick, but it adds a lit t le m ore com plexit y, since you have t o m anage yet anot her float in t he design.
11.6.3. Other IE Problems A few m ore bugs plague float - based layout s in I nt ernet Explorer 6. Many of t hem are so rare you m ay never com e across t hem in your Web design proj ect s. But j ust in case, here are a couple of weird t hings t hat can happen when viewing a page in I E 6 or earlier. ●
●
I f t h e bot t om pa r t of a floa t e d e le m e n t j u st disa ppe a r s, it m ay be t he guillot ine bug. For inform at ion on t he cause and solut ion ( which fort unat ely has not hing t o do wit h sharp, dangerous obj ect s) , visit www.posit ioniseveryt hing.net / explorer/ guillot ine.ht m l . Con t e n t in side a floa t e d e le m e n t doe sn 't a ppe a r , but som et im es reappears if you resize t he browser window or scroll. This oddit y is apt ly called t he peek- a- boo bug. Learn about it at www.posit ioniseveryt hing.net / explorer/ peekaboo.ht m l.
POWER USERS' CLINIC Got Layout?
Section 11.6. Handling Internet Explorer Bugs
As you've probably gat hered by now, I nt ernet Explorer for Windows has a long hist ory of browser bugs. Som e basic CSS t hat looks fine in Firefox or Safari crum bles in I nt ernet Explorer 6. As it t urns out , you can fix m any I E bugs by swit ching on a special I E- only propert y known as layout . This isn't a CSS concept , nor does it have anyt hing t o do wit h t he rules of HTML. I t 's j ust a concept built int o I nt ernet Explorer by t he engineers who creat ed I E ( who, rum or has it , were under m ind cont rol by ext rat errest rial beings at t he t im e, which explains a lot ) . As far as I E is concerned, each page elem ent eit her has layout or it doesn't . I n I E, float s, list it em s, and absolut ely posit ioned elem ent s display different ly depending on whet her or not t hey have layout . I n t he last chapt er ( Sect ion 9.1.1) , you saw how I E 6 doesn't m ake t he ent ire area of a link clickable when t he link is set t o display as a block. You can fix t hat problem by creat ing an I E- only st yle t hat set s t he links t o 1 pixel t all: * html a .nav a { height: 1px; }
The point of t hat st yle isn't t o m ake t he links 1 pixel t all: I E 6 ignores t he height specificat ion anyway and expands t he links t o t he height of t he links' cont ent . But t he height propert y t riggers layout in I E 6. For reasons known only t o Microsoft ( and t he ext rat errest rials) , swit ching on layout m akes I E t reat t he ent ire area of block- level links as clickable. Height isn't t he only propert y t hat swit ches on layout in I E. Several ot her CSS propert ies also give an elem ent layout : posit ion: absolut e; float : left ; float : right ; display: inline- t able; any widt h value, any height value, and an I E- only propert y called zoom . You can add t hat last propert y t o a st yle like t his: zoom : 1; . Zoom doesn't affect how t he elem ent looks in any ot her browser, and if you use zoom : 1, all it does in I E is give t he elem ent layout . The downside of using t his propert y is t hat it isn't valid CSS, so it won't pass W3C validat ion ( Sect ion 2.4.1) . I nt ernet Explorer 7 ( as of t his writ ing) st ill has a few bugs you have t o fix by adding layout . Any of t he propert ies list ed above add layout t o an elem ent in I E 7, as will t he following: m in- widt h, m ax- widt h, m in- height , and m ax- height ( see Sect ion 11.4.3) . Throughout t his book, you use layout t o overcom e m any different I E bugs. For an in- dept h ( so deep, you m ay need a life preserver) discussion of t he t opic, go t o www.sat zansat z.de/ cssd/ onhavinglayout .ht m l . Microsoft offers a friendly int roduct ion at ht t p: / / m sdn.m icrosoft .com / library/ default .asp?url= / library/ en- us/ I ETechCol/ cols/ dnexpie/ expie20050831. asp.
Section 11.7. Tutorial: Multiple Column Layouts
11.7. Tutorial: Multiple Column Layouts I n t his t ut orial, you'll creat e a m ult i- colum n, float - based layout . I n t he process, you'll creat e t wo- and t hree- colum n liquid designs, as well as a fixed- widt h design. To get st art ed, 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 t he files are in a ZI P archive, so you need t o unzip t hem first . ( Find det ailed inst ruct ions on t he layout 1 folder. Web sit e.) The files for t his t ut orial are in t he chapt er_11
11.7.1. Structuring the HTML The first st ep in creat ing a CSS- based layout is ident ifying t he different layout elem ent s on t he page. You do t his by wrapping chunks of HTML inside of < div> t ags, each of which represent s a different part of t he page. 1. Ope n t h e st a r t .h t m l file in a t e x t e dit or , a n d click in t h e e m pt y lin e follow in g t h e H TM L com m e n t :
The < ! - - [ if I E] > is t he condit ion it self. I t t ranslat es t o: " if t his browser is I nt ernet Explorer t hen process t he following HTML." So any I nt ernet Explorer browser act s on t he HTML t hat com es aft er t his line of code and st ops when it get s t o t he < ! [ endif] - - > st at em ent . I n t his way, you can add any HTMLt ext , im ages, st yles and even links t o ext ernal st yle sheet st o I nt ernet Explorer only.
Note: Non-IE-browsers simply view conditional statements as HTML comments and ignore them.
Section 14.5. Managing Internet Explorer Hacks
14.5.2.1. Conditional comments and IE 7 I nt ernet Explorer 7 underst ands CSS m uch bet t er t han earlier versions, so you m ay have t o hide som e I E hacks from t hat browser as well. Fort unat ely, condit ional com m ent s also let you specify which version of I nt ernet Explorer t he st yle sheet applies t o. Say you want t o have a part icular st yle sheet load only for I nt ernet Explorer 6 or earlier. Add t he following condit ional com m ent t o your Web page's head:
The lt e st ands for " less t han or equal t o," so if lt e I E 6 m eans " if t his browser is version 6 or earlier of I nt ernet Explorer."
14.5.2.2. Conditional comments and the cascade Use what ever m et hod you prefer for linking an ext ernal st yle sheet ( Sect ion 2.4) , but add any condit ional com m ent s aft er any ot her linked st yle sheet s. Most I E hacks t end t o redefine st yles already present in t he st yle sheet st yles t hat work for ot her browsers. And, due t o t he nat ure of t he cascade, rules defined lat er in a page can override earlier defined st yles. I n order t o m ake sure your redefined " I E- only" st yles successfully t ake hold in I nt ernet Explorer, t hey should appear aft er any ot her st yle sheet s at t ached t o t he page. Here's t he code you m ight use t o link a) a st yle sheet for all browsers, b) a st yle sheet j ust for I E 6, and c) a st yle sheet for version 5 or earlier of I E:
Note: For more information on Internet Explorer's conditional comments, visit the source: http://msdn.microsoft.com/workshop/author/ dhtml/overview/ccomment_ovw.asp.
Part V: Appendixes
Part V: Appendixes Appe n dix A: CSS Pr ope r t y Re fe r e n ce Appe n dix B: CSS in D r e a m w e a ve r 8 Appe n dix C: CSS Re sou r ce s
Appendix A. CSS Property Reference
Appendix A. CSS Property Reference Mast ering Cascading St yle Sheet s involves knowing how t o use a large num ber of CSS propert ies t hat cont rol t he appearance of t ext , im ages, t ables, and form s. To help you in your quest , t his appendix gives you a sum m ary of t he propert ies and values you'll use t o creat e your own st yles. This list covers nearly all of t he CSS 2.1 st andard propert iest he ones t hat m ost Web browsers support .
Note: This appendix leaves out properties that no (or hardly any) browsers recognize. Otherwise, the following descriptions mention the browsers with which each property works. For full details straight from the horse's mouth, visit the World Wide Web Consortium's CSS 2.1 specification at www.w3.org/TR/CSS21/.
Section A.1. CSS Values
A.1. CSS Values Every CSS propert y has a corresponding value. The color propert y, which form at s font color, requires a color value t o specify which color you want t o use. The propert y color: # FFF; creat es whit e t ext . Different propert ies require different t ypes of values, but t hey com e in four basic cat egories: colors, lengt hs and sizes, keywords, and URLs.
A.1.1. Colors You can assign colors t o m any different propert ies, including t hose for font , background, and borders. CSS provides several different ways t o specify color.
A.1.1.1. Keywords A color keyword is sim ply t he nam e of t he color, like whit e or black. There are current ly 17 recognized color keywords: aqua, black, blue, fuchsia, gray, green, lim e, m aroon, navy, olive, orange, purple, red, silver, t eal, whit e, and yellow. Som e browsers accept m ore keywords, and CSS 3 prom ises t o offer m any m ore in t he fut ure ( ht t p: / / www.w3.org/ TR/ css3- color/ ) .
A.1.1.2. RGB values Com put er m onit ors creat e colors using a m ixt ure of red, green, and blue light . These RGB values can creat e ( nearly) t he full spect rum of color. Alm ost every design, illust rat ion, and graphics program let s you specify colors using RGB, so it 's easy t o t ransfer a color from one of t hose program s t o a CSS propert y. CSS represent s RGB values in several ways: ●
H e x va lu e s. The m et hod m ost com m only used on t he Web for ident ifying color, hex color values consist of t hree t wo- charact er num bers in t he hexadecim al ( t hat is, base 16) syst em . # FF0033 represent s an RGB value com posed of red ( FF, which equals 255 in norm al, base 10 num bers) , green ( 00) , and blue ( 33) . The # t ells CSS t o expect hex num bers ahead, and it 's required. I f you leave off t he # , a Web browser won't display t he correct color.
Tip: If all three two-digit values have repeated digits, you can shorten the hex value by using just the first number of each pair. For example #361 means the same thing as #336611. ●
●
RGB pe r ce n t a ge s. You can also specify a color using percent age values, like t his: rgb( 100% , 0% , 33% ) . You can get t hese num bers from im age edit ing and design program s t hat can define colors using percent ages ( which is m ost of t hem ) . D e cim a l va lu e s. Finally, you can use decim al RGB values t o specify a color. The form at is sim ilar t o t he percent age opt ion, but you use a num ber from 0 t o 255 t o indicat e each color: rgb( 255, 0, 33) .
I t doesn't m at t er which m et hod you uset hey all work. For consist ency's sake, you should pick one way of specifying RGB values and st ick wit h it . The Windows and Mac operat ing syst em s bot h have color pickers which let you find t he perfect color from a palet t e of m illions, and t hen show you t he RGB value. Alt ernat ively, you can use t his free online color picker: www.ficm l.org/ j em im ap/ st yle/ color/ wheel.ht m l.
Section A.1. CSS Values
Tip: Many Mac programs such as TextEdit, let you open the color picker by pressing
-Shift-C.
A.2.1. Lengths and Sizes CSS provides m any different ways t o m easure t he size of t ype, t he widt h of a box, or t he t hickness of a borderline. To indicat e t ype size, you can use inches, picas, point s, cent im et ers, m illim et ers, em - height s, ex- height s, pixels, and percent ages. However, even t hough t here are a lot of opt ions, m ost don't apply t o t he world of onscreen display, for reasons discussed in Sect ion 6.2. You really need t o t hink about t hese t hree only pixels, em s, and percent ages.
A.1.2.1. Pixels A pixel is a single dot on a com put er screen. Pixels give you a consist ent m et hod of ident ifying lengt hs and font sizes from com put er t o com put er: 72 pixels on one m onit or is 72 pixels on anot her m onit or. That doesn't m ean t he act ual, real- world lengt h is t he sam e for everyone, t hough. Since people set t heir m onit ors t o different resolut ions800 x 600, 1024 x 768, 1600 x 1200, or what ever72 pixels m ay t ake up 1 inch on one m onit or, but only half an inch for som eone else. Nevert heless, pixels give you t he m ost consist ent cont rol over present at ion.
Note: There's just one drawback to using pixels: folks using Internet Explorer 6 or earlier can't resize any type that's sized using pixels. If your text is too small for someone's eyes, the visitor won't be able to enlarge it to make it more readable. (See Section 6.2.2 for more on pixel measurements.)
A.1.2.2. Ems Originally from t he t ypographic world, an em is a unit t hat represent s t he height of t he capit al let t er M for a part icular font . I n Web pages, one em is t he height of t he Web browser's base t ext size, which is usually 16 pixels. However, anyone can change t hat base size set t ing, so 1em m ay be 16 pixels for one person, but 24 pixels in som eone else's browser. I n ot her words, em s are a relat ive unit of m easurem ent . I n addit ion t o t he browser's init ial font size set t ing, em s can inherit size inform at ion from cont aining t ags. A t ype size of .9em would m ake t ext about 14 pixels t all on m ost browsers wit h a 16 pixel base size. But if you have a < p> t ag wit h a font size of .9em s, and t hen a < st rong> t ag wit h a font size of .9em s inside t hat < p> t ag, t hat < st rong> t ag's em size isn't 14 pixelsit 's 12 pixels ( 16 x .9 x .9) . So keep inherit ance in m ind when you use em values.
A.1.2.3. Percentages CSS uses percent ages for m any different purposes, like sizing t ext , det erm ining t he widt h or height of an elem ent , and specifying t he placem ent of an im age in t he background of a st yle, t o nam e a few. Now, what you're t aking a percent age of varies from propert y t o propert y. For font sizes, t he percent age is calculat ed based on t he t ext 's inherit ed value. Say t he general font size for a paragraph is 16 pixels t all. I f you creat ed a st yle for one special paragraph and set it s font size t o 200 percent , t hat t ext is displayed at 32
Section A.1. CSS Values
pixels t all. When applied t o widt h, however, percent ages are calculat ed based on t he widt h of t he page, or on anot her parent elem ent wit h a set widt h. You specify a percent age wit h a num ber followed by t he percent sign: 100% .
A.1.3. Keywords I nst ead of color or size, m any propert ies have t heir own specific values t hat affect how t he propert ies display and are represent ed by keywords. The t ext - align propert y, which aligns t ext on screen, can t ake one of four keywords: right , left , cent er, and j ust ify. Since keywords vary from propert y t o propert y, read t he propert y descript ions t hat follow t o learn t he keyword appropriat e t o each propert y. One keyword, however, is shared by all propert ies inherit . This keyword let s you force a st yle t o inherit a value from a parent elem ent . You can use t he inherit keyword on any propert y. This keyword gives you t he power t o m ake st yles inherit propert ies t hat aren't norm ally inherit ed from parent t ags. For inst ance, say you use t he t ext - decorat ion propert y t o underline a paragraph. Ot her t ags, such as < em > and < st rong> , inside t he < p> t ag don't inherit t his value, but you can force t hem t o do so wit h t he inherit keyword: em, strong { text-decoration: inherit; }
That way, t he em and st rong t ags display t he sam e t ext - decorat ion value as t heir parent < p> t agunderline, in t his case. So t he < em > and < st rong> elem ent s of t he paragraph each get underlined as does t he ent ire paragraph so you'd end up wit h double underlines under em phasized t ext ( a good reason why t hat propert y isn't inherit ed norm ally) . I f you change t he < p> t ag's t ext - decorat ion value t o overline inst ead of underline, t he < em > and < st rong> t ags inherit t hat value and display overlines, t oo.
Note: Underline/overline isn't a very useful example, mainly because inherit isn't a very useful value. But this wouldn't be a Missing Manual if it didn't give you all the facts.
A.1.4. URLs URL values let you point t o anot her file on t he Web. For exam ple, t he background- im age propert y accept s a URLt he pat h t o t he file on t he Webas it s value, which let s you assign a graphic file as a background for a page elem ent . This t echnique is handy for adding a t iling im age in t he background of a page or for using your own graphic for bullet ed list s ( see Sect ion 8.2) . I n CSS, you specify an URL like t his: url( im ages/ t ile.gif) . A st yle t hat adds an im age called t ile.gif t o t he background of t he page would look like t his: body { background-image: url(images/tile.gif); }
Unlike HTML, in CSS, quot es around t he URL are opt ional, so url( " im ages/ t ile.gif" ) , url( 'im ages/ t ile.gif') , and url( im ages/ t ile.gif) are equivalent .
Section A.1. CSS Values
Note: The URL itself is just like the HTML href attribute used for links, meaning you can use an absolute URL like http:// www.missingmanuals.com/images/tile.gif, a root-relative path like /images/tile.gif, or a document-relative URL like ../../ images/tile.gif. See Section 8.3 for the full story on these kinds of paths.
Section A.2. Text Properties
A.2. Text Properties The following propert ies affect how t ext is form at t ed on a Web page. Since m ost of t he propert ies in t his cat egory are inherit ed, you don't necessarily have t o apply t hem t o t ags specifically int ended for t ext ( like t he < p> t ag) . You can apply t hese propert ies t o t he < body> t ag, so t hat ot her t ags inherit and use t he sam e set t ings. This t echnique is a quick way t o creat e an overall font , color, and so on for a page or sect ion.
A.2.1. color (inherited) Set s t he color of t ext . Since it 's inherit ed, if you set t he color of t he < body> t ag t o red, for exam ple, all t ext inside of t he bodyand all ot her t ags inside t he < body> t agis red, t oo. ● ●
Va lu e s: any valid color value Ex a m ple : color: # FFFF33;
Note: The preset link colors for the tag override color inheritance. In the above example, any links inside the tag would still be standard hyperlink blue. See Section 9.1 for ways to change preset link colors.
A.2.2. font (inherited) This is a short cut m et hod for cram m ing t he following t ext propert ies int o a single st yle declarat ion: font st yle, font - variant , font - weight , font - size, line- height , and font - fam ily. ( Read on for t he individual descript ions.) You m ust separat e each value by a space and include at least font - size and font - fam ily, and t hose t wo propert ies m ust be t he last t wo it em s in t he declarat ion. The ot hers are opt ional. I f you don't set a propert y, t he browser uses it s own preset value, pot ent ially overriding inherit ed propert ies. ●
●
Va lu e s: Any value t hat 's valid for t he specific font propert y. When including a line- height , add a slash followed by t he line- height aft er t he font size like t his: 1.25em / 150% . Ex a m ple : font: italic small-caps bold 1.25em/150% Arial, Helvetica, sans-serif;
A.2.3. font-family (inherited) Specifies t he font t he browser should use t o display t ext . Font s are usually specified as a series of t hree t o four opt ions t o accom m odat e t he fact t hat a part icular font m ay not be inst alled on a visit or's com put er. See Sect ion 6.1.1. ●
●
Va lu e s: A com m a- separat ed list of font nam es. When a font has a space in it s nam e, surround t hat font nam e wit h quot es. The last font list ed is usually a generic font t ype inst ruct ing browsers t o choose a suit able font if t he ot her list ed font s aren't available: serif, sans- serif, m onot ype, fant asy, or cursive. Ex a m ple : font-family: "Lucida Grande", Arial, sans-serif;
Section A.2. Text Properties
A.2.4. font-size (inherited) Set s t he size of t ext . This propert y is inherit ed, which can lead t o som e weird behaviors when using relat ive lengt h m easurem ent s like percent ages and em s. ●
●
Va lu e s: Any valid CSS m easurem ent unit ( Sect ion A.1.1.1) , plus t he following keywords: xx- sm all, x- sm all, sm all, m edium , large, x- large, xx- large, larger, and sm aller. Medium represent s t he Web browser's norm al, preset font size, and t he ot her sizes are m ult iples of m edium . The exact num bers depend on t he browser, but t hey're generally a fact or of 1.2. For exam ple, large is 1.2 t im es as big as m edium . Due t o t he uncert aint y of how each browser handles t hese keywords, m any designers use pixels, em s, or percent ages inst ead. Ex a m ple : font-size: 1.25em;
Note: When the font-size property is inherited from another tag, these keywords multiply the inherited font size by the same factor (1.2 in most browsers).
A.2.5. font-style (inherited) Makes t ext it alic. Applied t o it alic t ext , it t urns it back t o plain t ext . The opt ions it alic and oblique are funct ionally t he sam e. ● ●
Va lu e s: it alic, oblique, norm al Ex a m ple : font-style: italic;
A.2.6. font-variant (inherited) Makes t ext appear in sm all caps, like t his: SPECI AL PRESENTATI ON. The value norm al rem oves sm all caps from t ext already form at t ed t hat way. ● ●
Va lu e s: sm all- caps, norm al Ex a m ple : font-variant: small-caps;
A.2.7. font-weight (inherited) Makes t ext bold, or rem oves bolding from t ext already form at t ed t hat way. ●
●
Va lu e s: CSS act ually provides 14 different font - weight keywords, but only a couple act ually work wit h t oday's browsers and com put er syst em sbold and norm al. Ex a m ple : font-weight: bold;
A.2.8. letter-spacing (inherited) Adj ust s t he space bet ween let t ers t o spread out let t ers ( adding spacing bet ween each) or cram let t ers
Section A.2. Text Properties
t oget her ( rem oving space) . ●
●
Va lu e s: Any valid CSS m easurem ent unit , t hough em s and pixels are m ost com m on. For t his propert y, percent ages don't work in m ost browsers. Use a posit ive value t o increase t he space bet ween let t ers and a negat ive value t o rem ove space ( scrunch let t ers t oget her) . The value norm al reset s let t er- spacing t o it s regular browser value of 0. Ex a m ple s: letter-spacing: -1px; letter-spacing: 2em;
A.2.9. line-height (inherited) Adj ust s space bet ween lines of t ext in a paragraph ( oft en called line spacing in word processing program s) . The norm al line height is 120 percent of t he size of t he t ext ( Sect ion 6.4) . ●
●
Va lu e s: Most valid CSS lengt hs ( Sect ion A.1.1.1) , t hough em s and pixels and percent ages are m ost com m on. Ex a m ple : line-height: 200%;
A.2.10. text-align (inherited) Posit ions a block of t ext t o t he left , right , or cent er of t he page or cont ainer elem ent . ● ●
Va lu e s: left , cent er, right , j ust ify ( t he j ust ify opt ion oft en m akes t ext difficult t o read on m onit ors) . Ex a m ple : text-align: center;
A.2.11. text-decoration Adds lines above, under, and/ or t hrough t ext . Underlining is com m on wit h links, so it 's usually a good idea not t o underline t ext t hat isn't a link. The color of t he underline, overline, or st rike- t hrough line is t he sam e as t he font color of t he t ag being st yled. The propert y also support s a blink value t hat m akes t ext flash off and on obnoxiously. ●
●
Va lu e s: underline, overline, line- t hrough, blink, none. The none value t urns off all decorat ion. Use t his t o hide t he underline t hat norm ally appears under links. You can also add m ult iple decorat ions by list ing t he nam e of each t ype ( except none) separat ed by a space. Ex a m ple : text-decoration: underline overline line-through;
A.2.12. text-indent (inherited) Set s t he indent size of t he first line of a block of t ext . The first line can be indent ed ( as in m any print ed books) or out dent ed, so t hat t he first line hangs off and over t he left edge of t he rest of t he t ext . ●
Va lu e s: Any valid CSS m easurem ent unit . Em s and pixels are m ost com m on; percent ages behave different ly t han wit h t he font - size propert y. Here, percent ages are based on t he widt h of t he box cont aining t he t ext , which can be t he widt h of t he ent ire browser window. So 50% would indent t he first line half of t he way across t he window ( see Sect ion 7.5.1 for a det ailed explanat ion) . To out dent ( hang t he first line off t he left edge) , use a negat ive value. This t echnique works well in conj unct ion wit h a posit ive left - m argin propert y ( Sect ion A.1.1) , which indent s t he left side of t he ot her lines of t ext a set am ount .
Section A.2. Text Properties ●
Ex a m ple : text-indent: 3em;
A.2.13. text-transform (inherited) Changes t he capit alizat ion of t ext , so t ext appears in all uppercase let t ers, all lowercase, or only t he first let t er of each word capit alized. ●
●
Va lu e s: uppercase, lowercase, capit alize, none. The none opt ion ret urns t he t ext t o what ever case is in t he act ual HTML code. I f aBCDefg are t he act ual let t ers t yped in HTML, t hen none rem oves any ot her inherit ed case set by an ancest or t ag and displays aBCDefg onscreen. Ex a m ple : text-transform: uppercase;
Va lu e s: baseline, sub, super, t op, t ext - t op, m iddle, bot t om , t ext - bot t om , a percent age value, or an absolut e value ( like pixels or em s) . Percent ages are calculat ed based on t he elem ent 's line- height value ( Sect ion A.1.1) . Ex a m ple s: vertical-align: top; vertical-align: -5px; vertical-align: 75%;
A.2.15. white-space Cont rols how t he browser displays space charact ers in t he HTML code. Norm ally, if you include m ore t han one space bet ween words" Hello Dave" a Web browser displays only one space" Hello Dave." You can preserve any whit e space exact ly as is in t he HTML using t he pre value, which does t he sam e as t he HTML < pre> t ag. I n addit ion, Web browsers will split a line of t ext at a space, if t he line won't fit wit hin t he window's widt h. To prevent t ext from wrapping, use t he nowrap value. But t he nowrap value m akes all of t he paragraph's t ext st ay on one line, so don't use it wit h long paragraphs ( unless you like t he idea of m aking your visit ors scroll endlessly t o t he right ) . ● ●
Va lu e s: nowrap, pre, norm al. Two ot her valuespre- line and pre- wrapdon't work in m any browsers. Ex a m ple : white-space: pre;
A.2.16. word-spacing (inherited) Works like t he let t er- spacing propert y ( Sect ion A.1.1) , but inst ead of let t ers, it adj ust s space bet ween words. ●
●
Va lu e s: Any valid CSS m easurem ent unit , t hough em s and pixels are m ost com m on; percent ages don't work in m ost browsers. Use a posit ive value t o increase t he space bet ween words and a negat ive value t o rem ove space ( scrunch words t oget her) . The value norm al reset s word spacing t o it s regular browser value of 0. Ex a m ple s: word-spacing: -1px; word-spacing: 2em;
Section A.2. Text Properties
Section A.3. List Properties
A.3. List Properties The following propert ies affect t he form at t ing of bullet ed list s ( < ul> ) and num bered list s ( < ol> ) .
A.3.1. list-style (inherited) This propert y is a short hand m et hod of specifying t he t hree propert ies list ed next . You can include a value for one or m ore of t hose propert ies, separat ing each by a space. You can even use t his propert y as a short cut for writ ing a single propert y and save a couple of keyst rokes: list - st yle: out side, inst ead of list st yle- posit ion: out side. I f you specify bot h a t ype and an im age, a Web browser will display t he bullet t ype ( disc, square, and so on) only if it can't find t he im age. This way, if t he pat h t o your cust om bullet im age doesn't work, you don't end up wit h a bullet less bullet ed list . ● ●
Va lu e s: Any valid value for list - st yle- t ype, list - st yle- im age, and/ or list - st yle- posit ion. Ex a m ple : list-style: disc url(images/bullet.gif) inside;
A.3.2. list-style-image (inherited) Specifies an im age t o use for a bullet in a bullet ed list . ● ●
Va lu e s: an URL value ( Sect ion A.1.1) or none. Ex a m ple : list-style-image: url(images/bullet.gif) ;
Tip: The background-image property does the custom bullet job just as well and offers more control (see Section 8.2).
A.3.3. list-style-position (inherited) Posit ions t he bullet s or num bers in a list . These m arkers can appear out side of t he t ext , hanging off t o t he left , or inside t he t ext ( exact ly where t he first let t er of t he first line norm ally begins) . The out side posit ion is how Web browsers norm ally display bullet s and num bers. ● ●
Va lu e s: inside, out side Ex a m ple : list-style: inside;
A.3.4. list-style-type (inherited) Set s t he t ype of bullet for a list round, square, rom an num eral, and so on. You can t heoret ically t urn an unordered ( bullet ed) list int o an ordered ( num bered) list by changing t he list - st yle- t ype propert y, but it doesn't work in all browsers ( including I nt ernet Explorer for Windows) . Use t he none opt ion t o com plet ely rem ove bullet s or num bers from t he list . ●
Va lu e s: disc, circle, square, decim al, decim al- leading- zero, upper- alpha, lower- alpha, upper- rom an,
Section A.3. List Properties
●
lower- rom an, lower- greek, none Ex a m ple : list-style-type: square;
Section A.4. Padding, Borders, and Margins
A.4. Padding, Borders, and Margins The following propert ies cont rol t he space around an elem ent , and let you add border lines t o a st yle.
A.4.1. border Draws a line around t he four edges of an elem ent . ●
Va lu e s: The widt h ( t hickness) of t he border line in any valid CSS m easurem ent unit ( except percent ages) . You can also specify a st yle for t he line: solid, dot t ed, dashed, double, groove, ridge, inset , out set , none, and hidden. ( See Figure 7- 7 in Sect ion 7.3 for an illust rat ion of t he different st yles.) The none and hidden values do t he sam e t hingrem ove any border.
●
Finally, you can specify a color using any valid CSS color t ype ( a keyword like green or a hex num ber like # 33fc44) . Ex a m ple : border: 2px solid #f33;
A.4.2. border-top, border-right, border-bottom, border-left Adds a border t o a single edge. For exam ple, border- t op adds a border t o t he t op of t he elem ent . ● ●
Va lu e s: sam e as for border. Ex a m ple : border-left: 1em dashed red;
A.4.3. border-color Defines t he color used for all four borders. ● ●
Va lu e s: Any valid CSS color t ype ( a keyword like green or a hex num ber like # 33fc44) . Ex a m ple : border-color: rgb(255,34,100) ;
A.4.4. border-top-color, border-right-color, border-bottom-color, border-left-color Funct ions j ust like t he border- color propert y but set s color for only one edge. Use t hese propert ies t o override t he color set by t he border propert y. I n t his way, you can cust om ize t he color for an individual edge while using a m ore generic border st yle t o define t he basic size and st yle of all four edges. ● ●
Va lu e s: see border- color above. Ex a m ple : border-left-color: #333;
A.4.5. border-style
Section A.4. Padding, Borders, and Margins
Defines t he st yle used for all four borders. ●
●
Va lu e s: One of t hese key words: solid, dot t ed, dashed, double, groove, ridge, inset , out set , none, and hidden. See Figure 7- 7 in Sect ion 7.3 for an illust rat ion of t he different st yles. The none and hidden values act ident icallyt hey rem ove any border. Ex a m ple : border-style: inset;
A.4.6. border-top-style, border-right-style, border-bottom-style, border-left-style Funct ions j ust like t he border- st yle propert y, but applies only t o one edge. ● ●
Va lu e s: see border- st yle above. Ex a m ple : border-top-style: none;
A.4.7. border-width Defines t he widt h or t hickness of t he line used t o draw all four borders. ●
●
Va lu e s: Any valid CSS m easurem ent unit except percent ages. The m ost com m on are em s and pixels. Ex a m ple : border-width: 1px;
A.4.8. border-top-width, border-right-width, border-bottom-width, border-left-width Funct ions j ust like t he border- widt h propert y but applies only t o one edge. ● ●
Va lu e s: see border- widt h above. Ex a m ple : border-bottom-width: 3em;
A.4.9. outline This propert y is a short hand way t o com bine out line- color, out line- st yle, and out - line- widt h ( list ed next ) . An out line works j ust like a border, except t he out line t akes up no space ( t hat is, it doesn't add t o t he widt h or height of an elem ent ) , and it applies t o all four edges. I t 's int ended m ore as a way of highlight ing som et hing on a page t han as a design det ail. Out line works in Firefox, Safari, and Opera, but not in I nt ernet Explorer. ● ●
Va lu e s: The sam e as for border wit h one except ionsee out line- color next . Ex a m ple : outline: 3px solid #F33;
A.4.10. outline-color Specifies t he color for an out line ( see out line above) . ●
Va lu e s: Any valid CSS color, plus t he value invert , which m erely reverses t he color t he out line is
Section A.4. Padding, Borders, and Margins
●
sit t ing on. I f t he out line is drawn on a whit e background, t he invert value m akes t he out line black. Works j ust like border- color ( Sect ion A.1.1) . Ex a m ple : outline-color: invert;
A.4.11. outline-style Specifies t he t ype of line for t he out line dot t ed, solid, dashed, and so on. ● ●
Va lu e s: Sam e as border- st yle ( Sect ion A.1.1) . Ex a m ple : outline-style: dashed;
A.4.12. outline-width Specifies t he t hickness of t he out line. Works j ust like border- widt h ( Sect ion A.1.1) . ●
●
Va lu e s: Any valid CSS m easurem ent unit except percent ages. The m ost com m on are em s and pixels. Ex a m ple : outline-width: 3px;
A.4.13. padding Set s t he am ount of space bet ween t he cont ent and border and edge of t he background. Use it t o add em pt y space around t ext , im ages, or ot her cont ent . ( See Figure 7- 1 in Sect ion 7.2 for an illust rat ion.) ●
●
Va lu e s: Any valid CSS m easurem ent unit , like pixels or em s. Percent age values are based on t he widt h of t he cont aining elem ent . A headline t hat 's a child of t he < body> t ag uses t he widt h of t he browser window t o calculat e a percent age value, so a padding of 20 percent adds 20 percent of t he window's widt h. I f t he visit or resizes his browser, t he padding size changes proport ionat ely. You can specify t he padding for all four edges by using a single value, or set individual padding sizes per edge using t his order: t op, right , bot t om , left . Exam ples: padding: 20px; padding: 2em 3em 2.5em 0;
A.4.14. padding-top Works j ust like t he padding propert y, but set s padding for t op edge only. ●
Ex a m ple : padding-top: 20px;
A.4.15. padding-right Works j ust like t he padding propert y, but set s padding for right edge only. ●
Ex a m ple : padding-right: 20px;
A.4.16. padding-bottom
Section A.4. Padding, Borders, and Margins
Works j ust like t he padding propert y, but set s padding for bot t om edge only. ●
Ex a m ple : padding-bottom: 20px;
A.4.17. padding-left Works j ust like t he padding propert y, but set s padding for left edge only. ●
Ex a m ple : padding-left: 20px;
A.4.18. margin Set s t he am ount of space bet ween an elem ent 's border and t he m argin of ot her elem ent s ( see Figure 7- 1 in Sect ion 7.2) . I t let s you add whit e space bet ween t wo elem ent sbet ween one pict ure and anot her pict ure, or bet ween a sidebar and t he m ain cont ent area of a page.
Note: Vertical margins between elements can collapse. That is, browsers use only the top or bottom margin and ignore the other, creating a smaller gap than expected (see Section 7.2.2).
●
●
Va lu e s: Any valid CSS m easurem ent unit like pixels or em s. Percent age values are based on t he widt h of t he cont aining elem ent . A headline t hat 's a child of t he body t ag uses t he widt h of t he browser window t o calculat e a percent age value, so a m argin of 10 percent adds 10 percent of t he window's widt h t o t he edges of t he headline. I f t he visit or resizes his browser, t he m argin size changes. As wit h padding, you specify t he m argin for all four edges using a single value, or set individual m argins in t his order: t op, right , bot t om , left . Ex a m ple s: margin: 20px; margin: 2em 3em 2.5em 0;
A.4.19. margin-top Works j ust like t he m argin propert y, but set s m argin for t op edge only. ●
Ex a m ple : margin-top: 20px;
A.4.20. margin-right Works j ust like t he m argin propert y, but set s m argin for right edge only. ●
Ex a m ple : margin-right: 20px;
A.4.21. margin-bottom Works j ust like t he m argin propert y, but set s m argin for bot t om edge only.
Section A.4. Padding, Borders, and Margins
●
Ex a m ple : margin-bottom: 20px;
A.4.22. margin-left Works j ust like t he m argin propert y, but set s m argin for left edge only. ●
Ex a m ple : margin-left: 20px;
Section A.5. Backgrounds
A.5. Backgrounds CSS provides several propert ies for cont rolling t he background of an elem ent , including coloring t he background, placing an im age behind an elem ent , and cont rolling how t hat background im age is posit ioned.
A.5.1. background Provides a short hand m et hod of specifying propert ies t hat appear in t he background of an elem ent , like a color, an im age, and t he placem ent of t hat im age. I t com bines t he five background propert ies ( described next ) int o one com pact line, so you can get t he sam e effect wit h m uch less t yping. However, if you don't set one of t he propert ies, browsers use t hat propert y's norm al value inst ead. For exam ple, if you don't specify how a background im age should repeat , browsers will t ile t hat im age from left t o right and t op t o bot t om ( see Sect ion 8.3) . ●
●
Va lu e s: The sam e values used for t he background propert ies list ed next . The order of t he propert ies isn't im port ant ( except for posit ioning as described below) but usually follow t he order of background- color, background- im age, background- repeat , background- at t achm ent , backgroundposit ion. Ex a m ple : background: #333 url(images/logo.gif) no-repeat fixed left top;
A.5.2. background-attachment Specifies how a background im age react s when your visit or scrolls t he page. The im age eit her scrolls along wit h t he rest of t he cont ent or rem ains in place. You can add a logo t o t he upper- left corner of a very long Web page, using t he background- at t achm ent propert y's fixed value, and m ake t hat im age st ay in t he upperleft corner even when t he page is scrolled. ( I n I nt ernet Explorer 6 and earlier, t his propert y works only for t he < body> t ag.) ●
●
Va lu e s: scroll or fixed. Scroll is t he norm al behavior: An im age will scroll off t he screen along wit h t ext . Fixed locks t he im age in place. Ex a m ple : background-attachment: fixed;
A.5.3. background-color Adds a color t o t he background of a st yle. The background sit s underneat h t he border and underneat h a background im age, a fact t o keep in m ind if you use one of t he non- solid border st yles like dashed or dot t ed. I n t hese cases, t he background color shows t hrough t he gaps bet ween t he dashes or dot s. ● ●
Va lu e s: any valid color value ( Sect ion A.1) . Ex a m ple : background-color: #FFF;
A.5.4. background-image Places an im age int o t he background of a st yle. Ot her page elem ent s sit on t op of t he background im age, so m ake sure t hat t ext is legible where it overlaps t he im age. You can always use padding t o m ove cont ent away from t he im age, t oo. The im age t iles from left t o right and t op t o bot t om , unless you set t he
Section A.5. Backgrounds
background- repeat propert y as well. ● ●
Va lu e s: The URL of an im age. Ex a m ple s: background-image: url(images/photo.jpg); background-image: url(http://www.example. org/photo.jpg) ;
A.5.5. background-position Cont rols t he placem ent of an im age in t he background of a page elem ent . Unless you specify ot herwise, an im age begins in t he elem ent 's t op- left corner. I f t he im age t iles, background- posit ion cont rols t he im age's st art point ( see background- repeat next ) . I f you posit ion an im age in t he cent er of an elem ent , t he browser put s t he im age t here, and t hen t iles t he im age up and t o t he left and down and t o t he right . I n m any cases, t he exact placem ent of an im age doesn't cause a visible difference in t he background t iling, but it let s you m ake subt le changes t o t he posit ioning of a pat t ern in t he background. ●
●
Va lu e s: You can use any valid CSS m easurem ent unit like pixels or em s, as well as keywords or percent ages. The values com e in pairs, wit h t he first being t he horizont al posit ion, and t he second being vert ical. Keywords include left , cent er, and right for horizont al posit ioning and t op, cent er, and bot t om for vert ical. Pixel and em values are calculat ed from t he t op- left corner of t he elem ent , so t o place a graphic 5 pixels from t he left edge and 10 pixels from t he t op, you'd use a value of 5px 10px. Percent age values m ap one point on t he im age t o one point in t he background of t he elem ent , calculat ed by t he specified percent age from t he left and t op edges of t he im age and t he specified percent age from t he left and t op edges of t he elem ent . 50% 50% places t he point t hat 's 50 percent across and 50 percent down t he im age on t op of t he point t hat 's 50 percent across and 50 percent down t he elem ent . I n ot her words, it put s t he im age direct ly in t he m iddle of t he elem ent ( see Sect ion 8.4.3) . You can m ix and m at ch t hese Values: I f you want , use a pixel value for horizont al placem ent and a percent age value for vert ical placem ent . Ex a m ple s: background-position: left top; background-position: 1em 3em; background-position: 10px 50%;
A.5.6. background-repeat Cont rols whet her, or how, a background im age repeat s. Norm ally, background im ages t ile from t he t op left t o t he bot t om right , filling t he elem ent 's ent ire background. ●
●
Va lu e s: repeat , no- repeat , repeat - x, repeat - y. The repeat opt ion is t he norm al m et hodt iling left t o right , t op t o bot t om . No- repeat places t he im age a single t im e in t he background wit h no t iling. Repeat - x t iles t he im age t op t o bot t om onlyperfect for adding a graphical sidebar. Repeat - y t iles t he im age from left t o right only, so you can add a graphical bar t o an elem ent 's t op, m iddle, or bot t om . Ex a m ple : background-repeat: no-repeat;
Section A.6. Page Layout Properties
A.6. Page Layout Properties The following propert ies cont rol t he placem ent and size of elem ent s on a Web page.
A.6.1. bottom This propert y is used wit h absolut e, relat ive, and fixed posit ioning ( see Sect ion A.1.1) . When used wit h absolut e or fixed posit ioning, bot t om det erm ines t he posit ion of t he bot t om edge of t he st yle relat ive t o t he bot t om edge of it s closest posit ioned ancest or. I f t he st yled elem ent isn't inside of any posit ioned t ags, t hen t he placem ent is relat ive t o t he bot t om edge of t he browser window. You can use t his propert y t o place a foot not e at t he bot t om of t he browser window. When used wit h relat ive posit ioning, t he placem ent is calculat ed from t he elem ent 's bot t om edge ( prior t o posit ioning) . See Sect ion 12.1.2. ●
●
Va lu e s: Any valid CSS m easurem ent unit , like pixels, em s, or percent ages. Percent ages are calculat ed based on t he widt h of t he cont aining elem ent . Ex a m ple : bottom: 5em;
Note: Internet Explorer 6 and earlier can have a problem when positioning an element using the bottom property. See Section 12.1.4 for details.
A.6.2. clear Prevent s an elem ent from wrapping around a float ed elem ent . I nst ead, t he cleared elem ent drops below t he bot t om of t he float ed elem ent . ●
●
Va lu e s: left , right , bot h, none. The left opt ion m eans t he elem ent can't wrap around left - float ed elem ent s. Sim ilarly, right drops t he elem ent below any right - float ed it em s. The bot h value prevent s an elem ent from wrapping around eit her left - or right - float ed elem ent s. None t urns t he propert y off, so you use it t o override a previously set clear propert y. This t rick com es in handy when a part icular t ag has a st yle t hat drops below a float ed elem ent but you want t he t ag t o wrap in j ust one case. Creat e a m ore specific st yle ( Sect ion 5.3) t o override t he float for t hat one t ag. Ex a m ple : clear: both;
A.6.3. clip Creat es a rect angular window t hat reveals part of an elem ent . I f you had a pict ure of your high- school graduat ing class, and t he class bully was st anding on t he far right edge of t he phot o, you could creat e a display area t hat crops out t he im age of your t orm ent or. The full im age is st ill int act , but t he clipping area only displays t he bully free port ion of it . The clip propert y is m ost effect ive when used wit h JavaScript program m ing t o anim at e t he clip. You can st art wit h a sm all clipping area and expand it unt il t he full phot o is revealed. ●
Va lu e s: Coordinat es of a rect angular box. Enclose t he coordinat es in parent heses and precede
Section A.6. Page Layout Properties
t hem by t he keyword rect , like so: rect ( 5px,110px,40px,10px) ; .
●
Here's how t he order of t hese coordinat es works: The first num ber indicat es t he t op offset t he t op edge of t he clipping window. I n t his exam ple, t he offset is 5px, so everyt hing in t he first four rows of pixels is hidden. The last num ber is t he left offset t he left edge of t he clipping window. I n t his exam ple, t he offset is 10px, so everyt hing t o t he left ( t he first 9 pixels of t he elem ent ) is hidden. The second num ber is t he widt h of t he clipping window plus t he last num ber; if t he left edge of t he clip is 10 pixels and you want t he visible area t o be 100 pixels, t he second num ber would be 110px. The t hird num ber is t he height of t he clipping region plus t he t op offset ( t he first num ber) . So, in t his exam ple, t he clipping box is 30 pixels t all ( 30px + 10px = 40px) . Ex a m ple : clip: rect(5px,110px,40px,10px) ;
Tip: Since the order of the coordinates is a little strange, most designers like to start with the first and last numbers, and then compute the two other numbers from them.
A.6.4. display Det erm ines t he kind of box used t o display a page elem ent block- level or inline ( Sect ion 7.2.4) . Use it t o override how a browser usually displays a part icular elem ent . You can m ake a paragraph ( block- level elem ent ) display wit hout line breaks above and below it exact ly like, say, a link ( inline elem ent ) . ●
●
Va lu e s: block, inline, none. The display propert y accept s 17 values, m ost of which have no effect in t he browsers available t oday. Block, inline, and none, however, work in alm ost all browsers. Block forces a line break above and below an elem ent , j ust like ot her block- level elem ent s ( like paragraphs and headers) . I nline causes an elem ent t o display on t he sam e line as surrounding elem ent s ( j ust as t ext wit hin a < st rong> t ag appears right on t he sam e line as ot her t ext ) . None m akes t he elem ent com plet ely disappear from t he page. Then, you can m ake t he elem ent reappear wit h som e JavaScript program m ing or t he : hover pseudo- class ( see Sect ion 3.1) . Ex a m ple : display: block;
A.6.5. float Moves ( float s) an elem ent t o t he left or right edge of t he browser window, or, if t he float ed elem ent 's inside anot her elem ent , t o t he left or right edge of t hat cont aining elem ent . Elem ent s t hat appear aft er t he float ed elem ent m ove up t o fill t he space t o t he right ( for left float s) or left ( for right float s) , and t hen wrap around t he float ed elem ent . Use float s for sim ple effect s, like m oving an im age t o one side of t he page, or for very com plex layout s like t hose described in Chapt er 11. ●
●
Va lu e s: left , right , none. None t urns off float ing ent irely, which com es in handy when a part icular t ag has a st yle wit h a left or right float applied t o it , and you want t o creat e a m ore specific st yle t o override t he float for t hat one t ag. Ex a m ple : float : left ;
A.6.6. height Set s t he height of t he cont ent areat he area of an elem ent 's box t hat cont ains cont ent like t ext , im ages, or ot her t ags. The elem ent 's act ual onscreen height is t he t ot al of height , t op and bot t om m argins, t op and
Section A.6. Page Layout Properties
bot t om padding, and t op and bot t om borders. ●
●
Va lu e s: Any valid CSS m easurem ent unit such as pixels, em s, or percent ages. Percent ages are calculat ed based on t he height of t he cont aining elem ent . Ex a m ple : height: 50%;
Note: Sometimes, your content ends up taller than the set heightif you type a lot of text, for instance, or your visitor increases text size in her browser. Browsers handle this situation differently: IE 6 and earlier simply make the box bigger, while other browsers make the content extend outside of the box. The overflow property controls what happens in this case (see Section 7.5.2).
A.6.7. left When used wit h absolut e or fixed posit ioning ( Sect ion 12.1) , t his propert y det erm ines t he posit ion of t he left edge of t he st yle relat ive t o t he left edge of it s closest posit ioned ancest or. I f t he st yled elem ent isn't inside of any posit ioned t ags, t hen t he placem ent is relat ive t o t he left edge of t he browser window. You can use t his propert y t o place an im age 20 pixels from t he left edge of t he browser window. When used wit h relat ive posit ioning, t he placem ent is calculat ed from t he elem ent 's left edge ( prior t o posit ioning) . ● ●
Va lu e s: Any valid CSS m easurem ent unit such as pixels, em s, or percent ages. Ex a m ple : left: 5em;
A.6.8. max-height Set s t he m axim um height for an elem ent . That is, t he elem ent 's box m ay be short er t han t his set t ing, but it can't be any t aller. I f t he elem ent 's cont ent s are t aller t han t he m ax- height set t ing, t hey overflow t he box. You can cont rol what happens t o t he excess using t he overflow propert y ( Sect ion 7.5.2) . I nt ernet Explorer 6 ( and earlier) doesn't underst and t he m ax- height propert y. ●
●
Va lu e s: Any valid CSS m easurem ent unit , like pixels, em s, or percent ages. Browsers calculat e percent ages based on t he height of t he cont aining elem ent . Ex a m ple : max-height: 100px;
A.6.9. max-width Set s t he m axim um widt h for an elem ent . The elem ent 's box can be narrower t han t his set t ing, but no wider. I f t he elem ent 's cont ent s are wider t han t he m ax- widt h set t ing, t hey overflow t he box, which you can cont rol wit h t he overflow propert y ( Sect ion 7.5.2) . You m ost ly use m ax- widt h in liquid layout s ( Sect ion 11.1) t o m ake sure a page design doesn't becom e unreadably wide on very large m onit ors. This propert y doesn't work in I nt ernet Explorer 6 ( or in earlier versions) . ●
●
Va lu e s: Any valid CSS m easurem ent unit , like pixels, em s, or percent ages. Percent ages are calculat ed based on t he widt h of t he cont aining elem ent . Ex a m ple : max-width: 950px;
Section A.6. Page Layout Properties
A.6.10. min-height Set s t he m inim um height for an elem ent . The elem ent 's box m ay be t aller t han t his set t ing, but it can't be short er. I f t he elem ent 's cont ent s aren't as t all as t he m in- height set t ing, t he box's height shrinks t o m eet t he m in- height value. I nt ernet Explorer 6 ( and earlier) doesn't recognize t his propert y. ●
●
Va lu e s: Any valid CSS m easurem ent unit , like pixels, em s, or percent ages. Percent ages are based on t he cont aining elem ent 's height . Ex a m ple : min-height: 20em;
A.6.11. min-width Set s t he m inim um widt h for an elem ent . The elem ent 's box m ay be wider t han t his set t ing, but it can't be narrower. I f t he elem ent 's cont ent s aren't as wide as t he m in- widt h value, t he box sim ply get s as t hin as t he m in- widt h set t ing. You can also use m in- widt h in liquid layout s, so t hat t he design doesn't disint egrat e at sm aller window widt hs. When t he browser window is t hinner t han m in- widt h, it adds horizont al scroll bars. I nt ernet Explorer 6 ( and earlier) doesn't underst and t his propert y. ●
●
Va lu e s: Any valid CSS m easurem ent unit , like pixels, em s, or percent ages. Percent ages are based on t he cont aining elem ent 's widt h. Ex a m ple : min-width: 760px;
Note: You usually use the max-width and min-width properties in conjunction when creating liquid layouts. See Chapter 11 (Section 11.4.3).
A.6.12. overflow Dict at es what should happen t o t ext t hat overflows it s cont ent area, like a phot o t hat 's wider t han t he value set for t he widt h propert y.
Note: IE 6 (and earlier) handles overflow situations differently than other browsers. See Section 7.5.2.
●
●
Va lu e s: visible, hidden, scroll, aut o. Visible m akes t he overflowing cont ent ext end out side t he boxpot ent ially overlapping borders and ot her page elem ent s on t he page. I E 6 ( and earlier) sim ply enlarges t he box ( borders and all) t o accom m odat e t he larger cont ent . Hidden hides any cont ent out side of t he cont ent area. Scroll adds scroll bars t o t he elem ent so a visit or can scroll t o read any cont ent out side t he cont ent areasort of like a m ini- fram e. Aut o adds scrollbars only when t hey're necessary t o reveal m ore cont ent . Ex a m ple : overflow: hidden;
A.6.13. position
Section A.6. Page Layout Properties
Det erm ines what t ype of posit ioning m et hod a browser uses when placing an elem ent on t he page. ●
●
Va lu e s: st a t ic, r e la t ive , a bsolu t e , fix e d. St at ic is t he norm al browser m odeone block- level it em st acked on t op of t he next wit h cont ent flowing from t he t op t o t he bot t om of t he screen. Relat ive posit ions an elem ent in relat ion t o where t he elem ent current ly appears on t he pagein ot her words, it can offset t he elem ent from it s current posit ion. Absolut e t akes an elem ent com plet ely out of t he page flow. Ot her it em s don't see t he absolut e elem ent and m ay appear underneat h it . I t 's used t o posit ion an elem ent in an exact place on t he page, or t o place an elem ent in an exact posit ion relat ive t o a parent elem ent t hat 's posit ioned wit h absolut e, relat ive or fixed posit ioning. Fixed locks an elem ent on t he page, so t hat when t he page is scrolled, t he fixed elem ent rem ains on t he screenm uch like HTML fram es. I nt ernet Explorer 6 ( and earlier) ignores t he fixed opt ion. Ex a m ple : position: absolute;
Note: You usually use relative, absolute, and fixed in conjunction with left, right, top, and bottom. See Chapter 12 for the full details on positioning.
A.6.14. right When used wit h absolut e or fixed posit ioning ( Sect ion 12.1) , t his propert y det erm ines t he posit ion of t he right edge of t he st yle relat ive t o t he right edge of it s closest posit ioned ancest or. I f t he st yled elem ent isn't inside of any posit ioned t ags, t hen t he placem ent is relat ive t o t he right edge of t he browser window. You can use t his propert y t o place a sidebar a set am ount from t he right edge of t he browser window. When used wit h relat ive posit ioning, t he placem ent is calculat ed from t he elem ent 's right edge ( prior t o posit ioning) . ● ●
Va lu e s: Any valid CSS m easurem ent unit , like pixels, em s, or percent ages. Ex a m ple : left: 5em;
Note: Internet Explorer 6 (and earlier) can have problems when positioning an element using the right property. See Section 12.1.4 for details.
A.6.15. top Does t he opposit e of t he bot t om propert y ( Sect ion A.1.1) . I n ot her words, when used wit h absolut e or fixed posit ioning, t his propert y det erm ines t he posit ion of t he t op edge of t he st yle relat ive t o t he t op edge of it s closest posit ioned ancest or. I f t he st yled elem ent isn't inside of any posit ioned t ags, t hen t he placem ent is relat ive t o t he t op edge of t he browser window. You can use t his propert y t o place a logo a set am ount from t he t op edge of t he browser window. When used wit h relat ive posit ioning, t he placem ent is calculat ed from t he elem ent 's t op edge ( prior t o posit ioning) . ● ●
Va lu e s: Any valid CSS m easurem ent unit , like pixels, em s, or percent ages. Ex a m ple : top: 5em;
Section A.6. Page Layout Properties
A.6.16. visibility Det erm ines whet her a Web browser displays t he elem ent . Use t his propert y t o hide part of t he cont ent of t he page, such as a paragraph, headline, or < div> t ag. Unlike t he display propert y's none valuewhich hides an elem ent and rem oves it from t he flow of t he paget he visibilit y propert y's hidden opt ion doesn't rem ove t he elem ent from t he page flow. I nst ead, it j ust leaves an em pt y hole where t he elem ent would have been. For t his reason, you m ost oft en use t he visibilit y propert y wit h absolut ely posit ioned elem ent s, which have already been rem oved from t he flow of t he page. Hiding an elem ent doesn't do you m uch good unless you can show it again. JavaScript program m ing is t he m ost com m on way t o t oggle t he visibilit y propert y t o show and hide it em s on a page. You can also use t he : hover pseudo- class ( Sect ion 9.1) t o change an elem ent 's visibilit y propert y when a visit or hovers over som e part of t he page. ● ●
Va lu e s: visible, hidden. You can use t he collapse value t o hide a row or colum n in a t able as well. Ex a m ple : visibility: hidden;
A.6.17. width Set s t he widt h of t he cont ent area ( t he area of an elem ent 's box t hat cont ains t ext , im ages, or ot her t ags) . The am ount of onscreen space act ually dedicat ed t o t he elem ent m ay be m uch wider, since it includes t he widt h of t he left and right m argin, left and right padding, and left and right borders. I E 6 ( and earlier) handles overflow sit uat ions different ly t han ot her browsers. ( See Sect ion 7.5.2.) ●
●
Va lu e s: Any valid CSS m easurem ent unit , like pixels, em s, or percent ages. Percent ages are based on t he cont aining elem ent 's widt h. Ex a m ple : width: 250px;
A.6.18. z-index Cont rols t he layering of posit ioned elem ent s. Only applies t o elem ent s wit h a posit ion propert y set t o absolut e, relat ive, or fixed ( Sect ion 12.1) . I t det erm ines where on t he Z- axis an elem ent appears. I f t wo absolut ely posit ioned elem ent s overlap, t he one wit h t he higher z- index appears t o be on t op. ●
●
Va lu e s: An int eger value, like 1, 2, or 10. You can also use negat ive values, but different browsers handle t hem different ly. The larger t he num ber, t he m ore " on t op" t he elem ent appears. An elem ent wit h a z- index of 20 appears below an elem ent wit h a z- index of 100 ( if t he t wo overlap) . However, when t he elem ent is inside anot her posit ioned elem ent , it 's " posit ioning cont ext " changes and it m ay not appear above anot her elem ent no m at t er what it s z- index value. See Figure 12- 6. Ex a m ple : z-index: 12;
Tip: The values don't need be in exact integer order. If element A has a z-index of 1, you don't have to set element B's zindex to 2 to put it on top. You can use 5, 10, and so on to get the same effect, as long as it's a bigger number. So, to make sure an element always appears above other elements, simply give it a very large value, like 10000.
Section A.6. Page Layout Properties
Section A.7. Table Properties
A.7. Table Properties There are a handful of CSS propert ies t hat relat e solely t o HTML t ables. Chapt er 10 has com plet e inst ruct ions on using CSS wit h t ables.
A.7.1. border-collapse Det erm ines whet her t he borders around t he cells of a t able are separat ed or collapsed. When t hey're separat ed, browsers put a space of a couple of pixels bet ween each cell. Even if you elim inat e t his space by set t ing t he cellspacing at t ribut e for t he HTML < t able> t ag t o 0, browsers st ill display double borders. That is, t he bot t om - border of one cell will appear above t he t op border of t he cell below causing a doubling of border lines. Set t ing t he border- collapse propert y t o collapse elim inat es bot h t he space bet ween cells and t his doubling up of borderlines ( Sect ion 10.2.1) . This propert y works only when applied t o a < t able> t ag. ● ●
Va lu e s: collapse, separat e Ex a m ple : border-collapse: collapse;
A.7.2. border-spacing Set s t he am ount of space bet ween cells in a t able. I t replaces t he < t able> t ag's cell- spacing HTML at t ribut e. However, I nt ernet Explorer doesn't underst and t he border- spacing propert y, so it 's best t o cont inue t o use t he cellspacing at t ribut e in your < t able> t ags t o guarant ee space bet ween cells in all browsers.
Note: If you want to eliminate the space browsers normally insert between cells, just set the border-collapse property to collapse.
●
●
Va lu e s: Two CSS lengt h values. The first set s t he horizont al separat ion ( t he space on eit her side of each cell) and t he second set s t he vert ical separat ion ( t he space separat ing t he bot t om of one cell from t he t op of t he one below it ) . Ex a m ple : border-spacing: 0 10px;
A.7.3. caption-side When applied t o a t able capt ion, t his propert y det erm ines whet her t he capt ion appears at t he t op or bot t om of t he t able. ( Since, according t o HTML rules, t he < capt ion> t ag m ust im m ediat ely follow t he opening < t able> t ag, a capt ion would norm ally appear at t he t op of t he t able.) ● ●
Va lu e s: t op, bot t om Ex a m ple : caption-side: bottom;
Note: Unfortunately, this property has no effect in any versions of Internet Explorer (as of this writing), so it's safest to
Section A.7. Table Properties
stick with the HTML equivalent: or .
A.7.4. empty-cells Det erm ines how a browser should display a t able cell t hat 's com plet ely em pt y, which in HTML would look like t his: < t d> < / t d> . The hide value prevent s any part of t he cell from being displayed. I nst ead, only an em pt y placeholder appears, so borders, background colors, and background im ages don't show up in an em pt ied cell. Apply t his propert y t o a st yle form at t ing t he < t able> t ag. ● ●
Va lu e s: show, hide Ex a m ple : empty-cells: show;
Note: The empty-cells property has no effect if the border-spacing property is set to collapse.
A.7.5. table-layout Cont rols how a Web browser draws a t able, and can slight ly affect t he speed at which t he browser displays it . The fixed set t ing forces t he browser t o render all colum ns t he sam e widt h as t he colum ns in t he first row, which ( for com plicat ed t echnical reasons) draws t ables fast er. The aut o value is t he norm al " browser j ust do your t hing" value, so if you're happy wit h how quickly your t ables appear on a page, don't bot her wit h t his propert y. I f you use it , apply t able- layout t o a st yle form at t ing t he < t able> t ag. ● ●
Va lu e s: aut o, fixed Ex a m ple : table-layout: fixed;
Section A.8. Miscellaneous Properties
A.8. Miscellaneous Properties CSS 2.1 offers a few addit ionaland som et im es int erest ing propert ies. They let you enhance your Web pages wit h special cont ent and cursors, offer m ore cont rol over how a page print s, and so on. ( Unfort unat ely, browser underst anding of t hese propert ies is spot t y at best .)
A.8.1. content Specifies t ext t hat appears eit her before or aft er an elem ent . Use t his propert y wit h t he : aft er or : before pseudo- elem ent s. You can add an opening quot at ion m ark in front of quot ed m at erial and a closing quot at ion aft er t he quot e. This propert y isn't support ed by I nt ernet Explorer ( not even I E 7 as of t his writ ing) , so it s use is lim it ed. ●
●
Va lu e s: Text inside of quot es " like t his" , t he keywords norm al, open- quot e, close- quot e, no- openquot e, no- close- quot e. You can also use t he value of an HTML at t ribut e. ( See " Revealing Links in Print " in Sect ion 13.3.4 for an exam ple.) Ex a m ple s: p.advert:before { content: "And now a word from our sponsor…"; } a:after { content: " (" attr(href) ") "; }
Note: Adding text in this way (like the opening and closing quote example) is called generated content. Read a simple explanation of the generated content phenomenon at www.westciv.com/style_master/academy/css_tutorial/advanced/ generated_content.html. For a deeper explanation, visit www.w3.org/TR/CSS21/generate.html.
A.8.2. cursor Let s you change t he look of t he m ouse point er when it m oves over a part icular elem ent . You can m ake a quest ion m ark appear next t o t he cursor when som eone m ouses over a link t hat provides m ore inform at ion on a subj ect ( like a word definit ion) . ●
●
Va lu e s: a u t o, de fa u lt , cr ossh a ir , poin t e r , m ove , e - r e size , n e - r e size , n w - r e size , n - r e size , se r e size , sw - r e size , s- r e size , w - r e size , t e x t , w a it , h e lp, pr ogr e ss. You can also use an URL value t o use your own graphic as a cursor ( but see t he Not e below) . Ex a m ple : cursor: help; cursor: url(images/cursor.cur) ;
Note: Only Internet Explorer and Firefox recognize URL cursor values, and only in Windows. For more information, visit www.echoecho.com/csscursors.htm and www.quirksmode.org/css/cursor.html.
A.8.3. orphans
Section A.8. Miscellaneous Properties
Specifies t he m inim um num ber of lines of t ext t hat can be left at t he bot t om of a print ed page. Suppose you're print ing your Web page on a laser print er, and a fiveline paragraph is split bet ween t wo pages, wit h j ust one line at t he bot t om of page one, and t he four rem aining lines at t he t op of page t wo. Because a single line all by it self looks odd ( sort of like a lost orphanget it ?) , you can t ell t he browser t o break a paragraph only if at least , say, t hree lines are left on t he bot t om of t he page. ( At t his writ ing, only t he Opera browser underst ands t his propert y.) ● ●
Va lu e s: a num ber like 1, 2, 3, or 5. Ex a m ple : orphans: 3;
A.8.4. page-break-after Det erm ines whet her a page break ( in print ing) occurs aft er a part icular elem ent . Wit h it , you can m ake sure t hat a part icular paragraph is always t he last it em t o appear on a print ed page. ●
●
Va lu e s: aut o, always, avoid, left , right . Aut o represent s t he norm al value and let s t he browser det erm ine when and how t o break cont ent across print ed pages. Always forces t he elem ent t hat follows t o appear at t he t op of a separat e print ed page, and it 's t he only value t hat works consist ent ly across browsers. Avoid prevent s a page break aft er an elem ent ; it 's a great way t o keep a headline wit h t he paragraph t hat follows it , but unfort unat ely, m ost browsers don't underst and it . Left and right det erm ine whet her t he elem ent following appears on a left - or right handed page, which m ay force t he browser t o print an ext ra em pt y page. But since no browsers underst and t hese values, don't worry about wast ing paper. Browsers t reat left and right t he sam e as always. Ex a m ple : page-break-after: always;
A.8.5. page-break-before Works like page- break- aft er, except t he page break appears before t he st yled elem ent , placing it at t he t op of t he next print ed page. You can use t his propert y t o m ake sure headlines for different sect ions of a long Web page each appear at t he t op of a page. ● ●
Va lu e s: sam e as page- break- aft er. Ex a m ple : page-break-before: always;
A.8.6. page-break-inside Prevent s an elem ent from being split across t wo print ed pages. I f you want t o keep a phot o and it s capt ion t oget her on a single page, wrap t he phot o and capt ion t ext in a < div> t ag, and t hen apply a st yle wit h page- break- inside t o t hat < div> . ( At t his writ ing, only Opera underst ands t his propert y.) ● ●
Va lu e s: avoid Ex a m ple : page-break-inside: avoid;
A.8.7. widows The opposit e of orphans ( Sect ion A.1.1) , it specifies t he m inim um num ber of lines t hat m ust appear at t he t op of a print ed page. Say t he print er can m anage t o fit four out of five lines of a paragraph at t he bot t om
Section A.8. Miscellaneous Properties
of a page and has t o m ove t he last line t o t he t op of t he next page. Since t hat line m ight look weird all by it self, use widows t o m ake t he browser m ove at least t wo or t hree ( or what ever num ber of) lines t oget her t o t he t op of a print ed page. ( Only Opera underst ands t his propert y, so it 's of lim it ed use.) Va lu e s: a num ber like 1, 2, 3 or 5. Ex a m ple : widows: 3;
Appendix B. CSS in Dreamweaver 8
Appendix B. CSS in Dreamweaver 8 Adobe's Dream weaver 8 is a Web sit e- building program t hat t akes t he drudgery out of creat ing HTML/ XHTML and CSS. I nst ead of t yping lines of code int o a t ext edit or, you can click convenient onscreen but t ons and m enus and wat ch your design unfold before your eyes. The program even has powerful sit em anagem ent t ools t hat help you keep t rack of your sit e's pages and links. Alt hough t his book gives you everyt hing you need t o know t o creat e your own CSS from scrat ch, t here's not hing wrong wit h t urning t o a visual edit or like Dream weaver t o save t im e. I n fact , knowing how CSS works, as t his book shows you, is a big help when t weaking or t roubleshoot ing pages creat ed in Dream weaver.
Note: This appendix focuses solely on Dreamweaver 8's CSS features. To learn everything Dreamweaver can do for your Web site design and maintenance, check out Dreamweaver 8: The Missing Manual.
Section B.1. Creating Styles
B.1. Creating Styles You begin m ost CSS- relat ed t asks in t he CSS St yles panel, which is Dream weaver's com m and cent er for CSS St yles ( or press Shift - F11) . creat ing st yles. To open it , choose Window Using Figure B- 1 as a guide, here's how t o find your way around t he CSS St yles panel: ●
The All but t on at t he t op of t he panel list s all int ernal and ext ernal st yles for t he current ly open docum ent . The ot her but t onCurrent let s you t ake a closer look at individual st yles ( Sect ion B.1.1) .
Tip: Clicking the minus (-) icon to the left of the style sheet collapses the list of styles, hiding them from view. (On a Mac, the button looks like a little triangle instead, but it does the same thing.) ●
●
●
An int ernal st yle sheet is indicat ed by < st yle> in t he panel. I n t his exam ple, t here's one t ag st yle ( for t he < body> t ag) . Ext ernal st yle sheet s are list ed by file nam e ( headlines.css) . The ext ernal st yle sheet 's rules are list ed below t he file nam e ( p, h1, .celebrit y, and so on) . The first t wo st yles are t ag st yles ( not ice t hat t he nam es m at ch various HTML t ags) , while t he last five are class st yles ( not e t he period at t he beginning of each nam e) . The Propert ies list in t he bot t om half of t he panel let s you edit a st yle as described in Sect ion B.1.1. The t hree but t ons at t he bot t om - left of t he panel ( circled in Figure B- 1) cont rol how t he propert y list is displayed.
Figu r e B- 1 . W it h t h e All bu t t on se le ct e d, t h e CSS St yle s pa n e l list s t h e n a m e s of a ll st yle s a va ila ble t o t h e cu r r e n t pa ge , in clu din g e x t e r n a l a n d in t e r n a l st yle sh e e t s. I n t h is e x a m ple , a n in t e r n a l st yle sh e e t con t a in s a sin gle st yle , a n d on e e x t e r n a l st yle sh e e t h e a dlin e s.csscon t a in s se ve n st yle s.
Section B.1. Creating Styles
B.1.1. Phase 1: Set Up the CSS Type CSS St yles New. Or, on t he CSS St yles panel, you can click To creat e a new st yle, choose Text t he New St yle but t on, or right - click anywhere in t he panel and select New from t he short cut m enu. The New CSS Rule dialog box appears ( Figure B- 2) , where you begin creat ing your new st yle: ●
●
Se le ct or Type . Click t he appropriat e radio but t on for t he kind of st yle you're creat ing: Class, t o creat e your own st yle from scrat ch; or Tag, t o creat e an HTML t ag st yle t hat Dream weaver will aut om at ically apply t o each occurrence of t he t ag. To creat e I Ds, pseudo- classes, and descendent select ors, click Advanced. ( And if you need help rem em bering what all t hese kinds of select ors do, t hen flip back t o Chapt er 3.) N a m e . I f you clicked t he Class but t on, t ype a nam e for t he new st yle. I f you're in a desperat e
Section B.1. Creating Styles
hurry, t hen you can leave out t he period t hat goes at t he beginning of every class st yle, since Dream weaver adds it aut om at ically when it put s t he st yle in t he st yle sheet .
Tip: Class style names must begin with a letter, too, and can contain only letters and numbers. Dreamweaver lets you know if you use any invalid characters for the name.
I f you chose Tag inst ead, select t he HTML t ag you want t o redefine from t he Tag pop- up m enu ( which appears when you click t he Tag radio but t on) . Or, if you're an old hand at HTML, j ust t ype t he t ag nam e wit hout t he bracket s. When you want t o creat e a st yle for all unordered ( bullet ed) list s, t ype ul. I f you clicked t he Advanced but t on, Dream weaver let s you t ype any valid CSS select or t ype, including plain old t ag and class st yles. ●
D e fin e in . Click " This docum ent only" if you want t he st yles t o apply only t o t he current Web page, creat ing an int ernal st yle sheet . To creat e a new ext ernal st yle sheet , choose New St yle Sheet File from t he " Define in" pop- up m enu. This opt ion not only creat es a new ext ernal CSS file ( which you can save anywhere in your sit e folder) , but adds t he necessary code in t he current docum ent t o link it t o t hat file. I f you've previously linked t his docum ent t o an ext ernal st yle sheet ( see Sect ion B.1.1) , t hat st yle sheet 's nam e appears in t he pop- up m enu, indicat ing t hat Dream weaver will st ore t he new st yle in t hat sheet . ( See Chapt er 2 for a review of int ernal and ext ernal st yle sheet s.)
Tip: If you create a bunch of internal styles in a particular page, and later realize you'd like to turn them into an external style sheet that you can use in other pages, then you're in luck. Dreamweaver has a command for this Export very task. Open the page containing the internal styles you want to reuse and choose File Export CSS Styles. A dialog box opens, letting you save the file as an external style sheet. Don't forget to add the .css extension to the end of the file name.
I f you indicat ed t hat you want t o creat e an ext ernal st yle sheet , clicking OK m akes a Save St yle Sheet As dialog box appear. Navigat e t o your sit e's folder and t ype a nam e for t he new ext ernal CSS file. ( Don't forget t he .css on t he end.)
Tip: If you'll be using this style sheet for all of the pages in your site, then you may want to save it in the root folder of your site, or in a folder specifically dedicated to style sheets and give it a general name like site_styles.css or global.css. (You don't have to type the .css file name extension, by the way. In this case, Dreamweaver adds it.)
Figu r e B- 2 . I n t h e N e w CSS Ru le dia log box , you ch oose a t ype of st yle a n d give it a n a m e . Th e la be l n e x t t o t h e n a m in g box ch a n ge s de pe n din g on t h e t ype of st yle you ch oose . I n t h is e x a m ple , sin ce Cla ss is se le ct e d, t h e N a m e la be l
Section B.1. Creating Styles
a ppe a r s. I t ch a n ge s t o Ta g if you click t h e Ta g bu t t on , or Se le ct or if you 'r e u sin g t h e Adva n ce d opt ion .
No m at t er what " Define in" opt ion you select ed, clicking OK event ually brings you t o t he CSS Rule Definit ion window.
B.1.2. Phase 2: Defining the Style The CSS Rule Definit ion window provides access t o all of t he form at t ing opt ions available t o you and your Web page t ext and graphics ( Figure B- 3) . Here you can click t o choose which propert ies t o add t o your st yle, inst ead of t yping t hem . Look, m ano spelling errors!
Figu r e B- 3 . For u lt im a t e for m a t t in g con t r ol, D r e a m w e a ve r le t s you se t 6 7 diffe r e n t Ca sca din g St yle Sh e e t pr ope r t ie s fr om t h e CSS Ru le D e fin it ion w in dow . Bu t it doe sn 't give you a cce ss t o a ll t h e a va ila ble CSS pr ope r t ie s a n d, in som e ca se s, D r e a m w e a ve r u se s diffe r e n t n a m e s for CSS pr ope r t ie s t h a n a r e u se d in t h is book a n d in t h e CSS r u le s. Tu r n t o Se ct ion B.1 for m or e de t a ils.
Section B.1. Creating Styles
Once you've defined t he st yle, click OK at t he bot t om of t he Rule Definit ion window. Dream weaver adds t he st yle t o t he specified st yle sheet , and displays it in t he CSS St yles panel.
Section B.2. Adding Styles to Web Pages
B.2. Adding Styles to Web Pages Once you've creat ed st yles, applying t hem is easy. I n fact , if you creat ed HTML t ag st yles, t hen you don't need t o do anyt hing t o apply t hem because t heir select ors aut om at ically dict at e which t ags t hey affect . When you put your st yles in an ext ernal st yle sheet , Dream weaver aut om at ically links it t o t he current docum ent . To use it s st yles in a different Web page, you m ust at t ach it t o t he page, as described next .
B.2.1. Linking to an External Style Sheet When you add a new Web page t o your sit e, usually you want t o use t he sam e CSS st yles as you did in exist ing pages, for a consist ent look. But you need t o t ell Dream weaver which st yle sheet you're using by at t aching it t o t he page. To do so, open t he Web page t o which you wish t o add t he st yle sheet . Then click t he At t ach St yle Sheet but t on ( see Figure B- 1) on t he CSS St yles panel. ( I f t he CSS St yles panel isn't open, choose Window
CSS St yles or press Shift - F11.)
Tip: You can also use Dreamweaver's Property inspector (at the bottom of the window) to attach a style sheet. Just choose Attach Style Sheet from the Style menu.
When t he At t ach Ext ernal St yle Sheet window appears ( Figure B- 4) , click Browse. I n t he Select St yle Sheet File dialog box t hat appears, navigat e t o and double- click t he CSS ( .css) file you wish t o at t ach t o t he docum ent . I f Dream weaver offers t o copy t he st yle sheet file int o your sit e's root folder, t hen click Yes.
Figu r e B- 4 . M ost of t h e opt ion s in t h e M e dia m e n u a r e n 't ve r y u se fu l, sin ce t h e r e a r e n 't a n y de vice s pr ogr a m m e d t o w or k w it h t h e m . H ow e ve r , " pr in t e r " a n d " scr e e n " a r e h a n dy w a ys t o con t r ol h ow you r pa ge displa ys w h e n vie w e d on a m on it or a n d w h e n pr in t e d on pa pe r .
The At t ach Ext ernal St yle Sheet window provides t wo ot her opt ions: how t o at t ach t he st yle sheet , and what t ype of m edia you want t he st yles t o apply t o. ●
●
When at t aching an ext ernal st yle sheet , you can choose t o eit her Lin k or I m por t it . These t wo choices are nearly ident ical, as described in Sect ion 2.2. The M e dia m enu defines which t ype of out put device or display should use t he st yle sheet . Select ing " print " m eans t hat t he st yle sheet will only apply when t he docum ent is print ed. Most of t hese opt ionssuch as TV for t elevisions, or TTY for t elet ype m achinesaren't of any use t o t he average Web designer. You can read about t hese different m edia t ypes and t he t wo m ost im port ant ones, " print er" and " screen," st art ing in Sect ion 13.1. Most of t he t im e, you can safely ignore t his m enu. The " all" opt ion in t he Media m enu is t he sam e as not select ing anyt hingt he st yle sheet applies when print ed, viewed on a m onit or, felt on a Braille reader, and so on. ( Dream weaver 8 also includes a helpful t oolbar for cont rolling t he display of st yle sheet s aim ed at different m ediasee Figure B- 5) .
Section B.2. Adding Styles to Web Pages
Tip: You can preview the effect of the style sheet on your page by clicking the Preview button on the Attach External Style Sheet window.
Aft er choosing your opt ions, click OK. Dream weaver adds t he necessary HTML code t o t he head of t he Web page, and aut om at ically form at s any t ags in t he docum ent according t o t he st yle sheet 's HTML t ag st yles. You'll see t he form at t ing changes t ake place in t he docum ent window im m ediat ely aft er at t aching t he ext ernal st yle sheet . I f t he st yle sheet cont ains class st yles, on t he ot her hand, you won't see t heir form at t ing effect s unt il you apply t hem t o an elem ent on t he page, as described next .
Figu r e B- 5 . To t u r n on D r e a m w e a ve r 's St yle Re n de r in g t oolba r ( t op r igh t ) , ch oose Vie w Toolba r s St yle Re n de r in g. Click a bu t t on on t h e t oolba r t o sh ow st yle s t h a t m a t ch t h e m e dia t ype you se le ct e d w h e n you a t t a ch e d t h e pa ge ( se e Se ct ion B.1 .1 ) . Scr e e n ( t op- le ft , cir cle d) a n d Pr in t ( bot t om - le ft , cir cle d) a r e t h e t w o m ost u se fu l, t h ou gh you ca n h ide a ll CSS st yle s by click in g t h e bu t t on on t h e fa r r igh t of t h e t oolba r ( bot t om - r igh t , cir cle d) .
Section B.2. Adding Styles to Web Pages
B.2.2. Applying a Class Style You can apply class st yles t o any select ion in t he docum ent window, whet her it 's a word, an im age, or an ent ire paragraph. ( You can apply any class st yle t o any elem ent , alt hough doing so doesn't always m ake sense. I f you form at a graphic wit h a st yle t hat specifies bold, red Courier t ype, t hen it won't look any different .) Suppose your com pany's nam e appears in a paragraph of t ext on a Web page t hat includes a class st yle nam ed .com pany ( eit her in an int ernal st yle sheet , or in a linked, ext ernal st yle sheet ) . To form at t hat t ext using t he class st yle, you select t he nam e in t he docum ent window and apply t he st yle, as described below. Sim ilarly, t o form at larger select ions, such as an ent ire paragraph, you'd select t he paragraph and apply t he class st yle. I n fact , you can apply a class st yle t o any HTML t ag, such as t he < p> ( paragraph) , < t d> ( t able cell) , or < body> t ags. When you apply a class st yle ( like .com pany) t o a t ag, Dream weaver adds a special class propert y t o t he page's code, like t his: < p class= " com pany" > . On t he ot her hand, when you apply a class t o a select ion t hat isn't a t aglike a single word t hat you've double- clicked Dream weaver wraps t he select ion wit hin a < span> t ag like t his: < span class= " com pany" > The Nat ional Exasperat or< / span> . This t ag, in ot her words, applies a st yle t o a span of t ext t hat can't be ident ified by a single t ag. To apply a class st yle t o t ext , select som e words. Then, from t he St yle m enu in t he Propert y inspect or, select t he st yle nam e ( Figure B- 6, t op) . To st yle an ent ire paragraph, place t he cursor anywhere inside t he paragraph ( or heading) before using t he Propert y inspect or. To apply a class st yle t o an obj ect like an im age, select t he obj ect ( t he t ag select or in t he bot t om of t he docum ent window is a great way t o select a t ag) . Then use t he Class pop- up m enu on t he Propert y inspect or ( Figure B- 6, bot t om ) t o select t he st yle nam e.
Figu r e B- 6 . Usin g t h e Pr ope r t y in spe ct or is t h e e a sie st w a y t o a pply a cla ss st yle . D e pe n din g on w h a t you 've se le ct e d on t h e pa ge ( t e x t , a n im a ge , or som e ot h e r H TM L t a g) , you 'll e n cou n t e r on e of t w o diffe r e n t m e n u st h e St yle m e n u ( t op) or t h e Cla ss m e n u ( bot t om ) . Eit h e r w a y, it 's t h e sa m e m e n u w it h t h e sa m e opt ion s, a n d you u se it t o se le ct t h e n a m e of a st yle t o a pply it t o w h a t e ve r you 've se le ct e d in t h e docu m e n t w in dow . You ca n a lso r e m ove a st yle by se le ct in g N on e fr om t h e m e n u .
Section B.2. Adding Styles to Web Pages
You can also apply a class st yle by select ing what ever elem ent you wish t o st yle, choosing Text CSS St yles, and t hen select ing t he st yle from t he subm enu. ( Alt ernat ive m et hod for t he ant i- m enu crowd: right - click [ Cont rol- click] t he st yle's nam e in t he CSS St yles panel, and t hen choose Apply from t he short cut m enu.) Finally, you can also apply a class from t he docum ent window's t ag select or, as shown in Figure B- 7.
Figu r e B- 7 . You ca n a pply a cla ss st yle dir e ct ly t o a t a g u sin g t h e docu m e n t w in dow 's t a g se le ct or . Ju st r igh t - click ( Con t r ol- click ) t h e t a g you w ish t o for m a t , a n d t h e n se le ct t h e cla ss st yle fr om t h e Se t Cla ss su bm e n u . I n a ddit ion , t h e t a g se le ct or le t s you k n ow if a t a g h a s a cla ss st yle a pplie d t o it . I f so, you 'll se e t h e st yle 's n a m e a t t h e e n d of t h e t a g. I n t h is figu r e , a cla ss st yle n a m e d .colCon t e n t h a s be e n a pplie d t o a < div> t a g ( cir cle d) .
B.2.3. Un-Applying a Class Style To rem ove a st yle from an obj ect on a Web page, sim ply select t he elem ent and t hen select None from t he Propert y inspect or's St yle m enu CSS St yles None t o rem ove a st yle from any select ion ( even non- t ext elem ent s like ( see Figure B- 6) . You can also choose Text im ages or t ables) .
Tip: If you've applied a class style to a selection of text, then you don't actually have to select all the text to remove the style. Just click anywhere inside it and select None from the Property inspector's Style menu (or choose Text
CSS Styles
None). If you applied the style to a tag, then Dreamweaver
removes the Class property from the tag. If you applied the style using the tag, then Dreamweaver removes that tag.
You can't rem ove t ag st yles from HTML t ags. Suppose you've redefined t he < h1> t ag using t he st eps out lined in Sect ion B.1.1. I f your page has t hree Heading 1 ( < h1> ) paragraphs, and you want t he t hird heading t o have a different st yle t han t he ot her t wo, t hen you can't sim ply " rem ove" t he < h1> st yle from t he t hird paragraph. I nst ead, what you'd need t o do is creat e a new class st yle wit h all of t he form at t ing opt ions you want for t hat t hird heading and apply it direct ly t o t he < h1> t ag ( by t he m agic of CSS, t he class form at t ing opt ions override any exist ing t ag st yle opt ionssee Sect ion 5.2 for m ore on t his sleight of hand) .
Section B.3. Editing Styles
B.3. Editing Styles While building a Web sit e, you cont inually refine your designs. That chart reuse color you assigned t o t he background of your pages m ay have looked great at 2 a.m ., but it loses som et hing in t he light of day. I n fact , one of Dream weaver's great est selling point s is how easy it m akes updat ing t he form at t ing on a Web sit e. Dream weaver 8 provides m any ways t o edit st yles:
FREQUENTLY ASKED QUESTION When Formatting Disappears Som et im es when I copy t ext from one Web page and past e it int o anot her Web page, all t he form at t ing disappears. What 's going on? When you use Cascading St yle Sheet s, keep in m ind t hat t he act ual st yle inform at ion is st ored eit her in t he < head> of t he Web page ( for int ernal st yle sheet s) or in a separat e CSS file ( an ext ernal st yle sheet ) . I f a page includes an int ernal st yle sheet , when you copy t ext , graphics, or ot her page elem ent s, t hen Dream weaver copies t hose elem ent s and any class st yle definit ions used by t hat cont ent . When you past e t he HTML int o anot her page, t he st yles are writ t en int o t he < head> of t hat page. This feat ure, new in Dream weaver 8, can save you som e t im e, but won't solve all of your woes. I t doesn't , for exam ple, copy any t ag st yles you've creat ed or m ost advanced st yles you m ight creat e ( see Sect ion 3.1) . So if you copy and past e som e t ext , say an < h1> t ag st yled wit h an h1 t ag st yle, t hen t he < h1> t ag and it s cont ent s will past e int o anot her page, but not t he t ag st yle. I n addit ion, if a page uses an ext ernal st yle sheet , t hen when you copy and past e t ext , t he st yles t hem selves don't go along for t he ride. When you copy a paragraph t hat has a class st yle applied t o it and past e it int o anot her docum ent , t he code in t he paragraph is past ed ( p class= " com pany" > , for inst ance) , but t he act ual .com pany st yle, wit h all it s form at t ing propert ies, is not . The best solut ion is t o use a com m on ext ernal st yle sheet for all pages on your sit e. That way, when you copy and past e t ext , all t he pages share t he sam e st yles and form at t ing. So in t he exam ple above, if you copy a paragraph t hat includes a class st yleclass= " com pany" int o anot her page t hat shares t he sam e st yle sheet , t hen t he paragraphs will look t he sam e on bot h pages.
●
Select a st yle in t he CSS St yles panel, and t hen click t he Edit St yle but t on t o open t he Rule Definit ion window ( t he sam e
Section B.3. Editing Styles
●
●
●
window you used when first creat ing t he st yle) . Make your changes, and t hen click OK t o ret urn t o t he docum ent window. Dream weaver reform at s t he page t o reflect any changes you m ade t o st yles used in t he current docum ent . Double- clicking t he nam e of a st yle in t he CSS panel also opens t he Rule Definit ion window. This is a change from t he previous version of Dream weaver ( MX 2004) , which swit ched t o Code view so you could edit t he raw CSS code. You can - U] ) , clicking t he CSS St yles cat egory, and resurrect t hat behavior, by opening t he Preferences window ( Ct rl+ U [ select ing t he last but t on " Edit using Code View." Right - click ( Cont rol- click) t he nam e of a st yle in t he CSS St yles panel and choose Edit from t he short cut m enu, which also opens t he Rule Definit ion Window. Make your changes t o t he st yle, and t hen click OK t o ret urn t o t he docum ent window. Select a st yle t o edit in t he CSS St yles panel, and t hen use t he Propert ies list ( Sect ion B.1.1) t o edit t he st yle's propert ies.
POWER USERS' CLINIC A Time to Design A Dream weaver feat ure called Design Tim e st yle sheet s let s you quickly " t ry out " different CSS st yle sheet s while developing your Web page. Using t he sim ple dialog box shown here, you can hide t he ( ext ernal) st yle sheet s you've at t ached t o a Web page and subst it ut e in new ones. Design Tim e st yle sheet s com e in handy when working on HTML t hat , lat er on, you int end t o m ake part of a com plet e Web page. Dream weaver Library it em s are a good exam ple; t his feat ure let s you creat e a chunk of HTML t hat you can use on any num ber of pages on your sit e ( see Dream weaver 8: The Missing Manual for inst ruct ions on how t o use t his feat ure) . When you updat e t he Library it em , every page t hat uses it is updat ed. A t im e- saving feat ure, for sure, but since a Library it em is only part of a page it doesn't include t he < head> port ion needed t o eit her st ore st yles or at t ach an ext ernal st yle sheet . So when designing a Library it em , you're working in t he dark ( or at least , wit hout any st yle) . But using Design Tim e st yle sheet s, you can access all t he st yles in an ext ernal st yle sheet and even preview t he effect s direct ly in Design view. You'll also t urn t o t his feat ure when working wit h Dream weaver 8's new XML t ools, which let you add an XSLT fragm ent t o a com plet e Web pageessent ially let t ing you convert XML ( like you'd find in an RSS news feed) int o a chunk of HTML. But t o accurat ely design t hese com ponent s, you'll need t o use Design Tim e st yle sheet s. By t he way, Design Tim e works only wit h ext ernal st yle sheet s. You can't use it t o prevent Dream weaver from displaying int ernal st yles. To apply a Design Tim e st yle sheet t o your Web page, choose Text CSS St yles Design Tim e. The Design Tim e St yle Sheet s window appears. Click t he t op + but t on t o select an ext ernal st yle sheet t o display in Dream weaver. Not e t hat clicking t his but t on doesn't at t ach t he st yle sheet t o t he page; it m erely select s a .css file t o use when viewing t he page inside Dream weaver. To properly view your page wit h t his new st yle sheet , you m ay need t o get an at t ached ext ernal st yle sheet out of t he way. To do t hat , use t he bot t om + but t on t o add it t o t he Hide list . Design Tim e st yle sheet s apply only when you're working in Dream weaver. They have no effect on how t he page looks in an act ual Web browser. That 's bot h t he good news and t he bad news. Alt hough Dream weaver let s you apply class st yles t hat you t ake from a Design Tim e st yle sheet t o your Web page, it doesn't act ually at t ach t he ext ernal st yle sheet t o t he page. You have t o at t ach it yourself when design t im e is over, or else your visit ors will never see your int ended result .
B.3.1. Editing in the Properties Pane The CSS Rule Definit ion window ( Figure B- 3) is a rat her t edious way of edit ing CSS propert ies. I t 's easy t o use, but t he cat egories and m enus m ay slow down experienced CSS folks. Dream weaver 8 int roduces a new t oolt he Propert ies panet o st ream line t he process of edit ing st yles. The Propert ies pane displays a select ed st yle's current ly defined propert ies, as well as a list of ot her not yet set CSS propert ies.
Note: MX 2004 veterans: The Properties pane is nearly identical to the Rule Inspector which has been spruced up a little and moved into the CSS panel.
Section B.3. Editing Styles
Select t he st yle you wish t o edit in t he CSS St yles panel, and t he Propert y pane displays CSS propert ies in one of t hree different views: a " set propert ies" view which displays only t he propert ies t hat have been defined for t he select ed st yle ( Figure B- 8) ; a cat egory view, which groups t he different CSS propert ies int o t he sam e seven cat egories used in t he Rule Definit ion window ( Figure B- 9, left ) ; and a list view which provides an alphabet ical list ing of all CSS propert ies ( Figure B- 9, right ) . Clicking t he view but t ons at t he bot t om - left corner of t he CSS st yles panel swit ches bet ween t hese t hree displays ( circled in bot h figures) .
FREQUENTLY ASKED QUESTION Help, My Styles Don't Work! I 've j ust edit ed a CSS st yle, but t he changes I m ade don't appear when I preview t he page. Why? When you edit a st yle locat ed in an ext ernal st yle sheet , Dream weaver opens t he .css filein t he background, where it t hen surrept it iously m akes t he change t o t he st yle. Unfort unat ely, t he program doesn't save t he file when it 's done, so while t he changes exist in t he st ill- open .css file, t he file safely saved on your hard drive doesn't yet cont ain t he changes. Therefore, if you preview a page on your sit e, and m errily click away t o see how t he newly edit ed st yles look on your sit e's pages, you'll be sadly disappoint ed. Those pages are loading t he .css file on your hard drive; t hey don't have access t o t he open file in Dream weaver. The m et hod t o t his apparent m adness: Dream weaver is giving you a chance t o undo changes you m ade t o t he ext ernal st yle sheet . Because t he program hasn't closed t he .css file, you can use t he Edit Undo com m and t o undo edit s t o t he file. To do so, you m ust have t hat file open in front of youbut where is it ? Just pull it forward by choosing from t he list of all open files at t he bot t om of t he Window m enu. I f you find t his arrangem ent m ore a nuisance t han a benefit , you can t urn it off. Open t he Preferences window by Preferences ( Dream weaver Preferences on t he Mac) . Select t he CSS St yles cat egory and choosing Edit t urn off t he " Open CSS files when m odified" box ( see Figure B- 10) . Rem em ber, t hough, if you t urn t his feat ure off, t hen you won't be able t o use Edit
Undo t o undo edit s you m ake t o ext ernal st yle sheet s.
Propert y nam es are list ed on t he left , and t heir values are on t he right . Figure B- 8 shows an exam ple of a st yle for t he < h1> t ag t hat list s 10 propert ies ( such as background- color, font - fam ily) and t heir corresponding set t ings ( # FFFFCC, " Arial, Helvet ica, sansserif" , and so on) .
Tip: As you've read, CSS lets you use various shorthand methods for combining several CSS properties into a single property. You can turn on this feature in Dreamweaver as well, as described in Figure B-10.
To add a new propert y, click t he Add Propert y link at t he bot t om of t he list , and select t he propert y nam e from t he pop- up m enu. You set ( and can edit ) t he value of a part icular propert y in t he space t o t he right of t he propert y nam e. Most of t he t im e, you don't have t o t ype in t he value. Dream weaver provides t he t ools you're likely t o need for each propert y: t he ubiquit ous color box for any propert y t hat requires a color, like font color; a pop- up m enu for propert ies t hat have a lim it ed list of possible values, like dashed for t he border- t op- st yle propert y shown in Figure B- 8; and t he fam iliar " browse for file" folder icon for propert ies t hat require a pat h t o a file.
Figu r e B- 8 . Th e Pr ope r t ie s pa n e pr ovide s a cle a r vie w of a st yle 's pr ope r t ie s. You ca n qu ick ly se e w h ich CSS pr ope r t ie s a r e u se d by t h e st yle , de le t e or e dit t h e m , a n d a dd a n e w pr ope r t y by se le ct in g it s n a m e fr om t h e pr ope r t y m e n u .
Section B.3. Editing Styles
The Propert ies pane is a great edit ing opt ion if you have som e experience t yping your own CSS code, as you've learned t hroughout t his book. Appendix A has a handy list of CSS propert ies. Also, Dream weaver includes a built - in CSS reference so you can sharpen your CSS chops even furt her: choose Window CSS Reference from t he Book m enu.
Reference t o open t he Reference panel, and t hen select O'Reilly
Note: The Properties pane can only edit styles. You can add and remove properties with it, but you can't create, delete, or rename styles using it. For those maneuvers, see Section B.1.
Even t hose who are not - so- experienced will find t he Propert ies pane helpful. First , it 's t he best way t o get a bird's- eye view of a st yle's propert ies. Second, for really basic edit ing such as changing t he colors used in a st yle or assigning it a different font , t he Propert ies pane is as fast as it get s. To rem ove a propert y from a st yle, j ust delet e it s value in t he right colum n. Dream weaver not only rem oves t he value, but t he propert y nam e from t he st yle sheet as well. I n addit ion, you can right - click ( Cont rol- click) a propert y nam e and choose Delet e from t he short cut m enu, or click a propert y nam e followed by t he t rash can icon t o banish it from your st yle sheet ( see Figure B- 8) .
Figu r e B- 9 . Th e Pr ope r t ie s pa n e 's t w o ot h e r vie w s a r e n 't a s st r e a m lin e d or a s e a sy t o u se a s t h e
Section B.3. Editing Styles
" se t pr ope r t ie s" vie w pict u r e d in Figu r e B- 8 . ( I n fa ct , t h e y'r e a h oldove r fr om D r e a m w e a ve r M X 2 0 0 4 's Ru le I n spe ct or pa n e l.) To a dd n e w pr ope r t ie s in t h e se vie w s, t ype a va lu e in t h e e m pt y box t o t h e r igh t of t h e pr ope r t y n a m e . At le ft , you ca n t ype in t h e e m pt y box t o t h e r igh t of " ba ck gr ou n d."
Section B.4. Managing Styles
B.4. Managing Styles Som et im es, inst ead of edit ing t he propert ies of a st yle, you want t o delet e it and st art over. Or you've com e up wit h a way t o bet t er organize your Web sit e and you want t o renam e som e st yles according t o your new syst em . Dream weaver m akes it easy t o do bot h t hose t hings. I t even let s you duplicat e a st yle, so you can quickly creat e a new st yle t hat bears som e sim ilarit ies t o one you've already built from scrat ch.
B.4.1. Deleting a Style At som e point , you m ay find you've creat ed a st yle t hat you don't need aft er all. Maybe you redefined t he HTML < code> t ag and realize you haven't even used t he t ag in your sit e. There's no need t o keep it around t aking up precious space in t he st yle sheet . CSS St yles) . Click t he nam e of t he st yle To delet e a st yle, m ake sure t he CSS St yles panel is open ( Window you wish t o delet e, and t hen click t he Trash can at t he bot t om of t he panel. You can also rem ove all of t he st yles in an int ernal st yle sheet ( as well as t he st yle sheet it self) by select ing t he st yle sheet indicat ed by " < st yle> " in t he CSS St yles panel ( see Figure B- 10) and clicking t he Trash can. When you t rash an ext ernal st yle sheet , you m erely unlink it from t he current docum ent wit hout act ually delet ing t he .css file.
Figu r e B- 1 0 . Som e CSS pr ope r t ie s ca n be con de n se d in t o a sh or t h a n d ve r sion . For e x a m ple , t h e va lu e s for t h e ba ck gr ou n d im a ge , ba ck gr ou n d- r e pe a t , ba ck gr ou n dcolor , a n d ba ck gr ou n d- posit ion pr ope r t ie s ca n be com bin e d u sin g t h e ba ck gr ou n d pr ope r t y lik e t h is: ba ck gr ou n d: # FFF u r l( im a ge s/ bg.gif) n or e pe a t le ft t op;. N or m a lly, D r e a m w e a ve r cr e a t e s a st yle u sin g e a ch in dividu a l pr ope r t y n a m e , r a t h e r t h a n t h e sh or t h a n d ve r sion . You ca n ch a n ge t h a t fr om t h e CSS St yle ca t e gor y of t h e Pr e fe r e n ce s w in dow ( ch oose Edit Pr e fe r e n ce s in W in dow s or D r e a m w e a ve r Pr e fe r e n ce s on t h e M a c) .
Section B.4. Managing Styles
Tip: A faster way to delete a style is to right-click (Control-click) the name of the style in the CSS Styles panel and choose Delete from the shortcut menu.
Unfort unat ely, delet ing a class st yle doesn't delet e any references t o t he st yle in t he pages of your sit e. I f you've creat ed a st yle called .com pany and applied it t hroughout your sit e, and you t hen delet e t hat st yle from t he st yle sheet , t hen Dream weaver doesn't rem ove t he < span> t ags or class propert ies t hat refer t o t he st yle. Your pages will st ill be lit t ered wit h orphaned code like t his< span class= " com pany" > The Nat ional Exasperat or< / span> even t hough t he t ext loses t he st yling. ( You can use Dream weaver's Find and Replace t ool t o locat e and rem ove < span> t ags wit h a part icular class, or t o locat e a t ag wit h a part icular class and j ust rem ove t he class at t ribut e from t he t ag's HTML.)
B.4.2. Renaming a Class Style
Section B.4. Managing Styles
While you have m any ways t o change t he nam e of a st yle in a st yle sheet ( open t he css file in Code view and edit t he nam e, for exam ple) , j ust changing t he nam e doesn't do m uch good if you've already applied a class st yle t hroughout your sit e. The old nam e st ill appears in each place you used it . What you really need t o do is renam e t he st yle and t hen perform a find- and- replace operat ion t o change t he nam e wherever it appears in your sit e. Dream weaver includes a handy t ool t o sim plify t his process. To renam e a class st yle: 1. I n t h e St yle m e n u ( or Cla ss m e n u ) on t h e Pr ope r t y in spe ct or ( Figu r e B- 6 ) , ch oose Re n a m e . The Renam e St yle window appears ( Figure B- 11) .
Figu r e B- 1 1 . Th e Re n a m e St yle t ool is a fa st a n d e a sy w a y t o ch a n ge t h e n a m e of a cla ss st yle e ve n if you 've a lr e a dy u se d t h e st yle h u n dr e ds of t im e s t h r ou gh ou t you r sit e .
2. Fr om t h e t op m e n u , ch oose t h e n a m e of t h e st yle you w ish t o r e n a m e . This m enu list s all class st yles available on t he current page, including ext ernal and int ernal st yles. 3. Type t h e n e w st yle n a m e in t h e " N e w n a m e " box . You m ust follow t he sam e rules for nam ing class st yles described in Sect ion 3.1. But , j ust as when creat ing a new class, you don't need t o precede t he nam e wit h a periodDream weaver t akes care of t hat . 4. Click OK. I f t he st yle whose nam e you're changing is an int ernal st yle, Dream weaver m akes t he change. Your j ob is com plet e.
Section B.4. Managing Styles
I f t he st yle belongs t o an ext ernal st yle sheet , Dream weaver warns you t hat ot her pages on t he sit e m ay also use t his st yle. To successfully renam e t he st yle, Dream weaver m ust use it s Find and Replace t ool t o search t he sit e and updat e all pages t hat use t he old st yle nam e. I n t hat case, cont inue t o st ep 5. 5. I f you ge t cold fe e t , click Ca n ce l t o ca ll off t h e n a m e ch a n ge , or click Ye s t o ope n t h e Fin d a n d Re pla ce w in dow , w h e r e you sh ou ld click Re pla ce All. One last warning appears, rem inding you t hat t his act ion can't be undone.
Note: If you click No in the warning box that appears after step 4, then Dreamweaver still renames the style in the external style sheet, but doesn't update your pages. 6. Click Ye s. Dream weaver goes t hrough each page of your sit e, dut ifully updat ing t he nam e of t he st yle in each place it appears. This hidden gem is a great t ool, and is part icularly useful if you use t he Propert y I nspect or t o set font colors, t ypes, and sizes. I n t hat case, you can use t his feat ure t o renam e t he non- descript ive class nam esSt yle1, St yle2, and so ont hat Dream weaver st art s you off wit h.
B.4.3. Duplicating a Style Dream weaver m akes it easy t o duplicat e a CSS st yle, which is handy when you've creat ed, say, an HTML t ag st yle, and now decide you'd rat her m ake it a class st yle. Or you m ay want t o use t he form at t ing opt ions from one st yle as a st art ing- off point for a new st yle. Eit her way, you st art by duplicat ing an exist ing st yle. CSS You can duplicat e a st yle in t wo ways. The easiest m et hod is t o open t he CSS St yles panel ( Window St yles) , right - click ( Cont rol- click) t he nam e of t he st yle you wish t o duplicat e, and t hen choose Duplicat e from t he short cut m enu. The Duplicat e CSS Rule dialog box appears ( Figure B- 12) , where you can give t he duplicat ed st yle a new nam e, reassign it s Type set t ing, use t he " Define in" m enu t o m ove it from an int ernal t o an ext ernal st yle sheet , and so on.
Figu r e B- 1 2 . Th e D u plica t e CSS St yle dia log box look s a n d a ct s j u st lik e t h e N e w Ru le box ( Figu r e B- 2 ) . You ca n se le ct a n e w st yle t ype , n a m e it , a n d a dd it t o a n e x t e r n a l or in t e r n a l st yle sh e e t . Th e on ly diffe r e n ce is t h a t t h e du plica t e d st yle r e t a in s a ll of t h e CSS pr ope r t ie s of t h e or igin a l st yle .
Section B.4. Managing Styles
When you click OK, Dream weaver adds t he duplicat e st yle t o t he page or ext ernal st yle sheet . You can t hen edit t he new st yle j ust as you would any ot her, as described earlier in t his appendix.
Section B.5. Examining Your CSS in the Styles Panel
B.5. Examining Your CSS in the Styles Panel As you read in Chapt ers 4 and 5, inherit ance and t he cascade are t wo very im port ant CSS concept s. I nherit ance provides a way of passing on com m on propert ies like a font color t o descendent s of a st yled t ag. Giving t he page's < body> t ag a font color, causes ot her t ags inside t he page t o use ( inherit ) t hat sam e font color. The cascade is a set of rules for det erm ining what a Web browser should do if m ult iple st yles apply t o t he sam e t ag and t here are conflict s bet ween t he t wo st yles. The cascade helps decide what t o do when one st yle dict at es t hat a part icular paragraph should be displayed in 24- pixel t ype, while anot her st yle dict at es t hat t he t ype should be 36 pixels t all.
B.5.1. Current Selection Mode Wit h all t his inherit ance and cascading going on, it 's very easy for st yles t o collide in unpredict able ways. To help you discern how st yles int eract and ferret out possible st yle conflict s, Dream weaver 8 includes anot her view of t he CSS St yles Panel ( see Figure B- 13) . When you click t he Current but t on, t he panel swit ches t o Current Select ion m ode, which provides insight int o how a select ed it em on a pagean im age, a paragraph, a t ableis affect ed by inherit ed st yles.
Tip: You can also switch the CSS Styles Panel into Current Selection mode by selecting text on a page, and then clicking the new CSS button on the Property inspector. Doing so also opens the CSS panel, if it's closeda nice shortcut. If the button's grayed out, then you're already in the right mode.
This is really an incredible t ool t hat 's invaluable in diagnosing weird CSS behavior associat ed wit h inherit ance and cascading. But like any incredible t ool, it requires a good m anual t o learn how it works. The panel cram s in a lot of inform at ion; here's a quick overview of what it provides: ●
●
●
●
A su m m a r y of st yle pr ope r t ie s for t h e cu r r e n t ly se le ct e d it e m in t h e Su m m a r y for Se le ct ion pa n e . Rem em ber t hat whole t hing about how parent s pass on at t ribut es t o child t ags, and how as st yles cascade t hrough a page, t hey accum ulat e ( which m eans it 's possible t o have an < h1> t ag form at t ed by m ult iple st yles from m ult iple st yle sheet s) ? The Sum m ary for Select ion sect ion is like t he grand t ot al at t he bot t om of a spreadsheet . I t t ells you, in essence, what t he select ed elem ent a paragraph, a pict ure, and so onwill look like when a Web browser t allies up all of t he st yles and displays t he page. Th e or igin of a pa r t icu la r pr ope r t y is displa ye d in t h e Abou t pa n e ( Figure B- 13, t op) . I f a headline is orange, but you never creat ed an < h1> t ag wit h an orange color, t hen you can find out which st yle from which st yle sheet is passing it s hideous orangeness t o t he heading. A list of st yle s t h a t a pply t o t h e cu r r e n t se le ct ion a ppe a r s in t h e Ru le s pa n e ( Figure B- 13, bot t om ) . Since any elem ent can be on t he receiving end of count less CSS propert ies handed down by parent t ags, it 's helpful t o see a list of all t he st yles cont ribut ing t o t he current appearance of t he select ed obj ect on t he page. Th e or de r of t h e ca sca de in t h e " Rules" pane ( Figure B- 13, bot t om ) . Not only are st yles t hat apply t o t he current select ion list ed, t hey're also list ed in a part icular order, wit h t he m ost general st yle at t he t op and t he m ost specific ones at t he bot t om . This m eans t hat when t he sam e propert y exist s in t wo ( or m ore) st yles, t he st yle list ed last ( furt hest down t he list ) wins.
Section B.5. Examining Your CSS in the Styles Panel
A few exam ples can help dem onst rat e how t o read t he CSS St yle panel when it 's in Current Select ion m ode. Figure B- 13 shows t he CSS propert ies affect ing a select ion of t ext ( in t his case, a paragraph) on a Web page. The Sum m ary for Select ion pane let s you know t hat if you viewed t his page in a Web browser, t his paragraph would be displayed in bold using t he Georgia t ype- face, at a font - size of 1.5em s wit h 150 percent line- height ( space bet ween each line of t ext ) . When you select a propert y from t he Sum m ary for Select ion pane and t hen click t he Show Propert y I nform at ion but t on ( Figure B- 13, t op) , t he About pane displays where t he propert y com es from in t his case, t hat propert y belongs t o t he < p> t ag st yle which is defined in t he int ernal st yle sheet of t he file index.ht m l.
Figu r e B- 1 3 . Th e t w o vie w sPr ope r t y I n for m a t ion ( t op) a n d Ca sca de ( bot t om ) of t h e st yle s pa n e l a r e m ost ly t h e sa m e . Bot h sh ow a su m m a r y of pr ope r t ie s t h a t a pply t o t h e cu r r e n t se le ct ion ; t h e y a lso bot h displa y t h e Pr ope r t y list pa n e ( se e Se ct ion B.1 .1 ) u se d t o e dit t h ose pr ope r t ie s. Th e Pr ope r t y I n for m a t ion vie w sh ow s w h ich st yle a n d w h ich st yle sh e e t s w e r e u se d in de fin in g a pr ope r t y. I n con t r a st , t h e Ca sca de vie w sh ow s a list of a ll st yle s ( r u le s) t h a t t h e cu r r e n t se le ct ion in h e r it s fr om .
Section B.5. Examining Your CSS in the Styles Panel
You've seen t he bot t om pane before. I t 's t he Propert ies pane, and it 's used t o delet e, add, and edit t he propert ies of a st yle ( see Sect ion B.1.1) . You sim ply click in t he area t o t he right of t he propert y's nam e t o change it s value, or click t he Add Propert y link t o select a new propert y for t he st yle. Not ice t hat in t his exam ple, t he Propert ies pane cont ains fewer propert ies t han t he sum m ary view. That 's because it displays only propert ies of a single st yle ( t he < p> t ag st yle) , while t he Sum m ary view shows all propert ies inherit ed by t he current select ion.
Tip: Sometimes one or more of the three panes are too small for you to be able to see the information displayed. You can use the gray bars containing the panes' names (circled in Figure B-13, bottom) as handles and drag them up or down to reveal more or less of each pane.
Section B.5. Examining Your CSS in the Styles Panel
B.5.2. Deciphering the Cascade Clicking t he Show Cascade but t on ( Figure B- 13, bot t om ) reveals a list of all st yles t hat affect t he current select ion. I n t his case, you can see t hat t wo t ag st ylesone for t he body t ag and one for t he p t agcont ribut e t o st yling t he select ed paragraph of t ext . I n addit ion, as m ent ioned above, t he order in which t he st yles are list ed is im port ant . The lower t he nam e appears in t he list , t he m ore " specific" t hat st yle isin ot her words, when several st yles cont ain t he sam e propert y, t he propert y belonging t o t he st yle lower on t he list wins out ( see Sect ion 5.1.4 for m ore on conflict s caused by cascading st yles) . The Propert ies pane provides even m ore inform at ion about conflict ing propert ies. Figure B- 14 shows t hat four st yles are affect ing t he form at t ing of a single paragraph of t ext : t hree t ag st yles ( < body> , < p> , and < p> ) and one class st yle ( .sidebar) . Why t wo < p> t ag st yles? One is in an ext ernal st yle sheet , while t he ot her belongs t o t he page's int ernal st yle sheet . Clicking a st yle nam e in t he Rules pane reveals t hat st yle's propert ies in t he pane below. I n t he bot t om - left im age in Figure B- 14, not ice t he sidebar class st yle has propert ies such as background color, t ext color, and so on. When a line appears t hrough a propert y nam e ( see t he circled areas in Figure B- 14, bot t om m iddle and bot t om right ) t hat propert y isn't applied t o t he current select ion. Eit her it 's overridden by a m ore specific st yle, or it 's not an inherit ed propert y. The second- t o- last st yle in t he list in Figure B- 14a < p> t ag st yleshows t hat it has a set t ing for t he font fam ily propert y. I n addit ion, t here's a line t hrough t he propert y nam e, indicat ing t hat it doesn't apply t o t he current select ion. Because t he m ore specific .sidebar class st yle also has t he font - fam ily propert y set , in t he bat t le of cascading st yle propert ies, .sidebar wins ( see Chapt ers 4 and 5 for m ore on inherit ance and cascading) .
Tip: When you hover over a property name that's crossed out in the Properties pane, a pop-up window explains why the property doesn't apply. This is a big help, when a certain property setting (such as a font color) from a style isn't being applied to your selection. The pop-up window will explain which style it's in conflict with, providing you with the diagnostic information you need to go fix the problem.
I f your Web pages are elegant ly sim ple and use only a couple of st yles, you m ay not find m uch need for t his aspect of t he CSS St yles panel. But as you becom e m ore proficient ( and advent urous) wit h CSS, you'll find t hat t his panel is a great way t o unt angle m asses of colliding and conflict ing st yles.
Figu r e B- 1 4 . Se le ct in g t h e Cu r r e n t vie w of t h e CSS St yle s pa n e l le t s you vie w a ll t h e pr ope r t ie s for you r W e b pa ge 's st yle s. A lin e ( cir cle d in t h e se im a ge s) st r ik e s ou t pr ope r t ie s fr om a st yle t h a t don 't a pply t o t h e give n se le ct ion on t h e pa ge . I n t h is e x a m ple , t h e fon t - fa m ily in t h e se con d < p> st yle is ove r r idde n by t h e fon t - fa m ily pr ope r t y in t h e m or e spe cific side ba r cla ss st yle ( bot t om r ow , m iddle ) . Lik e w ise , t h e side ba r cla ss a lso ove r r ide s t h e fon t - size , color , a n d m a r gin - le ft pr ope r t ie s in t h e t op < p> st yle ( bot t om r ow , r igh t ) .
Section B.5. Examining Your CSS in the Styles Panel
Section B.6. CSS Properties
B.6. CSS Properties For t he m ost part , t he Dream weaver's CSS Rule Definit ion window list s CSS propert ies using nearly t he sam e language as t he act ual propert y nam es; t he color propert y, for exam ple, is list ed in t he Type cat egory as Color. But som et im es Dream weaver uses very different nam es for CSS propert ies. Table B- 1 shows each cat egory of t he CSS Rule Definit ion window, and list s t he act ual CSS propert y nam e and a page reference where you can learn m ore about t he propert y. I n addit ion, Appendix A cont ains a com plet e list of CSS 2.1 propert ies.
Ta ble B- 1 . D r e a m w e a ve r pr ope r t y n a m e s a n d t h e ir CSS e qu iva le n t s D r e a m w e a ve r Pr ope r t y N a m e
Act u a l CSS Pr ope r t y N a m e
Cat egory: Type Font
font - fam ily ( Sect ion 6.1.1)
Size
font - size ( Sect ion 6.2)
Weight
font - Weight ( Sect ion 6.3.2)
St yle
font - St yle ( Sect ion 6.3.2)
Variant
font - Variant ( Sect ion 6.3.2.1)
Line height
line height ( Sect ion 6.4)
Case
t ext - t ransform ( Sect ion 6.3.2)
Decorat ion ( underline, overline, line- t hrough, blink, none)
t ext - decorat ion ( Sect ion 6.3.2.1)
Color
color ( Sect ion 6.1.2)
Cat egory: Background Background color
background- color ( Sect ion 7.4)
Background im age
background- im age ( Sect ion 8.2)
Repeat
background- repeat ( Sect ion 8.3)
At t achm ent
background- at t achm ent ( Sect ion 8.4.4)
Horizont al posit ion/ Vert ical posit ion
background- posit ion ( Sect ion 8.4)
Cat egory: Block Word spacing
word- spacing ( Sect ion 6.3.4)
Section B.6. CSS Properties
Let t er spacing
let t er- spacing ( Sect ion 6.3.4)
Vert ical alignm ent
vert ical- alignm ent ( Sect ion 10.2.1)
Text align
t ext - align ( Sect ion 6.4.1.2)
Whit espace
whit e- space ( Sect ion A.1.1)
Display
display ( Sect ion 7.2.4)
Cat egory: Box Widt h
widt h ( Sect ion 7.5.1)
Height
height ( Sect ion 7.5.1)
Float
float ( Sect ion 7.6)
Clear
Clear ( Sect ion 7.6.2)
Padding
padding ( Sect ion 7.2)
Top
padding- t op ( Sect ion 7.2)
Right
padding- right ( Sect ion 7.2)
Bot t om
padding- bot t om ( Sect ion 7.2)
Left
padding- left ( Sect ion 7.2)
Margin
m argin ( Sect ion 7.2)
Top
m argin- t op ( Sect ion 7.2)
Right
m argin- right ( Sect ion 7.2)
Bot t om
m argin- bot t om ( Sect ion 7.2)
Left
m argin- left ( Sect ion 7.2)
Cat egory: Border
[ 1]
St yle
border- st yle ( Sect ion 7.3)
Widt h
border- widt h ( Sect ion 7.3)
Color
border- color ( Sect ion 7.3)
Cat egory: List Type
list - st yle- t ype ( Sect ion 6.4.4)
Bullet im age
list - st yle- im age ( Sect ion 6.5.3)
Posit ion
list - st yle- posit ion ( Sect ion 6.5.2)
Cat egory: Posit ioning
Section B.6. CSS Properties
Type:
posit ion ( Sect ion 12.1)
Widt h
widt h ( Sect ion 7.5.1)
Height
height ( Sect ion 7.5.1)
Visibilit y
visibilit y ( Sect ion 12.1.5)
Z- I ndex
z- index ( Sect ion 12.1.4)
Overflow
overflow ( Sect ion 7.5.2)
Placem ent Top
t op ( Sect ion 12.1.1)
Placem ent Right
right ( Sect ion 12.1.1)
Placem ent Bot t om
bot t om ( Sect ion 12.1.1)
Placem ent Left
left ( Sect ion 12.1.1)
Clip Top, Right , Bot t om , Left
clip ( Sect ion A.1.1)
Cat egory: Ext ensions Before
page- break- before ( Sect ion 13.3.5)
Aft er
page- break- aft er ( Sect ion 13.3.5)
Cursor
cursor ( Sect ion A.1)
Filt er
Filt er is an I nt ernet Explorer for Windows only propert y. For m ore inform at ion go t o: ht t p: / / m sdn.m icrosoft .com / workshop/ aut hor/ filt er/ reference/ reference.asp ( Sect ion A.1)
[1]
There are many different border properties, all of which provide different ways to specify the same thing (see Section 7.3). Dreamweaver's CSS Styles Preferences determine exactly how Dreamweaver writes the CSS code for borders (Section B.1.1). You can't set the very useful border-collapse property in the Rule Definition window (see Section 10.2.1).
Appendix C. CSS Resources
Appendix C. CSS Resources Unfort unat ely, one book can't answer all of your CSS quest ions. ( We did t ry, however.) Thankfully, t here are m any CSS resources available for bot h t he beginning and expert Web designer. Below you'll find resources t o help you wit h general CSS concept s as well as resources t o help wit h specific CSS t asks such as building a navigat ion bar or laying out a Web page.
Section C.1. References
C.1. References References t hat cover CSS propert ies range from t he official t o t he obscure. There are Web sit es and online t ut orials, of course, but you don't have t o be on t he Web t o learn about CSS. Som e of t hese guides com e on good old- fashioned paper.
C.1.1. World Wide Web Consortium (W3C) ●
●
CSS 2.1 Specificat ion: www.w3c.org/ TR/ CSS21/ . For t he official word, go t o t he sourcet he W3Cand read t he act ual set of rules t hat m ake up t he m ost widely support ed version of CSS, version 2.1. CSS 3 Current Work: www.w3.org/ St yle/ CSS/ current - work. I f you want t o t ake a look at what t he fut ure holds, check out t he current work being done on t he CSS 3 specificat ion. I t prom ises som e very m aj or enhancem ent s t o CSS. Just not e t hat it 's probably going t o t ake a few years before t hese innovat ions are finalized and even longer before Web browsers underst and t hem . But it 's fun t o dream .
C.1.2. Books and PDFs ●
●
Cascading St yle Sheet s: The Definit ive Guide by Eric Meyer ( O'Reilly) . For com prehensive t echnical ( yet readable) coverage of CSS, check out t his guide. CSS Cheat Sheet ( www.ilovej ackdaniels.com / css_cheat _sheet .pdf) . Don't let t he URL put you off. This one- page PDF docum ent list s every CSS propert y, covers every t ype of CSS select or under t he sun, and includes a handy diagram of t he box m odel ( Sect ion 7.1) . Print it out , fold it up, and carry it in your back pocket .
C.1.3. Online Tutorial ●
West ernCiv's Com plet e CSS Guide: www.west civ.com / st yle_m ast er/ academ y/ css_t ut orial/ index. ht m l. A det ailed online guide t o CSS.
Section C.2. CSS Help
C.2. CSS Help Even wit h t he best references ( like t his book) , som et im es you need t o ask an expert . You can j oin a discussion list where CSS- heads answer quest ions by em ail, or peruse a wealt h of inform at ion in an online forum .
C.2.1. Email List ●
CSS- Discuss: ht t p: / / css- discuss.org/ . The longest living m ailing list dedicat ed t o j ust CSS. You'll find CSS m ast ers willing t o help get you out of your CSS t roubles.
Note: Before pestering the CSS-Discuss list with a question that 47,000 people have previously asked, check out their wikia collaborative Web site where group members freely add, edit, and update each other's articles. This wiki has evolved into a terrifically convenient index of tips and tricks, best practices, and in-depth treatment of CSS topics. Visit http://css-discuss.incutio.com/.
C.2.2. Discussion Boards ●
●
CSSCreat or Forum : www.csscreat or.com / css- forum / . A very act ive online forum offering help and advice for everyt hing from basic CSS t o advanced layout . Sit ePoint .com 's CSS Forum : www.sit epoint .com / forum s/ forum display.php?f= 53. Anot her helpful group of CSS addict s.
Section C.3. CSS Navigation
C.3. CSS Navigation Chapt er 9 shows you how t o creat e navigat ion but t ons for your Web sit e from scrat ch. But online t ut orials are a great way t o solidify your knowledge. Also, once you underst and t he process in det ail, you don't have t o do it yourself every single t im e. On t he Web you can find exam ples of navigat ion feat ures for inspirat ion.
C.3.1. Tutorials ●
●
ht t p: / / t ut orials.alsacreat ions.com / rollover_unique/ . How t o creat e a graphical m enu wit h a single im age. I ncludes rollovers! List ut orial: ht t p: / / css.m axdesign.com .au/ list ut orial/ . St ep- by- st ep t ut orials on building navigat ion syst em s from unordered list s.
C.3.2. Online Examples ●
●
●
●
●
●
●
●
Pure CSS Pop- ups: www.m eyerweb.com / eric/ css/ edge/ popups/ dem o.ht m l. Pop- up effect s, purely wit h CSS. CSS Tab Designer: www.highdot s.com / css- list / . Windows- only soft ware for quickly generat ing t abbed CSS m enus. CSS Showcase: www.alvit .de/ css- showcase/ . A gallery of navigat ion m enus, t abs and CSS navigat ion t echniques. List am at ic: ht t p: / / css.m axdesign.com .au/ list am at ic/ . Showcase of CSS- based navigat ion syst em s. Also lot s of links t o relat ed Web sit es. List am at ic2: ht t p: / / css.m axdesign.com .au/ list am at ic2/ . More CSS- m enus, including nest ed list s wit h subm enus. Horizont al Pop- Out Menus: www.alist apart .com / art icles/ horizdropdowns/ . The nam e's a lit t le deceiving. This t ut orial act ually creat es a vert ical m enu, wit h subm enus t hat pop up next t o t he m ain m enu. Free Vert ical Menu Designs: ht t p: / / exploding- boy.com / im ages/ EBm enus/ m enus.ht m l. A handful of cool designs. CSS Play Menu Showcase: www.cssplay.co.uk/ m enus/ index.ht m l. Lot s of cool m enus, m any useful t echniques. A m ust see.
Section C.4. CSS and Graphics
C.4. CSS and Graphics Once you've t ried t he phot o gallery in Chapt er 8, you're ready t o get even m ore creat ive. Here are som e Web sit es t hat showcase CSS graphics t ricks. ●
● ●
●
●
●
●
CSS Slideshow: www.cssplay.co.uk/ m enu/ slide_show.ht m l. CSS- only slideshow from t he creat ive m ind of St u Nicholls. Sliding Phot oGalleries: www.cssplay.co.uk/ m enu/ gallery3l.ht m l. Dynam ic, CSSdriven gallery. Mult i- page Phot o Gallery: / www.cssplay.co.uk/ m enu/ light box.ht m l# t ree1. Yet anot her im age gallery from St u Nicholls. CSS St ar Rat ing: kom odom edia.com / blog/ index.php/ 2006/ 01/ 09/ css- st ar- rat ing- part - deux. Creat e a very cool, Net flix- like st ar rat ing syst em . CSS I m age Maps: www.frankm anno.com / ideas/ css- im agem ap/ . Creat e pop- up labels for your phot os. CSS Phot o Capt ion Zoom : ht t p: / / randsco.com / _m iscPgs/ cssZoom PZ3.ht m l. Make a ginorm ous version of a phot o appear j ust by m ousing over a t hum bnail im age. Revised I m age Replacem ent : www.m ezzoblue.com / t est s/ revised- im age- replacem ent / . Overview of different ways t o swap out HTML headlines wit h st ylish graphics.
Section C.5. CSS Layout
C.5. CSS Layout CSS layout is so flexible you could spend a lifet im e exploring t he possibilit ies. And som e people seem t o be doing j ust t hat . You can gain from t heir labors by reading art icles, checking out online exam ples, and experim ent ing wit h t ools t hat can do som e of t he CSS work for you.
C.5.1. Box Model Information ●
●
●
I nt eract ive CSS Box Model: www.redm elon.net / t st m e/ box_m odel/ . Fun, int eract ive t ool for visualizing t he box m odel. On Having Layout : www.sat zansat z.de/ cssd/ onhavinglayout .ht m l. Not for t he faint of heart , t his highly t echnical analysis of I nt ernet Explorer explains t he m ain cause ( and som e solut ions) for m any of t he CSS bugs t hat plague Windows I nt ernet Explorer 6 and earlier. CSS Grid Calculat or: www.gwhit e.us/ downloads/ css_grid_calc.ht m l. A Flash applicat ion ( now t hat 's ironic) t hat asks for som e basic propert ies of t he layout you want num ber of colum ns, gut t er widt h, page widt h, and so onand generat es t he CSS t o m ake it happen.
C.5.2. Float Layouts ●
●
●
I n search of t he one t rue layout : www.posit ioniseveryt hing.net / art icles/ onet ruelayout / . I nt erest ingif slight ly m ind- bendingpresent at ion on how t o creat e a float - based layout t hat overcom es m ost of t he lim it at ions of float s. Any Order Colum ns: ht t p: / / bit esizest andards.com / bit es/ underst anding- any- order- colum ns. A sim ple int roduct ion t o using negat ive m argins for posit ioning colum ns regardless of t heir posit ion in t he HTML source code. CSS Discuss Wiki page on float - based layout s: ht t p: / / css- discuss.incut io.com / ?page= Float Layout s. Even m ore links t o float - based layout resources.
C.5.3. Absolute Position Layouts ●
●
●
CSS- Discuss Wiki on Absolut e Layout s: ht t p: / / css- discuss.incut io.com / ?page= Absolut eLayout s. Good resources wit h som e helpful background inform at ion. Learn CSS Posit ioning in Ten St eps: www.barelyfit z.com / screencast / ht m l- t raining/ css/ posit ioning/ . Quick, hands- on overview of CSS posit ioning. Making t he Absolut e, Relat ive: www.st opdesign.com / art icles/ absolut e/ . Guide t o using absolut e posit ioning for subt le design effect s.
C.5.4. Layout Examples ● ●
●
Mollio Tem plat es: www.m ollio.org. Great set of free CSS- layout t em plat es. Very nice design. Layout Gala: ht t p: / / blog.ht m l.it / layout gala/ . Fort y different CSS designs, running t he gam bit from t wo- colum n t o t hree- colum n, fixed- widt h t o liquid. ( All have been t est ed in I E, Firefox, and Safari.) I nt ensivst at ion Tem plat es: ht t p: / / int ensivst at ion.ch/ en/ t em plat es/ . Cool t em plat es, weird dom ain nam e.
Section C.5. CSS Layout
C.5.5. Miscellaneous Layout Resources ●
●
●
●
One clean HTML m arkup, m any layout s: ht t p: / / t j kdesign.com / art icles/ one_ht m l_m arkup_m any_css_layout s.asp. Great blog post t hat t akes a single HTML page and dem onst rat es eight different ways t o lay it out wit h j ust CSS. Variable fixed widt h layout : www.clagnut .com / blog/ 1663/ . Short blog post about a t echnique for adj ust ing t he num ber of colum ns on a page, based on t he widt h of t he browser window. 3- Colum n Layout I ndex: ht t p: / / css- discuss.incut io.com / ?page= ThreeColum nLayout s. A nearly exhaust ive ( or at least exhaust ing) list of different 3- colum n layout s. Sit e in an Hour: ht t p: / / left j ust ified.net / sit e- in- an- hour/ . Slide present at ion on how t o build a CSS Web sit e.
Section C.6. Browser Bugs
C.6. Browser Bugs CSS is t he best way t o form at Web pages, and I nt ernet Explorer 6 for Windows is t he world's m ost popular browser…so why doesn't I E 6 do a bet t er j ob displaying CSS? That 's a quest ion for t he ages, but one t hing's for sure: You'd be holding a t hinner book if it didn't have t o devot e so m uch paper t o I E workarounds. ( And t he following Web sit es would go out of business.)
C.6.1. Windows Internet Explorer ●
●
●
How t o At t ack an I nt ernet Explorer ( Win) Display Bug: www.com m unit ym x.com / cont ent / art icle.cfm ? page= 1&cid= C37E0. A great int roduct ion t o debugging I nt ernet Explorer CSS problem s. RichI nSt yle's guide t o I E 5/ 5.5 Bugs: www.richinst yle.com / bugs/ ie5.ht m l. That pesky browser is st ill around, and st ill causing Web designers t rouble. I f you need help m aking your pages work for I E 5, check t his page out . Explorer Exposed! www.posit ioniseveryt hing.net / explorer.ht m l. I nform at ion on t he m ost com m on I nt ernet Explorer bugs and how t o fix t hem .
C.6.2. Mac Internet Explorer 5 ●
Mac I E 5: Problem s wit h CSS Rendering: www.l- c- n.com / I E5t est s. This book doesn't cover I nt ernet Explorer 5 for t he Mac, since it 's j ust about a dead browser. Microsoft is no longer updat ing it or even providing t echnical support , giving Mac fans a perfect excuse t o swit ch t o t he superior Safari and Firefox browsers. However, if you st ill need t o accom m odat e I E 5 for t he Mac, check out t his sit e for helpful t ips on Mac I E- only CSS bugs.
Section C.7. Showcase Sites
C.7. Showcase Sites Knowing t he CSS st andard inside out is no help when your im aginat ion's running dry. A great source of inspirat ion is t he creat ive work of ot hers, so here's a bunch of sit es where you can appreciat e and st udy beaut iful CSS designs. ●
● ● ●
●
CSS ZenGarden: www.csszengarden.com . The m ot her of all CSS showcase sit es: m any different designs for t he exact sam e HTML. CSS Beaut y: www.cssbeaut y.com / . A wonderful gallery of inspirat ional CSS designs. CSS Vault : ht t p: / / cssvault .com / . More cool designs. CSS Mania: ht t p: / / cssm ania.com / . Yet anot her showcase sit e, whose non- gram - m at ical claim t o fam e is " Since March 2004, t he m ost updat ed CSS showcase all over t he globe." Showcase of Showcases: ht t p: / / css- discuss.incut io.com / ?page= ShowCase. The CSS- Discuss wiki present s a list of showcase sit es, and great exam ples of CSS design.
Section C.8. CSS Books
C.8. CSS Books Hey, not even t his book can t ell you everyt hing t here is t o know about CSS! ●
●
●
●
Web St andards Solut ions by Dan Cederholm ( Friends of Ed) . Though not st rict ly about CSS, t his book provides an excellent present at ion on how t o writ e good HTML. I f you have any doubt s about what t ags you should use t o creat e a navigat ion bar, how t o best creat e HTML form s, or what 's t he best m et hod for m aking your HTML code as sim ple as possible, t his book is a m ust read. Bullet proof Web Design by Dan Cederholm ( New Riders) . A great book covering how best t o creat e CSS st yles t hat can wit hst and t he pressure of visit ors changing t ext sizes, resizing t heir browser windows, and t he general inst abilit y of t he browser environm ent . Great t ips on building layout s, navigat ion bars and m ore. CSS Mast ery: Advanced Web St andards Solut ions by Andy Budd ( Friends of Ed) . Many advanced t ips for using CSS, including good exam ples of CSS- based layout s, and t echniques for st ream lining your CSS and HTML code. Head First HTML wit h CSS & XHTML by Elisabet h Freem an and Eric Freem an ( O'Reilly) . A lively, highly illust rat ed int roduct ion t o Web sit es int egrat ing HTML and CSS.
Section C.9. Must-Have RSS Feeds
C.9. Must-Have RSS Feeds RSS let s t he Web com e t o you in t he form of sum m aries of post s from your favorit e bloggers or inst ant not ificat ion of updat es t o t he sit es you follow. You can use t he free Google Reader ( www.google.com / reader/ ) , Firefox's built - in RSS Reader, or Safari's reader if you're on a Mac. I f you're not plugged int o RSS, you should be, especially if you'd like t o keep on t op of t he lat est in CSS news. Check out t hese feeds: ●
● ●
●
456 Berea St : www.456bereast reet .com / feed.xm l. Great t idbit s on CSS, accessibilit y and general best pract ices of Web design. And All That Malarkey: www.st uffandnonsense.co.uk/ at om .xm l. Fun, irreverent Web design info. Collylogic: ht t p: / / www.collylogic.com / index.php?/ weblog/ rss_2.0/ . Great com m ent ary on CSS, Web design, and t he Web in general. TJKDesign: www.t j kdesign.com / xm l/ TJKFeed.xm l. Lot s of good st uff, including t ut orials and deeply researched inform at ion on CSS.
Section C.10. CSS Software
C.10. CSS Software There are lot s of different ways t o creat e Cascading St yle Sheet s. Keeping it sim ple, you can st ick wit h t he free t ext edit ors t hat com e wit h Windows and Macint osh like Not epad or Text Edit . There are also CSS- only edit ors, as well as full- fledged Web page developm ent program s like Dream weaver t hat include CSS creat ion t ools. ●
CSS- Discuss list of CSS Edit ors: ht t p: / / css- discuss.incut io.com / ?page= CssEdit ors. A long list of m any different program s available for edit ing CSS.
C.10.1. Windows and Mac ●
●
St yle Mast er: www.west civ.com / st yle_m ast er/ product _info/ . This is a powerful CSS edit or wit h a long hist ory which includes m any t ools, including sim ple wizards t o get you st art ed, sam ple t em plat es, t ut orials, and a com plet e CSS guide. Dream weaver 8: www.adobe.com / dream weaver/ . Definit ely not j ust for CSS, t his prem ium Web developm ent t ool includes everyt hing you need t o build com plet e Web sit es. Visual edit ing t ools m ake it easier t o see t he effect of CSS on your Web pages as you work.
C.10.2. Windows Only ●
Top St yle: www.newsgat or.com / NGOLProduct .aspx?ProdI D= TopSt yle. The venerable CSS edit or t hat also let s you edit your HTML docum ent sa one- st op shop for Web page building. I ncludes m any t ools t o increase your product ivit y. There's also a free " lit e" version.
C.10.3. Mac Only ● ●
CSSEdit : www.m acrabbit .com / cssedit / . Sim ple, inexpensive CSS edit or. BBEdit : www.barebones.com / product s/ bbedit / . Not a CSS- edit or per se, BBEdit is a com plet e Webpage edit ing program . A slim m ed- down version, called Text - Wrangler, doesn't include as m any feat ures but is free.
Colophon
Colophon Philip Dangler was t he product ion edit or and proofreader for CSS: The Missing Manual. Dawn Mann wrot e t he index. Genevieve d'Ent rem ont and Marlowe Shaeffer provided qualit y cont rol. The cover of t his book is based on a series design by David Freedm an. Karen Mont gom ery produced t he cover layout wit h Adobe I nDesign CS using Adobe's Minion and Gill Sans font s. David Fut at o designed t he int erior layout , based on a series design by Phil Sim pson. This book was convert ed by Abby Fox t o Fram eMaker 5.5.6. The t ext font is Adobe Minion; t he heading font is Adobe Form at a Condensed; and t he code font is LucasFont 's TheSans Mono Condensed. The illust rat ions t hat appear in t he book were produced by Robert Rom ano and Jessam yn Read using Macrom edia FreeHand MX and Adobe Phot oshop CS.
Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Y] [Z] hacks CSSHOVER IE7 (selectors) Internet Explorer 2nd 3rd link-spacing bug layout property overflow: hidden property placement of zoom property handheld (media type) hanging indents headings Heerema height property 2nd 3rd Internet Explorer and max-/min-height properties hexadecimal color notation 2nd hidden (overflow property keyword) 2nd hiding elements (visibility property) horizontal navigation bars 2nd 3rd 4th 5th 6th tutorial 2nd horizontal placement (in positioning properties) HTML attributes col and colgroup tags color keywords doctype declarations for tables form tags framesets history of linking external style sheets
H
search engines and structuring text tags 2nd 3rd 4th 5th 6th 7th nested relationships span tag transitional version htmldog.com 2nd
I
Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Y] [Z] icons ID selectors 2nd JavaScript and linking to specific parts of Web pages validating HTML and vs. class selectors IE Developer Toolbar IE7 (scripts) images 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th :visited selector and background 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th free linked removing borders from tutorial 2nd 3rd 4th 5th 6th 7th img (image) tag 2nd padding/margins and tables and indenting text inherit keyword inheritance 2nd 3rd 4th 5th 6th 7th 8th 9th 10th directly applied styles and font size and 2nd limits of line-height property and proximity and specificity and style sheets and tutorial 2nd 3rd inline boxes 2nd inline elements 2nd 3rd
I
floated padding and Web browsers inline tags 2nd internal style sheets 2nd 3rd 4th 5th 6th 7th closing converting to external 2nd 3rd Internet Explorer !important and ' (single quotation marks) and :after selector and :hover selector and (non-link elements) border bug borders and bugs cache conditional comments CSS 3 link selectors and customized lists and double-margin bug fieldset tags and fixed positioning and 2nd hacks 2nd 3rd layout property and 2nd margins and max-/min-height/width properties and overflow and pixel measurements and pseudo-classes/elements and 2nd text sizing and 2nd 3rd zoom property and italicizing text Internet Explorer and
J
Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Y] [Z] JavaScript changing Web site appearance with column positioning and creating pop-up tool tips with for striping tables ID selectors and Internet Explorer and jeffhowden.com justifying text
sidebars rounding corners of 2nd 3rd 4th sIFR single quotation marks (') SitePoint.com sizing font Sliding Doors technique (tabs) small caps software Some Random Dude Son of Suckerfish (creating pop-up menus) source order search engines and spacing (text) span tag Dreamweaver and element positioning and specificity 2nd 3rd 4th breaking ties changing of pseudo-elements/class selectors overruling style sheets and speech (media type) Sperling.com square bullets (lists) 2nd Squidfingers stacking elements standards (HTML star html (* html) hack states 2nd 3rd static positioning stuffandnonsense.co.uk style (border property) Style Master style sheets 2nd 3rd 4th 5th 6th Design Time (Dreamweaver) external 2nd 3rd 4th 5th 6th 7th 8th
tables (styling) 2nd text 2nd 3rd 4th 5th 6th 7th 8th tv (media type)
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