/
P1OSOOVYP2OSOOVYQCOSOOVYT1OSO P1OSOOVYP2OSOOVYQCOSOOVYT1OSO

P1OSOOVYP2OSOOVYQCOSOOVYT1OSO - PDF document

kylie
kylie . @kylie
Follow
343 views
Uploaded On 2021-10-08

P1OSOOVYP2OSOOVYQCOSOOVYT1OSO - PPT Presentation

GTBL01303GTBL013Jacksonv10July1220061036CHAPTER3StyleSheetsCSSAswehavelearnedHTMLmarkupcanbeusedtoindicateboththesemanticsofadocumentegwhichpartsareelementsoflistsanditsdocumentsCSSprovidesagreatde ID: 897852

font oso css style oso font style css border jackson color 03gtbl013 gtbl013 ovyqc ovyp2 ovyt1 july12 200610 v10

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "P1OSOOVYP2OSOOVYQCOSOOVYT1OSO" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1 P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTB
P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 CHAPTER3 StyleSheets CSS Aswehavelearned,HTMLmarkupcanbeusedtoindicateboththe semantics ofadocument (e.g.,whichpartsareelementsoflists)andits documents. CSSprovidesagreatdealofcontroloverthepresentationofadocument,butto exercisethiscontrolintelligentlyrequiresanunderstandingofanumberoffeatures.And, whileyouasasoftwaredevelopermaynotbeparticularlyinterestedingettingyourweb pagetolookÒjustso,Ómanywebsoftwaredevelopersaremembersofteamsthatinclude professionalwebpagedesigners,someofwhommayhaveprecisepresentationrequire- type attribute.The style1.css Þlecontains thelines 121 P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 122 Chapter3StyleSheets html PUBLIC"-//W3C//DTDXHTML1.0Strict//EN" �"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" &#xhtml;&#x-602;xmlns="http://www.w3.org/1999/xhtml" &#xhead; &#xtitl; CSSHelloWorld.html &#x/tit;&#xle00; rel="stylesheet"type="text/css"href="style1.css" title="Style1"�/ rel="alternatestylesheet"type="text/css"href="style2.css" title="Style2"�/ &#x/hea;퀀 ody; &#xp000; HelloWorld! &#x/p00; &#x/bod;&#xy000; &#x/htm;&#xl000; FIGURE3.1 HTMLsourceforÒHelloWorld!Óusingstylesheets. body{background-color:lime} p{font-size:x-large;background-color:yellow} TheÞrstlinesimplysaysthat,forrenderingpurposes,the body elementofthedocument shouldbetreatedasifitcontainedtheattribute style="background-color:lime" .Thesecond lineissimilar,exceptthatitspeciÞesastylethatshouldbeappliedtoevery p elementofthe document.ThesecondlinealsospeciÞesvaluesfortwodifferentstyle properties , font-size and background-color .WeÕlllearndetailsabouttheseandmanyotherstylepropertieslater inthischapter,butfornowtheirmeaningshouldbeclearfromtheirnamesandtheeffects showninFigure3.2. TheÞle style2.css containsthesingleline p{font-size:smaller;letter-spacing:1em} Thissaysthat p elementsshouldbesetinasmallerthannormalfontsizeandthatthere shoul

2 dbespacebetweenadjacentletters.However,t
dbespacebetweenadjacentletters.However,thisstyleisnotappliedtothedocument FIGURE3.2 Browserrenderingof CSSHelloWorld.html . P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.2CascadingStyleSheetFeatures 123 FIGURE3.3 SelectingthestylesheettobeusedbyMozilla. renderedinFigure3.2,becausethisstylesheetisspeciÞedasan alternatestylesheet bythe rel (relationship)attributeofthe link elementthatimportsthissheet.Astylesheetsuch astheonein style1.css ,whichisreferencedbya link elementhavinga rel withvalue stylesheet aswellasa title speciÞcation,isknownasa preferredstylesheet .Analternate sheetcanbeselectedbytheuser,asillustratedinFigure3.3.Noticethatthevaluesofthe title attributesofthe link tagsaredisplayedintheUseStylemenualongwiththedefault BasicPageStyle;preferredandalternatestylesheet link elementsmustalwayscontain title attributespeciÞcations.Afterthealternatestylesheetisselected,thepagerendersin thesecondstyle,asshowninFigure3.4.(Alternatestylesheetsarenotusedoftenatthe timeofthiswriting,becausetheuserinterfaceforIE6doesnotsupportuserselectionof alternatestylesheets.) Nowthatwehavesomeunderstandingofwhatastylesheetis,wewilldiscusssome ofthemajorfeaturesofCSS. 3.2CascadingStyleSheetFeatures Thekeypropertyofstylesheettechnologyisthatitcanbeusedtoseparatethepresenta- tionofinformationfromtheinformationcontentandsemantictagging.Thecontentand FIGURE3.4 Browserrenderingof CSSHelloWorld.html usingstylesheetfrom style2.css . P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 124 Chapter3StyleSheets TABLE3.1 PossibleValuesfor media AttributeDeÞnedbyHTML4.01Standard ValueMediaType all Alltypes(default) aural Speechsynthesizer braille Tactiledevicegeneratingbraillecharacters handheld Handhelddevice,suchasacellphoneorPDA print Printer projection Projector,suchasoneusedtodisplayalargemonitorimageonascreen screen Computermonitor tty Fixed-widthcharacteroutputdevice tv Television(monitorwithlowresolutionandlittleornoscroll

3 ing) semanticsoftheÒHelloWorld!Ópagedidn
ing) semanticsoftheÒHelloWorld!Ópagedidnotchangeinthepreviousexample:itconsisted ofasingleparagraphcontainingsometext.Putanotherway,the body elementsofthe HelloWorld.html and CSSHelloWorld.html Þleswillhaveexactlythesameabstractsyntax tree.Butbychangingthestylesheetusedbythebrowsertodisplaythistree,wecanachieve differentpresentationsofthesameinformation. TherearesigniÞcantadvantagestohavingsuchaseparationbetweentheinformation containedinadocumentanditspresentation.First,itallowstheinformationinthedocument tobepresentedwithoutchangeinavarietyofways.Wehavealreadyseenanexampleof thisfeaturewithuser-selectablealternativestylesheets.ButCSScandoevenmorethan this.Forexample,the link elementdeÞnesa media attributethatcanbeusedtodeÞnethe typesofmediaforwhichastylesheetisdesigned,suchasfordisplayonamonitororoutput toaprinter(seeTable3.1foracompletelistofmediatypesdeÞnedbytheHTML4.01 standard).So,forexample,ifwehadusedthe link elements rel="stylesheet"type="text/css"href="style1.css" media="screen,tv,projection"�/ rel="stylesheet"type="text/css"href="style2.css" media="handheld,print"�/ thenthestylesheetof style1.css wouldbeusedfordisplayonmonitors,televisions, andprojectors,thestylesheetof style2.css foroutputtohandhelddevicesandprint- ers,andthebrowserÕsdefaultstylesheetforallotherformsofoutput.(TheexampleÞle CSSHelloWorldPrint.html demonstratesthisfeature:tryloadingitintoyourbrowserand thenprintingit.)YouÕllnoticethatthe title attributedoesnotappearinthe link elements inthisexample.Thisisbecausethesestylesheetscannotbeselectedbytheuser,butinstead willapplyregardlessofuseractions.Suchstylesheetsarecalled persistent andcanbe recognizedbytheirlackofa title attributespeciÞcationinthe link elementreferencing thestylesheet. FromadeveloperÕsperspective,anotherusefulfeatureofusingstylesheetsisthatit isrelativelyeasytogivealloftheelementsonapageaconsistentappearance.Thatis,if wewantallofthe h1 headersonapagetohaveacertainsize,wecanaccomplishthiseasily P1:OSO/OVYP2:OSO/OVYQC:OSO/OV

4 YT1:OSO GTBL013-03GTBL013-Jackson-v10 Ju
YT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.3CSSCoreSyntax 125 usingastylesheet.Furthermore,ifatalatertimewewishtochangethesizeoftheheaders, weneedonlymakethechangeinthatonestylesheet.Moregenerally,ifweuseasingle stylesheetforallofthepagesatasite,thenallofthesitepageswillhaveaconsistentstyle, andonethatcanbechangedwithlittlework. Inadditiontotheseproperties,whichapplytoanystylesheetlanguageÑincluding olderprint-orientedstylesheetlanguagesÑthecascadingqualityofCSSmakesitparticu- larlyappealingforusewithwebdocuments.Aswewilllearn,boththedocumentauthor andthepersonviewingthedocumentcanspecifyaspectsofthedocumentstyleasitisdis- playedbythebrowser(orotheruseragentdisplayingthedocument).Forexample,auser mayinstructtheirbrowsertodisplayallHTMLdocumentsusingonlyawhitebackground, regardlessofthesettingofthe background-color propertyinstylerulessuppliedbythe pageauthor.Thiscanbeanimportantfeatureto,forexample,auserwhobecauseofan eyesightlimitationneedshighcontrastbetweentextanditsbackground. Itshouldalsobenotedthat,thoughIamgoingtocoverCSSinthecontextofproviding styleforHTMLdocuments,itcanalsobeusedwithnon-HTMLXMLdocuments(Section 7.10containsanexample). So,therearemanyreasonstolearnaboutstylesheettechnologyingeneral,andCSS inparticular.WeÕllstartbycoveringsomeofthecoreCSSsyntacticelements.Afterthat, weÕllstudythecascadingaspectsofCSSinmoredetail.Finally,weÕllconsiderdetailsofa numberofspeciÞcstylepropertiesandapplyCSStothebloggingcasestudy. 3.3CSSCoreSyntax AswithHTML,thereareseveralW3C-recommendedversionsofCSS.Atthetimeofthis writing,therearetechnicallytwoW3CrecommendationsforCSS:CSSlevel1[W3C-CSS- 1.0]andCSSlevel2[W3C-CSS-2.0](oftenreferredtoasCSS1andCSS2).Workisalso underwayonCSSlevel3,andseveralspecializedversionsofCSSforlimiteddevices,such ascellphones,low-costprinters,andtelevisions,areinvariousstagesofstandardization. AlthoughCSS2hasbeenaW3Crecommendationsince1998,atthistimenowidely usedbrowserimplementstheentirerecommendation.Recognizingthisfact,theW3Chas bee

5 ndevelopingCSS2.1,whichislargelyascaled-
ndevelopingCSS2.1,whichislargelyascaled-backversionofCSS2thatattemptsto capturethosefeaturesofCSS2thatareÑasofthetimeoftherecommendationÕsofÞcial publicationÑimplementedbymultiplebrowsers.UsingtheFebruary2004candidatever- sionofCSS2.1[W3C-CSS-2.1]asaguide,inthischapterIwillspeciÞcallyfocusonkey aspectsofCSS2thatareimplementedinbothIE6Ñthelatestgenerally-availableversion ofInternetExploreratthetimeofthewritingÑandMozilla1.4.Forthemostpart,thebasic CSSsyntaxisthesameforbothlevels1and2,somuchofwhatispresentedshouldalso becompatiblewitholderbrowsers.Furthermore,justasbrowsersgenerallyignoreHTML elementsthattheydonotrecognize,theyalsogenerallyignoreCSSstylepropertiesthat theydonotrecognize.So,ifyouuseCSSasdescribedinthischapter,almostallbrowsers shouldbeabletodisplayyourdocument(althoughsomeolderonesmaynotstyleitprop- erly).ItwillofcoursebeadvisableforyoutomonitortheprogressoftheCSS2.1andCSS 3recommendationssothatyoucanusenewerstylesheetfeaturesastheybecomewidely available;seetheReferencessection(Section3.12)formoreonthis. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 126 Chapter3StyleSheets property names declarations selector string p { } background-color : yellow declaration block font-size: x-large FIGURE3.5 Partsofasingleruleset-typestylerule. OneotherwordofwarningisthatversionsoftheInternetExplorerbrowserbefore IE6supportedstylesheetsbutdeviatedfromtheCSSrecommendationinseveralways. EveninIE6,thesedeviationswillbepresentunlessyouuseadocumenttypedeclaration suchastheoneforXHTML1.0Strictusedinourexamples.Atthetimeofthiswriting,IE5 isstillusedonasubstantialnumberofmachines,althoughitsusageisdwindlingrapidly. So,ifyoudevelopreal-worldCSSstylesheetsinthenearterm,youmayneedtodeviate somewhatfromthematerialpresentedinthischapter.However,theconceptstaughthere aresimilartothosefoundinIE5,andastimegoesonthedetailspresentedhereshould applytothebulkofbrowsersinuse.Again,seeSection3.12formoreinformation. ACSSstylesheetconsistsofoneormorestylerules(some

6 timescalled statements ). Eachlineinthe
timescalled statements ). Eachlineinthe style1.css ÞleinSection3.1isanexampleofarule.Thisformofruleis calleda ruleset andconsistsoftwoparts:a selectorstring followedbya declarationblock , whichisenclosedincurlybraces( { and } )(seeFig.3.5).Thedeclarationblockcontainsa list(possiblyempty)of declarations separatedbysemicolons(;)(theÞnaldeclarationcan alsobefollowedbyasemicolon,andmanystylesheetauthorsfollowthisconvention).The selectorstringindicatestheelementstowhichtheruleshouldapply,andeachdeclaration withinthedeclarationblockspeciÞesavalueforonestylepropertyofthoseelements.While theexampleshowsoneruleperline,itissyntacticallylegaltosplitaruleoverseverallines or(thoughnotrecommended)writemultiplerulesonasingleline.Nospecialcharacteris neededtomarktheendofarule(nosemicolonasinJava),duetotheuseofthebracesto distinguishthepartsoftherule. WeÕllhavemuchmoretosayaboutthepropertiesthatmaybesetwithindeclarations inalatersection.Forthemoment,thepropertiesthatweuse,suchas color (textcolor)and font-style ,shouldbefairlyself-explanatory.Beforeconsideringotherproperties,wewill focusonselectorstrings. 3.3.1SelectorStrings Inthefollowingparagraphs,wewillbereferringtoanexamplestylesheetandHTML documentshowninFigure3.6andFigure3.7,respectively.Noticethatcommentsare writtenusingtheJava-stylemultilinesyntax;HTML-stylecommentsarenotrecognizedin P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.3CSSCoreSyntax 127 /*Headershavedarkbackground*/ h1,h2,h3,h4,h5,h6{background-color:purple} /*Allelementsbold*/ *{font-weight:bold} /*Elementswithcertainid'shavelightbackground*/ #p1,#p3{background-color:aqua} /*Elementsincertainclassesareitalic,largefont, orboth*/ #p4,.takeNote{font-style:italic} span.special{font-size:x-large} /*Hyperlink('a'element)styles*/ a:link{color:black} a:visited{color:yellow} a:hover{color:green} a:active{color:red} /*Descendantselectors*/ ulspan{font-variant:small-caps} ulolli{letter-spacing:1em} FIGURE3.6 StylesheetÞle sel-demo.css used

7 todemonstratevarioustypesofCSSselectors.
todemonstratevarioustypesofCSSselectors. CSS,norareJavaend-of-line( // )comments.AbrowserrenderingofthisHTMLdocument usingthegivenstylesheetisshowninFigure3.8. Probablythesimplestformofselectorstring,whichwehavealreadyseen,consists ofthenameofasingleelementtype,suchas body or p .Arulecanalsoapplytomultiple elementtypesbyusingaselectorstringconsistingofthecomma-separatednamesofthe elementtypes.Forexample,therule h1,h2,h3,h4,h5,h6{background-color:purple} saysthatanyofthesixheadingelementtypesshouldberenderedwithapurplebackground. Therefore,inourexampledocument,themarkup &#xh100;&#x/h10;Tests hasapurplebackgroundwhendisplayedinthebrowser. Intheprecedingstylerule,eachofthe selectors (comma-separatedcomponentsof theselectorstring)wassimplythenameofanelementtype.Thisformofselectoriscalled a typeselector .SeveralotherformsofselectorarealsodeÞnedinCSS.Oneisthe universal P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 128 Chapter3StyleSheets html PUBLIC"-//W3C//DTDXHTML1.0Strict//EN" �"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" &#xhtml;&#x-602;xmlns="http://www.w3.org/1999/xhtml" &#xhead; &#xtitl; Selectors.html &#x/tit;&#xle00; rel="stylesheet"type="text/css"href="sel-demo.css"&#xlink;&#x-602;/ &#x/hea;퀀 ody; &#xh100;&#x/h10;Tests id="P1"&#xp-60; class="takeNote" Paragraphwithid="P1"andclass="takeNote". &#x/p00; id="p2"&#xp-60; class="special" Secondparagraph.class="takeNotespecial&#xspan;&#x-602;cool"Thisspan belongstoclassestakeNote,special,and&#x/spa;&#xn000;cool. &#xul00; &#xli00;withinthislistarein&#xspan;&#x/spa;&#xn000; &#x/li0;style. &#xol00; &#xli00;itemspaces&#x/li0;letters. &#x/ol0; &#x/ul0; &#x/p00; &#xp-60; id="p3" Thirdparagraph(id="p3")containsa -60; &#x/a00;href="http://www.example.net"hyperlink &#xol00; &#xli00;itemcontainsaspanbutdoesnotdisplayitin &#xspan;&#x/spa;&#xn000;capsnordoesitspace&#x/li0;letters. &#x/ol0; &#x/p00; &#x/bod;&#xy000; &#x/htm;&#xl000; FIGURE3.7 HTMLdocumentusedtodemonstratevarioust

8 ypesofCSSselectors. selector ,whichisden
ypesofCSSselectors. selector ,whichisdenotedbyanasterisk( * ).Theuniversalselectorrepresentseverypossible elementtype.So,forexample,therule *{font-weight:bold} speciÞesavalueof bold forthe font-weight propertyofeveryelementinthedocument. Anotherformofselectoristhe IDselector .RecallthateveryelementinanXHTML documenthasanassociated id attribute,andthatifavalueisassignedtothe id attribute foranelementthennootherelementÕs id canbeassignedthesamevalue.Ifaselectoris precededbyanumbersign( # ),thenitrepresentsan id valueratherthananelementtype name.So,forexample,ifadocumentcontainsthemarkup P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.3CSSCoreSyntax 129 FIGURE3.8 Browserrenderingof Selectors.html afterapplyingstylesheet sel-demo.css . &#xp-60; id="p3" ... &#x/p00; thenthefollowingrulewillcausethisparagraph(andanotherelementwith id value p1 ,if suchanelementexists)tobedisplayedwithanaquabackground: #p1,#p3{background-color:aqua} Notethat id valuesarecase-sensitive,sothisrulewillnotapplytoanelementthathasan id valueof P1 .ThisiswhytheÞrstparagraphinFigure3.8doesnothaveabackground color. AnotherHTMLattributethatisfrequentlyusedwithstylesheetsis class .This attributeisusedtoassociatestylepropertieswithanelementasfollows.First,thestyle sheetmustcontainoneormorerulesetshaving classselectors ,whichareselectorsthatare precededbyaperiod( . ),suchas .takeNote intherule #p4,.takeNote{font-style:italic} P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 130 Chapter3StyleSheets ThenanyelementthatspeciÞes takeNote (withouttheleadingperiod)asthevalueof its class attributewillbegiventhepropertiesspeciÞedinthedeclarationblockofthe correspondingstylerule.Thus,theÞrstparagraphoftheexampleisdisplayedinanitalic font.Anelementcanbeassignedtomultiplestyleclassesbyusingaspace-separatedlistof classnamesasthevalueofthe class attribute.Forexample,a span elementwithstarttag class="takeNotespecial&#xspan;&#x-602;cool" willbeaffected

9 byanyrulesforforthe takeNote , special ,
byanyrulesforforthe takeNote , special ,and cool classes.Thus,the secondsentenceofthesecondparagraphoftheexampleisitalicized,sinceitbelongsto the takeNote class,amongothers.Ifaclassnamedoesnotcorrespondtoaclassselector inanyofthestylerulesforadocument(forexample, .cool isnotusedasaclassselector in sel-demo.css ),thenthatclassvalueisignored. Notethat,like id values, class valuesarecasesensitiveandcannotbeginwitha decimaldigit.However,unlike id ,multipleelementscanhavethesamevaluefortheir class attributes.Allbutafewelements,suchas html , head ,andelementsthatappearas contentof head ,havethe class attribute. IDandclassselectorscanalsobepreÞxedbyanelementtypename,whichrestricts theselectortoelementsofthespeciÞedtype.Forexample,thestylerule span.special{font-size:x-large} appliesonlyto span elementsthathavea class valueof special .So,inourexample,the secondparagraphitselfisnotsetintheextralarge( x-large )fontsize,butthesecond sentenceofthatparagraphisdisplayedusingtheextralargefont,becausethesentenceis containedinaspanwith class value special .Also,anasteriskcanbeusedinplaceofan elementnameinsuchapreÞx,and(aswiththeuniversalselector)representsthesetofall elementnames.Inotherwords,theselectors *.takeNote and .takeNote areequivalent. InadditiontoIDandclassselectors,severalpredeÞned pseudo-classes areassociated with a (anchor)elementsthathavean href attribute(sourceanchors).Table3.2liststhese pseudo-classselectors.Figure3.8showsalinkthathasnotbeenvisitedrecently,andis thereforedisplayedinblack.Positioningthecursoroverthatlinkwithoutclickingthemouse buttonwillcausethelinktochangetogreen,andclickingandholdingthemousebutton willchangethecolortored.Ifthelinkisvisited,thenthenexttime Selectors.html is TABLE3.2 Pseudo-ClassesAssociatedwith a ElementType SelectorAssociated a Elements a:visited Anyelementwith href correspondingtoaURLthathasbeenvisitedrecentlybytheuser a:link Anyelementthatdoesnotbelongtothe a:visited pseudo-class a:active Anelementthatisintheprocessofbeingselected;forexample,t

10 hemousehasbeenclicked ontheelementbutnot
hemousehasbeenclicked ontheelementbutnotreleased a:hover Anelementoverwhichthemousecursorislocatedbutthatdoesnotbelongtothe a:active pseudo-class P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.3CSSCoreSyntax 131 loadedintothebrowserthelinkwillbeyellow.AÞnepointisthatthecurrentCSS2.1 draftrecommendation[W3C-CSS-2.1]allowsabrowsertoignoreapseudo-classstylerule thatwouldchangethepositioningofanyelementswithinthebrowser.Colorchangesare thereforegoodchoicesasdeclarationsforarulethatusesapseudo-classselector,while evenaseeminglyinnocuousdeclarationinvolvingboldfacingshouldbeusedwithcaution (sinceboldfacingcanincreasethewidthoftextandthereforemoveotherelements). Finally,aselectormaybespecializedsothatitholdsonlywithinthecontentofcertain elementtypes.Forexample,therule ulspan{font-variant:small-caps} saysthatthetextwithina span elementthatisinturnpartofthecontentofanunordered,or bulleted,list( ul element)shouldbedisplayedusingasmall-capfontform.Suchaselector isknownasa descendantselector .Noticethatonlythespanwithinthebulletedlistitemin Figure3.8isdisplayedinthesmall-capformat. Classselectorscanalsobeincludedintheancestorlist;forexample,theselector .specialspan wouldapplytoany span elementwithinthecontentofanyelementbelongingtotheclass special .Moregenerally,awhite-space-separatedlistofelementand/orclassnamesmay beusedasaselector,representingachainofelementseachofwhichmustbeadescendant oftheelementtoitsleftinorderfortheselectortoapply.Forexample,therule ulolli{letter-spacing:1em} appliesonlytoan li elementwithinan ol (ordered,ornumbered,list)elementthatiswithin a ul element.Thus,thenumberediteminthesecondparagraphdisplaysintheletterspaced format,becausethisparagraphÕsnumberedlistiscontainedwithinabulletedlist;butthe numberedlistinthethirdparagraphdoesnotusethisformat,becauseitisnotcontained withinabulletedlist. 3.3.2At-Rules Sofar,wehavecoveredtherulesetformofstylerules.Theotherformofruleiscalledan at-rule .Theonlyat-rulethatiswidelysupport

11 edandusedatthetimeofthiswritingisthe rul
edandusedatthetimeofthiswritingisthe rulebeginningwith @import .ThisruleisusedtoinputonestylesheetÞleintoanotherone. Forexample,astylesheetsuchas @importurl("general-rules.css"); h1,h2{background-color:aqua} willÞrstreadinrulesfromtheÞle general-rules.css beforecontinuingwiththeotherrule inthisstylesheet.The url() functionisusedtomarkitsstringargumentasaURL.Single quotescanbeusedforthisargumentratherthandoublequotes;infact,thequotesarenot requiredatall.TheURLcanbeabsoluteorrelative.IfitisarelativeURL,liketheone P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 132 Chapter3StyleSheets showninthisexample,thenitwillbetakenasrelativetotheURLoftheÞlecontaining theimportat-rule,ratherthanrelativetotheHTMLdocument.The @import rulemustend withasemicolon,asshown.Also,all @import rulesmustappearatthebeginningofastyle sheet,beforeanyrulesetstatements. 3.4StyleSheetsandHTML Sofar,thestylesheetswehaveusedhavebeenstoredinÞlesandincludedinanHTML documentthroughtheuseofa link element.Suchstylesheetsareknownas external style sheets.AnotheroptionistoembedastylesheetdirectlyinanHTMLdocumentasthe contentoftheHTML style element,whichcanappearanynumberoftimesinthe head contentofadocument.Forexample,anXHTMLdocumentmightcontainthefollowing markup: &#xhead; &#xtitl;&#x/tit;&#xle00; &#xstyl;-60; type="text/css" h1,h2{background-color:aqua} &#x/sty;&#xle00; &#x/hea;퀀 Asyouwouldexpect,thiswillhavethesameeffectasifthegivenstylerulehad beencontainedinanexternalstylesheetandincludedintheHTMLdocumentviaa link element.Astylesheetthatisincludedinthecontentofa style elementisknownasan embedded stylesheet. Ihavetwonotesofcautionaboutusingembeddedstylesheets.First,ifanyXML specialcharacter,suchasless-than( )orampersand( & ),appearsinthestylerules,thenthe charactermustbereplacedbytheappropriateentityorcharacterreference.Ontheother hand,suchreferencesshould not beusedinanexternalstylesheet,becauseanexternal stylesheetisnotanXMLdocumentandthereforeisnotprocessedlikeone.Seco

12 nd,the HTML4.01speciÞcationsuggestsenclo
nd,the HTML4.01speciÞcationsuggestsenclosingthecontentofa style elementwithinan SGMLcomment,forexample, &#xstyl;-60; type="text/css" h1,h2{background-color:aqua} �-- &#x/sty;&#xle00; Thiswassuggestedbecausesomeolderbrowsersdidnotrecognizethe style element.Such abrowserwouldignorethe style startandendtagsbutwouldstillattempttoprocessthe contentoftheelement,asdiscussedinChapter2.Therefore,a style elementcouldproduce strangebehaviorinsuchbrowsers.Tocircumventthisproblem,CSSwasdeÞnedsothatthe SGMLcommentstartandenddelimiters and �-- areignoredbystylesheetprocessors (thedelimitersthemselvesareignored,butthecontentwithinthedelimitersisnotignored). Soanolderbrowserwouldignoreboththe style tagsandthecontentina style element P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.5StyleRuleCascadingandInheritance 133 writtenasshown,whileastyle-cognizantHTML4.01browserwouldprocessthe style elementasifthecommentdelimiterswerenotpresent. However,usingSGMLcommentdelimitersinembeddedstylesheetsisnotrecom- mendedinXHTML,asXHTMLparsersareallowedtostripoutcommentsandtheircon- tentregardlessofwhatelementsmaycontainthecomments.So,inanXHTML-compliant browseranembeddedstylesheetenclosedwithincommentdelimitersmaybeignored. Giventhatalmostallbrowsersinusetodayrecognizethe style element,andgiventhis potentialdifÞcultyinXHTMLbrowsers,IsuggestthatyounotuseSGMLcomment delimiterswithin style elements. The media attributedescribedearliercanbeusedwiththe style elementaswell aswith link elements,andthereforeappliestobothexternalandembeddedstylesheets. However,the rel attributeappliesonlytothe link element,notto style .Soanembedded stylesheetistreatedmuchthesameasapersistentexternalstylesheet:itcannotbeselected ordeselectedbythebrowseruser,butinsteadalwaysappliestothedocument. Aswelearnedinthepreviouschapter,mostHTMLelementshavea style attribute thatcanbeusedtodeÞnestylepropertiesfortheelement.Technicallyspeaking,thevalueof a style attributeisnotastyles

13 heet,sinceitisnotasetofstylerulesbutisin
heet,sinceitisnotasetofstylerulesbutisinsteadessentially asinglelistofstyledeclarationsthatappliestoasingledocumentelement.Infact,theuse ofstylesheetsisrecommendedovertheuseof style attributes,foranumberofreasons. Onereasoniseaseofcoding:ifyouwantalloftheparagraphsinyourdocumenttohavethe samestyleapplied,itismucheasiertoaccomplishthisbywritingasinglestylerulethan byaddinga style attributespeciÞcationtoevery p element.Similarly,itisgenerallymuch easiertomodifythestyleofadocumentthatusesstylesheetstodeÞnestylethanitisto modifyonethatuses style attributes.A style attributevaluealsocannotvaryautomatically withmediatype.Thislastobservationisaspecialcaseofthemoregeneralrecommendation thatsincemarkupisdesignedtocarrystructuralandsemanticinformation,itisgenerally besttokeepallstyleinformationoutofthebodyofanHTMLdocument.Allthatsaid,there aretimeswhenthe style attributeisconvenient(e.g.,tomakeanimagecoveranentire tablecell,asinSection2.7).So,whileyoushouldnÕtnecessarilyavoiditsusealtogether, trytousethe style attributewisely. 3.5StyleRuleCascadingandInheritance BeforedescribingindetailmanyofthekeyCSSstyleproperties,itwillbehelpfulto understandtwoconcepts:cascadingofstylesheetrulesandelementinheritanceofstyle properties. 3.5.1RuleCascading ThestylesheetofFigure3.6containstherule *{font-weight:bold} whichappliestoeveryelementoftheHTMLdocument.Italsocontainstherule #p1,#p3{background-color:aqua} P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 134 Chapter3StyleSheets Aswehaveseen,bothoftheserulesappliedtoanelementwith id attributevalue p3 .That is,ifmultiplerulesapplytoanelement,andthoserulesprovidedeclarationsfordifferent properties,thenallofthedeclarationsareappliedtotheelement.Butwhatwouldhappen iftherule #p3{font-weight:normal} alsoappearedinastylesheetforthedocument?Whichrulewouldapplytothe font-weight propertyofthe p3 element? Thisisoneexampleofamoregeneralquestion:Foreverypropertyofeveryelement onapage,thebrowsermustdecideonavaluetouseforthatproper

14 ty.Howdoesitdetermine thisvalueifmultipl
ty.Howdoesitdetermine thisvalueifmultiplestyledeclarationsapplytothatpropertyofthatelement?Furthermore, whatshouldthebrowserdoifnodeclarationatalldirectlyappliestothatelementproperty? WeÕlldealwiththeÞrstquestioninthissubsection,andthesecondquestioninthenext. Inordertochoosebetweenmultipledeclarationsthatallapplytoasingleproperty ofasingleelement,thebrowser(orotheruseragent)applies rulecascading ,amultistage sortingprocessthatselectsasingledeclarationthatwillsupplythepropertyvalue.Thevery Þrststepofthisprocessinvolvesdecidingwhichexternalandembeddedstylesheetsapply tothedocument.Forexample,ifalternateexternalstylesheetsareavailable,onlyonewill apply,andrulesintheotheralternatestylesheetswillbeignored.Similarly,ifamediatype isspeciÞedforanembeddedorexternalstylesheetandthattypeisnotsupportedbythe useragentrenderingthepage,thenthatstylesheetÕsruleswillbeignored. OncetheappropriateexternalandembeddedstylesheetshavebeenidentiÞed,thenext stageofthesortingprocessinvolvesassociatinganoriginandweightwitheverydeclaration thatappliestoagivenpropertyofagivenelement.The origin ofastylesheetdeclaration hastodowithwhowrotethedeclaration:thepersonwhowrotetheHTMLdocument,the personwhoisviewingthedocument,orthepersonwhowrotethebrowsersoftwarethatis displayingthedocument.SpeciÞcally,theoriginofadeclarationisoneofthefollowing:  Author: Ifthedeclarationispartofanexternalorembeddedstylesheetorispartofthe valuespeciÞedforthe style attributeofthegivenelement,thenitoriginatedwiththe authorofthedocumentthatisbeingstyled.  Useragent: AbrowserorotheruseragentmaydeÞnedefaultstylepropertyvaluesfor HTMLelements.IntheMozilla1.4 View | UseStyle menu,thisisthestylesheetrep- resentedbytheÒBasicPageStyleÓoption.AppendixAoftheCSS2.0recommendation [W3C-CSS-2.0]containsanexampleuseragentstylesheet.  User: Mostmodernbrowsersallowuserstoprovideastylesheetortootherwiseindicate stylepreferencesthataretreatedasstylerules. InMozilla1.4,theuserstylerulescanbedeÞnedintwoways.First,underthe Edit | Preferences |

15 Appearance category,theFontsandColorspan
Appearance category,theFontsandColorspanelsallowausertoselect variousstyleoptions,whichwillbetreatedasuserstylerules.Second,theusercanex- plicitlycreateastylesheetÞlethatthebrowserwillinputwhenitisstarted.However, thisisnotaneasy-to-usefeatureinMozilla1.4:youmustcreateaÞlewithacertainÞle- name( userContent.css )andplaceitinacertaindirectory(the chrome subdirectoryofthe P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.5StyleRuleCascadingandInheritance 135 directoryspeciÞedbytheCacheFolderÞeldof Edit | Preferences | Advanced | Cache ). SimilarfeaturesareprovidedinIE6underthe General tabofthe Tools | Internet Options window.TheColorsandFontsbuttonsallowtheusertosetstyleoptions,and astylesheetÞlecanbereadintoIEbyclickingtheAccessibilitybutton,checkingthe checkboxintheUserStyleSheetpanel,andselectingtheÞle. Inadditiontoanorigin,everyauthoranduserstyledeclarationhasoneoftwo weight values:normalandimportant.Adeclarationhasimportantweightifitendswithanexcla- mationmark( ! )followedbythestring important (orsimilarstrings:caseisnotimportant, andtheremaybewhitespacebeforeoraftertheexclamationmark).Sotherule p{text-indent:3em;font-size:larger!important} givesimportantweighttothedeclarationofthe font-size property.Adeclarationwith- outthe !important stringÑsuchasthedeclarationofthe text-indent propertyinthat exampleÑwouldhavenormalweight.Alluser-agentdeclarationscanalsobeconsidered tohavenormalweight. Oncetheoriginandweightofalldeclarationsapplyingtoanelementpropertyhave beenestablished,theyareprioritized(fromhightolow)asfollows: 1. Importantdeclarationwithuserorigin 2. Importantdeclarationwithauthororigin 3. Normaldeclarationwithauthororigin 4. Normaldeclarationwithuserorigin 5. Anydeclarationwithuseragentorigin Thatis,wecanthinkofeachdeclarationasfallingintooneofÞveprioritybins.Wethenlook throughthebins,startingwiththeÞrst,untilweÞndanonemptybin.Ifthatbinhasasingle declaration,thedeclarationisappliedtotheelementpropertyandwearedone.Otherwise, th

16 erearemultipledeclarationsintheÞrstnonem
erearemultipledeclarationsintheÞrstnonemptybin,andwecontinuetothenextsorting stageinordertoselectasingledeclarationfromamongthecandidateswithinthisbin. Beforegettingtothisnextstage,youmaybewonderingwhyimportantuserdeclara- tionshavehigherprioritythanauthordeclarationswhilenormal-weightuserdeclarations havelowerpriority.Thereasonisaccessibility.Ifavisuallyimpairedwebusermusthave highcontrastbetweentextandbackgroundalongwithlargeboldfontsinordertoreadtext onamonitor,thatusercanbeaccommodatedbywritingdeclarationswithimportantweight, regardlessofthepageauthorÕsdesigndecisions.Ontheotherhand,auserwhoismerely statingstylepreferenceswillgenerallynotwanttheirdefaultpreferencestooverridethose ofawebsiteauthorwhomadespeciÞcstylechoicesforhisorherwebsite.OnesigniÞcant changebetweenCSS1andCSS2wastheadoptionofthesortorderjustlisted,whichisalso supportedbythemajormodernbrowsers. Nowwereturntothecaseinwhichthetopnonemptybinoftheweight-originsort containsmultiplestyledeclarationsforasingleelementproperty.Thenextstepistosort thesedeclarationsaccordingtotheir speciÞcity .First,ifadeclarationispartofthevalue ofa style attributeoftheelement,thenitisgiventhehighestpossiblespeciÞcityvalue P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 136 Chapter3StyleSheets (technically,inCSS2thisspeciÞcityvaluecanbeoverridden,butthatfeaturedoesnotseem tobewidelyimplementedbycurrentbrowsers).Ifadeclarationispartofaruleset,thenits speciÞcityisdeterminedbytheselector(s)fortheruleset.Webeginbytreatingaruleset withacomma-separatedselectorstringasifitweremultiplerulesetseachwithasingle selector;thatis,arulesetsuchas h1,#head5,.big{font-size:x-large} istreatedastheequivalentthreerulesets h1{font-size:x-large} #head5{font-size:x-large} .big{font-size:x-large} Next,weconceptuallyplaceeachrulesetinoneormorebins,eachbinlabeledwitha classofselectors.Thebinsweuseforthispurpose,fromhighesttolowestspeciÞcity,are: 1. IDselectors 2. Classandpseudo-classselectors 3. Descendantandtypeselectors(th

17 emoreelementtypenames,themorespeciÞc) 4.
emoreelementtypenames,themorespeciÞc) 4. Universalselectors Arulesetwithaselectorsuchas li.special wouldgointwobins,sincethisisbotha classandatypeselector.NowweselectarulesetfromtheÞrstnonemptybin.If,say,two rulesetsappearsinthisbin,wesearchlowerbinsfortheÞrstrecurrenceofeitherruleset. Ifoneoftherulesetsrecursbeforetheother,thenitischosen.So,forexample, li.special wouldbechosenover  .special . Evenafterthissortingprocess,twoormoredeclarationsmaystillhaveequallyhigh weight-originrankingandspeciÞcity.TheÞnalstepinthestylecascadeisthenapplied,and isguaranteedtoproduceasingledeclarationforagivenpropertyofagivenelement.First, ifthereisadeclarationinthe style attributefortheelement,thenitisused.Otherwise, conceptually,allofthestylesheetrulesarelistedintheorderinwhichtheywouldbe processedinatop-to-bottomreadingofthedocument,withexternalandimportedstyle sheetsinsertedatthepointofthe link elementor @import rulethatcausesthestylesheet tobeinserted.Thedeclarationcorrespondingtotherulethatappearsfarthestdowninthis listischosen.Asanexample,iftheÞle imp1.css containsthestatements @importurl("imp2.css"); p{color:green} andtheÞle imp2.css containsthestatement p{color:blue} andadocument head containsthemarkup P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.5StyleRuleCascadingandInheritance 137 &#xtitl;&#x/tit;&#xle00; &#xstyl;-60; type="text/css" p{color:red} &#x/sty;&#xle00; rel="stylesheet"type="text/css"href="imp1.css"&#xlink;&#x-602;/ &#xstyl;-60; type="text/css" p{color:yellow} &#x/sty;&#xle00; thenthestylerulesetsareeffectivelyintheorder p{color:red} p{color:blue} p{color:green} p{color:yellow} and p elementswillbedisplayedwithyellowtext.Noticethatsincetheimportat-rulesmust alwayscomeatthebeginningofastylesheet,anyimportedrulescanalwaysbeoverridden byrulesinthebodyofthestylesheetcausingtheimport.Thisissensible,sincerules importedfromaÞlearepresumablymeanttobeofareusable,general-purposenatureand thereforeshouldbesubjecttorevisionf

18 oraspeciÞctask. Finally,certain(oftendep
oraspeciÞctask. Finally,certain(oftendeprecated)HTMLattributesotherthan style canbeusedto affectthepresentationofanHTMLdocument.Forexample,the height attributeofthe img elementtypecanaffectpresentation.But img alsohasa height stylepropertythatcan besettoachievethesameeffect.IfbotharedeÞnedforan img element,whichshould takeprecedence:theattributeorthestyleproperty?ThegeneralansweristhatanyCSS styledeclarationtakesprecedenceoverstyle-typedeclarationsmadeviaHTMLattribute speciÞcations.MorespeciÞcally,thebrowseroruseragenttreatsnon-CSSattributestyling asifanequivalentCSSstylerulehadbeeninsertedattheverybeginningoftheauthor (normalweight)stylesheetwithaspeciÞcitylowerthanthatfortheuniversalselector.So anyimportant-weightuserstyleruleaswellasanystylerulewrittenbythedocumentauthor willtakeprecedenceoverstylerulesderivedfromattributessuchas height ,whichinturn willtakeprecedenceovernormal-weightuseranduser-agentstylerules. ThestylecascadeissummarizedinFigure3.9.WeÕrenowreadytotackletheother questionposedearlier:ifapropertyofanelementhasnoassociatedstyledeclarations, howisthevalueofthepropertydetermined?Theansweristhatthevalueisinheritedfrom ancestorsoftheelement,asdiscussednext. 3.5.2StyleInheritance Whilecascadingisbasedonthestructureofstylesheets,inheritanceisbasedonthetree structureofthedocumentitself.Thatis,conceptuallyanelement inherits avalueforoneof itspropertiesbycheckingtoseeifitsparentelementinthedocumenthasavalueforthat property,andifso,inheritingtheparentÕsvalue.Theparentmayinturninherititsproperty valuefromitsparent,andsoon.Putanotherway,whenattemptingtoinheritaproperty value,anelement(saywith id value needValue )willsearchupwardthroughitstreeof ancestorelements,beginningwithitsparentandendingeitherattheroot html elementor P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 138 Chapter3StyleSheets Alternate style sheets 1. Select style sheets and insert rules for HTML attributes 4. Break ties based on position within style sheet (last o

19 ccuring wins) 3. Break ties based on sp
ccuring wins) 3. Break ties based on specificity ( style attribute or most specific selector) 2. Prioritize declarations by origin and weight FIGURE3.9 StepsintheCSScascade. attheÞrstelementthathasavaluefortheproperty.Ifthesearchendsatanelementwith avaluefortheproperty,thatvaluewillbeusedby needValue asitspropertyvalue.Ifno ancestorelementhasavaluefortheproperty,thenasalastresortthepropertywillbegivena valuespeciÞedforeachpropertybytheCSSspeciÞcation[W3C-CSS-2.0]andknownas thepropertyÕs initialvalue .Thisterminologymakessenseifyouthinkofeachelement propertyashavingitsinitialvalueassignedwhenthedocumentisÞrstreadandthenhaving thisvaluechangedifeitherthecascadeortheinheritancemechanismsuppliesavalue. Figure3.10showsthesourceofanHTMLdocumentthatillustratesinheritance.No- ticethatthestylesheetforthisdocumentcontains font-weight declarationsforboththe body and span elementtypes.Sofor span elements,the font-weight isspeciÞedbyan authorrule,andnovaluewillbeinheritedforthisproperty.Forotherelementswithinthe body ,though,thereisnoauthorrule,andassumingthatthereisalsonouseroruser-agent rule,the font-weight propertyvaluewillbeinheritedfromthe body element.Therefore, P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.5StyleRuleCascadingandInheritance 139 html PUBLIC"-//W3C//DTDXHTML1.0Strict//EN" �"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" &#xhtml;&#x-602;xmlns="http://www.w3.org/1999/xhtml" &#xhead; &#xtitl; Inherit.html &#x/tit;&#xle00; &#xstyl;-60; type="text/css" body{font-weight:bold} li{font-style:italic} p{font-size:larger} span{font-weight:normal} &#x/sty;&#xle00; &#x/hea;퀀 ody; &#xul00; &#xli00; Listitemoutsideand&#xspan;&#x/spa;&#xn000;aspan. &#xp000; Embeddedparagraphoutsideand&#xspan;&#x/spa;&#xn000;aspan. &#x/p00; &#x/li0; &#x/ul0; &#x/bod;&#xy000; &#x/htm;&#xl000; FIGURE3.10 HTMLdocumentdemonstratinginheritance. asshowninFigure3.11,thewordÒinsideÓ(whichisthecontentoftwo span elements) appearswithanor

20 malfontweight,whileallothertextisboldfac
malfontweight,whileallothertextisboldfaced.However,sincethere arenootherpropertydeclarationsforthetwo span elements,theseelementsdoinheritother propertyvaluesfromtheirancestors.TheÞrst span inheritsitalicizationfromitsparent li element,whilethesecondinheritsalargerfontsizefromits p elementparentanditaliciza- tionfromits li elementgrandparent.The p elementsimilarlyinheritsitalicizationfromits li parent. FIGURE3.11 Renderingofdocumentdemonstratinginheritance. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 140 Chapter3StyleSheets AfewÞnalpointsshouldbementionedaboutinheritance.First,whilemanyCSS propertiesareinheritable,anumberofotherpropertiesarenot.Ingeneral,yourintuition aboutwhetherornotapropertywillbeinheritedshouldbecorrect.Forexample,the height propertyofanelementisnotinheritedfromitsparent,whichissensible,sinceoftenthe parenthasmanychildrenonmanylinesandthereforehasagreaterheightthananyone child.AsIcoverspeciÞcCSSpropertiesinlatersectionsofthischapter,youshouldassume thateachpropertyisinheritedunlessIexplicitlysayotherwise.Ofcourse,youcanconsult theCSSspeciÞcations[W3C-CSS-2.0]ifindoubtorforinformationaboutinheritanceof propertiesnotcoveredinthischapter. Asecondpointaboutinheritancehastodowithexactlywhichofseveralpossible propertyvaluesisinherited.Thevaluecontainedinastyledeclarationforapropertyis knownasthe speciÞedvalue fortheproperty.Thisvaluecanbeeitherrelativeorabsolute. An absolutevalue isavaluethatcanbeunderstoodwithouttheneedforanycontext,such asthevalue 2cm (twocentimeters).A relativevalue ,ontheotherhand,cannotbeunderstood withoutknowingsomecontext.Forexample,thepropertydeclaration font-size:larger usestherelativevalue larger tosetthesizeofthefontofanelement.Exactlywhatthis valueisrelativetoisdiscussedinSection3.6.3.Fornow,itÕssufÞcienttoknowthatthe browsermustperformacalculationÑwhichdependsontheparticularrelativevalueÑto obtaina computedvalue fortheproperty.Inthecaseofthefont-sizevalue larger ,this calculationmightinvolvemul

21 tiplyingthebasefontsizebyafactorsuchas1.
tiplyingthebasefontsizebyafactorsuchas1.2toobtainthe computedfontsize.IfthespeciÞedvalueisabsolute,thenthecomputedvalueisidentical tothespeciÞedvalue.Finally,thecomputedvaluemaynotbesuitableforimmediateuseby thebrowser.Forexample,aspeciÞedfontsizeÑrelativeorabsoluteÑmaynotbeavailable forthefontcurrentlyinuse,sothebrowsermayneedtosubstitutetheclosestavailablefont size.Thevalueactuallyusedbythebrowserforapropertyisknown,appropriatelyenough, asthe actualvalue . Intermsofinheritance,thecomputedvalueisnormallyinheritedforaproperty,not thespeciÞedoractualvalue.Theoneexceptiontothisamongthepropertiesdiscussedin thischapteris line-height ;itsinheritancepropertieswillbedescribedindetailinSection 3.6.4. AÞnalnoteaboutinheritanceisthattheCSS2recommendationallowseverystyle propertytobegiventhevalue inherit ,whetherornotthepropertyisinheritednormally. WhenthisvalueisspeciÞedforaproperty,thecomputedvalueofthepropertyissupposed tobeobtainedfromitsparent.However,youshouldbeawarethatthisinheritancefeature isnotsupportedbyIE6,andthereforeshouldbeusedwithcareifatall.Iammentioningit mainlybecauseitappearsoftenintheCSS2recommendation.Sincethisvaluecanbeused foreveryCSS2property,Iwillnotmentionitexplicitlywhenlistingpossiblevaluesfor propertiesinthefollowingsections. WearenowreadytobeginlearningaboutmanyoftheavailableCSS2properties. WeÕllbeginwithanumberoftextproperties. 3.6TextProperties Inthissection,wewillcovermanyoftheCSSpropertiesrelatedtothedisplayoftext. SpeciÞcally,wewilllearnabouthowtoselectafontandhowtomodifytextproperties suchascolor.WeÕllalsocoverinsomedetailhowbrowsersdeterminethespacingbetween P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.6TextProperties 141 linesoftextandhowdocumentauthorscaninßuencethisspacing.Latersectionswillcover someotheraspectsoftext,suchasalignment,oncewehavecoverednecessarybackground material. Onenotebeforebeginning:CSSdeÞnesa direction propertythatcanbethought ofasdeÞningthedefaultdirectioninwhichtextiswritten.It

22 takestwopossiblekeyword values: ltr indi
takestwopossiblekeyword values: ltr indicatesaleft-to-rightlanguage,and rtl indicatesright-to-left.Thisproperty affectsthedefaultbehaviorofmanyotherCSSpropertiesaswellassomeoftheirinitial values.Forexample,theinitialvalueforthe text-align property,usedtospecifyhow aparagraphoftextshouldbealigned,is left if direction Õsvalueis ltr andis right otherwise.Forsimplicity,Iwillassumeleft-to-rightlanguagesthroughoutthischapter;if thereisanasymmetrybetweenleftandrightforaproperty(suchastheinitialvalueof text-align ,whichgivespreferenceto left ),simplyswitchtherolesofleftandrightifyou usearight-to-leftlanguage. 3.6.1FontFamilies Figure3.12isabrowserrenderingofanHTMLdocumentthatdisplayscharactersusing fourdifferentfontfamilies(weÕlllearnlaterhowtowriteadocumentsuchastheonethat generatedthisÞgure).A fontfamily isacollectionofrelatedfonts,anda font isamapping fromacharacter(UnicodeStandardcodepoint)toavisualrepresentationofthecharacter (a glyph ).Eachglyphisdrawnrelativetoarectangular charactercell (alsoknownasthe characterÕs contentarea ),whichisshownshadedforeachcharacterintheÞgure.Thefonts withinafontfamilydifferfromoneanotherinattributessuchasboldnessordegreeof slantedness,buttheyallshareacommondesign.Thefontfamiliesusedinthisexample are,inorderofuse,Jenkinsv2.0,TimesNewRoman R  ,Jokewood,andHelvetica TM ;they illustratewellhowdifferentfontfamilydesignscanbefromoneanother.(TheJenkinsand Jokewoodfontsmaynotbeavailableonyourmachine,sothisexamplemaynotappearthe sameinyourbrowserasitdoesinFig.3.12.) ThefontfamilytobeusedfordisplayingtextwithinanHTMLelementisspeciÞed usingthe font-family styleproperty.Forexample,thestarttag style="font-family:'Jenkins&#xp-60; v2.0'" FIGURE3.12 Renderingofdocumentillustratingfourdifferentfontfamilies. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 142 Chapter3StyleSheets indicatesthatthetextwithintheparagraphstartedbythistagshouldusetheJenkinsv2.0 font(unlessachildelementspeciÞesadifferentfont).Somefontfamilynamesmustb

23 e quotedand/orspecialcharacterscontained
e quotedand/orspecialcharacterscontainedinthenamesmustbeescaped;forsimplicity,I recommendthatyoualwaysquotefontfamilynames.Eithersingleordoublequotescanbe used,whichisespeciallyconvenientwhenthedeclarationappearswithina style attribute asshown. Mostend-usercomputerscontainÞlesdescribingavarietyoffontfamilies.How- ever,thereisnoguaranteethatafontfamilythatyouwouldliketodisplayinanHTML documentyouareauthoringwillbeavailableonalloftheclientmachinesviewingyour document.AlthoughIE6hasamechanismfordownloadingfontsfromtheWebforuse withinanHTMLdocument,thisfacilityisnotincludedinthecurrentversionofCSS2.1 [W3C-CSS-2.1].Instead,arecommendedmechanismforspecifyingafontfamilyinCSS istouseacomma-separatedlistoffontfamiliesasthevalueofthe font-family property, suchas font-family:"EdwardianScriptITC","FrenchScriptMT",cursive ThebrowserwillattempttousetheÞrstfamilyspeciÞed( EdwardianScriptITC inthis example),butifthatfamilyisnotavailableonthebrowserÕssystem,thenthebrowserwill proceedthroughthelistuntilitÞndsafamilythatisavailable.Thelastelementinthe list( cursive inthisexample)shouldbethenameofa generic fontfamily.Thegeneric fontfamiliesdeÞnedbyCSSarelistedinTable3.3.Unlikenormalfontfamilynames,the namesofgenericfamiliesareCSSkeywordsandthereforemustnotbequotedwithina font-family declaration. Thebrowserwillattempttoassociateareasonablefontfamilyavailableonthe userÕssystemwitheachgenericname.InMozilla1.4,theusercanspecifytheactualfont familyassociatedwitheachgenericfamilythroughapreferencesettingasillustratedin Figure3.13. TABLE3.3 CSSGenericFontFamilies FontFamilyDescription serif A serif isashort,decorativelineattheendofastrokeofaletter.Therearethreeserifsat thetopoftheWinFigure3.12,forexample.Mostglyphsinaseriffontfamilywillhave serifs,andsuchafamilyistypically proportionately spaced(differentglyphsoccupy differentwidths). sans-serif Usuallyproportionatelyspaced,butglyphslackserifs,sotheydonÕtlookasfancyasserif fonts. cursive Looksmorelikecursivehandwritingthanlikeprinting. fantasy Glyphsares

24 tillrecognizableascharacters,butarenontr
tillrecognizableascharacters,butarenontraditional. monospace Allglyphshavethesamewidth.Sincemonospacefontsareoftenusedineditorswhen programming,thesefontfamiliesarefrequentlyusedtodisplayprogramcodeorother computerdata. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.6TextProperties 143 FIGURE3.13 ExampleofassociationsofactualwithgenericfontfamiliesinMozilla. 3.6.2LengthSpeciÞcationsinCSS Fontsizeisoneofthekeyfeaturesusedtodistinguishbetweenindividualfontswithina fontfamily.InCSS,thesizeofafontisspeciÞedusingthe font-size property.Onetypeof valuethatcanbeassignedto font-size isa CSSlength .Infact,CSSlengthscanbeassigned tomanyCSSproperties,notjust font-size .Therefore,wewillcoverlengthspeciÞcation separatelyinthissectionbeforemovingontohowtospecifyfontpropertiessuchassize inCSS. InCSS,alengthvalueisrepresentedeitherbythenumber 0 orbyanumberfollowed byoneoftheunitidentiÞersgiveninTable3.4.Someexampledeclarationsinvolvinglength valuesare: font-size:0.25in font-size:12pt font-size:15px P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 144 Chapter3StyleSheets TABLE3.4 CSSLengthUnitIdentiÞers IdentiÞerMeaning in Inch cm Centimeter mm Millimeter pt Point:1/72inch pc Pica:12points px Pixel:typically1/96inch(seetext) em Em:referencefontsize(seetext) ex Ex:roughlytheheightofthelowercaseÒxÓcharacterinthereferencefont(seetext) TheÞrstsixunitsinTable3.4are,inpractice,allrelatedtooneanotherbymultiplica- tivescalefactors.Inparticular,bothMozilla1.4andIE6appeartomaintaintherelationships 1in. = 2.54cm = 25.4mm = 72pt = 6pc = 96pxbothonscreenandwhenprintinga document.BothalsoappeartousepixelstodeÞnealloftheotherunitswhendisplayinga documentonamonitor.Forexample,ifyourmonitorresolutionissetto1024by768pixels andyouspecifyahorizontallengthas 1024px ,thenthislengthwillroughlycorrespondto thewidthofthemonitorÕsdisplayarea.Thedisplayareawillalsobetreatedasifitwere 1024 / 96  10 . 7in.across,regardlessofitstruephysicalw

25 idth.Thus,theunits in , cm , mm , pt ,an
idth.Thus,theunits in , cm , mm , pt ,and pc areallonlyapproximationsonscreen,anddependingontheresolutionmaybe offby50%ormore(allbythesamefactor).Whenprinting,however,itappearsthatboth browsersdeÞne px as1/96in.(orclosetoit)anddeÞnetheotherunitsaccordingly. Notethat,despitetheimprecisions,lengthsdeÞnedusingtheÞrstÞveunitsinTable3.4 areabsolutelengthsinthesensedeÞnedearlier:theydonotdependonotherstyleproperty values.Suchunitsarereferredtoas absoluteunits .Theotherthreeunitsare relativeunits . Technically,CSSdeÞnes px asarelativeunit,sinceitsphysicalvalueshoulddependonthe mediumdisplayingthedocument.However,asindicated,inpracticeitseemstobetreated bytypicalbrowsersasanabsoluteunit.WeÕllseewhy em and ex arerelativeunitsina moment. BeforedeÞningthe em and ex unitsformally,itwillbehelpfultounderstandseveral detailsaboutfonts.First,allcharactercellswithinagivenfonthavethesameheight. However,generallyspeaking,thisheightisnotexactlythesameasthecomputedoreven theactualvalueoftheCSS font-size property.Forexample,inFigure3.12,asingle font-size valueÑ72ptÑappliestoallofthecharacters,yetobviouslythecharactercells varysomewhatinheight.Thusacombinationofthefontfamilyandthe font-size property determinestheactualheightofcharactercells.The font-size computedvalueisknown asthe emheight; formostfontfamilies,thecellheightis10Ð20%greaterthantheem height. AnotherfeaturethatthefontdeÞnesisthebaselineheight.The baselineheight isthe distancefromthebottomofacharactercelltoanimaginarylineknownasthe baseline , whichisthelinethatcharactersappeartoreston.AsshowninFigure3.12,whenasingle lineoftextcontainscharactersfromdifferentfonts,thecharactersarebydefaultaligned P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.6TextProperties 145 M x baseline height baseline ex height cell height FIGURE3.14 SomefeaturesandquantitiesdeÞnedbyafont. verticallybyaligningtheirbaselines.Thus,althoughwecanseefromtheÞgurethatthe characterscellsdonotalignvertically,thecharacterglyphsthem

26 selvesappeartoallbe writtenonasinglehori
selvesappeartoallbe writtenonasinglehorizontalline. YetanotherquantitydeÞnedbyeachfontisthe exheight .Thisquantityshouldbe thoughtofasthefontdesignerÕsdeÞnitionoftheheight(abovethebaseline)oflowercase letterssuchasÒx.ÓFigure3.14illustratesthisquantityandseveralotherfontfeatures. NowwecandeÞnethe em and ex units.First,asnotedinTable3.4,theseunitsare deÞnedrelativetoareferencefont(andarethereforerelativeunits).Withoneexception explainedintheparagraphafternext,thereferencefontisjustthefontoftheelementto whichtherelativeunitapplies.So,forexample,inthemarkup &#xp-60; style="width:20em" thereferencefontisthefontthatapplies(viaastyleruleorinheritance)tothe p element. Oncethereferencefontisknown,1emissimplytheemheightofthefont,thatis, thecomputedvalueofthe font-size propertyofthereferencefont.So,continuingour example,ifthecomputedvalueofthe p elementÕs font-size propertyis0.25in.,thenthe computedvalueforits width propertywillbe5in.Similarly,1existheexheightofthe referencefont. Theoneexceptionwhendeterminingthereferencefontforthesereferenceunitsis whenoneofthemisusedina font-size declaration.Inthiscase,thereferencefontisthe fontoftheparentoftheelementtowhichthedeclarationapplies.Sointhemarkup id="d1" iv-;怠style="font-size:12pt" id="d2" iv-;怠style="font-size:2em" thereferencefontforthe div with id attributevalue d2 willbe d1 Õsfont.Sincethecomputed font-size for d1 willbe12pt(becauseabsoluteunitsareused),thecomputed font-size for d2 willbe24pt. Nowwearereadytomorefullydescribe font-size andseveralotherfontproperties. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 146 Chapter3StyleSheets 3.6.3FontProperties TheCSS font-size property,wenowknow,isusedtospecifytheapproximateheightof charactercellsinthedesiredfontwithinafontfamily.Thispropertyhasaninitial(default) valueof medium ,whichisassociatedwithaphysicalfontsizebythebrowser(thesemay varywithfontfamily;Mozilla1.4defaultsto14ptforproportionalfontfamiliesand12pt formonospace).Avarietyofotherva

27 luescanbespeciÞedforthisproperty. First,
luescanbespeciÞedforthisproperty. First,ofcourse,alengthvaluecanbespeciÞedfor font-size ,usinganyofthelength unitsdescribedintheprevioussection.Asecondwaythata font-size propertymaybe speciÞedisasapercentageofthecomputed font-size oftheparentelement.Since 1em representsthecomputedvalueoftheparentÕs font-size ,thefollowingspeciÞcationsare essentiallyequivalent: font-size:0.85em font-size:85% Third,the font-size speciÞcationmaybegivenusingwhatistermedan absolutesize keyword.Oneofthesekeywordsis medium ,theinitialvaluefor font-size .Theremaining keywordsare xx-small , x-small , small , large , x-large ,and xx-large .Thebrowserorother useragentcreatesatableofactuallengthscorrespondingtoeachofthesesizekeywords. TheCSS2recommendation[W3C-CSS-2.0]isthateachofthesebeapproximately20% largerthanitsnext-smallersize. Finally,the relativesize keywords smaller and larger maybespeciÞed.Again,like therelativeunits em and ex ,eachofthesekeywordsspeciÞesthefontsizeforthecurrent elementrelativetothefontsizeofitsparent.Theserelativesizekeywordsconceptually sayÒmoveonepositioninthefont-sizetable.ÓSo,iftheparentelementhasafontsizeof large ,thenarelativesizespeciÞcationof larger foritschildisequivalenttoanabsolute sizespeciÞcationof x-large .IftheparentfontsizeisoutsidetherangeofthebrowserÕs font-sizetable,thenanappropriatenumericalfontchange(forexample,20%)isapplied instead. CSSalsoprovidesseveralotherfontstyleproperties;threeofthemostcommonly usedareshowninTable3.5.Severalotherfont-relatedproperties,including color ,are coveredlaterinthissection. TABLE3.5 AdditionalFontStyleProperties PropertyPossibleValues font-stylenormal (initialvalue), italic (morecursivethannormal),or oblique (moreslanted thannormal) font-weightbold or normal (initialvalue)arestandardvalues,althoughothervaluescanbeusedwith fontfamilieshavingmultiplegradationsofboldness(seeCSS2[W3C-CSS-2.0]for details) font-variantsmall-caps ,whichdisplayslowercasecharactersusinguppercaseglyphs(small uppercaseglyphsifpossible),or normal (initia

28 lvalue) P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1
lvalue) P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.6TextProperties 147 Line boxes Thisis surefun! FIGURE3.15 Aboxrepresentinga p elementthatconsistsoftwolineboxes,eachpartiallyÞlledwithcharacter cells. 3.6.4LineBoxes Wenowwanttoconsiderhowabrowserdetermineswheretextshouldberenderedwithin anHTMLelement.WewillassumeinthissectionthatthetextisthecontentofanHTML p element,butthedetailsareessentiallythesameformostotherHTMLblockelements, suchas div . Thesimplestcaseistheoneinwhichthecontentofthe p elementconsistssolely oftext.Inthiscase,wecanthinkofthe p elementasbeingrenderedasarectangularbox composedentirelyofastackofimaginaryboxescalledlineboxes.Each linebox contains onelineoftext.Theheightofalineboxispreciselytheheightofacharactercellinthe p elementÕsfont.Charactercellsrepresentingthetextareplacedsidebysideinthetopmost lineboxuntilitcontainsasmanywords(stringsofcontiguousnon-white-spacecharacters) aspossible;asinglespace(withwidthdeÞnedbythefont)separateseachword.Whenthe Þrstlineboxcanholdnomorewords,thisprocesscontinueswiththesecondlinebox,and soonuntilalloftextofthe p elementhasbeenaddedtolineboxes.Therewillbejustenough lineboxestocontainthetext,sotheheightoftheboxrepresentingthe p elementwillbe thenumberoflineboxesmultipliedbytheheightofacharactercell.Figure3.15illustrates therenderingofthetextÒThisissurefun!Óusingamonospacefontwithina p -elementbox thatisonlywideenoughtohold10characters.Noticethattheboxconsistsentirelyoftwo lineboxes,andthatneitherofthelineboxesinthiscaseiscompletelyÞlledbycharacter cells. ThebrowserÕsdefaultsettingoftheheightoflineboxescanbeoverriddenbyspec- ifyingavalueforthe p elementÕs line-height property.Theinitialvalueofthisproperty is normal ,whichaswehaveseensetstheheightoflineboxesequaltotheheightofa charactercell(atypicalvaluemightbe1.15em,or15%greaterthanthecomputedvalue of font-size ).OtherlegalvaluesforthispropertyareaCSSlength(usinganyofthe unitsdeÞnedearlier),apercentage(treatedasapercentageoft

29 hecomputedvalueofthe p elementÕs font-si
hecomputedvalueofthe p elementÕs font-size ),oranumberwithoutunits.IntheÞnalcase,thenumberistreated asifitsunitsare em ,exceptintermsofinheritance(wedealwiththisinamoment).Thus, thefollowingdeclarationsareallequivalentintermsoftheireffectonthe p elementitself: line-height:1.5em line-height:150% line-height:1.5 Iftheheightofalineboxisgreaterthanthecharactercellheight,thenthecharacter cellsareverticallycenteredwithinthelinebox.Thedistancebetweenthetopofacharacter P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 148 Chapter3StyleSheets Half-leading Text cell height line-height Half-leading G FIGURE3.16 Defaultplacementoftextcellwithinalineboxwhenthevalueof line-height exceedstheheight ofatextcell.Anequalamountofspace(half-leading)isinsertedaboveandbelowthetextcell. cellandthetopofalinebox(whichisthesameasthedistancebetweenthebottomofa cellandthebottomofthelinebox)issometimescalledthe half-leading (piecesoflead wereoftenusedtoseparatelinesoftypeinearlymanualtypesettingsystems,hencethe term).Thus,increasingthe line-height valueaboveits normal valuenotonlyincreasesthe distancebetweenlines,butactuallymovesthetextoftheÞrstlinedownbythehalf-leading distanceaswellasincreasingthedistancebetweenthelastlineoftextandwhateverfollows the p elementÕsboxbythesamedistance(Fig.3.16).Wewilllearnhowtooverridethis defaultcenteringoftextwithintalllineboxeslaterinthischapter. AÞnepointaboutinheritanceofthisproperty:If normal oranumberwithoutunits isspeciÞedasthevalueof line-height ,thenthisspeciÞedvalueisinheritedratherthan thecomputedvalue.ForanyotherspeciÞedvalue,suchas 1.5em ,thecomputedvalueis inherited.Anexerciseexploresthisfurther. Nowthatwehavelearnedaboutthe line-height property,Icandescribeaconvenient propertycalled font .ThispropertyisanexampleofaCSS shortcutproperty ,whichisa propertythatallowsvaluestobespeciÞedforseveralnonshorthandpropertieswithasingle declaration.Asanexampleoftheuseofthe font shortcut,thedeclarationblock {font:italicbold12pt"Helvetica",s

30 ans-serif} isequivalenttothethedeclarati
ans-serif} isequivalenttothethedeclarationblock {font-style:italic; font-variant:normal; font-weight:bold; font-size:12pt; line-height:normal; font-family:"Helvetica",sans-serif} Noticethatthe font shortcutalwaysaffectsallsixofthepropertiesshown,resettingthose forwhichavalueisnotspeciÞedexplicitlyinthe font declarationtotheirinitial(default) values.Thefontsizeandfontfamily(inthisorder)mustbeincludedinthespeciÞed valuefor font .Ifvaluesforanyofstyle,variant,andweightappear,theymustappear P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.6TextProperties 149 TABLE3.6 PrimaryCSSTextProperties PropertyValues text-decorationnone (initialvalue), underline , overline , line-through ,orspace-separatedlistof valuesotherthan none . letter-spacingnormal (initialvalue)oralengthrepresentingadditionalspacetobeincludedbetween adjacentlettersinwords.Negativevalueindicatesspacetoberemoved. word-spacingnormal (initialvalue)oralengthrepresentingadditionalspacetobeincludedbetween adjacentwords.Negativevalueindicatesspacetoberemoved. text-transformnone (initialvalue), capitalize (capitalizesÞrstletterofeachword), uppercase (convertsalltexttouppercase), lowercase (convertsalltexttolowercase). text-indent Length(initialvalue0)orpercentageofboxwidth,possiblynegative.Specifyforblock elementsandtablecellstoindenttextwithinÞrstlinebox. text-alignleft (initialvalueforleft-to-rightcontexts), right , center ,or justified .Specify forblockelementsandtablecells. white-spacenormal (initialvalue), pre .Usetoindicatewhetherornotwhitespaceshouldbe retained. beforethefontsizeandmayappearinanyorderamongthemselves.Tospecifyavaluefor line-height ,immediatelyfollowthefontsizevaluebyaslash(/)andthe line-height value.Forexample, {font:boldobliquesmall-caps12pt/2"TimesNewRoman",serif} isavalid font declarationthatexplicitlysetsallsixfontproperties. 3.6.5TextFormattingandColor Beyondfontselection,severalotherCSSpropertiescanaffecttheappearanceoftext.These arelistedinTable3.6.Allof

31 thesepropertiesexcept text-decoration ar
thesepropertiesexcept text-decoration areinherited.And, whilenotinherited, text-decoration automaticallyappliestoalltextwithintheelement, whileskippingnontext,suchasimages.ThedecorationusestheelementÕscolorvalue. Someofthesepropertiesmayinterferewithoneanother.Forexample,sincetextjustiÞ- cation(lininguptextwithastraightedgeonbothleftandrightsides)generallyinvolves insertingspacebetweenlettersand/orwords,specifying justify for text-align andalso specifyingvaluesfor letter-spacing and word-spacing maynotproducetheresultsyou expect.Asusual,seetheCSS2recommendation[W3C-CSS-2.0]fordetailsonsuchspecial cases. Finally,aswelearnedinearlyexamplesinthischapter,the color propertyisusedto specifythecolorfortextwithinanelement.Therearemanypossiblevaluesforthe color property,whichwenowcover.ItshouldbenotedthatthesevaluescanalsobespeciÞedfor severalotherCSSproperties,asdiscussedlater. CSS2colorpropertiescanbeassignedseveraltypesofvalues.Themostßexibletype isanumericalrepresentationofthecolor.Inparticular,threenumericalvaluesareused P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 150 Chapter3StyleSheets TABLE3.7 AlternativeFormatsforSpecifyingNumericColorValues FormatExampleMeaning Functional,integerarguments rgb(255,170,0) UseargumentsasRGBvalues. Functional,percentagearguments rgb(100%,66.7%,0%) Multiplyargumentsby255androundtoobtain RGBvalues(atmostonedecimalplace allowedinarguments). Hexadecimal #ffaa00 TheÞrstpairofhexadecimaldigitsrepresents theredintensity;thesecondandthird representgreenandblue,respectively. Abbreviatedhexadecimal #fa0 DuplicatetheÞrsthexadecimaldigittoobtain redintensity;duplicatethesecondandthird toobtaingreenandblue,respectively. tospecifyacolor,representingintensitiesofred,green,andbluetobemixedtogetherin ordertosimulatethedesiredcolor(thetypicalhumaneyecanbeÒtrickedÓintoperceiving lightfrommultiplesourcesatvariousintensitiesandwavelengthsasifitwerefromasingle sourcewithasingleintensityandwavelength).ThespeciÞccolormodelusedinvol

32 ves specifyinganintegerbetween0and255,in
ves specifyinganintegerbetween0and255,inclusive,foreachoftheintensitiesofred,green, andblue,inthatorder(earlyWebpagesusedalimitedrangeofintensitiesduetohardware limitationsofmanycomputersinuseatthetime,butmostmachinestodaycanreliably displayanyoftheseintensities).Suchanintegerisknownasan RGBvalue .Manyreadily availablesoftwaretools,includingMicrosoftPaint,providevisualmapsfromcolorsto RGBvalues.Fourdifferentformatscanbeusedtospecifythesethreevalues,asshownin Table3.7.Alloftheexamplesinthistablespecifythesamecolorvalue.(Awordofcaution: itÕseasytoforgettheleading # forthethirdandfourthformats.) Manyofourearlierstylesheetexamplesusedasecond,moreconvenientway tospecifycommoncolors:manycolorvalueshaveastandardnameassociatedwith them.Alistofthe16colorsnamedinCSS2andtheirassociatedRGBvaluesisgiven inTable3.8.ThecurrentCSS2.1speciÞcationalsoadds orange ( #ffa500 )tothelist. Furthermore,Mozilla1.4supportsallandIE6supportsalmostall(therearesomeex- ceptionscontaining gray or grey )ofthe147colornamesrecognizedaspartofthe W3CÕsScalableVectorGraphicsrecommendation[W3C-SVG-1.1].Thisprovides130 colornamesinadditiontothoseofCSS2.1,from aliceblue through yellowgreen (see http://www.w3.org/TR/SVG11/types.html#ColorKeywords foracompletelist). Finally,colorvaluescanbespeciÞedbyreferencingcolorssetforotherpurposes ontheuserÕssystem.Forexample,thekeyword Menu representsthecolorusedformenu backgrounds,and MenuText thecolorusedfortextwithinmenus.Thiscanbeuseful,for example,ifyouplantoprovidemenuswithinyourpageandwantthemtousecolorsfamiliar toyourusers,regardlessofuserselectedmenucolorpreferences.Afulllistoftheseso-called systemcolornamesisprovidedinSection18.2oftheCSS2speciÞcation[W3C-CSS-2.0]. However,beadvisedthatthedraftforCSS3currentatthetimeofthiswritingdeprecates suchsystemcolornames. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.7CSSBoxModel 151 TABLE3.8 CSS2ColorNamesand RGBValues ColorNameRGBValue black #000000 gray #808080 silver #c0c0c0 white #f

33 fffff red #ff0000 lime #00ff00 blue #000
fffff red #ff0000 lime #00ff00 blue #0000ff yellow #ffff00 aqua #00ffff fuchsia #ff00ff maroon #800000 green #008000 navy #000080 olive #808000 teal #008080 purple #800080 Wehavereferredthroughoutthissectiontothenotionofaboxcorrespondingtoa p element.Inthenextsection,webegintomakethisconceptmoreprecise. 3.7CSSBoxModel InthissectionwedeÞneanumberofCSSpropertiesthatrelatetotheboxesthatabrowser renderscorrespondingtotheelementsinanHTMLdocument.Insubsequentsectionswe willlearnhowbrowserspositiontheseboxesrelativetothebrowserclientareaandrelative tooneanother. 3.7.1BasicConceptsandProperties InCSS,eachelementofanHTMLorXMLdocument,ifitisrenderedvisually,occupies arectangularareaÑa box Ñonthescreenorothervisualoutputmedium.WhatÕsmore, everyboxconsistsconceptuallyofanestedcollectionofrectangularsubareas,asshown inFigure3.17.SpeciÞcally,thereisaninnermostrectangleknownasthe contentarea thatenclosestheactualcontentoftheelement(lineboxesorboxesforotherelements,or both). Padding separatesthecontentareafromtheboxÕs border .Thereisthena margin surroundingtheborder.Thecontentandmarginedgesarenotdisplayedinabrowser,but aredrawninFigure3.17fordeÞnitionalpurposes.NotethesimilaritybetweentheCSSbox modelandtheconceptofacellinHTMLtables.However,aswewillsee,styleproperties inCSSprovideÞner-grainedcontroloverboxesthanHTMLprovidesfortablecells. Someotherterminologyrelatedtotheboxmodelwillalsobehelpful.Thecontent andmarginedgesofanelementÕsboxaresometimesreferredtoasthe inner and outer edgesofthebox,respectively.Also,asshowninFigure3.18,theouter(margin)edgesofa P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 152 Chapter3StyleSheets the Margin area Margin edge Border area Border edge Padding area Padding edge Content areaContent edge FIGURE3.17 DeÞnitionofareasandedgesintheCSSboxmodel. boxdeÞnethe boxwidth and boxheight ,whiletheinner(content)edgesdeÞnethe content width and contentheight ofthebox. Figure3.18alsogivestheCSSpropertynamescorrespondingtothe12distances be

34 tweenadjacentedgesintheboxmodel.Noticeth
tweenadjacentedgesintheboxmodel.NoticethattheborderpropertieshavethesufÞx -width .ThissufÞxisusedtodistinguishborderpropertiesrelatedtodistancesfromother borderpropertiesthataffectthecolorandstyleofborders(andhavethesufÞxes -color and -style ,respectively).NotethatthesamesufÞxisusedforbothhorizontalandvertical distances,whichcanbeconfusing,sinceintherestoftheboxmodelÒwidthÓnormally referstoahorizontaldistance. border-bottom-width margin-bottom margin- left padding-bottom Content Height Content Width margin-top border-top-width margin- right Box Height Box Width padding-top padding- right padding- left border- right- width border- left- width FIGURE3.18 DeÞnitionofvariouslengthsintheCSSboxmodel. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.7CSSBoxModel 153 html PUBLIC"-//W3C//DTDXHTML1.0Strict//EN" �"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" &#xhtml;&#x-602;xmlns="http://www.w3.org/1999/xhtml" &#xhead; &#xtitl; SpanBoxStyle.html &#x/tit;&#xle00; rel="stylesheet"type="text/css"href="span-box-style.css"&#xlink;&#x-602;/ &#x/hea;퀀 ody; &#xp000; The&#xspan;&#x/spa;&#xn000;spanand&#xspan;&#x/spa;&#xn000;span &#x/p00; &#x/bod;&#xy000; &#x/htm;&#xl000; FIGURE3.19 HTMLdocumentdemonstratingbasicboxmodelstyleproperties. Asasimpleexampleofwhatcanbedonewithwhatwehavealreadylearned(anda fewotherthingsthatwewilllearnshortlyaboutborder-stylepropertyvalues),considerthe followingstylesheet: /*span-box-style.css*/ /*solidisaborderstyle(asopposedtodashed,say).*/ span{margin-left:1cm; border-left-width:10px; border-left-color:silver; border-left-style:solid; padding-left:0.5cm; border-right-width:5px; border-right-color:silver; border-right-style:solid} andassumethatthisstylesheetiscontainedinaÞlenamed span-box-style.css ,asindicated bythecomment.ThentheHTMLdocumentshowninFigure3.19willberenderedbya CSS2-compliantbrowserasillustratedinFigure3.20.Notethatfor span elements,any margin,border,orpaddingdistancethatisnotspeciÞ

35 edbyanauthororuserstylesheetis giventhev
edbyanauthororuserstylesheetis giventhevalue0. FIGURE3.20 Renderingofdocumentdemonstratingbasicstyleproperties. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 154 Chapter3StyleSheets 3.7.2BoxModelShorthandProperties CSS2deÞnesanumberofshorthandpropertiesrelatedtotheboxmodel.Forexample,the declaration padding:30px; isshorthandforfourdeclarations: padding-top:30px; padding-right:30px; padding-bottom:30px; padding-left:30px; Table3.9listsanumberofsuchshorthandpropertiesaswellasthepropertiesalready coveredandgivesforeachpropertyitsallowablevalues.Noneofthepropertiesinthistable isinherited. The auto valuethatcanbeusedwhensettingmarginwidthshasameaningthat dependsonitscontext,sowewilldeferdiscussingittotheappropriatelatersections.IÕll trytoanswerotherquestionsyoumayhaveaboutTable3.9here. First,noticethatÞveofthepropertiesinTable3.9( padding , border-width , border-color , border-style ,and margin )takefromonetofourspace-separatedval- ues.Eachofthesepropertiesisashorthandforspecifyingvaluesforthefour TABLE3.9 BasicCSSStylePropertiesAssociatedwiththeBoxModel PropertyValues padding- { top,right,bottom,left } CSSlength(Section3.6.2). padding Onetofourlengthvalues(seetext). border- { top,right,bottom,left } -widththin , medium (initialvalue), thick ,oralength. border-width Onetofour border-*-width values. border- { top,right,bottom,left } -color Colorvalue.InitialvalueisvalueofelementÕs color property. border-colortransparent oronetofour border-*-color values. border- { top,right,bottom,left } -stylenone (initialvalue), hidden , dotted , dashed , solid , double , groove , ridge , inset , outset . border-style Onetofour border-*-style values. border- { top,right,bottom,left } Onetothreevalues(inanyorder)for border-*-width , border-*-color ,and border-*-style .Initialvalues areusedforanyunspeciÞedvalues. border Onetothreevalues;equivalenttospecifyinggivenvalues foreachof border-top , border-right , border-bottom ,and border-left . margin- { top,right,bot

36 tom,left } auto (seetext)orlength. margi
tom,left } auto (seetext)orlength. margin Onetofour margin-* values. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.7CSSBoxModel 155 TABLE3.10 MeaningofValuesforCertainShorthandPropertiesthatTakeOnetoFourValues Numberof ValuesMeaning OneAssignthisvaluetoallfourassociatedproperties( top , right , bottom ,and left ). TwoAssignÞrstvaluetoassociated top and bottom properties,secondvaluetoassociated right and left properties. ThreeAssignÞrstvaluetoassociated top property,secondvalueto right and left ,andthird valueto bottom . FourAssignÞrstvaluetoassociated top property,secondto right ,thirdto bottom ,andfourthto left . associatedpropertiesthatinclude top , right , bottom ,or left intheirnames.For example, border-style isashorthandforspecifyingvaluesfor border-top-style , border-right-style , border-bottom-style ,and border-left-style .Table3.10showsthe meaningofthevaluesfortheseproperties.Wehavejustseenanexampleofsuchashort- handdeclaration,whenasinglepaddingdeclarationwasequivalenttofourdeclarations. Asanotherexample,thestyledeclaration margin:15px45px30px isequivalentto margin-top:15px margin-right:45px margin-left:45px margin-bottom:30px YoumayalsohaveaquestionabouttheborderstyleslistedinTable3.9.There isnoprecisedeÞnitionformostoftheseborderstyles,sotheirvisualappearancemay varysomewhatwhendisplayedindifferentbrowsers.Forexample,Figure3.21showstwo paragraphs p1 and p2 displayedintwodifferentbrowsersusingthefollowingstylesheet: /*border-styles.css*/ #p1{ background-color:yellow; border:6pxmaroon; border-style:soliddasheddotteddouble } #p2{ border:16pxteal; border-style:grooveridgeinsetoutset } Obviously,youmaywanttoexperimentwiththeseborder-stylevaluesinbrowsersyou aretargetingbeforeusingthesevalues.Alsonotethatbothoftheborderstylevalues P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 156 Chapter3StyleSheets FIGURE3.21 Illustrationofsomeborderstylesindifferentbrowsers. hidden and none effectivelyel

37 iminateaborderfromaboxelement,but hidden
iminateaborderfromaboxelement,but hidden behaves slightlydifferentwithinHTMLtableelementsincertaincircumstances(refertotheCSS2 speciÞcation[W3C-CSS-2.0]fordetails). Finally,youprobablyhavenoticedthatshorthandpropertiesmakeitpossibleto declaremultiplevaluesforasinglepropertywithinasingledeclarationblock.Forexample, thevalueof border-top-style canbespeciÞedbyadirectdeclarationofthispropertyas wellasbydeclarationsforthe border-top and border shorthandproperties.Ifmultiple declarationswithinasingledeclarationblockapplytoaproperty,thelastdeclarationtakes precedenceoveranyearlierdeclarations.So,forexample,inthedeclarationblock {border:15pxsolid; border-left:30pxinsetred; color:blue} P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.8NormalFlowBoxLayout 157 theborderonthetop,right,andbottomwillbe15-px-widesolidblue,whiletheleftborder willbea30-px-wideredinsetstyle.ThisisbecausetheÞrstdeclarationsetsallfourborders to15pxwideandsolid,withthebordercolorsettoitsinitialvalue,whichforborder colorsisthevaluespeciÞedfortheelementÕscolorproperty(blueinthiscase).Thesecond declarationeffectivelyoverridesthesevaluesforthe border-left property. 3.7.3BackgroundColorsandImages The background-color propertyspeciÞesthecolorunderlyingthecontent,padding,and borderareasofanelementÕsbox.Thebackgroundcolorintheborderareawillnormally becoveredbytheborderitself,butwillbevisibleifthebordercolorisspeciÞedas transparent orpartlyvisibleiftheborderstyleis dashed , dotted ,or double (seeFig.3.21). Noticethatthemarginareaisnotaffectedbythebackgroundcolor.Themarginareais alwaystransparent,whichallowsthebackgroundcoloroftheparentelementtobeseenin themarginarea.Strictlyspeaking,the background-color propertyÕsvalueisnotinherited; however,theinitialvalueof background-color is transparent ,andthebackgroundcolor ofanelementwillbevisiblethroughtransparentareasofchildelements.Inotherwords, forCSSboxmodelpurposes,weshouldthinkofthebrowserasrenderingparentelements Þrstandthenrenderin

38 gthenontransparentportionsofthechildelem
gthenontransparentportionsofthechildelementsovertopofthe parents. ArelatedpropertythatisusedinmanyWebpagesis background-image .Theaccept- ablevaluesforthispropertyare none ,theinitialvalue,oraURLspeciÞedusingthesame url() functionalnotationusedwiththe @import stylerule.Bydefault,theimagefoundat thespeciÞedURLwillbe tiled overthepaddingandcontentareasoftheelementtowhich thispropertyisapplied(suchasthe body elementofanHTMLdocument). Tiling simply meansthatifanimageistoosmalltocovertheelement,eitherfromlefttorightorfrom toptobottomorboth,thentheimageisrepeatedasneeded. Like background-color , background-image isnotinherited.Conceptually,theelement towhichthebackgroundimagewillbeappliedisÞrstdrawn,includingitsbackground colorifany.Thenthebackgroundimageisdrawnovertopoftheelement,withtheelement showingthroughanytransparentareasoftheimage.Finally,anychildelementsaredrawn overtopofthebackgroundimage.Thepositioningofabackgroundimageandwhetherit istiledornotcanbespeciÞedusingvariousCSSproperties;seetheCSS2speciÞcation [W3C-CSS-2.0]forcompletedetails. ThisconcludesourdiscussionofthebasicCSSboxmodel.Wenextturntoconsidering howthismodelrelatestosomespeciÞcHTMLelements. 3.8NormalFlowBoxLayout InabrowserÕsstandardrenderingmodel(whichiscalled normalßowprocessing ),every HTMLelementrenderedbythebrowserhasacorrespondingrectangularboxthatcontains therenderedcontentoftheelement.Theprimaryquestionweaddressinthissectionis wheretheseboxeswillbeplacedwithintheclientareaofthebrowser. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 158 Chapter3StyleSheets 3.8.1BasicBoxLayout First,recallthatthe html elementistherootelementofanHTMLdocument.Thebrowser generatesaboxcorrespondingtothiselement,whichiscalledthe initialcontainingblock . TheCSS2recommendationdoesnotspecifythelengths(margin,padding,etc.)ordi- mensions(widthandheight)ofthisbox,butinsteadleavesittoeachbrowsertochoose valuesfortheseparameters.InbothIE6andMozilla1.4,bydefaulttheborder,margin,and paddinglengthsare

39 allzero,sotheinner(content)andouteredges
allzero,sotheinner(content)andouteredgesoftheboxcoincide.As fordimensionsoftheinitialcontainingblockbox,ifthebrowserÕshorizontalandvertical scrollbarsarenotactive,thentheboxcoincideswiththebrowserÕsclientarea,andtherefore hasthesamedimensions.Ontheotherhand,ifeitherscrollbarisactive,thenthetheouter edgesoftheinitialcontainingblockarelocatedattheedgesoftheunderlyingareaover whichthebrowsercanbescrolled.Conceptually,itisasifthedocumentisdrawnonan imaginary canvas .Thebrowserclientareaactsasa viewport throughwhichallorpartof thecanvasisviewed.TheinitialcontainingblockÕsheightisthetotalheightofthiscanvas, ortheheightofthebrowserÕsclientareaifthatisgreaterthanthecanvasheight.Thewidth oftheinitialcontainingblockisdeÞnedsimilarly.Figure3.22illustratestherelationship Paragraph 1: blah blah blah more blah blah blah blah blah blah blah blah blah blah blah blah blah blah Paragraph 2: blah blah blah more blah blah blah blah blah blah blah blah blah blah blah blah blah blah Paragraph 3: Image 2 a span a span Image 1 Canvas Initial Containing Block Browser Client Area FIGURE3.22 Initialcontainingblockboxwhencanvasistallerthanclientareabutclientareaiswiderthan canvas. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.8NormalFlowBoxLayout 159 betweenthecanvas,clientarea,andinitialcontainingblockboxwhenthecanvasistaller thantheclientareabutnotaswide.Notethatifthebrowserwindowisresized,theinitial containingblockÕsboxwillberesizedautomaticallyasneeded. AllotherCSSboxeswithintheclientareaarelaidout(eitherdirectlyorindirectly) relativetotheinitialcontainingblockbox.ForanHTMLdocument,theÞrstsuchboxto beaddedtotheclientareaistheonecorrespondingtothe body element.Becausethe body elementiscontainedwithinthe html element,theboxcorrespondingtothe body element isplacedwithintheinitialcontainingblockbox(whichcorrespondstothe html element). Thisisthedefaultbehaviorforallboxes:ifoneHTMLelementispartofthecontentofa secondHTMLelement,thentheboxcorrespon

40 dingtotheÞrstelementwillbecontained with
dingtotheÞrstelementwillbecontained withinthecontentareaoftheboxforthesecondelement.Thisdefaultbehaviorisknown as normalßow processingofboxes.Thus,ifnormalßowprocessingisusedforanentire HTMLdocument,alloftheboxescorrespondingtoelementswithinthe body elementof thedocumentwillbecontainedwithintheboxgeneratedforthe body ,whichinturnwillbe containedwithintheinitialcontainingblockbox.Inessence,innormalßowprocessing,the blockcorrespondingtothe body elementisthecanvasonwhichboxesforallotherelements willbedrawn. Bydefault,the body boxwillbeplacedsothatitsleft,top,andrightouteredges coincidewiththeleft,top,andrightinner(content)edgesoftheinitialcontainingblock.If thewidthofthebrowserwindowischanged,thenthewidthofthe body boxmaychange aswell,sincethewidthoftheinitialcontainingblockcanchangeautomaticallywhenthe browserwidthchanges.Theheightofthe body box,ontheotherhand,isdeterminedbyits content.Youmightthinkoftheboxasstartingwiththeheightofitscontentareasetto0. Then,asthebrowsergeneratesboxescorrespondingtoelementscontainedwithinthe body , itincreasesthisheightsothatitisjustsufÞcienttocontainallthegeneratedboxes.The heightwhenthisprocessisdonedeterminestheÞnalheightofthecontentareaofthe body elementÕsbox(theoverallheightoftheboxalsodependsonthevaluesofstyleproperties suchas margin-top ). Similarrulesapplytothedefaultplacementofboxeswithinthe body box.Thatis,the ÞrstchildelementÕsboxwillbeplacedsothatitsleft,top,andrightouteredgescoincide withthecorrespondingcontentedgesofthe body box.Theheightofthisboxwillthenbe determinedbygeneratingboxesforalloftheelementscontainedwithintheÞrstelement andlayingtheseboxesoutwithinthisÞrstchildbox(byrecursivelyapplyingthelayout rulesbeingdescribed).ThesecondchildelementÕsboxwillbeplacedsothatitstopouter edgecoincideswiththebottomouteredgeoftheÞrstchildbox(thisisnÕtquitecorrect;see Section3.8.3formoredetails).Theleftandrightedgesofthissecondchildboxwillalso coincidewiththeleftandrightcontentedgesofthe body .ThesecondchildisthenÞlled withallofitsdescendants

41 Õboxes.Thisprocesscontinueswiththeremain
Õboxes.Thisprocesscontinueswiththeremainingchildrenof the body . Figure3.23isanHTMLdocumentthatillustratesthelayoutconceptsdiscussedthus far(Ihaveusedanembeddedstylesheetinthisdocumentandseveralothersinthischapter foreaseofreading,butinpracticeIwouldprobablyhaveusedanexternalstylesheet). Figure3.24showshowMozilla1.4rendersthisdocument(theIE6renderingissimilar, althoughmycopyofIE6incorrectlydrawstheinitialcontainingblockÕsbordersothat italwayscoincideswiththeclientarea,regardlessofhowthebrowserwindowissized). P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 160 Chapter3StyleSheets html PUBLIC"-//W3C//DTDXHTML1.0Strict//EN" �"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" &#xhtml;&#x-602;xmlns="http://www.w3.org/1999/xhtml" &#xhead; &#xtitl; BlockBoxes.html &#x/tit;&#xle00; &#xstyl;-60; type="text/css" html,body{border:solidredthin} html{border-width:thick} body{padding:15px} div{margin:0px;padding:15px;border:solidblack2px} .shade{background-color:aqua} .topMargin{margin-top:10px} &#x/sty;&#xle00; &#x/hea;퀀 ody; iv-;怠id="d1" iv-;怠id="d2" id="d3" iv-;怠&#x/div;class="shade" &#x/div; id="d4"class="shade iv-;怠&#x/div;topMargin" &#x/div; &#x/bod;&#xy000; &#x/htm;&#xl000; FIGURE3.23 HTMLdocumentcontainingnested div elements. Figure3.24showsthebordersofanumberofboxes.Theoutermostborder(thickredborder attheedgesofthebrowserÕsclientarea)isfortheinitialcontainingblockboxgeneratedby the html element.Thethinredborderimmediatelyinsidethe html elementÕsboxbelongs tothe body elementÕsbox.YouÕllnoticethatthe body borderdoesnottouchthe html border. ThisisbecausetheMozilla1.4useragentstylesheetspeciÞesanonzeromarginvalue (apparentlyabout8pxinMozilla1.4and10pxinIE6)forthe body box,andtheembedded authorstylesheetdoesnotoverridethisvalue.Insidethe body blockboxthereisabox withamedium-widthblackbordergeneratedbythe div withID d1 .Insidethisboxaretwo childboxes,oneforeachofthe div childrenof d1 ( d2 and d4 ).Finally,theÞr

42 stofthese childelements( d2 )itselfhasac
stofthese childelements( d2 )itselfhasachild div withid d3 ,whichgeneratesitsownbox.Theboxes forthe div elements d3 and d4 ,whichhavenocontent,aregivenabackgroundcolorin Figure3.24. 3.8.2The display Property ThelayoutrulesdescribedsofaronlyapplytoHTMLelementsthatCSSrecognizesas block elements .TheseareelementsforwhichtheCSS display propertyhasthevalue block .Of theelementscoveredinChapter2,standarduseragentstylesheetswilldeÞnethefollowing HTMLelementsasblockelements: body , dd , div , dl , dt , fieldset , form , frame , frameset , hr , html , h1 , h2 , h3 , h4 , h5 , h6 , ol , p , pre ,and ul .Youmayrecallfromthelastchapterthat P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.8NormalFlowBoxLayout 161 FIGURE3.24 Nestedboxes. weinformallyintroducedtheconceptofblockelementsasthoseelementsforwhichthe browseressentiallygeneratesanewlinebeforeandaftertheelement.Nowweseethatwhat actuallyhappensisthatthebrowserstackstheboxesfortheseelementsoneontopofthe next. CSSdeÞnesanumberofotherpossiblevaluesforthe display property.Many ofthesevaluesareassociatedwithspeciÞcHTMLelements.Forexample,thereisa list-item valuethatisintendedtobeusedasthe display valuefor li elements,a table valueforHTML table elements,anda table-row valuefor tr elements.Infact,nearly everyelementassociatedwiththeHTMLtablemodelhasitsownvalueforthe display property( td and th sharethe table-cell value).Wewillnotdiscussthesevaluesfurther; see[W3C-CSS-2.0]fordetails. Inadditiontotheseandothersomewhatspecializedvaluesfor display ,thereis anothervaluethatissharedbyanumberofHTMLelements: inline .Again,recallfrom thepreviouschapterthatinlineHTMLelementsarethosethatdonotinterrupttheßow ofadocumentbystartinganewlineasblockelementsdo.Examplesofinlineelements were span and strong .Inatypicalbrowser,alloftheHTMLelementsdiscussedinthelast chapterexcepttheblockelementslistedatthebeginingofthissubsection,the li element, andtable-relatedelementswillbetreatedashavingthevalue inline ,whichistheini

43 tial valueforthe display property. Asyou
tial valueforthe display property. Asyoumightexpect,therulesforlayingouttheboxesforelementswitha display valueof inline (whichIÕllrefertoas inlineboxes )aredifferentfromthoseforlayingout boxesforelementswitha display valueof block ( blockboxes ).Infact,howcontentislaid outwithininlineandblockboxesalsodiffers.WeÕllcoversomemoredetailsconcerning blockboxesinthenextfewsectionsandthenlookmorecloselyatinlineboxes. Beforeleavingthissection,letmementionthatanauthorstylesheetcanoverride thedefaultvalueofanelementÕs display propertyjustasanyotherdefaultpropertyvalue P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 162 Chapter3StyleSheets canbeoverridden.Forexample,supposethatanHTMLdocumenthasalargenumberof consecutive p elementsbutthatforsomereasonwewouldlikeÑwithaminimalamountof changetothedocumentÑtohavealloftheseseparateparagraphsinthedocumentdisplayed asone(long)paragraph.Wecanaccomplishthisbyaddingtothedocumentthestylerule p{display:inline} Obviously,thisstylerulesigniÞcantlychangestheexpectedsemanticsofthe p element,so arulesuchasthisshouldbeusedwithsomecaution. 3.8.3MarginCollapse EarlierIsaidthat,roughlyspeaking,consecutiveblockboxesarepositionedoneontopof thenext.IÕllnowexplainwhythisisnÕtexactlythecase. Whentwoconsecutiveblockboxesarerendered(theÞrstontopofthesecond),a specialrulecalled margincollapse isusedtodeterminetheverticalseparationbetweenthe boxes.Asthenameimplies,twomarginsÑthebottommarginoftheÞrst(upper)boxand thetopmarginofthesecond(lower)boxÑarecollapsedintoasinglemargin. SpeciÞcally,let m 1 representthevalueof margin-bottom forthetopbox,andlet m 2 representthevalueof margin-top forthelowerbox.Withoutmargincollapse,thedistance betweenthebordersoftheseboxeswouldbe m 1 + m 2 .Withbordercollapse,thedistance willinsteadbemax( m 1 , m 2 )(seeFig.3.25). 3.8.4BlockBoxWidthandHeight Eachblockelementhasa width property(notinherited)thatdeÞnesthewidthofthecontent areaoftheelementÕsblockbox.Theinitialvalueofthispropertyis auto ,whichproduces

44 thewidth-deÞningbehaviordescribedearlie
thewidth-deÞningbehaviordescribedearlier:theboxwillautomaticallybestretchedhor- izontallysothatitsleftandrightouteredgesalignwiththeleftandrightcontentedgesof itsparentbox.Asanexample,ifthebrowserwindowshowninFigure3.24iswidened,the blockboxesdisplayedinthecontentareawillalsobecomewider(Fig.3.26). Moreprecisely,ifthevalueof width is auto ,andifavalueotherthan auto isspeciÞed forboth margin-left and margin-right (theinitialvalueforthesepropertiesis0),thenfor displaypurposes width willbegiventhevalue width=parent'sdisplayedcontentwidth- (margin-left+border-left-width+padding-left+ padding-right+border-right-width+margin-right) Thisvalueisnotinanywayassociatedwiththe width propertyitself,asaspeciÞedor computedvalueis.Instead,itisusedbythebrowserstrictlyfordisplaypurposes.Sucha valueissometimesreferredtoasapropertyÕs usedvalue . Inadditionto auto ,alengthvaluecanbespeciÞedasthevalueofthe width property ofablockelement.ThelengthvaluecanuseanyoftheunitsdescribedinSection3.6.2. Furthermore,thespeciÞedlengthvaluecanbea percentage ,whichisanumber(integer ordecimal)immediatelyfollowedbyapercentsign( % ).Inthecaseofthe width property, P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.8NormalFlowBoxLayout 163 margin-bottom 1 margin-bottom 1 margin-edge 1 margin-edge 1 margin-edge 2 margin-top 2 border-edge 2 border-edge 2 border-edge 1 border-edge 2 (a) (c) (b) FIGURE3.25 (a)Ablockbox(onlymarginandborderedgesareshown).(b)Asecondblockboxwith margin- top smallerthan margin-bottom ofÞrstbox.(c)Firstandthensecondboxesrendered,illustratingmargin collapse. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 164 Chapter3StyleSheets FIGURE3.26 BlockBoxes.html displayedinawiderwindow. thisrepresentsapercentageofthewidthoftheparentelementÕscontentarea,ormore precisely,apercentageoftheusedvalueassociatedwiththecontentwidth.Forexample, thedeclaration width:50% saysthatthewidthofthecontentareaofaboxshouldbehalfthe(used)widthoft

45 hecontent areaofitsparentbox.Percentages
hecontent areaofitsparentbox.PercentagescanalsobeusedwithmanyotherCSSpropertiesthat takealengthvalue,althoughthelengthtowhichthepercentageisappliedvariesfrom propertytoproperty.SeetheCSS2recommendation[W3C-CSS-2.0]fordetailsregarding propertiesnotexplicitlymentionedinthischapter. Youmightexpect(Ididinitially)thatthepercentage width declarationwouldcause anassociatedelementtobecenteredwithintheparentbox.However,thisisnotthecase bydefault.Instead,theelementwillappearleft-justiÞedwithinitsparentbox.Inessence, whenonlythe width isspeciÞedforanelement,thebrowsercomputesausedvalueforthe margin-right propertyoftheelementÕsboxsothattheoverallwidthofthebox(sumofthe elementwidthplusleftandrightmargins,borders,andpaddings)isequaltothewidthof itsparentÕscontentarea.The margin-left ,however,isunchanged.Tocenteranelement, inadditiontospecifyingavaluefortheelementÕs width property,thevalue auto shouldbe speciÞedforboththe margin-left and margin-right propertiesoftheelement.Thebrowser willthenuseasinglevalueforbothmargins,withtheusedvaluebeingcomputedsothat theborders(butnotnecessarilythecontent)oftheboxwillbecenteredwithinthecontent areaoftheparentbox. So,forexample,assumethatwecreateanHTMLdocument BlockBoxesWidth. html fromtheearlier BlockBoxes.html example(Fig.3.23)byaddingthefollowingtwo rulestotheembeddedstylesheet: P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.8NormalFlowBoxLayout 165 #d3{width:50%} #d4{width:50%;margin-left:auto;margin-right:auto} Notethattheseruleswilloverridethedeclarationshavingelementselector div ,dueto thehigherspeciÞcityofIDselectors.Thenew BlockBoxesWidth.html documentwillbe renderedasshowninFigure3.27.Noticethatalthoughbothoftheshadedboxeshave speciÞedwidthsof 50% ,theiractualwidthsaredifferentbecausethepercentageisapplied toparentboxesthathavedifferentcontentwidths.Also,keepinmindthatthevalueofthe width propertydeÞnesthewidthofthecontentareaofabox.Thus,theshadedboxesare bothwiderthanhalfthewidthoftheirparentsÕconte

46 ntareas,becauseeachboxincludesa totalof3
ntareas,becauseeachboxincludesa totalof30pxofhorizontalpadding(15pxforeachside)inadditiontothecontentarea. Ingeneral,thevalue auto canbespeciÞedforanycombinationof width , margin-left ,and margin-right .Forexample,ifforagivenbox margin-left is auto , width isaspeciÞedlength,and margin-right is0,thentheboxwillberight-justiÞed withinitscontainingblock.SeetheCSS2recommendation[W3C-CSS-2.0]forde- tailsonhowCSSinterpretsotherpossiblecombinationsforvaluesofthesethree properties. Blockboxesalsohavea height property(notinherited)withaninitialvalueof auto . Aswiththe width property,thedefaultblockboxheightcalculationdescribedearliercanbe overriddenbyspecifyingavalue(lengthwithunitsorpercentage)fortheblockelementÕs height property.IfapercentageisspeciÞed,itisinterpretedasapercentageofthevalue (ifany)speciÞedfortheparentblockÕs height property.IfnovaluewasspeciÞedforthe parentÕs height ,thenthepercentagespeciÞcationisessentiallyignoredandtreatedasa speciÞcationof auto . WeÕrenowreadytoconsiderhowinlineboxesarerenderedwithinablockbox. FIGURE3.27 RenderingwhenwidthsofshadedboxesarespeciÞedaspercentages.Lowerboxiscentered becauseleftandrightmarginsare auto . P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 166 Chapter3StyleSheets 3.8.5SimpleInlineBoxes Untilnow,wehavethoughtofblockboxesaseithercontainingtext(ormoreprecisely,a stackoflineboxescontainingcharactercells)orcontainingotherblockboxes.Butablock elementcanalsocontaininlineelements,suchas span and strong ,andthebrowserwill generateinlineboxescorrespondingtotheseelements.Theseinlineboxeswillbeadded tolineboxeswithinthecontainingblockbox,muchliketextcharacters.Infact,wehave alreadyseenanexampleofthisinFigure3.20.Inthissection,wewilllookmoreclosely athowbrowserslayout simpleinlineboxes ,thatis,boxesforinlineelementsthatcontain onlytextorthatareoftype img .WeÕllbrießyconsidermorecomplexinlineelementsinthe nextsection. WewillÞrstconsidersimpleinlineboxesconsistingoftext,generatedbyelements suchas &#xspan;

47 &#x-602;&#x/spa;&#xn000;style="font-size
&#x-602;&#x/spa;&#xn000;style="font-size:36pt"BIG Theheightofthecontentareaofsuchaboxwillbedeterminedexactlyastheheightof alineboxisdetermined:theheightofacharactercell(intheinlineelementÕsfont)will beusedunlesstheinlineelementÕs line-height propertyhasavalueotherthan normal , inwhichcasethisvaluewilldeterminethecontentareaheight.Characterglyphsarethen addedtothecontentareaoftheinlineboxasiftheywerebeingaddedtoalinebox,with half-leadingaddedifneededtocenterthecharactercellsvertically.Notethatthisprocess deÞnesabaselinefortheinlinebox:itisatthebaselineheight(asdeÞnedbytheinline elementÕsfont)abovethebottomedgeofthecontentareaoftheinlinebox.Wetherefore nowhaveaboxthathasawell-deÞnedheight(theheightofthecontentarea),width(the overallwidthofthebox,includingleftandrightpadding,border,andmarginlengths),and baselineheight.Theseareessentiallythesamecharacteristicsthatacharactercellhas,sothe browsercanaddthisinlineboxtoalineboxasifitwereacharactercell,verticallyaligning thebaselineoftheinlineboxwiththebaselineofthelinebox.Iftheinlineboxistoolong toÞtwithinthecurrentlinebox,itmaybebrokenonwordboundariesintoasequenceof shorterinlineboxesthatwilleachbeaddedtoaseparatelinebox.Ifthetoporbottomof aninlineboxextendsbeyondthecorrespondingedgeofthelinebox,thelineboxheight willautomaticallybeexpandedasneededtocontaintheinlinebox.Ifthelineboxheightis extendedupward,thenthelineboxwillbemoveddownwithinthecontainingblockboxby thesameamountsothatthelineboxeswithintheblockboxwillstilleffectivelybestacked oneontopoftheother(Fig.3.28). Youprobablynoticedthatthereisanasymmetryinhowtheheightandwidthofthe ÒcharacterÓrepresentationofaninlineboxaredetermined.SpeciÞcally,theheightofthis ÒcharacterÓisdeterminedbythecontentheightoftheinlinebox,butthewidthisdetermined bytheoverallboxwidth.Toillustrate,supposewechangethe d3 elementofthedocument ofFigure3.23asfollows: id="d3" iv-;怠class="shade" Hereare style="border:dottedsilver&#xspan;&#x-602;&#x/spa;&#xn000;10px"some linesoftext. &#x/div; P1:OSO/OVYP2:OSO/OV

48 YQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jack
YQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.8NormalFlowBoxLayout 167 Some letters. BIG inline box line boxes FIGURE3.28 Twolineboxes,thetopboxcontaininganinlineboxwithalargerfontsizethanthetextelsewhere inthelineboxes.Noticethatthebaselinesarealignedinthetoplineboxandthatthelineboxesstackdespite havingdifferentheights. ThenthedocumentwillberenderedasinFigure3.29.NoticethatthewordÒsomeÓis movedtotherighttomakeroomfortheborder,butthelineheightisunchanged,andin facttheborderoverlapssomewhatthetextinthesecondlinebox. Theothertypeofsimpleinlineelementisan img .An img elementissimilarlytreated, forrenderingpurposes,asacharactertobeaddedtoalinebox.However,theheightand widthoftheÒcharacterÓarethevaluesspeciÞedforthe height and width propertiesof theelement(or,ifthesepropertiesarenotspeciÞed,thevaluesofthe height and width attributes,or,ifthesevaluesarealsonotprovided,thenvaluescontainedwithintheimage Þleitself).Thebaselineheightofanimageisalwaysconsideredtobe0.Therefore,the bottomoftheimagewillcoincidewiththebaselineofthelinebox.Aswithinlineboxes, ifthetopofan img boxextendspastthetopofthelinebox,thentheheightofthelinebox FIGURE3.29 Aspanelementwithaborderisaddedtothetext. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 168 Chapter3StyleSheets willbeincreasedtoÞt.Unlikeotherinlineelements,theborder,margin,andpaddingofan img elementareconsideredpartoftheheightoftheimageforpurposesofdeterminingthe heightofalineboxcontainingtheimage. Thedefaultverticalplacementofaninlineboxwithinalineboxcanbeoverrid- denbyspecifyingavalueforthe vertical-align property(notinherited)oftheele- mentgeneratingtheinlinebox.Theinitialvalueof vertical-align is baseline ,which producesthedefaultbehaviordescribed.Someotherpossiblevaluesare text-bottom , whichalignsthebottomoftheinlineboxwithwherethebottomofanycharactercell writtenintothelineboxwouldbelocated; text-top ,whichissimilarexceptitaligns thetopoftheinlineboxwiththetopofthelocationforcharact

49 ercells;and middle , whichalignstheverti
ercells;and middle , whichalignstheverticalmidpointoftheinlineboxwiththe character middleofthe linebox,alocationthatisone-halftheexheightabovethebaselineofthelinebox.The CSS2recommendationspeciÞesseveraladditionalkeywordvaluesfor vertical-align , butmycopyofIE6doesnotseemtohandlethemproperly,soIwillnotcoverthem here. Inadditiontothesekeywords,thevaluespeciÞedfor vertical-align canbealength orapercentage(ofthevalueofthe height ofan img elementorthe line-height ofanyother inlineelement).ForbothpercentageandlengthspeciÞcations,apositivevalueindicates thattheinlineboxshouldberaisedbythespeciÞeddistancerelativetothedefaultbaseline position,andanegativevalueindicatesthatitshouldbelowered. 3.8.6NestedInlineBoxes Howaretextandboxeslaidoutwithinaninlineelement?Wewillconsiderthestandard caseforHTML,inwhichaninlineelementcontainsonlytextandotherinlineelements (seetheCSSspeciÞcation[W3C-CSS-2.0]fordetailsonhowablockboxishandledwithin aninlinebox). Actually,thelayoutofinlineboxesandtextwithinaninlineboxisessentiallyidentical tothelayoutofinlineboxesandtextwithinalinebox.Inparticular,thecontentareaof thecontaininginlineboxistreatedasalineboxthatinitiallyhasaheightandbaseline locationdeÞnedbythefontand line-height propertiesofthecorrespondinginlineelement. Charactersandboxesarethenaddedtothiscontentareajustastheywouldbetoaline box,includinghavingtheverticalalignmentofboxesdeterminedbythe vertical-align property.Onedifferenceisthattheheightofthecontentareaisnotadjustedtocontain inlineboxeswhosetoporbottomedgesextendbeyondtherespectiveedgesofthecontent area.However,whentheseboxesareeventuallytransferredfromthecontentareatoaline box,thatlineboxÕsheightwillbeadjusted.Forexample,changingthe d3 elementofthe documentofFigure3.23to id="d3" iv-;怠class="shade" Herearesomelinesoftext. This &#xstro;&#xng-6;∗&#x/str;&#xong0;style="line-height:3"bold wordhasaline-heightof3. &#x/div; P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.9BeyondtheNormalFlow 169

50 FIGURE3.30 Effectofsetting line-height o
FIGURE3.30 Effectofsetting line-height onaninlineelement(thewordÒboldÓ). causesthebrowsertoincreasetheheightofthelineboxcontainingthewordÒbold,Óas showninFigure3.30.However,theheightsofotherlineboxesarenotaffected. 3.9BeyondtheNormalFlow WhatwehavedescribedsofaristhedefaultwayinwhichabrowserwillformatanHTML document.Inthissection,weÕlllearnthatthereareseveralCSSalternativestothenormal ßowprocessingwehaveseensofarthatcanbeusedtocontrolthepositionofboxes withinabrowserwindow.Threealternativestonormalßowpositioningsupportedbyboth Mozilla1.4andIE6are:relativepositioning,inwhichthepositionisalteredrelativetoits normalßowposition;ßoatpositioning,inwhichaninlineelementmovestoonesideor theotherofitslinebox;andabsolutepositioning,inwhichtheelementisremovedentirely fromthenormalßowandplacedelsewhereinthebrowserwindow. WeÕlllookateachofthesethreepositioningschemesindetailinSections3.9.2Ð3.9.4. First,though,weÕllbrießylearnabouttheCSSpropertiesusedtoindicatewhetherornota boxshoulduseanalternativepositioningscheme. 3.9.1PropertiesforPositioning ThetypeofpositioningforanelementisdeÞnedbyspecifyingtwostyleproperties. The position propertytakesthevalue static (theinitialvalue)toindicatenormalßow, relative and absolute torepresenttherespectiveßowpositionings,or fixed ,whichisa specialtypeofabsolutepositioningdiscussedintheexercises.The float propertycanbe setforelementswitheither static or relative speciÞedfor position .Possiblevaluesfor P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 170 Chapter3StyleSheets FIGURE3.31 HTMLdocumentusingrelativepositioningtonudgetexttotheleft. float are none (theinitialvalue), left ,or right .Thelattertwovaluesindicatethattheele- mentÕsboxshouldmovetothefarleftorfarrightsideofthecurrentlinebox,respectively. Neither position nor float isaninheritedproperty. Anyelementwitha position valueotherthan static issaidtobe positioned .If the position valueofapositionedelementis absolute or fixed ,thenitissaidtobe absolutelypositioned ;o

51 therwiseitis relativelypositioned .Four(
therwiseitis relativelypositioned .Four(noninherited)properties applyspeciÞcallytopositionedelements: left , right , top ,and bottom .Eachofthese propertiestakesavaluethatiseitheralength,apercentage,orthekeyword auto (theinitial value).Themeaningofthesepropertiesisexplainedforeachpositioningschemeinthe followingSections3.9.2Ð3.9.4. 3.9.2RelativePositioning Relativepositioningisusefulwhenyouwanttonudgeaboxabitfromthepositionwherethe browserwouldnormallyrenderit,andyouwanttodosowithoutdisturbingtheplacement ofanyotherboxes.Thatis,allotherboxesarepositionedasifthenudgedboxhadnever moved. Forexample,supposethatyouwereaskedtoproducetherenderedHTMLdocument showninFigure3.31.NoticethattheÞrstletterofeachofthewordsÒRed,ÓÒYellow,Óand ÒGreenÓhasabackgroundthatispartlyshadedandpartlynot.Thisisnotaneffectthatwe wouldexpecttoproduceinthenormalßowprocessingmodel.Butwithrelativepositioning, itÕseasy:weuseastylerule .right{position:relative;right:0.25em} andwrapeachwordtobemovedina span thatspeciÞes right forthevalueofits class attribute.AsasidebeneÞt,wegetalittlemoreseparationbetweeneachwordandtheshaded boxtoitsrightthanwewouldhavehadinnormalßowprocessing,sincethelocationsof theseboxesisnotaffectedbytherelativeshiftingofthewords. Noticethatforrelativelypositionedboxes,apositivevalueforthe right property movestheboxtotheleftbythespeciÞedamount.Youcanthinkofthisasaddingspaceto therightmarginofthebox.Recallthattheinitialvalueof left is auto ;inthisexample,the correspondingcomputedvalueforthe left propertywillbe Š 0.25em.Alternatively,ifthe stylerulehadbeen .right{position:relative;left:-0.25em} P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.9BeyondtheNormalFlow 171 thenthebrowserwouldhavedisplayedthesamerenderingand left and right wouldhave hadthesamecomputedvaluesastheydidwiththeoriginalstylerule.If,forsomereason, both left and right havespeciÞedvaluesotherthan auto ,thenthevalueof left willbe usedforthepositioning,andthecomputedvalueof right willbe

52 settothenegativeofthe valueof left (assu
settothenegativeofthe valueof left (assuming direction is ltr ).Similarrulesapplyto top and bottom ,with top ÒwinningÓifbothpropertieshavenon- auto values. 3.9.3FloatPositioning Floatpositioningisoftenusedwhenembeddingimageswithinaparagraph.Forexample, recallthattheHTMLmarkup &#xp000; src="http://www.w3.org/Icons/valid-xhtml10" alt="ValidXHTML1.0!"height="31"width="88" style="float:right"�/ See -60; href="http://www.w3.org/TR/html4/index/elements.html"the W3CHTML4.01Element&#x/a00;Index foracompletelistofelements. &#x/p00; ispartofthedocumentdisplayedinFigure2.13.The float:right declarationcausesthe imagetobetreatedspeciallyinseveralways.First,theimageisnotaddedtoalinebox. Instead,thewidthsofoneormorelineboxesareshortenedinordertomakeroomforthe imagealongtherightcontentedgeoftheboxcontainingthelineboxesandimage(the blockboxgeneratedbythe p element,inthiscase).TheÞrstshortenedlineboxistheone thatwouldhaveheldtheimageifithadnotbeenßoated.Subsequentlineboxesmayalso beshortenedifnecessarytomakeroomfortheimage.Lineboxesbelowtheßoatedbox extendtothefullwidthofthecontainingblock,producingavisualeffectoftextwrapping aroundtheßoatedblock(Fig.3.32). FIGURE3.32 Wrappingoftextaroundaßoatedbox. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 172 Chapter3StyleSheets ThemarkupusedtogeneratethisÞgureincludesthefollowing: &#xstyl;-60; type="text/css" .bigNum{float:left;font-size:xx-large;font-weight:bold} &#x/sty;&#xle00; ... &#xp000; Thistextisgoingtowrap aroundthe &#xspan;&#x-602;&#x/spa;&#xn000;class="bigNum"I.  bigRomannumeral embeddedwithintheparagraph,becausethenumeralisfloated. &#x/p00; Noticethat,unlikearelativelypositionedbox,thewordsÒtheÓandÒbigÓarenotseparated bythewidthoftheßoated span thatseparatesthesewordsinthesourcedocument.Inother words,portionsofthisdocumentthatarepartofthenormalßowareformattedasifthe ßoatedelementwerenotpresentatall(exceptforitseffectonthewidthoflineboxes).We saythatßoatboxesare removedfromthenormalßow

53 toindicatethatmakingthemßoat hasanimpact
toindicatethatmakingthemßoat hasanimpactonhownormalßowelementsarerendered. Onesmalldetailaboutßoatedboxesisthataßoatedinlineboxbecomesablockbox fordisplaypurposes;thatis,aninlineboxÕs display propertywillhaveacomputedvalue of block iftheboxisßoated.Thismeans,forexample,thatvaluescanbespeciÞedforthe height and width ofaßoatedinlineelement. Formoredetailsonßoatpositioning,suchaswhathappenswhenmultipleßoated boxestouchoneanotherorwhenßoatedinlineboxesextendbelowtheircontainingblock, seetheCSS2speciÞcation[W3C-CSS-2.0]. 3.9.4AbsolutePositioning Absolutepositioningofferstotalcontrolovertheplacementofboxesonthecanvas.This powershouldbeusedwithcare:whileyoucancreateinterestingvisualeffectsthisway, anyinformationconveyedbytheseeffectswillgenerallynotbeavailabletouserswhoare accessingthedocumentinotherways(text-basedbrowsing,speechsynthesis,etc.).That said,therearecertaintimeswhenitisusefultobeabletoplaceaboxexactlywhereyou wantit. Forexample,supposethatyouwouldliketobeabletoeasilyaddmarginalnotesto theleftofparagraphsinanHTMLdocument,asshowninFigure3.33.SpeciÞcally,youÕd liketobeabletoembedeachnotewithintheparagraphtowhichitapplies,asin &#xp000; Thissecondparagraphhasanote. &#xspan;&#x-602;class="marginNote"Thisnoteisprettylong,so itcouldcause&#x/spa;&#xn000;trouble... &#x/p00; Thenyouwouldlikethebrowsertoautomaticallyplacethenotenexttotheparagraph, startingverticallyatthetopoftheparagraph. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.9BeyondtheNormalFlow 173 FIGURE3.33 Absolutepositioningusedtocreatemarginalnotes. Thiscanbedoneeasilyusingabsolutepositioning.Whenaboxisabsolutelyposi- tioned,asindicatedbyspecifying absolute forthe position property,the left , top , right , and bottom propertiescanbeusedtoplacetheboxrelativetoacontainingblock.The con- tainingblock forpurposesofabsolutepositioningisdeÞnedasfollows.First,welocatethe nearestpositionedancestoroftheabsolutelypositionedelement(recallthatapositioned elementhas position valueothert

54 han static ).Ifthisancestorisablockeleme
han static ).Ifthisancestorisablockelement(which wewillassume;seetheCSS2recommendationforotherpossibilities),thenthecontaining blockisformedbythepaddingedgeoftheelementÕsbox, not thecontentedgeasyou mightexpect(thenextexamplewillshowwhythisisagoodchoiceofedge).Ifthereisno positionedancestor,thentheinitialcontainingblockisusedasthecontainingblock. Similartorelativepositioning,specifyingavaluesuchas 10em forthe left prop- ertyofanabsolutelypositionedboxtellsthebrowsertopositiontheleftouteredgeof thatbox10emstotherightoftheleft(padding)edgeofthecontainingblock.Positive valuesfortheotherthreepositioningpropertieshavesimilareffects,whilenegativeval- uesforthesepropertieshavetheoppositeeffects(e.g.,anegativevalueof left moves theboxtotheleftratherthantotheright).Likeßoats,iftheboxofaninlineelement ispositionedabsolutely,theboxbecomesablockbox,andthereforecanhaveitswidth setexplicitly. Inourmarginalnoteapplication,wewouldlikeeachnotetobepositionedstarting verticallyatthetopoftheparagraphcontainingthenoteandhorizontallytotheleftofthe paragraph.Thismeansthatwewanttheparagraphscontainingnotestobepositioned,so thattheycanactascontainingblocksforabsolutelypositionedelements.Also,wewantto leaveroomnexttoparagraphsforthenotes.Sowewillusethestylerule p{position:relative;margin-left:10em} P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 174 Chapter3StyleSheets Inrelativepositioning,ifnovalueisspeciÞedfor left ortheotherpositioningproperties, thentheelementisnotmoved.Sothe position:relative declarationhasnovisibleeffect. Instead,itmarks p elementsaspositioned,makingthemeligibletoactascontainingblocks forabsolutelypositionedelements. Theruleforthe marginNote classislonger,butnotparticularlydifÞculttounderstand. Theruleis .marginNote{position:absolute; top:0;left:-10em;width:8em; background-color:yellow} Thissaystoputanyboxbelongingtothe marginNote classandthatiscontainedwithina p elementwherewehavesaidwewouldlikeitplaced:beginningtotheleftofthetoplineof thepara

55 graph.Noticethat,forthegivenstylerules,t
graph.Noticethat,forthegivenstylerules,theouterleftedgeofa marginNote box willcoincidewiththeouterleftedgeofthe p elementcontainingthe marginNote element, regardlessofthepaddingvalueofthe p element(andassumingthatthe p elementhasno border).Youcannowseeanadvantagetopositioningtheboxrelativetothepaddingedge ofthecontainingelementratherthanthecontentedge:wedidnothavetoaddinthepadding distanceinordertoplaceournoteinthemargin. Aswithßoatpositioning,elementsthatareabsolutelypositionedareremovedfrom thenormalßow.Thiscanbeseenfromthefactthatthereisnoadditionalspacebetweenthe secondandthirdparagraphsintheÞgure.Incontrastwithßoatboxes,however,thenormal ßowwillnotßowaroundabsoluteboxes.Infact,absoluteboxeswillnotßowaroundone another,either.Forexample,ifwewidenthebrowserwindowsothatthesecondparagraph Þtsonasingleline,thetwomarginalnoteboxescollideandthesecondobscuressomeof thetextoftheÞrst(Fig.3.34).Thisisanotherreasontouseabsolutepositioningwithcare. 3.9.5Positioning-RelatedProperties AfewadditionalCSSpropertiesdeservementioninrelationtopositioning.TheÞrstofthese isrelatedtotheoverlayphenomenonthatwehavejustdiscussedwithabsolutepositioning. FIGURE3.34 Absolutelypositionedboxescanobscureoneanother. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.9BeyondtheNormalFlow 175 FIGURE3.35 Anoverlayofoneboxontopofanother. Theremaybetimeswhenyouwantseveralboxestooverlieoneanother,atleastpartially, butyouwanttobecertainthattheyoverlieinacertainorder.Forexample,youmaywant oneboxtobedrawnÞrst,thenasecondboxtobedrawnasanoverlayovertopofthe Þrstbox,possiblyobscuringsomeoralloftheÞrstbox.Figure3.35illustratesthis:abox containingtextisdrawnÞrst,andthenanemptybox(basicallyjustaborder)isdrawnover topofthetextbox. The z-index propertycanbeusedtodeÞneadrawingorderforpositionedboxes.In itssimplestform,therootelementofeachpositionedboxisassignedaninteger z-index value(thisassumesthatnormalßowisfollowedforallofthedescendantsofapositioned box).Ifthisisdone,thendrawingwi

56 llproceedasfollows.First,theboxwiththemo
llproceedasfollows.First,theboxwiththemost negative z-index value(ifany)willbedrawn.Otherboxeswithnegative z-index values willthenbedrawnontopofthisbox,proceedinginascendingorder,untiltheboxwiththe negativevalueclosestto0hasbeendrawn.Atthispoint,alloftheelementsthatarenot positionedaredrawn.Finally,allelementswithpositive z-index valuesaredrawn,again inascendingorder.ThefulldeÞnitionof z-index ,includinghowtiesarebrokenbetween elementswiththesame z-index value(ornovalueatall)iscontainedinSection9.9.1of theCSS2speciÞcation.Butformostpurposes,thesimpleuseof z-index describedshould besufÞcienttoguaranteethedrawingorderyouwant. ToproducetheeffectshowninFigure3.35,Iusedthefollowingstylerules: #text{position:absolute;top:10px;left:10px; font-family:"Courier",monospace;letter-spacing:0.1ex; background-color:yellow; z-index:1} #overlay{position:absolute;top:10px;left:10px; width:1.1ex;height:4.5em; border:solidred1px; z-index:2} TheÞrstruleisappliedtoa div containingthetext,andthesecondtoanempty div .The keyitemtonoticeisthatthe z-index valueofthesecond div isgreaterthanthatoftheÞrst, sothesecond div isdrawnontopoftheÞrst. Wediscussedthe display propertyearlier,butithasakeywordvaluethatwedidnot cover.Specifying none forthevalueof display tellsthebrowserto,fordisplaypurposes, treattheelementandallofitsdescendantsasiftheydidnotexist.Inotherwords,the P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 176 Chapter3StyleSheets elementiseffectivelyremovedfromthenormalßowandisalsonotdisplayedelsewhere. Thisissometimesusedwithscriptingtoallowportionsofadocumenttobeeasilyadded toorremovedfromthebrowserwindow. TheÞnalproperty, visibility ,isrelated.Ifthevalueofthispropertyis hidden ,then theelementanditschildrenÑexceptthosethatspecify visible forthispropertyÑwillnot berendered.However,muchaswithrelativepositioning,thespaceoccupiedbytheelement willremainrendered.Inotherwords,whetheranelementisvisibleornotdoesnotaffectthe renderingofothernondescendantelements.Like d

57 isplay ,thispropertyisgenerallyused insc
isplay ,thispropertyisgenerallyused inscriptingcontexts. 3.10SomeOtherUsefulStyleProperties WhilewehavecoveredasigniÞcantportionoftheCSS2speciÞcation,wehavealsoomitted anumberofdetailsandquiteafewproperties.Afewoftheremainingitemsarecoveredin thissection. 3.10.1Lists The list-style-type propertycanbeusedtovarythedefaultstylesusedforbulletedand numberedlistitems.InHTML,thispropertynormallyonlyappliestothe li elementtype. However,itisinherited,socanbesetonaparent ol or ul elementinordertoaffectthe styleofallofthatelementÕschildren.Forbulletedlists,thevalues disc , circle ,and square maybespeciÞed.Fornumberedlists,someofthenormalvaluesare decimal (1,2,...), lower-roman (i,ii,...), upper-roman (I,II,...), lower-alpha (a,b,...),and upper-alpha (A,B,...).Avalueof none canalsobespeciÞedtoindicatethatno marker (leadingbullet ornumber)shouldbegeneratedforan li element. Arelated li elementtypepropertyis list-style-image ,whichhasaninitialvalue of none .IfaURIisspeciÞedforthisproperty(usingthe url("...") syntaxdescribedin Section3.3),andifanimagecanbeloadedfromthisURI,thenthisimagewillbeusedin placeofthenormalmarkerasspeciÞedby list-style-type .Onceagain,thispropertyis inheritedandisoftensetonparentelementsratherthandirectlyon li elements. The list-style-position propertycanbeusedtochangethelocationofthemarker relativetothecontentofan li .Abrowsernormallygeneratestwoboxesforan li : aspecialboxtoholdthemarker,andablockboxtoholdtheelementcontent.If list-style-position hasitsinitialvalueof outside ,themarkerboxisoutsidethecontent blockbox.However,ifthevalueisspeciÞedas inside ,thentheboxgeneratedforthe markerwillbetheÞrstinlineboxplacedwithinthecontentblockbox.Thevisualeffectin thiscasewillbethattheÞrstlineofthelistitemcontentisindentedtomakeroomforthe marker. Finally,theshortcutproperty list-style canbeusedtospecifyvaluesforanyorall ofthementionedproperties,inanyorder. 3.10.2Tables Forthemostpart,theboxmodelpropertiesdiscussedinthischapter,suchas border-style and padding ,canbeusedwitheleme

58 ntsrelatedtotables( table , td ,etc.),al
ntsrelatedtotables( table , td ,etc.),althoughtheir effectontableelementsmayvaryslightlyfromtheireffectwithotherboxes.Furthermore, P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.11CaseStudy 177 thevalues top , bottom , middle ,and baseline maybespeciÞedforthe vertical-align propertyof td and th elements.A top valuecausesthetopofthecontentofthecellto coincidewiththetopoftherowcontainingthecell, bottom makesthebottomofthecontent coincidewiththerowbottom,and middle centersthecontentwithintherow.Ifmultiple cellsspecify baseline ,thenthebaselinesoftheirÞrstlinesoftextwillbealignedwithone another.If baseline isspeciÞedforacellcontainingasingle img element,thenthebottom oftheimageistreatedasthebaselineofthecellforalignmentpurposes.The baseline cells aredisplayedashighaspossiblewithintherowwhilekeepingthecontentofallcellswithin therow. CSS2alsospeciÞestwodifferentmodelsforhowbordersshouldbehandled:a separate modelinwhicheachcellhasitsownborder,anda collapse modelinwhich adjacentcellbordersmaybecollapsedintoasingleborder.Theuseragentstylesheetsfor bothMozilla1.4andIE6apparentlyspecifytheseparatemodelasthedefault.Youcan overridethedefaultbyassigningavalueof collapse or separate tothe border-collapse stylepropertyofa table element.FulldetailsofCSSsupportfortablesarewellcov- eredinChapter17oftheCSS2speciÞcation,whichshouldnotbehardtounder- standifyouhavemasteredthematerialinthischapter.SoIwillnotcovertables furtherhere. 3.10.3CursorStyles CSSspeciÞesanumberofdifferentcursorstylesthatcanbeused.Theinitialvaluefor the cursor propertyis auto ,whichallowsthebrowsertochooseacursorstyleasitdeems appropriate.Mozilla1.4,forexample,willdisplayatextcursorwhenthemouseisovertext, apointingÞngerwhenoverahyperlink,anarrowandhourglasswhenalinkisclickedanda newdocumentisloading,andanarrowinmostothercontexts.Otherkeywordsthatcanbe usedtospecifyavalueforthe cursor propertyinclude default (oftenanarrow), text (used overtextthatmaybeselected), pointer (oftenusedove

59 rhyperlinks),and progress (often usedwhe
rhyperlinks),and progress (often usedwhenalinkisclicked).Someotherkeywordsproducecursorsthatwouldnormally beseenoutsidethebrowserclientarea,suchas move (usedtoindicatewindowmovement), variousresizingarrows( e-resize , ne-resize , sw-resize ,andothercompasspoints), wait (program-busy,oftenanhourglass),and help (oftenanarrowwithaquestionmark). Likesomeotherproperties, cursor isnormallyusedbyscriptsrunningwithinthe browser,atopiccoveredinChapter5. 3.11CaseStudy WeÕllnowcreateastylesheetsuitableforourbloggingapplicationandalsomodifyourpre- viousview-blogdocument,formattingitusingstylepropertiesratherthantables.Forcolors, fonts,andtoalesserextentspacing,ourstylesheetwillbesimilartotheOldstylestylesheet availableaspartofW3CÕsCoreStylesproject( http://www.w3.org/StyleSheets/Core/ ), givingusanopportunitytoseesomereal-worldstyling(andsomethingthatlooksmuch betterthananythingIwouldhaveproduced).Ultimately,thestylesheetandmarkupchanges presentedinthissectionwilltransformtheview-blogpagefromthatshowninFigure2.31 tothatshowninFigure1.12. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 178 Chapter3StyleSheets /*TheW3CCoreStyles,Copyright C  1998W3C(mit,inria,Keio).All RightsReserved.W3Cliability,trademark,documentuseandsoftware licensingrulesapply.See http://www.w3.org/Consortium/Legal/ipr-notice.html ThisisamodifiedversionoftheOldstylestylesheetavailable athttp://www.w3.org/StyleSheets/Core/ AlistofmodificationsmadetotheoriginalOldstylestylesheetis athttp://www.mathcs.duq.edu/jackson/webtech/OldstyleMods.txt*/ /*Elements*/ body { background-color:#fffff5; font-family:"Verdana","MyriadWeb","Syntax",sans-serif; font-size-adjust:.58; margin:1.5em5%; } p { margin-top:.75em; margin-bottom:.75em; } h1 { font-family:"Georgia","MinionWeb","Palatino", "BookAntiqua","Utopia","TimesNewRoman", serif; font-size-adjust:.4; font-size:2.0em; font-weight:600; color:#C00; } hr { height:1px; background-color:#999; border-style:none; } FIGURE3.36 Stylerulesfornonan

60 chorelements. Thestylesheetruleswecreate
chorelements. ThestylesheetruleswecreatewillallbestoredinaÞlenamed style.css .Eachof theHTMLdocumentsfortheapplicationwillbemodiÞedtoincludethisstylesheetÞle usingmarkupsuchas rel="stylesheet"href="style.css"type="text/css"&#xlink;&#x-602;/ inthe head elementofthedocument.NotethattherelativeURLusedinthe href attribute assumesthattheHTMLÞlesand style.css Þleallresidewithinthesamedirectory. Figure3.36showstheÞrstportionofthe style.css Þle.Thefourrulesshowneach haveaselectorstringthatisatypeselector.TheÞrstrulestatesthatthebackgroundcolor ofthebodywillbeslightlyoff-white(recallthatwhiteis #ffffff ).Thedefaultfontfamily (unlessoverriddenbyanotherelement)willbeVerdanaor,ifVerdanaisnotavailableto thebrowser,oneofthreeotherfontfamilieslisted(theÞnaloptionisthegenericsans-serif P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.11CaseStudy 179 /*Hyperlinks*/ a{ font-weight:bold; text-decoration:none; } a:link{ color:#33F; background:#fffff5; } a:visited{ color:#93C; background:#fffff5; } a:active{ color:black; background:#ccf; } a:hover{ color:#fffff5; background:#33F; } FIGURE3.37 Stylerulesforanchorelements. family).The font-size-adjust property,whichisnotsupportedbyIE6,hasaneffectifthe Þrstfontfamilyisnotavailable.GivenanappropriatespeciÞedvalue,thesizeoftheselected fontfamilyisscaledsothatitsexheightisroughlythesameasthatoftheÞrstfontfamily. Thisshouldmakethelettersappeartobeaboutthesamesizeregardlessofthefontactually used.Finally,noticethattheleftandrightmarginsofthebodyaresetat5%ofthewidthof thebrowserwindow,providingsidemarginsthatchangeasthewindowwidthchanges. The p and h1 rulesarereasonablystraightforward,althoughthe h1 ruledoesusea numericvalueforits font-weight property.Thisvaluecorrespondstotwostepsbolderthan normal andonesteplighterthan bold .The hr ruleturnsofftheborder,whichtheuseragent stylesheetsforbothIE6andMozilla1.4apparentlyturnon,andinsteaddisplaysonlya 1-pixel-highgrayline.Notetheuseofboththree-digitandsix-digitcolorvalue

61 s. Figure3.37showsthestylerulesrelatedto
s. Figure3.37showsthestylerulesrelatedtohyperlinks(anchorelements).TheÞrst rulemakeslinksboldandremovestheunderliningthatwouldnormallybeassociatedwith links.Theremainingpseudo-classruleschangethetextandbackgroundcolorsofahyperlink dependingonitsstatus,asdescribedearlier. Sofar,wehavebeenslightlyadaptingtheW3COldstyleCorestyleforourpurposes. WenextwanttocreateanumberofstylerulesspeciÞcallyfortheview-blogdocument. Recallthatthisdocumenthasthreeoverallsegments:animageabovetwosegments,the blogentriesontheleft,andsomenavigationhyperlinksontheright.Itisnaturaltolay outthesesegmentsbycreating div elementsandpositioningthemusingCSS.Figure3.38 showsthestructureofthebodyofthenewdocument(stillcalled index.html ). ThecorrespondingstylerulesaregiveninFigure3.39.TheÞrsttworulescenterthe topimageandthebody(mainportion)ofthedocument,whichcontainstheblogentries andnavigationlinks.ItalsoÞxesawidthforthebodyportionofthedocument.Thisvalue P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 180 Chapter3StyleSheets iv-;怠class="imgcentered" Bannerimage&#x!---;怠-- src="banner.gif"width="438"height="120" alt='"MyOwnBlog!"Banner'�/ &#x/div; iv-;怠class="bodycentered" iv-;怠class="leftbody" Blogentries&#x!---;怠-- iv-;怠class="entry" ... &#x/div; &#xhr-6;∗/ iv-;怠class="entry" ... &#x/div; &#x/div; iv-;怠class="rightbody" Sideinformation&#x!---;怠-- ... &#x/div; &#x/div; FIGURE3.38 StructureoftheHTMLdocumentfortheview-blogpageusingCSSratherthanatableforlayout. /*Classesforview-blogpage*/ .imgcentered{ width:438px; margin-left:auto; margin-right:auto; } .bodycentered{ width:660px; margin-left:auto; margin-right:auto; } .leftbody{ width:410px; float:left; } .rightbody{ width:230px; float:right; } .entry{ margin-top:.75em; margin-bottom:.75em; } FIGURE3.39 Stylerulesfor div elementsusedforpositioning. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Section3.11CaseStudy 181 iv-;怠class="dateti

62 me"AUGUST9,2005,5:04PM&#x/div;EDT iv
me"AUGUST9,2005,5:04PM&#x/div;EDT iv-;怠class="entrytitle"I'm&#x/div;hungry iv-;怠class="entrybody" &#xp000; Strange.Iseemtogethungryataboutthesametime everyday.Maybeit'ssomethinginthewater. &#x/p00; &#x/div; &#xhr-6;∗/ FIGURE3.40 Markupforablogentry. isnarrowenoughtobeviewedwithouthorizontalscrollingonalmostanymodernmonitor, yetwideenoughtodisplayareasonablenumberofwordsperlineintheblogentries.The div Õsfortheentriesandnavigationlinksarethenßoatedtotheleftandright,respectively, withinthisbody div .Noticethatthesumofthewidthsofthese div Õsis20pxlessthanthe widthofthecontaining div ,providingsomevisualseparationbetweentheblogentriesand thenavigationlinks.TheÞnalruledeÞnesverticalspacingbetweenblogentries,ormore speciÞcally,betweenblogentriesandthehorizontalruleseparatingthem. WecanalsouseCSStostylethecomponentsofablogentry.Forexample,themarkup fortheÞrstentryofourexampleisshowninFigure3.40,andFigure3.41givesstylerules correspondingtothismarkup.Giventheearlierdiscussion,theserulesshouldnotneedany explanation. Finally,letÕsuseCSStoaddaÒdisplayedquoteÓfeature,asillustratedinFigure3.42. Thebasicideaisthatifmarkupsuchas .datetime{ color:#999; font-size:x-small; } .entrytitle{ /*basedonh2ofOldstyle*/ font-family:"Georgia","MinionWeb","Palatino", "BookAntiqua","Utopia","TimesNewRoman", serif; font-size-adjust:.4; font-size:1.75em; font-weight:500; color:#C00; margin-top:.25em; } .entrybody{ font-size:small; } FIGURE3.41 Stylerulesusedforformattingcomponentsofablogentry. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 182 Chapter3StyleSheets FIGURE3.42 Exampleofadisplayedquote(inapreviewwindow,whichsuppressesthenavigationlinks). &#xspan;&#x-602;class='dquote'It'smoreimportantthan&#x/spa;&#xn000;that. isincludedwithintext,thenthecontentofthe span willbedisplayedwithintheentryand alsoßoatedtotheleftoftheenclosingtext,enlarged,andenclosedwithinathree-sided, dottedborder.Thisdisplayed-quotefeatureisnotfoolproof:ifthe span isincludednearthe bot

63 tomofthetext,thenitmightoverlapwiththene
tomofthetext,thenitmightoverlapwiththenextentry,sinceaßoatedelementistaken outofthenormalßow.But,ifusedcarefully,itprovidesaninterestingeffect. Figure3.43givesasuitableruleforproducingthedisplayed-quoteeffect.Onething tonoticeisthatthethree-sidedborderwascreatedusingtwodeclarations,andthattheorder ofthesedeclarationsisimportant(thesecondruleoverridesaportionoftheÞrstduetothe cascaderules). /*Fordisplayingaquote*/ .dquote{ float:left; font-size:larger; padding:1px; margin-right:5px; width:10em; border-style:dotted; border-left-style:none; border-color:#999; } FIGURE3.43 Stylerulesfor span elementusedtodisplayaquote. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Exercises 183 3.12References TheprimaryreferenceforthematerialcoveredinthischapteristheCSS2recom- mendation[W3C-CSS-2.0],andIhavealsoconsultedaversionoftheCSS2.1can- didaterecommendation[W3C-CSS-2.1]forguidanceonwhichaspectsofCSS2seem mostlikelytoÞndwidespreadsupportbybrowsers.TheW3ChomepageforCSS, http://www.w3.org/Style/CSS/ ,containslinkstoallCSSrecommendationsaswellasto CSS-relateddevelopmentsoftware,books,tutorials,discussiongroups,andotherresources, includingaCSSvalidator.PreliminaryversionsofCSS3arealsoavailableatthissite. AsmentionedearlierinSection3.3,versionsofInternetExplorerpriortoIE6did notfullysupportevenCSS1,andIE6alsodoesnotfollowtheCSSrecommendationun- lessyouuseanappropriatedocumenttypedeclarationinyourHTMLdocument.See http://msdn.microsoft.com/library/en-us/dnie60/html/cssenhancements.asp forinfor- mationonCSSinpre-IE6versionsofInternetExploreraswellasfordetailsonhowto turnonCSS-complianceinIE6. http://www.mozilla.org/catalog/web-developer/css/ is MozillaÕsdocumentationforCSSdevelopers,whichcontainsfewdetailsonMozillaÕssup- portforCSS2atthetimeofthiswriting(butseethenextparagraphforotherwaystolearn aboutMozillaÕsCSSsupport). Goingforward,asnewbrowserscontinuetoemergeandolderbrowsersbecome morerare,youwillwanttoperiodicallyacquaintyourselfwithemergingbrowserCSS capab

64 ilities.ApreliminarysetofCSS2tests(andot
ilities.ApreliminarysetofCSS2tests(andotherhelpfulCSSinformationcom- piledbyEricMeyer,whohaswrittenextensivelyaboutCSS)iscurrentlyavailableat http://www.meyerweb.com/eric/css/ .Presumably,aÞnalCSS2suitewilleventuallybe availableattheW3Csite(aCSS1suiteisalreadyavailablethere).Youcanrunsuchtests onvariousbrowsersyourselforrelyontheresultsoftestsperformedbyothers.Forex- ample,asIwrotethischapter,IreferredtotheresultsoftestsrunbyChristopherHester ( http://www.designdetector.com/articles/CSS2TestSuiteFailures.php )forinformation aboutCSS2support(andlackthereof)inMozillaandIE6.Whilethisresourcemayormay notbeuptodatewhenyoureadthis,abitofWebsearchingforÒCSStestsuitesÓshould providetheinformationyouneed. Exercises 3.1. Practicewritingsimplestylerules.Inthefollowingexercises,makeuseofthefollowing declarations(oneperline): background-color:silver; font-size:larger; ThesewillbereferredtoasÒthebackgrounddeclarationÓandÒthetextdeclaration,Ó respectively. (a) WriteCSSstylerulesthatapplythebackgrounddeclarationto div elementsand thetextdeclarationto strong elements. (b) Writeasinglestylerulethatappliesboththebackgroundandtextdeclarationsto both p and em elements. (c) WriteasinglestylerulethatappliesthebackgrounddeclarationtoHTMLelements havingavalueof Nevada fortheir id attributesaswellastoelementsbelongingto the shiny class. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 184 Chapter3StyleSheets (d) Writeastylerulethatappliesthetextdeclarationto span elementsthatbelongto the bigger class. (e) Writeastylerulethatappliesthetextdeclarationto span elementsthataredescen- dantsofother span elements. (f) Writeastylerulethatappliesthebackgrounddeclarationwhenthecursorhovers overahyperlink. 3.2. Createthreeexternalstylesheets,usingadifferentsubsetofthestylerulesyouwrote forthepreviousexerciseineachstylesheet.ThenwriteacompleteXHTML1.0Strict documentthatusesallofyourstylerules. (a) Yourdocumentshouldtreatyourstylesheetsasbeingofthreedifferenttypes:  Anon-persist

65 entandpreferredstylesheet  Analterna
entandpreferredstylesheet  Analternatestylesheet  AstylesheetusedonlyiftheXHTMLdocumentisprinted (b) Usethe @import ruletohavetheÞrstofyourstylesheetsimportthesecond,which importsthethird.YourXHTMLdocumentshouldtreattheÞrststylesheetasa persistentstylesheet. 3.3. Writeanembeddedstylesheet(includingtheappropriateHTMLtags)thatsetsthevalue ofthe font-family propertyto GillSansBoldSmallCaps&OSF forallelementsof thedocument. 3.4. Assumethattheauthor,user,anduseragentstylesheetsforanHTMLdocumentareas follows:  Author: div{color:blue} p{color:green; font-size:smaller!important} .hmm{color:fuchsia}  User: p{color:white; background-color:black; font-size:larger!important} body{color:yellow}  Useragent: body{color:black} Assumethatthesearetheonlystylerulesforthedocument(i.e.,no style attributes appear). (a) WhatspeciÞedvaluewillthebrowseruseforthe color propertyof p elements? Forthe background-color propertyof p elements?Forthe font-size property? Doanyofyouranswerschangeifthe p elementbelongstothe hmm class?Justify youranswers. (b) WhatspeciÞedvaluewillthebrowseruseforthe color propertyof div elements? Doesyouranswerchangeifthe div elementbelongstothe hmm class?Doesthe valuedependonwhichelementtypecontainsthe div ?Justifyyouranswers. (c) What color valuewillbegiventoa ol elementthatisachildofthe body element, assumingthatneitherthe ol elementnorthe body elementbelongstothe hmm class? Doesyouranswerchangeifthe body element(notthe ol element)belongstothe hmm class?Justifyyouranswers. (d) Assumenowthattheuseragentruleischangedto *{color:black} andanswerthepreviousquestion. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Exercises 185 3.5.(a) Writeastyleruletocreateaclassnamed quote .Thisruleshouldsetthetopand bottommarginsto 0 andtheleftandrightmarginsto 4em .Theruleshouldcontain asingle(shortcut)declaration. (b) Explainwhy em mightbeabetterlengthunittouseforthetaskofindentingquoted textthan px oroneoftheabsolutelengthunits. 3.6. Base

66 donthetextbookdescriptionofatypicalbrows
donthetextbookdescriptionofatypicalbrowserÕsimplementationoftheCSS px (pixel)lengthmeasure,quantifyhowa 1px lengthchangesifamonitorÕsresolutionis changedfrom1024by768to1280by1024. 3.7. PictureÒframing.Ó (a) WriteastylerulethatwillplaceaniceÒframeÓaround img elements.TheÒframeÓ shouldbebrown.TheinsideedgesoftheÒframeÓshouldtouchtheoutsideedges oftheimage.Thereshouldbe10-pxdistancebetweenadjacentimages(either horizontallyorvertically).SeetheleftimageinFigure3.44. (b) ModifyyourstyleruletoÒmatÓyourimages.Inparticular,thereshouldnowbe a3-pxgapbetweentheoutsideedgesofyourimagesandtheinsideedgesofthe Òframes.ÓThisgapshouldbeatancolor.SeetherightimageinFigure3.44. 3.8. Figure3.22showsaclientareawiderthanthecanvas.Explainhowsuchasituationcould occurinanHTMLdocument. 3.9. Theemandexunitsarebothrelatedtotheheightofcharacters;thereisnounitrelated tocharacterwidth.Givearationaleforthisdifference. 3.10. CreateanHTMLdocumentandCSSstylesheetthattogetherproducethestairstepeffect showninFigure3.45.Therightsidesofthestepsshouldlineupinthemiddleofthe document,regardlessofthewidthofthebrowserwindow.Also,eachstepshouldhave thesameheightasallothersteps,regardlessofthenumberoflinesoftextcontainedin thestep(seetheloweststepintheÞgure,forexample). 3.11. AssumethatanHTMLdocumentusesthefollowingstylesheet: body{margin:5px;border:0;padding:2px} div{margin:3px;border:1pxsolidblue;padding:4px} FIGURE3.44 TwoÒframedÓimages.TherightimageisÒmatted.Ó(GraphicscourtesyofBenJackson.) P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 186 Chapter3StyleSheets FIGURE3.45 Stairstepscontainingtext. Relativetotheupperleftcorneroftheinitialcontainingblock,foreachofthethree div elementsinthefollowingHTML body givethecoordinatesoftheupperleft cornerofthecontentareaoftheblockboxgeneratedbythat div .Show/explain yourwork. ody; iv-;怠id="div1" iv-;怠id="div2" &#x/div; &#x/div; iv-;怠&#x/div;id="div3" &#x/bod;&#xy000; 3.12. Assumethatthe normal valueforthe line-height propert

67 yofagivenfontcorre- spondstothevalue 1.2
yofagivenfontcorre- spondstothevalue 1.2em .Alsoassumethattheheightofthebaselineabovethe bottomofacharactercellinthisfontis 0.2em .Ifavalueof 2em isspeciÞedfor line-height ,whatisthecorrespondinghalf-leadingvalue?Whatistheheightofthe baselineabovethebottomofalineboxcontainingonlytextinthegivenfontandgiven thatthe line-height valueis 2em ? 3.13. Assumethatthe line-height valueforablockboxis 2em . (a) Assumethatoneofthelineboxeswithinthisblockboxcontainsanimagewith height equalto 1.5em andadefaultvaluefor vertical-align .Ifyouknewthe heightofcharactercellsaswellastheheightofthebaselinewithinacharactercell fortheblockboxÕsfont,howcouldyouusethisinformationtodeterminewhether ornottheheightofthelineboxcontainingtheimagewouldneedtobeincreased tomakeroomfortheimage? (b) IfoneofthelineboxescontainsaninlineelementhavingaspeciÞedfontsizetwice thefontsizeforthecontainingblockbox,willthebaselineheightofthislinebox necessarilybegreaterthanitisinlineboxesthatcontainonlytextinthedefault font?Explain. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Exercises 187 3.14.(a) Identifyatleastthreeproblemswiththefollowingstyledeclaration: font:2em/12ptitalic"TimesNewRoman"serif (b) Rewritethedeclarationsothatitissyntacticallycorrect. (c) AssumethatthecorrectedstyledeclarationappliestoanelementEcontainedwithin anelementtowhichthefollowingdeclarationapplies: font-weight:bold WhatwillbethevalueofEÕs font-weight property? 3.15. ThefollowingHTMLdocumentproducesanimagefollowedbyalabelthatisroughly verticallycenteredwithrespecttotheimage: html PUBLIC"-//W3C//DTDXHTML1.0Strict//EN" �"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" &#xhtml;&#x-602;xmlns="http://www.w3.org/1999/xhtml" &#xhead; &#xtitl; CenteredText.html &#x/tit;&#xle00; &#xstyl;-60; type="text/css" .labeledImage{font-size:100px} .image{vertical-align:middle;height:100px} .label{vertical-align:middle; font-size:medium;font-weight:bold} &#x/sty;&#xle00; &#x/hea;퀀 ody; iv-;怠class="l

68 abeledImage" src="../images/CFP1.png"alt
abeledImage" src="../images/CFP1.png"alt="cucumber" class="image"�/ &#xspan;&#x-602;class="label"A&#x/spa;&#xn000;cucumber. &#x/div; &#x/bod;&#xy000; &#x/htm;&#xl000; (a) Howwouldtherendereddocumentdifferifthe vertical-align declarationwere removedfromthe label rule?Why? (b) Howwouldtherendereddocumentdifferifthe vertical-align declarationwere removedfromthe image rule?Why? (c) Thereisalargespacebetweentheimageandthelabelwhenthedocumentisren- dered.Whyissuchalargespacepresent,andhowcanasmallerspacebedisplayed instead? 3.16. Considerthefollowingmarkup: style="font-size:12pt;&#xp-60; line-height:1.15em" Thisparagraphhas &#xspan;&#x-602;&#x/spa;&#xn000;style="font-size:30pt"line-height:1.15em whichis"normal". &#x/p00; P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 188 Chapter3StyleSheets FIGURE3.46 Renderingofmarkupwithdifferentfontsizes. TheMozillabrowserrenderingofthismarkupinanarrowwindowisshownin Figure3.46.Whydoestextinthesecondlineoverlaptheothers?Whatsmallchangeto themarkupwouldÞxthisproblem? 3.17. Boththe vertical-align propertyandrelativepositioningcanbeusedtomoveaninline boxvertically.Giveastyleruleforeachapproachthatcouldbeusedtomoveaninline boxupadistanceof1cm.Inadditiontomovingtheboxup,whatotherdisplaychange(s) mightoccurifthe vertical-align approachisused? 3.18. SomeWebpagescreateanavigationbar(navbar)ontheleftsideofthepageandthe maincontentinawidercolumnontherightsideofthepage.Writestylerulesthatcould beusedtowrapthecontentaroundthenavbar.Thatis,atthetopofthecanvasthenavbar andcontentshouldeachbedisplayedsidebyside.However,loweronthecanvas,when thebottomofthenavbarisreached,thecontentareashouldextendacrosstheentire widthofthebrowserclientarea. 3.19. Assumethatyouwanttolayoutanumberofplayingcardimagessothattheyoverlap oneanother,asshownatthetopandbottomofFigure3.47.Woulditbeeasiertouse absoluteorrelativepositioningtoaccomplishthis?Explain. 3.20. Writeastylesheetthatwillcausethe li elementswithinany ol elementtobenumbered in

69 anoutlinestyle:thetop-level li elementss
anoutlinestyle:thetop-level li elementsshoulduseuppercaseRomannumerals,the nextleveluppercaseletters,thenextlevellowercaseRomannumerals,thenlowercase letters,andÞnallydecimalnumeralsattheÞfthlevel. ResearchandExploration 3.21. Createadocumentthatdisplaystwoboxes.TheÞrstboxshouldhaveathinborderand awidthof6in.Thesecondboxshouldhaveanequivalentwidthinpixels,usingthe relation1in.=96px.Nowanswerthefollowingquestionsusingthebrowser(s)assigned byyourinstructor: (a) Dothetwoboxesappeartobethesamelengthwhendisplayedbyyourbrowser? (b) MeasuretheÞrstboxwitharuler.Howmanyinches(orcentimeters)acrossisit? IfthewidthofthesecondboxdiffersfromtheÞrst,measureitaswell. (c) Printyourdocument.Nowwhataretheactualwidthsoftheboxes? 3.22. LocateaWebsite(orvisitasitespeciÞedbyyourinstructor)thatdisplaysthecolors oftheso-calledÒbrowser-safecolorpalette,Óacollectionofcolorsthatcanreliablybe P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Exercises 189 FIGURE3.47 Overlappingimagesofplayingcards(facecardandcardbackimagescourtesyofBenJackson) displayedevenusingvideocardsthatarecapableofshowingonly256differentcolors simultaneously. (a) Howmanycolorsarecontainedinthispalette? (b) Ofthecolorsred,orange,yellow,green,blue,purple,andbrown,identifythe color(s)thatseemtohavethemostdifferentshadesinthebrowser-safepaletteand thecolor(s)thathavethefewest. (c) VisitsomepopularWebsites(asdirectedbyyourinstructor)andanalyzetheiruse ofCSScolorvaluesbyviewingdocumentandstylesheetsources.Whichsitesuse thebrowser-safepaletteandwhichdonot? 3.23. IdentifyallofthecolorkeywordscontainingÒgrayÓorÒgreyÓat http://www.w3.org/ TR/SVG11/types.html#ColorKeywords .CreateanHTMLdocumentandCSSstylesheet thatcanbeusedtotestabrowserÕssupportforthesekeywords.Useyourdocumenttotest andreportonthesupportforthesecolorkeywordsprovidedbyIE6(orotherbrowser(s) asassignedbyyourinstructor). RefertotheCSS2recommendation[W3C-CSS-2.0]ÑoralaterW3Crecommendation asspeciÞedbyyourinstructorÑinordertoanswerthefollowingquesti

70 ons. 3.24. Giveastylesheetruleforthe bod
ons. 3.24. Giveastylesheetruleforthe body elementofadocumentthatwillcauseabackground imagetoberepeatedacrosstheverticalcenterofthebrowserclientarea.Theimage shouldremaininthecenterofthewindowevenifthewindowisscrolled(seeFig.3.48, inwhichÒDraft...Óisanimage). 3.25. Describewhatthe fixed valueforthe position stylepropertydoeswhenviewinga documentinabrowser.Giveanexampleofhowthisfeaturemightbeuseful.Testtosee whichbrowsers(asassignedbyyourinstructor)supportthisvaluefor position (IE6 doesnot). P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 190 Chapter3StyleSheets FIGURE3.48 AbackgroundimagecontainingÒDraf t...Óis repeatedacrossthecenterofthebrowserclientarea. Projects 3.26. CreateanexternalstylesheettobeusedwiththeHTMLreferencepagesyouwrotefor Exercise2.30inordertoaccomplishthefollowing(withminimalchangestoyourHTML source): (a) Usea seashell backgroundcolorforallpages( seashell isoneoftheSVGcolor keywords). (b) Changethestyleofthebulletsusedintheshortlistoftwohyperlinks(youchoose thestyle). (c) DeÞnealternativecolorsforallfouroftheanchorpseudo-classes. (d) Maketablecaptionsboldface,andtableheaders( th elements)normalweightbut italicized. (e) Usea14-ptsansseriffontforall td elements. (f) Forcetextincellsthatspanmultiplerowstobedisplayedatthetopofthecell, ratherthanthedefaultmiddleofthecell. (g) OnthedeÞnitionpages,causeeachtermanditsdeÞnitiontobedisplayedinabox thathasa3-pxsolidyellowborder.Theboxshouldoccupy75%ofthewidthofthe clientarea(orframe,ifyoucompletedtheframedversionoftheearlierassignment) andshouldbecentered. (h) TheW3CsuggeststhefollowingmarkupbeincludedinaWebpagethatisvalid XHTML1.0: &#xp000; -60; href="http://validator.w3.org/check?uri=referer" src="http://www.w3.org/Icons/valid-xhtml10" alt="ValidXHTML1.0!"height="31"width="88"�&#x/a00;/ &#x/p00; UsethismarkuponallofyourvalidXHTML1.0pages.Alsoincludea class speciÞcation(ofyourchoosing)inthe img element.Then,withoutfurtherchange tothismarkup,writeastylerulethatwillmakethes

71 eimagesappearontheright sideofthebrowser
eimagesappearontheright sideofthebrowserclientareaanddisplaytheimagesatroughlyhalftheheightand widthshown. P1:OSO/OVYP2:OSO/OVYQC:OSO/OVYT1:OSO GTBL013-03GTBL013-Jackson-v10 July12,200610:36 Exercises 191 3.27.(a) CreateanHTMLdocumentthatrenderssimilarlytoFigure3.47.Cardimagescan befoundinthe images/PlayingCards directoryoftheexampleÞlesdownload availableattheWebsitegiveninthePreface. (b) WriteaJavaprogramthatcreatesanHTMLdocumentsuchastheonejustdescribed. Yourprogramshouldacceptasinputthenumberofcardstobeheldineachhand (theupperandlowerpartsoftheÞgurerepresenthandsheldbyplayersofacard game).Theprogramshouldrandomlyselecttheimagestodisplayforallface-up cards(therightcardinthesecondrowandallofthecardsinthelowerhand).You willprobablywanttousethe java.util.Random packageforrandomlyselecting cardimages,butbecarefulnottodisplaythesamecardimagetwice. 3.28. ThefollowingquestionssuggestextensionstothecasestudyofSection3.11.Implement asubsetofthefollowingrequirementsasspeciÞedbyyourinstructor. (a) UseCSStostylethecommentsdocumentdescribedinExercise2.33.First,linkthe commentsdocumenttothe style.css ÞledescribedinSection3.11(andavailable fordownloadfromthetextbookWebsitegiveninthePreface).Thenaddclasses to style.css appropriateforstylingvariouselementsofthecommentsdocument, includingeachcommentasawholeandtheindividualcomponentsofacomment: authorname,commentheading,andcommentbody.Yourclassrulesshouldcenter thecommentheadingoverthecommentbodyandright-justifytheauthorname followingthebody.Finally,rewritethedocumenttouseyournewclassdeÞnitions. (b) Addacompaniontothe dquote class,named drquote ,thatislike dquote except thatitßoatstexttotherightinsteadoftheleft.Also,textwithintheßoatedbox shouldberight-justiÞedratherthanleft-justiÞed,andtheboxbordershouldbeopen ontherightandclosedontheleft.Createanexampledocumentthatdemonstrates theuseofyourclass. (c) Usethevalidatorat http://jigsaw.w3.org/css-validator/ toensurethatthe stylesheetrulesaddedin(a)and(b)arevalidCSS.TurninacopyoftheWebpage, showing

Related Contents


Next Show more