practical css3...practical css3: develop and design chris mills peachpit press 1249 eighth street...
TRANSCRIPT
![Page 1: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/1.jpg)
![Page 2: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/2.jpg)
![Page 3: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/3.jpg)
PracticalCSS3DevelopandDesign
ChrisMills
![Page 4: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/4.jpg)
PracticalCSS3:DevelopandDesignChrisMills
PeachpitPress1249EighthStreetBerkeley,CA94710510/524-2178510/524-2221(fax)
FindusontheWebat:www.peachpit.comToreporterrors,pleasesendanoteto:errata@peachpit.comPeachpitPressisadivisionofPearsonEducation.Copyright©2013byChrisMills
AcquisitionsEditor:RebeccaGulickDevelopmentandCopyEditor:AnneMarieWalkerTechnicalReviewers:PeterGasston,BruceLawsonProductionCoordinator:MyrnaVladicCompositor:DavidVanNessProofreader:PatriciaPaneIndexer:ValerieHaynes-PerryCoverDesign:ArenHowellStraigerInteriorDesign:MimiHeft
NoticeofRightsAllrightsreserved.Nopartofthisbookmaybereproducedortransmittedinanyformbyanymeans,electronic,mechanical,photocopying,recording,orotherwise,withoutthepriorwrittenpermissionofthepublisher.Forinformationongettingpermissionforreprintsandexcerpts,[email protected].
NoticeofLiabilityTheinformationinthisbookisdistributedonan“AsIs”basis,withoutwarranty.Whileeveryprecautionhasbeentakeninthepreparationofthebook,neithertheauthornorPeachpitPressshallhaveanyliabilitytoanypersonorentitywithrespecttoanylossordamagecausedorallegedtobecauseddirectlyorindirectlybytheinstructionscontainedinthisbookorbythecomputersoftwareandhardwareproductsdescribedinit.
Trademarks
![Page 5: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/5.jpg)
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarks.Wherethosedesignationsappearinthisbook,andPeachpitwasawareofatrademarkclaim,thedesignationsappearasrequestedbytheownerofthetrademark.Allotherproductnamesandservicesidentifiedthroughoutthisbookareusedineditorialfashiononlyandforthebenefitofsuchcompanieswithnointentionofinfringementofthetrademark.Nosuchuse,ortheuseofanytradename,isintendedtoconveyendorsementorotheraffiliationwiththisbook.
ISBN-13:978-0-321-82372-4ISBN-10:0-321-82372-9
987654321
PrintedandboundintheUnitedStatesofAmerica
![Page 6: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/6.jpg)
Acknowledgments
I’dliketogiveashoutouttoallthespiffingchapsandchapessesofawesomenessandbeautythathavehelpedandinspiredmeduringthistime,anddrivenmetogetthisbookwritten!MycolleaguesandfriendsatOperaforbeingalmostlikeasecondfamily,forteachingmesomuch,forhelpingmefixmycode,andformakingwebstandardsfun.ODevRel2012:Andreas,Bruce,Daniel-san,Karl,Luz,Mike,Patrick,Shwetank,Tiffany,Vadim,andZiBin.AndthankstoalltheothertalentedpeoplewhomakeOperaagreatplacetowork.Myalliesinthewiderwebdevcommunityforgivingmemuchinspirationandsmiles,mainlyonTwitter:Jake74,DanDonald,PhilSherry,Shaun/LeslieJensen-Inman,DougSchepers,JonHicks,ChrisMurphy,andtherestoftheIrishposse,RemySharp,AnnaDebenham,MarkandEmmaBoulton,andtherestoftheFSScrew,HennySwan,andtheW3CWebEducationCommunityGroup—phew.IfIforgotyournameonthislist,pleaseabusemeonTwitter:@chrisdavidmills.PeterGasstonforanawesometechreviewjobonthisbook.Ioweyoumate.AnneMarieWalker,RebeccaGulick,andtherestofthePeachpitcrewforkickingmyassintodeliveringthisthingandhelpingtoshapeit.ConquestofSteel(Vic/DD/Dan/Claymore)forbeingalmostlikeathirdfamily,ormaybemorelikehavingfourwhinginggirlfriends.Cheersguysforthe15yearsandcountingofheavymetal.\m/Myfriendsinotherfar-flungplacesforalwaysgivingmeloveandsupport,eveniftheydidn’tunderstandthisinterwebthing.Myparentsfor“bringingmeupproper.”Iloveyoubothverydearly.AndmostofallI’dliketogivethanksandlovetoKirsty,Gabriel,Elva,andFreidaforputtingupwithmeforfourmonthswhileignoringthemtowritethisbook,andforbeingthemainreasonIgetoutofbedinthemorning.
![Page 7: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/7.jpg)
Contents
OnlineResourcesWelcometoCSS3
CHAPTER1INTRODUCTIONTOCSS3ANDMODERNWEBDESIGNWhyCSS3?ModernWebDesignPhilosophyThoughtProcessforContentCSS3ModulesinThisBookGeneralCSS3FeaturesWrappingUp
CHAPTER2BUILDINGASOLIDCROSS-BROWSERTEMPLATEWITHHTML5ANDJAVASCRIPT
StartingwithSemanticHTML5BuildingaTemplateValidatingHTML5ExploringHTML5ElementsCSSResetsandnormalize.cssJavaScriptLibraryRoundupIEConditionalCommentsWrappingUp
CHAPTER3SPICINGUPYOURFONTSANDTEXTUpthePythons!UsingWebFontsCSS3TextWranglingCSS3TypographyWrappingUp
CHAPTER4ENHANCINGBOXESWITHCSS3BLING
![Page 8: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/8.jpg)
ABrightFuturewithCSS3BlingBorder-Radius:GodBlessThoseRoundedCornersAddingDepthwithbox-shadowBringtheBlingwithCSSGradientsMultipleBackgroundsBoxClever:border-imageBox-Decoration-BreakAddingBlingtoaBannerADWrappingUp
CHAPTER5ANIMATEDEFFECTSUSINGCSS3BringingAnimationtoCSSTransformsTransitionsAnimationsEnhancingaBannerADwithAnimationsProvidingAlternativeswithModernizrWrappingUp
CHAPTER6USINGCSSTOIMPLEMENTICONSIconsRock!UsingIconsonWebsitesWhentoUseIconsTheBasicsofIconImplementationWebFontsasIconsPureCSSIcons:Peculiar?WrappingUp
CHAPTER7CSS3LAYOUTCHOPSCSS3LayoutModulesinBriefMulti-colLayoutsUsingFlexbox
![Page 9: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/9.jpg)
ExploringGridsOtherLayoutModulesWorthyofMentionWrappingUp
CHAPTER8RESPONSIVEANDADAPTIVEDESIGNABriefHistoryofWebBrowsersResponsiveDesignStrategiesFlexibleLayoutTechniquesMediaQueriesMediaQueryPolyfillsServingImagesResponsivelyMobileBrowsersLie!High-fidelityDevicesAResponsiveHeavyMetalBannerAD!WrappingUp
Index
BONUSCHAPTER
CHAPTER9STYLINGHTML5MEDIAANDFORMSCustomizing<video>and<audio>FormImprovementsWrappingUp
![Page 10: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/10.jpg)
OnlineResources
ThroughoutthisbookIuseseveralthird-party,onlineresourcesthatincludescriptsandstylesheets,andIpresentandreferencemanyexamplesthatIwrotetoillustratetheconceptsinthisbook.Thethird-partyresourcesarereferencedwhereappropriate,soyou’llbeabletofindthemwhenneeded.Tofindmyexamplesiseveneasier:Youcandownloadthemallathttp://peachpit.com/practicalcss3.Butthat’snotall!Alsoavailableathttp://peachpit.com/practicalcss3arethefollowing:
•Abonuschapter.InChapter9,“StylingHTML5MediaandForms,”Idiscussbuildingcustom-styledcontrolsforyourHTML5<video>and<audio>elements,andstylingformelementsusingtheform-relatedpseudo-classesinCSS3.•Acheatsheet.ThisreferencedocumentdetailsthesyntaxofallthenewCSS3featuresIuseinthisbookandhowtheyaresupportedinbrowsers.Printitoutandhangitonyourwallasanat-a-glanceguide!I’llupdatethisreferenceasthedatachanges.
Botharecourtesyofyourverygenerousauthor.
![Page 11: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/11.jpg)
WelcometoCSS3
CSS3providesyouwithexcitingnewtoolsforyourwebdevelopmenttoolbox,allowingyoutoaccomplishmanystylingtasksinamucheasier,moreflexible,andlesshackishmannerthanyou’vebeenusedtowhenworkingwithCSS2.Thefollowingchapterswillintroduceyoutothemostuseful,newCSS3featuresandshowyouhowtousetheminrealprojectstoday,aswellasprovidealternativesandfallbacksforless-capablebrowsers.Beforeyoustartthisbook,makesureyouhavethefollowingprerequisites.Nowthatyouhaveallofthetoolsyouneedlaidoutinfrontofyou,you’rereadytogoandmakebeautifulCSS3music.Let’sgetgoing.
HTMLandCSSBasicKnowledge
ThisbookassumesyouarewellversedinbasicHTML(4)andCSS(2)featuresandtechniques.Butjustincaseyouneedtolookupanyofthebasics,keepsomedecentreferencematerialtohand.AwealthofexcellenttutorialsisavailableontheW3CWebEducationCommunityWikiatwww.w3.org/community/webed/wiki/Main_Page.
TheLatest,GreatestBrowsers
BesuretoinstallthelatestversionsofdesktopOpera,Firefox,Chrome,Safari,andInternetExplorer(IE).Ideally,youshouldhaveatestingenvironmentavailableforallmodernbrowsers;haveasmanytohand
![Page 12: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/12.jpg)
asyoucan.
Older,Less-capableBrowsers
Haveolder,less-capablebrowsersavailablefortestingfallbacks,polyfills,andgracefuldegradation.RunolderversionsofIEonmultiplevirtualmachines(VirtualBoxisanacceptable,freeoptionatwww.virtualbox.org).CaminoisagoodoptionforatestMac-basedbrowserthatdoesn’tsupportmostofthenewCSS3/HTML5features.
AlternativeBrowsingDevices
Totestsitesondifferentscreensizes,resolutions,andcontrolmechanisms,haveatleastoneortwoalternativebrowsingdevices.Mobilephonesandtabletsareessentialfodder.Aweb-enabledTVwouldalsobefun!
Debuggingenvironments
![Page 13: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/13.jpg)
Whenitcomestochoosingdebuggingenvironments,youhavesomanychoices!DragonflyonOpera,FirebugonFirefox;hell,everybrowsertendstocomewitharespectabledebuggingenvironmentthesedays.Besuretobecomefamiliarwithasmanyaspossiblesoyou’llhavethebestchanceattrackingdownirksomebugs.
ADecentTextEditor
AgoodtexteditorisallyouneedtowriteCSSandHTML.CodaontheMacisawesome(http://panic.com/coda),butit’snotfree.GoodfreealternativesareNotepad++forWindows,TextWranglerforMac,andBluefishforLinux.WYSIWYGenvironmentsarenotrecommended,especiallyforlearning.I’mabigfanofJaredSpool’squipaboutthembeingmorelike“WYSI...WTF”!
![Page 14: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/14.jpg)
1.IntroductiontoCSS3andModernWebDesign
CSS3,thenew,modularversionoftheCSS3spec,containsmanyawesomenewfeaturesthatwillmakeyourwebdesignworkeasier,moreflexible,andmoreinteresting.What’snottolove?Browsersupportisnotcompleteyet,butmanyofthefeatureshaveenoughsupporttobeusefulinaproductionenvironment,andyoucanworkaroundnonsupportingbrowsers.InthischapterI’llprovidetherationalebehindwhythenewversioncameaboutandgentlypreachamanifestoofmodernwebdesigntoyou.ThenI’llprovideabriefroundupoftheCSS3modulesbeforeexaminingsomeofthegeneralnewfeaturesofCSS3thatareusefultoexploreasbackgroundknowledgebeforeyougoanyfurther.
WhyCSS3?CSS3hasbeenaroundforlongerthanyoumightthink.Infact,workhadstartedontheearliestpartsofCSS3ataboutthesametimeastheCSS2specwasbeingfinishedinthelate1990s.CSS2hasmanyverypowerfulfeatures,andyoucandoalotwithit,butitwasclearallthoseyearsagothatdespitethisanumberoffeaturesweremissingfromthespec.Thiswasevidencedbythefactthatwebdesignerstriedtodomanytasksusingweirdandinterestinghacksorunusualtechniques,ofteninvolvinglotsofnested<div>sorothersemanticbackstabbery,images,orevenproprietarytechnologieslikeFlash.Someexamplesthatspringtomindinclude:
•Fontembedding.DownloadingcustomfontsforuseonwebsiteshasbeenavailableinInternetExplorer(IE)sinceversion4butwasn’tstandardizeduntilyearslaterwithCSS3webfonts.Beforewebfontsgainedpopularityandcross-browsersupport,webdevelopersusedtorelyonallkindsofweirdreplacementtechniques,suchasimagereplacementandsiFR(ScalableInmanFlashReplacement—seehttp://en.wikipedia.org/wiki/Scalable_Inman_Flash_Replacement)iftheywantedcustomfontsinheadings.•BulletproofCSS.Backinthelate1990sandearly2000salotofpioneeringtechniquesstartedtospringupforcreatingCSSUIfeaturesthatwouldn’tbreakifthetextwasresized.Thetextwouldn’tspillmessilyoutofitscontainers;instead,thedesignwouldexpandalongwithit.Thesetechniqueswerereferredtoas“BulletproofCSS,”andtheyworkedwellif
![Page 15: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/15.jpg)
doneproperly.Butoftentheyrequiredanumberofnested<div>s,eachwithasinglebackgroundimagehungoffit.Bulletproofroundedcornersonacontainerrequiredfournested<div>s!Suchdesignswereinflexibleaswell.Ifyouwantedtothenchangethecolorofthebackground,you’dhavetogobackintoyourpreferredgraphicseditorandupdateallthebackgroundimageseachtime.Thisisexactlythekindofproblemthatpropertieslikeborder-radiuswerecreatedtofix.•Multiplecolumnlayouts.ItisverycommontouseCSSfloatstocreatemultiplecolumnlayouts;thiseveryoneknows.Butthisissomewhatofahack.Floatswereneveroriginallyintendedforthispurpose.Theywereintendedforsimplemagazinelayoutimagefloats.•DynamicUIs.Many“dynamicUIfeatures,”suchaslayoutsthatautomaticallyadapttodifferentscreenwidthsandsmoothanimationsandtransitionsforuserfeedback,havebeentraditionallydoneusingJavaScript.TherewasnowaytoachievethemusingCSSaloneuntilrecently;hence,theriseofDHTMLinthelate1990s(yuck!)andmorerecently,theoverwhelmingpopularityofJavaScriptlibraries,suchasjQueryandDojo.
Andthelistgoeson.CSS3wascreatednottogiveusersacompletelynewsetofamazingfeaturestoplaywithandcreate“spanglywebinnovations”(agreatdesignagencynameifevertherewasone),butmoretoprovideuserswithstandardized,moreflexiblewaysofsolvingexistingproblems.Therearenowmorethan40modulesinCSS3atvariousstagesofcompletionandbrowsersupport.Themodularsystemisbeneficialinmanyways.ItmakesCSS3easiertowritebythespecteamsandimplementbythebrowservendors:Itisalwayseasiertotacklesmallchunksthanasinglegiantmonolith.Italsomakesiteasierforwebdesignersanddeveloperstogettheirheadsaround,andinmyopinion,itmakesiteasierto“sell”toclientswhomayhaveissuesaboutusing“unfinished”technologiesintheirsites(yes,CSS2.1wastechnicallyonlyfinishedin2011,buthey).
ModernWebDesignPhilosophyIamagreatsupporterofCSSandtherestoftheopenstandardslandscape.Thelastcoupleofyearshavebeenveryexcitingforopenstandards.You’veseenbrowsersleapforwardintermsofrenderingspeed,featuresupport,andsoon.NewwebtechnologieslikeCSS3andHTML5/WebGLreallydoallowyoutocreatesomeamazingdigitalexperiences(Figure1.1).
![Page 16: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/16.jpg)
Figure1.1It’shighlyimpressivetobeabletocreatewebpageslikethis,justusingopenstandards(seehttp://operasoftware.github.com/Emberwindand
http://helloracer.com/webgl).
Buteveryoneneedstotakeastepbackwhenconsideringsuchinnovationsand
![Page 17: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/17.jpg)
notlosesightoftheoriginalqualitiesandbestpracticesthatmadethewebgreat,suchasaccessibility,usability,andgracefuldegradation.
AccessibilityComesFirstIntermsofmyperspectiveonwebdesign,Iamreallya“web1.0”kindaguy.Innovativetechnologiesareexciting,andyoucanfullyappreciatetheirimportanceintheevolutionoftheweb.Butwhatismoreexcitingistheuniversalnatureoftheweb.It’sthefactthatyoucantakethesamecontent,styleitinamilliondifferentways,andstillhaveitremainaccessibletoallwebuserstheworldoverregardlessofhowtheyusetheweb—beitonamobilephone,usingonlykeyboardcontrols,orviaascreenreader.Itissomethingdesignersanddevelopersshouldn’tlosesightof,butoftenwedo.Wheneveranexcitingnewwebtechnologycomestotheforefront,toomanysitestendtopopupthatgowildwiththeshinyandforgetaboutthebasictenets.Recently,you’veseenasadreemergenceof“Thissiteisbestviewedin...”messages,whichshouldhavebeeneliminatedaftertheoriginalbrowserwarsendedadecadeorsoago.Andwhataboutimportanttextcontentrenderedin<canvas>,whichisthereforeinaccessible?AndhowaboutCSS3featuresthatcouldworkacrossmultiplebrowsersbutdon’tbecausethedesignerhasonlyusedthe-webkit-prefixedversionoftheproperty?Thatdesignermightsay,“Oooh,butit’sanapp;therefore,it’simportanttolockoutanyonewhoisn’tusingadeviceofthecorrectlevelofshininess”(Figure1.2).
Figure1.2“BestviewedinGoogleChrome”soundslikeastepbacktothedaysof“BestviewedinIE4.”Now,I’mnotsayingthatallcontentshouldbeaccessibletoallpeople:Itisnotalwaysthatsimple.Butyoushouldmake
suchallowanceswheneverpossible.
UsabilityNext!Onceyourusershavemanagedtoaccessyourcontentandservices,cantheymakesenseofitandgleantheinformationtheywantedfromit?Thisisasimple,perhapsobviouspointtomake,butI’velostcountofthetimesI’vegonetoacompanywebsiteandscratchedmyheadinvainwhiletryingtofindcontactdetails,openingtimes,oranaddress.Instead,Ifindnothingusefulamidstthe
![Page 18: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/18.jpg)
seaofmarketingBS,cheesyvideos,andotherpropagandabeingpresented.Whydopeoplenotthinkmoreaboutwhatinformationismostusefultopeopleviewingtheirwebsitesandhowtopresentthatinformationinaneasilydigestibleway?Asimple,well-written,andclearlyavailablebitofcopyisnearlyalwaysmoreeffectivethanreamsofflashy,whizzy,technicalstuff.Mymantraforusability(andmanyotherpeople’s,too)is“don’tmakemethink.”Don’tmakeyourusersthinkabouthowtogetwhattheywant.Ifyou’venotalreadyreadit,SteveKrug’sbookDon’tMakeMeThink:ACommonSenseApproachToWebUsability,2ndEditionisessentialreading.
GracefulDegradationandProgressiveEnhancementGracefuldegradationandprogressiveenhancementweretwotermsthatfirstbecamepopular(oratleastnoteworthy)aboutadecadeago.Bothwereusedwhentalkingaboutwhathappenstocontentwhenthebrowserviewingitdoesn’tsupportallthefeaturesusedtocreateit.Gracefuldegradationmeansthatthecontentfallsbacktosomethingsimplerbutstillperfectlyaccessibleandusable.So,forexample,ifacontentboxisbuiltandthenstyledusinglotsofCSS3glitz,olderbrowsersshouldstillbeabletodisplaythetextinareadableform,evenifitdoesn’tlookasnice.Progressiveenhancementmeansthatthebasecontentisaccessiblebyall,butthenusabilityandstylisticenhancementsarebuiltontopofthatbaseforthosebrowsersthatsupportthoseenhancements.ThesearedesignphilosophiesthatIhavealwayshelddear.Theyhavenotalwaysbeeneasytouphold,becauseyouoftenmeetclientswhoare“obsessedwithpixelperfectionacrossallbrowsers”orsomesimilarweirdfetish.Buttheyarecertainlybecomingcoolagain,especiallywithalltheCSS3featurestomakeuseofandlotsofmobilesandotheralternativebrowsingdevicestomakeyourcontentworkacross.Oh,andIE6,7,and8stillhavesignificantmarketshareandoftenneedtobesupported.Thewidevarietyofnewdevicesyouhavetosupportthesedays(mobilephones,tablets,TVs,etc.)actuallymakesthingseasierintermsofclientscravingpixelperfectionacrossalldevices:Itisimpossibleforsitestolookandfunctionthesameacrossalldesktopandmobileplatforms,andindeeditdoesn’tmakesense(asapedbydowebsitesneedtolookexactlythesameineverybrowser.com,seeninFigure1.3).Itisallaboutcontext.Whatmakessenseonastandarddesktopcomputermightwellprovideabaduserexperienceonatouchscreenmobiledeviceortablet.
![Page 19: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/19.jpg)
Figure1.3DanCederholmsaiditbestwiththischeekylittlesite.
ThegoodnewsisthatCSS3isfairlyeasytoprogressivelyenhanceandgracefullydegrade,andotherwisegettoworkOKacrossoldbrowsers.Mostofthefeatures,ifusedintherightway,willdegradegracefullysothatthebasecontentwillstillbeaccessibleinnonsupportingbrowsers.Also,therearemechanismsthatallowyoutobuildinsupportorprovidealternativecontentifneedbe.
ThoughtProcessforContentAgoodthoughtprocesstogothroughwhenimplementingshinyfeaturesonawebsiteinterfaceisasfollows:1.CreateabaseofaccessibleHTMLcontent.Thestylingandbehavioryoubuildontopofthiscontentshould,whereverpossible,beusabilityandstylisticenhancements,andnotessentialforaccessingthecontent.
2.Considerwhetheryouneedtouseallthecool,cutting-edgetechnologiesorwhetheryoujustwanttobecauseyou’reacoolkidwhowantstobeinwiththeincrowd.
3.Checkwhetheryourproposedimplementationwillgracefullydegradewhileleavingthebasecontentaccessible.
4.TestwhetherthecontentisaccessibleandOKlookingacrossvaryingdevices(e.g.,differentscreensizes,controlmechanisms).
5.IncaseswherethecontentisnotaccessiblewithouttheCSS3,WebGL,orwhatever,ornotaccessibletocertainusers,doyourbesttobuildinalternativemechanismsthatwillprovideaccesstothatcontent.
![Page 20: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/20.jpg)
Youshouldconstantlylookatmakingcontentworkforasmanyusersaspossibleby:1.Keepinggracefuldegradation/progressiveenhancementinmind.2.Providingalternativesforinaccessiblecontentusingbuilt-infeatures(e.g.,alttext,transcriptsforvideo).
3.Buildinginyourownalternativeswhennobuilt-inmechanismsexist(e.g.,featuredetectionandprovisionofalternativestylesusingModernizr).
4.Usingpolyfillstoprovidesupportforfeatureswherenoneexists.TheruleIusedfordecidingwhattocoverinthisbookwastoincludeaCSS3featureonlyifithassupportacrossatleasttwomajorbrowsersandifyoucanmakedesignsemployingitworkinolderbrowsersthatdon’tsupportitviapolyfills,alternativecontent,gracefuldegradation,andsoon.I’vebrokenthisruleafewtimes,butonlywhenIthoughtafeaturewasverysignificantandlikelytohavemoreimplementationssoon,andwhennonsupportdidn’tcompletelybreaksites.
Tip
AgreatsitetoconsultforquicksummariesofwhichCSS3andHTML5featuresarereadytouseonproductionsites,andwhetherfallbacksandthelikeshouldbeprovidedishttp://html5please.usbyDivyaManian,PaulIrish,etal.
CSS3ModulesinThisBookLet’slookatabriefroundupofthemajorCSS3modulesyou’llbeutilisingandtheirmainfeatures.YoucanfindmoredetailsonthelateststatusofeachmoduleattheW3CCSSCurrentWorkpageatwww.w3.org/Style/CSS/current-work.en.html.Asyou’llsee,manyofthemodulesarenotyetfinished,butthisshouldn’tstopyoufromusingsomeofthosefeatures.Manysuchfeaturesarealreadysupportedinbrowsers,albeitwithvendorprefixes(seethesection“VendorPrefixes”formoredetails).ThemajorCSS3modulesfeaturedinthisbookinclude:
•CSSColor(www.w3.org/TR/css3-color).CSSColordefinesthemanywaystospecifycolorinCSS3,includingRGB(red,green,blue),HSL(hue,saturation,lightness),RGBAandHSLA(sameasbeforebutincludes
![Page 21: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/21.jpg)
analphachanneltospecifytransparency),andaseparateopacitypropertytoapplytransparencytoawholeselectionofelements.•CSSFontsLevel3(www.w3.org/TR/css3-fonts).Aswellascontainingthedefinitionsfordownloadablewebfonts(previouslyinaseparatemoduleknownas,youguessedit,CSSwebfonts),thismodulealsocontainsdefinitionsforotherfont-affectingproperties,suchasfont-feature-settings.Iwon’ttalkaboutmanyofthesebeyondwebfonts,becausemanydonothavemuchbrowsersupportyet.You’llmostlymeettheseinChapter3.•CSSTextLevel3(www.w3.org/TR/css3-text).ThisgoeshandinhandwithCSSFontsLevel3togiveyoumorepoweroveryourwords!AswellashousingfamiliaritemsfromCSS2,suchasletter-spacingandtext-transform,CSSTextintroducesnewfriends,suchashyphenationandtextshadow.•SelectorsLevel3(www.w3.org/TR/css3-selectors).SelectorsLevel3definesamuchmorepowerful,robustsetofmechanismsforselectingtheelementsyouwanttoapplystylestothanwasavailableinCSS2.Prettymuchalloftheseselectorshavegoodsupportacrossmodernbrowsers.Thesearediscussedlaterinthe“CSS3Selectors”sectionofthischapter.•MediaQueries(www.w3.org/TR/css3-mediaqueries).Theprimarymeansbywhichyoucannowserveoptimizeddifferentlayoutsofthesamecontenttowidelydifferingbrowsingdevices—forexample,widescreenandnarrowscreen.You’llmostlymeettheseinChapter8.•BackgroundsandBordersLevel3(www.w3.org/TR/css3-background).BackgroundsandBordersdefinesanythingtodowithbackgroundandborders,includingroundedcorners(border-radius),dropshadows(box-shadow),andfancybordereffects(border-image).•CSSMulti-columnlayout(www.w3.org/TR/css3-multicol).CSSMulti-columnlayoutdefinesaneasywaytobreakupcontentintomulti-columnlayoutsthatreflownicelyratherthanhavingtohackitwithimprecisefloats.You’llmeettheseinChapter7.•CSStransforms(www.w3.org/TR/css3-2d-transformsandwww.w3.org/TR/css3-3d-transforms).Thesetwospecificationsdefinemechanismsfortransformingthesize,position,andshapeofelementsintwoandthreedimensions.I’llmainlytalkabouttheseinChapter5.•CSStransitions(www.w3.org/TR/css3-transitions).CSStransitionsgiveyouawaytosmoothlyanimatechangesinstate,suchasachangeinlink
![Page 22: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/22.jpg)
colororanincreaseinbannersizeonhover.You’llmainlyseetheseinChapter5.•CSSanimations(www.w3.org/TR/css3-animations).CSSanimationsallowyoutoimplementFlash-styledeclarativeanimationsusingkeyframesdetailingdifferentpropertyvalues,whichthebrowserthen“tweens”between.ThesearealsocoveredinChapter5.•CSSFlexibleboxlayout(www.w3.org/TR/css3-flexbox).Mainlyintendedforequallydistributingtheheightorwidthofrowsorcolumns,thismoduledefinesnewvaluesforthedisplaypropertytoallowmorepowerfullayouttechniques.Thisissupportedtovaryingdegreesacrossmodernbrowsers,butitisdefinitelyworthmentioning.•CSSImageValuesandReplacedContentLevel3(www.w3.org/TR/css3-images).Thismodulecontainssomeusefulfeaturesforcontrollingbackgroundimagesandreplacedcontent,someofwhichisstartingtobesupportedacrossbrowsers.I’llcoverlinearandradialgradientsamongotherfeatures.
GeneralCSS3FeaturesTowhetyourappetite,let’snowlookatsomegeneralCSS3features.Thesefeaturesaregroupedtogetherbecausetheyaregeneralfeaturesthatyou’llmeettimeandtimeagainthroughoutdifferentchapters:Theyareusefulinmanydifferentcircumstances.
VendorPrefixesVendorprefixesarenotexactlyspecificCSS3features,butatthetimeofthiswriting(andforsometimeafter),you’llmeetthemrepeatedlywhenworkingwithCSS3.Thereasonisthatmanyofthemodulesyou’llbeusingfeaturesfromaren’tfinished.TheideaisthatbeforeaCSSfeatureiscompletely“finished”(e.g.,thespecisnotquitestable,andchangesmaybemadebeforethefinalversion),itcanstillbeimplementedinsidebrowsers.Atthisstage,browservendorsaddtheirownvendorprefixtothestartofthefeatureandusetheprefixedversion.Thisallowseachvendortosupportthefeatureinsideitsown“sandbox,”asitwere,soifthespecchangesandfutureversionsworkdifferently,thiswon’tresultinasinglepropertythatworksdifferentlyacrossdifferentbrowsers.Asanexample,CSStransitionsarecurrentlysupportedacrossbrowserswithvendorprefixes.Asampleblockofcodemightlooklikethis:a:link{
![Page 23: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/23.jpg)
background-color:#666666;-webkit-transition:1sall;-moz-transition:1sall;-ms-transition:1sall;-o-transition:1sall;transition:1sall;}a:hover{background-color:#ffffff;}
APrefixedNightmare?
I’veputtheprefixedpropertiesinmyexampleintheordertheyareinfortworeasons.First,itlooksaestheticallypleasingtohavethewidestprefixfirstandthenarrowestlast.Second,atthetimeofthiswriting,anumberofnon-WebKitbrowsermakerswerediscussingaddingsupportfor-webkit-prefixedversionsofsomeproperties,aswellastheirownprefixedversions.Byputting-webkit-first,youcanmakesurethatifthishappens,suchbrowserswillendupusingtheirownprefixedversionifitispresent,not-webkit-,becausetheothersallappearafterwardsinthecascade.Usingthecorrectprefixedpropertywillalwaysbebetterandmoreaccuratethanrelyingonfaked-webkit-support,especiallyconsideringthatinsomecasesyoumightfeedthedifferentbrowsersdifferentpropertyvaluesbecauseofvaryingsupport.Forexample,atthetimeofthiswritingOperadoesnotyetsupport3Dtransforms,soyoucouldprovideOperawiththis2Dtransformthatwouldwork:
Clickheretoviewcodeimage-webkit-transform:rotate3D(1,0,0,10deg)translateX(300px);-o-transform:translateX(300px);
Whyareotherbrowsersconsideringadding-webkit-support?Becausesomanydevelopershavebeenharboringanill-conceivedideathatWebKitistheonlybrowserengineworthsupporting.SotheywereusinglotsofCSS3featuresonlywiththe-webkit-prefix,therebymakingthosefeaturesarbitrarilyfailinotherbrowsersthatsupportthem.Asfarasusersareconcerned,itisthebrowsersthatareatfault.Theaveragesitevisitorsdon’tknowanybetter,andneithershouldtheybeexpectedto.Messyasitis,non-WebKitbrowsersadding-webkit-supportisasomewhatdesperatepotentialmeasuretotrytofixthisbrowsersupportmesstosomedegree.
![Page 24: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/24.jpg)
Tosumup,itmaysoundnightmarishhavingtoincludefivedifferentversionsofthesamepropertyinsuchsituations.Quiteafewpeoplethinkthatyoushouldn’tusevendorprefixesatallinproductionprojects,andthattheyareonlyfortestingpurposes(thisistheW3C’sofficialstancetoo).Butdon’tletthatstopyou.Asyou’lldiscoverthroughoutthisbook,itiseasyinmostcasestoretainanacceptableuserexperienceinbrowsersthatdon’tsupportthoseproperties,aslongasyougiveitabitofforethought!IfyouwanttouseprefixedCSS3features,pleasedosoresponsiblyanduseallthedifferentprefixesforallsupportingbrowsers.Anddon’tmakeyoursitesdependentonaparticularfeaturethatdoesn’thavecross-browsersupport!
Thistransitionshorthandpropertytellsthebrowsertosmoothlytransitioneverypropertythatchangeswhenthelink’sstatechangesoveradurationof1second(seeChapter5formoredetails).Inthiscaseitisjustthebackgroundcolorthatchanges.Theaspecttofocusoninthiscodeisthefactthattherearefivecopiesofthetransitionproperty.Thefirstfourincludevendorprefixes.Atthetimeofthiswriting,youneedtoincludethesesotheeffectwillworkinChromeandotherWebKit-basedbrowsers(-webkit-),FirefoxandotherGecko-basedbrowsers(-moz-),IE(-ms-),andOpera(-o-).I’vealsoincludedthefifth—prefixless—propertysothatwhenbrowsersstarttosupporttheprefixlessversioninsteadoftheirownspecificprefixedproperty,thecodewillstillworkforthem,andyouwon’thavetoupdateitunlessthespechaschangedsincethen.Thereisnosinglecorrectwaytoorderthevendorprefixesinyourcode,anddifferentpeoplehavedifferentopinionsabouthowitshouldbedone.I’mjustpresentingmyopinionofwhatIthinkworksbest.
CSS3ColorsThenewCSS3Colorunits(www.w3.org/TR/css3-color)aremostuseful,particularlybecausetheyallowyoutoprogrammaticallydefinetransparencyforcolors.ThisallowsyoutocreateadvancedgraphicsandfeaturesthatblendnicelyintoeachotherandtheirbackgroundswithouthavingtocreateloadsoftransparentPNGsallthetime.Table1.1showswhatcurrentsupportlookslike.
Table1.1BrowserSupportforCSS3ColorUnits
![Page 25: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/25.jpg)
RGBandRGBA
RGB(actuallyavailablesinceCSS2)worksinasimilarwaytohexvalues.Youdefinered,green,andbluechannels,butyoudoitusingnumbersbetween0and255,notpairsofhexadecimalnumbers:
•rgb(255,0,0). Equivalentto#ff0000orred•rgb(255,255,255). Equivalentto#fffffforwhite
RGBAtakesthisastepfurther,addingafourthvaluethatspecifiesthealphachannel,ortheopacityofthecolor.Thisvalueisbetween0and1;0iscompletelytransparent,and1iscompletelyopaque:
•rgba(255,0,0,1). Fullredwithfullopacity•rgba(255,0,0,0.5). Fullredbut50percenttransparent•rgba(255,0,0,0.2). Fullredbut80percenttransparent
HSLandHSLA
HSL—hue,saturation,andlightness—isadifferentwayofdefiningacolor,whichmakesalotofsensetomanypeople,especiallydesignerswhoareusedtousinggraphicseditors.Thesyntaxlookslikethis:
•hsl(0,100%,50%). Equivalentto#ff0000orred•hsl(0,0%,100%). Equivalentto#fffffforwhite
Thefirstvalue—hue—takesavaluebetween0and360.It’sbasicallyapoint
![Page 26: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/26.jpg)
aroundastandardcolorwheelcircle.Thesecondvalue—saturation—takesavalueof0–100%andreferstohowbrightthecoloris;100%isfullcolor,and0%isgreyscale.Thethirdvalue—lightness—takesavalueof0–100%andreferstohowlightthecoloris;100%iscompletelylight/white,and0%iscompletelydark/black.HSLmakessenseinalotofways;forexample,youcouldselectcomplementaryshadesofredtogowiththeprecedingredcolor,justbyvaryingthelightness,likethis:hsl(0,100%,30%)hsl(0,100%,40%)hsl(0,100%,50%)hsl(0,100%,60%)
HSLAworksinthesamewayasRGBA.Youjustaddthealphachannelvaluetotheexistingcolorlikethis:hsla(0,100%,50%,0.5),whichresultsinfullredbutis50percenttransparent.Opacity
AseparateopacitypropertyisavailableinCSS3.Youcanaddittoanyelementtosetaleveloftransparencyforthatentireelementandeverythingwithinit,includingallchildelements.Asyou’dexpect,ittakesavalueof0–1:opacity:0;
Thispropertymakeselementscompletelyvanish!ThecontentisstillavailableintheDOM,justinvisibletosightedviewers(incontrasttoothermethodsofhidingcontent,suchasdisplay:none;,whichrendersthecontentinaccessibletoscreen-readerusers).Imainlyfindthisusefulforhidingcertaincontentandthenmakingitappearagainwhenyoumouseover/focusonacertainareaofthedocument,asinpop-upinformationboxesandsuchlike.
Note
BecauseoldversionsofIEdonotsupporttransparentCSScolorsoropacity,you’llneedtomakeprovisionsforthisbyaddinginsupportoralternatives.You’lllearnvariouswaysofdoingthisthroughoutthebook.
SizingTextUsingRems
![Page 27: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/27.jpg)
CSS3introducesafewnewsizeunits(seewww.w3.org/TR/css3-values);oneinparticularthatseemsstableandisgettinggoodbrowsersupportistherem,orrootem.Thismakestextstylingaloteasierbecauseallsizesdefinedinremsarerelativetothetextsizeoftherootelement—<html>.Remsgetridofthecomplicationscausedbyemsandpercentages:Theyworkrelativetothesizingoftheirparentelements.So,fornestedelements,you’lloftenhavetodoallkindsofweirdcalculationstoworkoutwhatvaluestousetogetthefontsizeyouwant.Considerthefollowingexample(seerem_example.htmlinthechapter1codedownloadfolder):Clickheretoviewcodeimage<h1>Example<em>rem</em>exploration</h1><p>ThisexampleiswrittentoshowwhythenewCSS3remunitisuseful.Itallowsyoutomuchmoreeasilysizetextandboxes,asremsizingisalwaysrelativetothesizeofthe<code><html></code>element.</p>
Hereyoucanstartoffbysizingyourtextlikeso:html{font-size:62.5%;}
h1{font-size:3em;}
p{font-size:1.4em;}
ThisissimpleCSS.Youstartwiththetriedandtested62.5%fontsettingtotakethebasefontsizeforthewholedocumentdownto10px(62.5%of16px,thestandarddefaultbodytextfontsizeinallbrowsers).Thenyousetthe<h1>sizetothreetimesthat,whichresultsinacomputedsizeof30px.The<p>issetto1.4timesthesizeofthebasefont,or14px.Thetroublestartswhenyoutrytoresizechildrenofthoseelements.Ifyouwantedto,say,sizeyour<code>elementat11px,howwouldyoudothatwithems?Well,1.1emwouldn’twork,becauseitwouldbe1.1emof14px(thesizeofitsparentelement).Theactualvalueyouneedis11/14=0.786em.Extrapolatethistomorecomplicatedandprecisedesigns,andyou’relookingatawholeloadofcomplicatedmathandhairpulling.Remsmaketextsizingaloteasier.Ifyouinsteadusedremsforthesetextsizes,everythingwouldberelativetothefont-sizeonthe<html>.Sogetting11pxcodefontwouldbeamatterofusingthefollowing:
![Page 28: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/28.jpg)
code{font-size:1.1rem;}
Table1.2showsthecurrentstateofbrowsersupportforremunits.Table1.2BrowserSupportMatrixforRemUnits
IEonlysupportsremssinceversion9,sosupportforolderversionsneedssomeattention.ThebestwaytohandlethisistoprovidefallbacksinpixelsizessoolderIEversionsatleastgetthesamesizing,albeitwithalesserdegreeofflexibility.Forexample:code{font-size:11px;font-size:1.1rem;}
Tip
IE6andIE7don’tresizetextsetinpixels,soforaccessibility’ssake,ifyouareplanningonusingremsfortextsizing,youmightwanttoconsiderbumpingupthetextsizejustforthesebrowsersusinganIEconditionalstylesheet(seeChapter2.)
![Page 29: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/29.jpg)
CSS3SelectorsCSS3featuresanentiretoolboxofnewselectorsthatallowyoutoselectmorespecificelementsforstylingwhilenullifyingtheneedforalotofthosearbitraryIDsandclassesyoutendtooftenincludetoselect“thelastiteminthelist,”or“thefirstparagraphinthepostthatalwayscontainstheintroduction,”oreven“thetwelfthdivacrossonthe17thshelfbecauseIwantittobetheprettiest.”Iwon’tdiscusseveryselectorexhaustively.Ifyouwantadetailedreferenceforeachone,consultaresourcesuchaswww.w3.org/community/webed/wiki/Advanced_CSS_selectors.Instead,I’llprovideaquickreferenceinTable1.3foralltheselectors,andthenshowcasesomeofthemostpowerfulandinterestingones(aswellassomeseldom-exploredselectorsfirstincludedinCSS2)togiveyouagoodflavorofwhatselectorsarenowcapableof.
Table1.3CSSSelectorsReference
![Page 30: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/30.jpg)
![Page 31: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/31.jpg)
![Page 32: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/32.jpg)
![Page 33: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/33.jpg)
![Page 34: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/34.jpg)
Notes
ThewordAllinTable1.3meansallthebrowsersyou’lllikelyneedtosupportinmostprojects.SomeinterestingnewselectordevelopmentsareintheCSS4Selectorsmodule,sokeepcheckingwww.w3.org/TR/selectors4forthelatest.
Let’smoveforwardandlookatafewcasesinpointtoillustratewhyCSS3selectorsareuseful.CSS3AttributeSelectors
CSS3extendsthebasicattributeselectorfunctionalitybyallowingyoutoselectelementsbasedonstringswithinattributevalues.Forexample,youcouldselectandstyle<imgsrc="alert.gif">usingthefollowing:img[src^="alert"]{border:1pxsolid#000000;}
The^characterdictatesthatthisselectorshouldselect<img>elementsonlyiftheyhavethestring'alert'atthestartofthesrcattributevalue.<imgsrc="alert.gif">couldalsobestyledlikethis:img[src$="gif"]{border:1pxsolid#000000;}
The$characterdictatesthatthisselectorshouldselect<img>elementsonlyiftheyhavethestring'gif'attheendofthesrcattributevalue.Thisisreallyusefulforstylinglinksthatpointtospecifictypesofresources:YoucouldperhapsaddspecificiconstodifferentlinksdependingonwhethertheylinktoPDFs,Worddocuments,andsoforth.Youcouldalsostyle<imgsrc="alert.gif">likethis:img[src*="ert"]{border:1pxsolid#000000;}
The*characterdictatesthat<img>elementswiththestring'ert'anywherewithinthesrcattributewillbeselected.TheNegation(Not)Pseudo-Class
Thenegationpseudo-classcanbeusedtoexplicitlyapplystylestoelementsthatarenotselectedbyasimpleselector.Let’ssayyouwantedtoapplyaspecific
![Page 35: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/35.jpg)
widthtoanumberofformelementsbutnotthesubmit.Youcoulddothis:Clickheretoviewcodeimageinput[type="text"],input[type="url"],input[type="email"],select,textarea,etc,etc{width:15em;}
Butthiscodeisatotalmessypain.The:notselectorallowsyoutodothis:input:not([type="submit"]){width:15em;}
Youcanputmultiplesimpleselectorsinsidetheparenthesesseparatedbycommas,likeso:input:not([type="submit"],[type="file"])
CSS3Pseudo-Classes
Pseudo-classesdon’tjustselectelements;theyselectelementsincertainstates—forexample,a{}toselectlinks,butthena:hover{}toselectlinksonlywhentheyarebeinghoveredoverbythemouse.CSS3introducessomenewpseudo-classesforyoutosinkyourteethinto.Myfavorite,:target,allowsyoutoselectelementsthatarethetargetofthecurrentpageURL.Thisisveryusefulandallowsforsomecooleffects,becauseiteffectivelyletsyousetstylestobeappliedwhenlinksareclicked.Forexample:<ahref="#target">Clickme</a><divid="target">Woot!</div>
ThepageURLtargetsthe<div>whenthelinkisclicked.Tostyleitinthisstate,youcouldusethis:div:target{...}
NotethatyoucanseearealworkingexampleofCSS-onlytabsusing:targetinsidethetarget-demofolderinthechapter1codedownloadfolder.Newpseudo-classesarealsoavailableforstylingforminputswhenthedataisvalidandinvalid(seeChapter2formoreaboutHTML5forms).Funnilyenough,theyare:input:valid{color:green;}
andinput:invalid{color:red;}
:nth-childallowsyoutoselectarepeatingpatternofelementsinsideacontinuous
![Page 36: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/36.jpg)
series—forexample,severallistitemsorseveralparagraphsorarticlesnexttooneanother.Let’slookatanexample:<ul><li>First</li><li>Second</li><li>Third</li><li>Fourth</li><li>Fifth</li><li>Sixth</li><li>Seventh</li><li>Eighth</li><li>Ninth</li><li>Tenth</li></ul>
Toselectlistitems,you’ddothis,wherenisaformula,number,orkeyword:li:nth-child(n)
Toselectjusttheoddorevenlistitems,you’ddothis(averyeasywaytocreatetheinfamouszebra-stripedtableeffect):li:nth-child(odd)li:nth-child(even)
Or,youcouldusethis:li:nth-child(2n+1)li:nth-child(2n)
Tocreatethesamezebrastripes,let’slookatsomeotherformulaexamples:•li:nth-child(5).Selectsthefifthadjacentlistitem.•li:nth-child(4n+1).Selectseveryfourthlistitem,andthenadds1toeachresult.Sonumbers5and9.•li:nth-child(3n-2).Selectseverythirdlistitem,andthensubtracts2fromeachresult.Sonumbers1,4,and7.
nth-last-childdoesthesamethingasnth-child,butitcountsbackwardfromthelastelementinthesequence.nth-of-typeandnth-last-of-typeareverysimilarbuthaveoneimportantdifference:of-typeignoresanyrogueelementsinterspersedwithintherepeatedsequenceofelementsbecausetheselectionisdonebytypeofelement,notchildnumber.Forexample:Clickheretoviewcodeimage<div>1.<articleclass="abstract">...</article>2.<articleclass="abstract">...</article>3.<articleclass="abstract">...</article>
![Page 37: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/37.jpg)
4.<articleclass="abstract">...</article>5.<articleclass="abstract">...</article>6.<blockquote><p>...</p></blockquote>7.<articleclass="abstract">...</article>8.<articleclass="abstract">...</article>9.<articleclass="abstract">...</article></div>
The<blockquote>ischildnumber6outof9.Ifyouusedarticle:nth-child(2n)asyourselectortoselectalltheeven-numberedchildrenofthe<div>,you’dselectthe<article>sinpositions2,4,and8.The<blockquote>(positionnumbersix)wouldn’tbeselectedbecauseitisnotan<article>.Ifyouusedarticle:nth-of-type(2n)asyourselector,youwouldselectthe<article>sinpositions2,4,7,and9.Thereasonisthatthisselectsbythetypeofelement,notthechildposition.Therefore,inthiscasethe<blockquote>iscompletelyignoredandtheeven-numbered<article>sareselected.Yes,twoofthemareoddnumberedaccordingtomyoriginalnumberingscheme,becauseinrealitythe<blockquote>existsandoffsetstheirposition.Butarticle:nth-of-type(2n)ignoresthe<blockquote>,effectivelycountingpositions7and9as6and8.Hereareafewotherpseudo-classestoquicklyconsider:
•only-child.Selectsanelementonlyifitistheonlychildofitsparent—forexample,article:only-childwouldn’tselectanythingintheprecedingexamplebecausethereismorethanone<article>child.•only-of-type.Selectsanelementonlyifitistheonlysiblingofitstypeinsidetheparentelement.Forexample,blockquote:only-of-typewouldselectthe<blockquote>intheprecedingexamplebecauseitistheonlyoneofitstypepresent.•empty.Selectsanelementonlyifithasnochildrenwhatsoever(includingtextnodes).Forexample,div:emptywouldselect<div></div>butnot<div>1</div>or<div><p>Hi!</p></div>.
Pseudo-Elements
Pseudo-elementsdifferfrompseudo-classesinthattheydon’tselectstatesofelements;theyselectpartsofanelement:
•first-letterandfirst-line.Youcanselectthefirstletterinsideagivenelementusingthefirst-letterpseudo-elementandthefirstlineusingfirst-line.InmyKingArthurblogexample(introducedinChapter2andfoundintheking-arthur-blog-examplecodedownloadfolder),I’vecreatedarathercooldropcapandfirst-lineeffectusingbothofthesepseudo-elementsintandem(seeFigure1.4fortheresult):
![Page 38: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/38.jpg)
#main>article>p:first-of-type:first-line{font-variant:small-caps;
}
#main>article>p:first-of-type:first-letter{font-size:400%;float:left;/*loadsmorestyling!*/}
Figure1.4first-letterand:first-lineineffect!
•Generatedcontentusing:beforeand:after.Youcanusethe:beforeand:afterpseudo-elementstospecifythatcontentshouldbeinsertedbeforeandaftertheelementyouareselecting.Youthenspecifywhatcontentyouwanttoinsertorgenerate.Asasimpleexample,youcanusethefollowingruletoinsertadecorativeimageaftereverylinkonthepage:a:after{content:""url(flower.gif);}
Youcanalsousetheattr()functiontoinsertthevaluesofattributesoftheelementsaftertheelement.Forexample,youcouldinsertthetargetofeverylinkinyourdocumentinbracketsaftereachoneusingthefollowing:a:after{content:"""("attr(href)")";}
ThisisagreattechniquetouseinaprintstylesheetwhereyouwanttojustshowtheURLsinthedocumentratherthanhavingthemhiddeninsidelinks(uselessonaprintedpage).CSS3Pseudo-ElementDouble-ColonSyntax
NotethatthenewCSS3wayofwritingpseudo-elementsistouseadoublecolon—forexample,a::after{...},tosetthemapartfrompseudo-classes.CSS3,however,alsostillallowsforsinglecolonpseudo-elementsforthesakeofbackwardcompatibility.ThisiswhatI’llbeusingthroughoutthebook,althoughyoumightwanttousedouble-colonsyntaxforbetterfutureproofing;itisreally
![Page 39: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/39.jpg)
uptoyou.GettingtheNewBreedofSelectorstoWorkAcrossOlderBrowsers
Asyou’llhavegathered,manyofthenewselectorsavailabledon’tworkinthoseirksomeolderversionsofIEthatarestillhangingaround(likesomeone’srhythmicallychallengeddadonthedancefloorataweddingreception).Sowhathopedoyouhaveofusingtheseselectorsintherealworld?Asluckwouldhaveit,forsituationsinwhichyoureallyneedoldIEsupport,JavaScriptcancometotherescueintheshapeofKeithClark’sSelectivizr(http://selectivizr.com).ItsitsontopofanexistingJavaScriptlibraryandaddssupporttoIE6–8formanyofthenewselectors.Toadditin,downloadSelectivizrandapplyittoyoursite.ThenmakesureyoualsohaveoneofthecompatiblelibrariesdetailedontheSelectivizrsiteappliedtoyourpage(I’musingNWMatcherinmyexample).Thecodewilllooksomethinglikethis(again,checkoutmykingarthurblogexampleinthechapter2codedownloadfolder):Clickheretoviewcodeimage<scriptsrc="http://s3.amazonaws.com/nwapi/nwmatcher/nwmatcher-1.2.5-min.js"></script><!--[if(gteIE6)&(lteIE8)]><scripttype="text/javascript"src="script/selectivizr-min.js"></script><![endif]-->
Andthereyougo!ThisCSS3selectorsupportforIE6–8workslikeacharm!
Note
SelectivizrworksonlyonCSScontainedinexternalstylesheets,notinlineorinternalCSS.
WrappingUpBynowI’msureyou’veconcededthatCSS3isawesome,andthatyoushouldstarttoembraceitassoonaspossible.You’vereadaboutthephilosophyandgeneralapproachyou’llbeadoptingforthisbook,reviewedthemainCSS3modulesyou’llbedippingintoalongtheway,andlearnedaboutsomegeneralCSSfeaturestowhetyourappetites.Withallthisinformationunderyourbelt,you’rereadyforthenextchapter,whichfocusesmainlyonmarkup—riveting
![Page 40: Practical CSS3...Practical CSS3: Develop and Design Chris Mills Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: To report](https://reader034.vdocuments.site/reader034/viewer/2022051603/5fee6193cff77a4bc674024a/html5/thumbnails/40.jpg)
material.