HTML and CSS The Complete Reference 5th Edition - Free PDF Book
HTML and CSS The Complete Reference 5th Edition - Free PDF Book
com
HTML & CSS:
The Complete Reference,
Fifth Edition
www.allitebooks.com
About the Author
ThomasA.Powell(tpowell@pint.com)isalong-time
industryveteran.AfteranearlystintatCERFnetinthe
early‘90s,hefoundedPowellInternetConsulting(later
renamedPINT)in1994,aWebdesignandconsultingservices
firm.Today,PINT(pint.com)providesWebdevelopment,
design,andconsultingservicestolargeandsmallcorporations
allovertheUnitedStatesinavarietyofindustries.
BeyondhisinvolvementatPINT,Thomasisheavily
involvedintheacademiccommunity.Hedevelopedthe
UniversityofCalifornia,SanDiegoExtensionWebPublishing
programinthelate1990sandcontinuestoteachclassesthere
inWebdevelopmentanddesign.Heisalsoaninstructorfor
theUCSDComputerScienceDepartment,whereheteaches
classesinWebdevelopmentandthetheoryofprogramming
languages.
Mr.Powelliswellpublished,andhisworkhasappeared
innumeroustradepublications.Hecontinuestopublish
regularlyinNetworkWorld.Healsohaspublishednumerous
booksonWebtechnologyanddesign,includingAjax:The
CompleteReference,JavaScript:TheCompleteReference,and
manyothers.Hisbookshavebeentranslatedintoover
12languagesandareusedaroundtheworldbothinindustry
andcollegesettings.
www.allitebooks.com
HTML & CSS:
The Complete Reference,
Fifth Edition
ThomasA.Powell
NewYorkChicagoSanFrancisco
LisbonLondonMadridMexicoCity
MilanNewDelhiSanJuan
SeoulSingaporeSydneyToronto
www.allitebooks.com
Copyright © 2010 by The McGraw-Hill Companies. All rights reserved. Except as permitted under the United States Copyright Act of 1976, no
part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the
prior written permission of the publisher.
ISBN: 978-0-07-174170-5
MHID: 0-07-174170-4
The material in this eBook also appears in the print version of this title: ISBN: 978-0-07-149629-2, MHID: 0-07-149629-7.
All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked name,
we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark. Where
such designations appear in this book, they have been printed with initial caps.
McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training
programs. To contact a representative please e-mail us at bulksales@mcgraw-hill.com.
Information has been obtained by McGraw-Hill from sources believed to be reliable. However, because of the possibility of human or
mechanical error by our sources, McGraw-Hill, or others, McGraw-Hill does not guarantee the accuracy, adequacy, or completeness of any
information and is not responsible for any errors or omissions or the results obtained from the use of such information.
TERMS OF USE
This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGraw-Hill”) and its licensors reserve all rights in and to the work.
Use of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of
the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute,
disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use the work for your own
noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be terminated if you fail to
comply with these terms.
THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE
ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY
INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY
DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. McGraw-Hill and its licensors do not warrant or guarantee that the
functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill nor
its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages
resulting therefrom. McGraw-Hill has no responsibility for the content of any information accessed through the work. Under no circumstances
shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from
the use of or inability to use the work, even if any of them has been advised of the possibility of such damages. This limitation of liability shall
apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise.
www.allitebooks.com
Contents at a Glance
www.allitebooks.com
This page intentionally left blank
www.allitebooks.com
Contents
Acknowledgments ................................................ xxi
Introduction ..................................................... xxiii
vii
www.allitebooks.com
viii HTML&CSS:TheCompleteReference
HTML5:EmbracingtheRealityofWebMarkup ....................... 62
PresentationalMarkupRemovedandRedefined ...................... 63
OutwiththeOldElements ................................... 64
InwiththeNewElements .................................... 66
SampleofNewAttributesforHTML5 ......................... 66
HTML5DocumentStructureChanges ............................... 69
AddingSemantics ................................................ 75
MarkingText ............................................... 75
IndicatingDatesandTime ................................... 76
InsertingFigures ............................................ 76
SpecifyingNavigation ....................................... 77
HTML5’sOpenMediaEffort ....................................... 78
<video> ................................................... 78
<audio> ................................................... 80
MediaConsiderations ....................................... 82
Client-SideGraphicswith<canvas> ................................. 82
DrawingandStylingLinesandShapes ........................ 85
DrawingArcsandCurves .................................... 90
Scaling,Rotating,andTranslatingDrawings .................... 93
UsingBitmapsinDrawings .................................. 97
TextSupportforcanvas ...................................... 98
<canvas>Conclusions ....................................... 101
HTML5FormChanges ............................................ 101
NewFormFieldTypes ....................................... 101
ValidatingDataEntry ....................................... 104
AutocompleteLists ......................................... 105
MiscellaneousUsabilityImprovements ........................ 105
EmergingElementsandAttributestoSupportWebApplications ........ 106
menuElementRepurposed .................................. 106
commandElement .......................................... 108
meterandprogressElements ................................. 109
detailsElement ............................................. 109
outputElement ............................................. 110
TheUncertainFutureofFrames .............................. 110
ThedraggableAttributeandtheDragandDropAPI ............ 112
contenteditableAttribute .................................... 114
spellcheckAttribute ......................................... 115
InternationalizationImprovements .................................. 116
HTML5MetadataChanges ......................................... 116
data-XAttributes ........................................... 116
Microdata .................................................. 117
HTML5:BeyondMarkup .......................................... 120
deferAttribute .............................................. 121
HTML,JavaScript,andtheDOMRenewed ..................... 121
StandardizingandExtendingAdHocJavaScriptConventions .... 125
MajorHTML5Themes ............................................. 126
HTML5TodayorTomorrow? ................................. 126
HTML5asaCatch-All ....................................... 130
HTML5:WebPoliticsasUsual ................................ 131
HTML5:ImperfectImprovement .............................. 131
Summary ........................................................ 132
www.allitebooks.com
Contents ix
www.allitebooks.com
x HTML&CSS:TheCompleteReference
www.allitebooks.com
This page intentionally left blank
Acknowledgments
T
hefiftheditionofthisbookmightaswellbethefirsteditionofabrand-newbook.
TheHTML5specificationmarksareturntopastideasandanexplosionoffuture
ideas.Ittookagreatdealofworktoputthisneweditiontogether.Giventheamount
ofeffortrequired,Iwanttomakesurethatallthosethathelpedaregiventheirdue.First,I
wanttoacknowledgethenumerousfixesandimprovementsthatcamefromthefeedback
frombothmystudentsatUCSDandreadersaroundtheworld.Iwritethesebooksforyou,
andIamgladyouareputtingthisinformationtogooduse.
IwouldalsoliketoshowmyappreciationtothemanystaffmembersatPINTwho
helpedonthisbookprojectinsomedirectorindirectway.Ican’tspecificallythankand
mentionthedozensofemployeeswehaveatPINTandmyotherfirmPort80Softwarewho
keepthelightson,butI’llcallafewoutwhowarrantsomeextrakudos.
ChristieSorensononceagainhelpedthistimewithheavyliftingparticularlyintheCSS
effort,andIcansafelysaythatshehaslearned,relearned,andevenforgottenmoreabout
WebdevelopmentthanprobablyanyoneIknow,besidesmaybemyself.Lookingforwardto
moreprojectfuninthefuture,Christie!
PlentyofotherPINTstershelped.RobMcFarlane,AndrewSimpkins,andBryanSleiter
helpedoutwithimagery.Theprojectmanagers,particularlyMineOkano,RobinNobel,
MattPlotner,andOliviaChen,gavememoralsupportandoccasionalpityasItoiledaway
upstairs.GlennDawsonaddressedmymanyserverchangesandhelpeddebugsome
annoyingaspectsofHTML5.DanWhitworthassistedonafewchaptershereandthereand
probablyhadnightmaresaboutgettingacalltoreallydivein.
JoeLimalistenedtosomeofmyverbalnonsenseandhelpedguidemetosomedeeper
insightsthanIcouldhaveeverarrivedatonmyown.
DaisyBhonslekeptupaverylong-standingproofingrelationship,andIamveryglad
shealwayshelpsout.Thestudentcertainlyhasbecomethemaster.
ThefolksatMcGraw-HillProfessionalarealwaysapleasuretoworkwith.Meghan
Rileyhelpedguidemealong,andMeggMorindidn’tlosefaith,atleastnotcompletely.
Thanksforbeingmypatronthelastdecade,Megg!
Mytechnicaleditor,JamesPence,probablywonderedwhenthisprojectwasgoingto
finish,andsomehowhefinishedanontechnicalbookofhisownduringtheproject.
xxi
xxii HTML&CSS:TheCompleteReference
Finally,tomyfriendsandfamilywhotriedtogivemespacetowritethisthing,you
deservethebiggestthanks.Mychildren,Graham,Olivia,andDesmond,hadtoputup
withagrouchydadandfartoomanyabsentweekends,sowenowreturnyoutoour
regularlyscheduledweekends!Cecilia,youprovidedalotofhelpaswellthatmade
thingsabiteasieronallofus,sothankyouforthat.Finally,Sylvia,youalwayssupport
myonlineefforts,ashardastheymaybe.Iknowyou,morethananyone,appreciatethe
importanceofthisproject,consideringtheroleHTMLhasplayedinourlives.
ThomasA.Powell
tpowell@pint.com
October2009
Introduction xxiii
Introduction
T
hefiftheditionofthisbookrepresentsasignificantchangeinstructureandcontentto
addressHTML5.Thebookissimilartothepreviouseditioninmaybeathirdofthe
content;otherwise,itisanall-neweffort.Mostobviously,ascomparedtotheprevious
editions,whichfocusedmainlyonXHTMLandHTML4,thiseditionfocusesonHTML5,
whichrepresentsbothareturntothemarkuppastandtheunveilingofanexcitingfutureof
Webapplications.However,wedoretainsomeinformationfrompreviouseditionsbecause
inorderforthisworktobetrulycomplete,wemustnotfocusonlyonthefuturebutalso
presentalltheelementssupportedinbrowserstoday,includingthearchaic,proprietary,and
standard(X)HTMLtags.Thesewillstillbeencounteredforyearstocome,andwewantthis
booktoprovidethereferenceyouneedinaddressingtheirsyntax.
CSScoveragehasbeenexpandedgreatlytofullycoverCSS2.1aswellaseveryproprietary
andemergingCSS3propertysupportedinoneormorepopularshippingbrowserscirca2009.
Novaluejudgmentismade;ifInternetExplorerhassupportedaproprietaryCSSfeaturefor
thelastdecade,it’sincluded.However,wedoavoidpresentingCSSfeaturesthataretruly
speculativeingreatdepth,butwhereappropriate,wesummarizeorpresentpointerstothe
emergingsyntax.
TheramificationoftheincreasedmarkupandCSScoverageissimplythebookdoesn’t
havespacelefttodoeverythingitdidbefore.TeachingnearlyeverythingaboutHTMLand
CSSinproseformandthenpresentingacompletesyntaxreferenceforthetechnologies
wouldhaveproducedabookwellover2,000pages.Wewerewellonthewaytothatwhen
weadjustedoureffortstocreatewhatyouhaveinyourhands,asolidreferencebookthat
maybeusedforyearstocome.Thisisn’ttosaythatlearningmaterialisnotpresentatall.
ThereareverysolidintroductorychaptersforthemarkupandCSSsections,whichshould
succinctlyaddressdetailsandstandardsissues.Therejustisn’tastep-by-stepcookbookfor
eachelementorproperty.GiventhematurityoftheWebindustry,weaimednotforthe
completetutorial,butinsteadforthecompletereference.
ItshouldgowithoutsayingthatmoremarkupchangestoHTMLandCSSareinevitable.
HTML5,inparticular,isacompletemovingtarget,andratherthanpuntingonit,wetook
thebestshotatitsfirstreleaseversionasitsettledinlate2009.Becauseoftheinevitable
changesgivenHTML5’srapidevolution,thesupportWebsite,http://htmlref.com,should
beconsideredanimportantbookmarkforreaderslookingforupdatesortheunavoidable
correction.
xxiii
This page intentionally left blank
PART
I
Core Markup CHAPTER 1
TraditionalHTML
andXHTML
CHAPTER 2
IntroducingHTML5
CHAPTER 3
HTMLandXHTML
ElementReference
This page intentionally left blank
CHAPTER
1
Traditional HTML and XHTML
M
arkuplanguagesareubiquitousineverydaycomputing.Althoughyoumaynot
realizeit,wordprocessingdocumentsarefilledwithmarkupdirectivesindicating
thestructureandoftenpresentationofthedocument.Inthecaseoftraditional
wordprocessingdocuments,thesestructuralandpresentationalmarkupcodesaremore
oftenthannotbehindthescenes.However,inthecaseofWebdocuments,markupintheform
oftraditionalHypertextMarkupLanguage(HTML)anditsExtensibleMarkupLanguage
(XML)-focusedvariant,XHTML,isalittlemoreobvious.Thesenot-so-behind-the-scenes
markuplanguagesareusedtoinformWebbrowsersaboutpagestructureand,somemight
argue,presentationaswell.
<em>Thisisimportanttext!</em>
3
4 Part I: Core Markup
WhenaWebbrowserreadsadocumentthathasHTMLmarkupinit,itdetermineshow
torenderitonscreenbyconsideringtheHTMLelementsembeddedwithinthedocument:
So,anHTMLdocumentissimplyatextfilethatcontainstheinformationyouwantto
publishandtheappropriatemarkupinstructionsindicatinghowthebrowsershould
structureorpresentthedocument.
Markupelementsaremadeupofastarttag,suchas<strong>,andtypically,thoughnot
always,anendtag,whichisindicatedbyaslashwithinthetag,suchas</strong>.Thetag
pairshouldfullyencloseanycontenttobeaffectedbytheelement,includingtextandother
HTMLmarkup.
NOTE Thereisadistinctionbetweenanelement(forexample,strong)andthetags(<strong>
and</strong>)thatareusedbytheelement.However,youwilllikelyoftenfindtheword
“tag”usedinplaceof“element”inmanyifnotmostdiscussionsaboutHTMLmarkup.This
observationevenincludeshistoricallyrelevantdocumentsdiscussingHTML1writtenbyTim
Berners-Lee,thefoundingfatheroftheWeb.Fortunately,despiteanyimprecisionofwordchoice
thatpeoplemayexhibitwhendiscussingmarkup,meaningisusuallywellunderstoodandthis
shouldnotbeatremendousconcern.
UndertraditionalHTML(notXHTML),theclosetagforsomeelementsisoptional
becausetheirclosurecanbeinferred.Forexample,a<p>tagcannotencloseanother<p>
tag,andthustheclosing</p>tagcanbeinferredwhenmarkuplikethisisencountered:
<p>Thisisaparagraph.
<p>Thisisalsoaparagraph.
Suchshortenednotationsthatdependoninferencemaybetechnicallycorrectunderthe
specification,butstylisticallytheyarenotencouraged.Itisalwayspreferabletobeprecise,
sousemarkuplikethisinstead:
<p>Thisisaparagraph.</p>
<p>Thisisalsoaparagraph.</p>
1
HistoricintrotoHTMLthatclearlyusesthetermtaginsteadofelementwww.w3.org/History/19921103-
hypertext/hypertext/WWW/MarkUp/Tags.html
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 5
Therearemarkupelements,calledemptyelements,whichdonotencloseanycontent,thus
neednoclosetagsatall,orinthecaseofXHTMLuseaself-closeidentificationscheme.For
example,toinsertalinebreak,useasingle<br>tag,whichrepresentstheemptybrelement,
PART I
becauseitdoesn’tencloseanycontentandthushasnocorrespondingclosetag:
<br>
However,inXMLmarkupvariants,particularlyXHTML,anunclosedtagisnotallowed,so
youneedtoclosethetag
<br></br>
or,morecommonly,useaself-identificationofclosurelikeso:
<br/>
Thestarttagofanelementmightcontainattributesthatmodifythemeaningofthetag.
Forexample,inHTML,thesimpleinclusionofthenoshadeattributeinan<hr>tag,as
shownhere:
<hrnoshade>
indicatesthatthereshouldbenoshadingappliedtothishorizontalrule.UnderXHTML,
suchstyleattributesarenotallowed,becauseallattributesmusthaveavalue,soinstead
youhavetousesyntaxlikethis:
<hrnoshade="noshade"/>
Astheprecedingexampleshows,attributesmayrequirevalues,whicharespecifiedwithan
equalsign;thesevaluesshouldbeenclosedwithindoubleorsinglequotes.Forexample,
usingstandardHTMLsyntax,
<imgsrc="dog.gif"alt="Angus-BlackScottishTerrier"height="100"
width="100">
specifiesfourattributesforthis<img>tagthatareusedtoprovidemoreinformationabout
theuseoftheincludedimage.UndertraditionalHTML,inthecaseofsimplealphanumeric
attributevalues,theuseofquotesisoptional,asshownhere:
<pclass=fancy>
RegardlessoftheflexibilityprovidedunderstandardHTML,youshouldalwaysaimto
usequotesonallattributes.Youwillfindthatdoingsomakesmarkupmoreconsistent,
makesupgradingtostrictermarkupversionsfareasier,andtendstohelpreduceerrors
causedbyinconsistency.
www.allitebooks.com
6 Part I: Core Markup
AgraphicaloverviewoftheHTMLmarkupsyntaxshownsofarispresentedhere:
Tag Attribute Attribute
Name Name Value
O NLINE http://htmlref.com/ch1/html4helloworld.html
Asimplemodificationoftheinitial<!DOCTYPE>lineisreallyallthatisnecessaryto
makethisanHTML5example,thecommentandtextischangedsoyoucankeepthe
examplesstraight:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HelloHTML5World</title>
<!--SimplehelloworldinHTML5example-->
</head>
<body>
<h1>WelcometotheFutureWorldofHTML5</h1>
<hr>
<p>HTML5<em>really</em>isn'tsohard!</p>
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 7
<p>Soonyouwill♥usingHTML.</p>
<p>Youcanputlotsoftexthereifyouwant.
Wecouldgoonandonwithfaketextforyou
toread,butlet'sgetbacktothebook.</p>
PART I
</body>
</html>
O NLINE http://htmlref.com/ch1/html5helloworld.html
InthecaseofXHTML,whichisaformofHTMLthatisbaseduponthesyntaxrulesof
XML,wereallydon’tseemanymajorchangesyetinourexample:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>HelloXHTMLWorld</title>
<!--SimplehelloworldinXHTML1.0strictexample-->
</head>
<body>
<h1>WelcometotheWorldofXHTML</h1>
<hr/>
<p>XHTML<em>really</em>isn'tsohardeither!</p>
<p>Soonyouwill♥usingXHTMLtoo.</p>
<p>TherearesomedifferencesbetweenXHTML
andHTMLbutwithsomeprecisemarkupyou'll
seesuchdifferencesareeasilyaddressed.</p>
</body>
</html>
O NLINE http://htmlref.com/ch1/xhtmlhelloworld.html
Theprecedingexamplesusesomeofthemostcommonelementsusedin(X)HTML
documents,including:
• The<!DOCTYPE>statement,whichindicatestheparticularversionofHTML
orXHTMLbeingusedinthedocument.Thefirstexampleusesthestrict4.01
specification,thesecondusesareducedformforHTML5themeaningofwhich
willbeexplainedabitlateron,andthefinalexampleusestheXHTML1.0strict
specification.
• The<html>,<head>,and<body>tagpairsareusedtospecifythegeneralstructure
ofthedocument.Therequiredinclusionofthexmlnsattributeinthe<html>tagis
asmalldifferencerequiredbyXHTML.
• The<meta>tagusedintheexamplesindicatestheMIMEtypeofthedocumentand
thecharactersetinuse.NoticethatintheXHTMLexample,theelementhasatrailing
slashtoindicatethatitisanemptyelement.
• The<title>and</title>tagpairspecifiesthetitleofthedocument,which
generallyappearsinthetitlebaroftheWebbrowser.
• Acommentisspecifiedby<!---->,allowingpageauthorstoprovidenotesfor
futurereference.
8 Part I: Core Markup
• The<h1>and</h1>headertagpairindicatesaheadlinespecifyingsomeimportant
information.
• The<hr>tag,whichhasaself-identifyingendtag(<hr/>)underXHTML,inserts
ahorizontalrule,orbar,acrossthescreen.
• The<p>and</p>paragraphtagpairindicatesaparagraphoftext.
• Aspecialcharacterisinsertedusinganamedentity(♥),whichinthiscase
insertsaheartdingbatcharacterintothetext.
• The<em>and</em>tagpairsurroundsasmallpieceoftexttoemphasizewhicha
browsertypicallyrendersinitalics.
Therearenumerousothermarkupelementsthatmaybeemployed,allofwhichwillbe
exploredthroughoutthebook,butfornowthissamplingisenoughtogetourfirstexample
renderedinabrowser.
NOTE ExamplesinthebookwillgenerallybepresentedinHTML5.Syntaxspecifictoparticular
browsers,olderHTMLvariants,orXHTMLwillalwaysbenotedwhenused.
Onceyourbrowserreadsthefile,itshouldrenderapageliketheoneshownhere:
PART I
Ifforsomereasonyoudidn’tsaveyourfilewiththeappropriateextension,thebrowser
shouldn’tattempttointerprettheHTMLmarkup.Forexample,noticeherewhathappens
whenyoutrytoopenthecontentwitha.txtextension:
Ifyouwanttomakeachangetothedocument,youcouldupdatethemarkup,savethe
file,gobacktothebrowser,andclicktheReloadorRefreshbutton.Sometimesthebrowser
willstillreloadthepagefromitscache;ifapagedoesnotupdatecorrectlyonreload,hold
downtheSHIFTkeywhileclickingtheReloadbutton,andthebrowsershouldrefreshthepage.
Asyouwritemarkup,keepingthebrowserandeditoropensimultaneouslyisavery
goodideatoavoidconstantlyreopeningoneortheother.ManyWebeditorswillassistyou
inloadingyourWebpagesintovariousbrowsersorevenpreviewthevisualizationofthe
markupdirectly.Figure1-1showsthisprocessinAdobe’spopularDreamweaverprogram
(www.dreamweaver.com).
10 Part I: Core Markup
Onceyougetthehangofmarkupproduction,you’llseethat,atthisrawlevel,itis
muchliketheedit,compile,andruncyclesofamiliartoprogrammers.However,this
manualprocesscertainlyisn’tthewaythatyouwanttodevelopWebpages,becauseitcan
betedious,errorprone,andinefficientwhenthinkingofpagestructureandvisualdesign.
Forourcurrentillustrativepurposestolearnthelanguagehowever,itworksfine.
Tomakeyourfilesavailableviatheserver,youmightuseaprocessofuploadinga
filefromyoursystemtoaremoteserverviaanFTP(FileTransferProtocol)program,as
shownhere:
PART I
ManyWebeditorsalsoallowyoutosynchronizefilesbetweenalocaldirectoryand
yourremoteserver.Forexample,asnippetofthesynchronizationfacilityprovidedin
Dreamweaverisshownhere:
12 Part I: Core Markup
OntheWebserver,youmostlikelywillusethe.htmlor.htmfileextensionforyour
files.WhenHTMLfilesareplacedintheappropriatedirectory,theuserwouldissueaURL
intheirbrowserlike
http://yoursitename/sitepath/helloworld.html
andthatwillthenreturnthefileinquestion.However,notethatwhenamarked-up
documentisdeliveredoverthenetwork,itisnotthefileextensionthatindicatestothe
browserthatthecontentisHTML,butrathertheContent-Type:headerfoundinthe
networkstream:
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 13
Thebrowserthentakestheheaderandmapsittotheactionofparsingthedocumentas
HTML.Insomeolderbrowsers,themappingbetweenMIMEtypeorfileextensionand
browseractionisobvious:
PART I
ThisPreferencesdialogboxshowsthattheextensionorheaderiswhattriggerstheaction
bythebrowser.Thegoalhereissimplytoillustratethatthereissomethingdifferentgoing
onbetweenreadinglocallyandremotely.
Beforewrappingupthisbriefintroductoryexample,itshouldbenotedthatinsome
caseswhenyouhaveconfiguredthewrongfileextensionorMIMEtype,somebrowsersmay
“sniffout”thecontenttypeandparseanyHTMLfoundwithin.Forexample,inFigure1-2
youcanseethatmanyversionsofInternetExplorer2renderafilewitha.txtextensionas
HTMLwhileFirefoxdoesnot.Wehavetopayattentiontodetailseveninthesimplest
examplesifwewanttoavoidheadachesfromquestionablebrowserpracticesandplainold
bugs.HTML5willaimtoremovesuchproblemsinthedistantfuture,butfornowlet’sget
downtothemostimportantdetails,startingfirstbyenumeratingalloftheversionsof
(X)HTMLthatwemightneedtoknowabout.
2
InternetExplorer8introducessomechangestoavoidsniffing;youcansetX-Content-Type-Options:
nosniffasaresponseheadertodisableInternetExplorer’spermissivebehavior,thoughthisonlyworks
inIE8andbeyond.
14 Part I: Core Markup
FIGURE 1-2 Irregularities with browsers handling MIME types and file extensions
PART I
tables and forms, but does not consider any of the browser innovations
of advanced features such as style sheets, scripting, or frames.
HTML 3.0 The proposed replacement for HTML 2.0 that was never widely
adopted, most likely due to the heavy use of browser-specific markup.
HTML 3.2 An HTML finalized by the W3C in early 1997 that standardized most of
the HTML features introduced in browsers such as Netscape 3. This
version of HTML supports many presentation-focused elements such
as font, as well as early support for some scripting features.
HTML 4.0 Transitional The 4.0 transitional form finalized by the W3C in December of 1997
preserves most of the presentational elements of HTML 3.2. It
provides a basis of transition to Cascading Style Sheets (CSS) as
well as a base set of elements and attributes for multiple-language
support, accessibility, and scripting.
HTML 4.0 Strict The strict version of HTML 4.0 removes most of the presentation
elements from the HTML specification, such as font, in favor of using
CSS for page formatting.
4.0 Frameset The frameset specification provides a rigorous syntax for framed
documents that was lacking in previous versions of HTML.
HTML 4.01 Transitional/ A minor update to the 4.0 standard that corrects some of the errors in
Strict/Frameset the original specification.
HTML5 Addressing the lack of acceptance of the XML reformulation of HTML
by the mass of Web page authors, the emerging HTML5 standard
originally started by the WHATWG3 group and later rolled into a W3C
effort aimed to rekindle the acceptance of traditional HTML and
extend it to address Web application development, multimedia, and
the ambiguities found in browser parsers. Since 2005, features now
part of this HTML specification have begun to appear in Web browsers,
muddying the future of XHTML in Web browsers.
XHTML 1.0 Transitional A reformulation of HTML as an XML application. The transitional
form preserves many of the basic presentation features of HTML 4.0
transitional but applies the strict syntax rules of XML to HTML.
XHTML 1.0 Strict A reformulation of HTML 4.0 Strict using XML. This language is rule
enforcing and leaves all presentation duties to technologies like CSS.
XHTML 1.1 A restructuring of XHTML 1.0 that modularizes the language for easy
extension and reduction. It is not commonly used at the time of this
writing and offers minor gains over strict XHTML 1.0.
3
WebHypertextApplicationTechnologyWorkingGroup(www.whatwg.org).
www.allitebooks.com
16 Part I: Core Markup
BeyondthestandardformsofmarkupdescribedinTable1-1,thereareofcoursevarious
nonstandardformsinplay.Forexample,thebrowservendorsintroducedvariousextensions
toHTMLand,interestingly,continuetodoso.Wealsohavetocontendwiththeadhocuse
ofmarkupthatdoesn’treallyconformfullytoanyparticularstandardotherthantowhat
usuallyrendersincommonWebbrowsers.Sucha“tagsoup”iscertainlynotthebestway
toapproachbuildingWebpages,regardlessofwhetherbrowsersacceptit.Standardsforall
formsofmarkupexistandshouldbeadheredtowheneverpossible.
<!--===================Paragraphs=====================================-->
<!ELEMENTP-O(%inline;)*--paragraph-->
<!ATTLISTP
%attrs;--%coreattrs,%i18n,%events--
>
Thefirstlineisacommentindicatingwhatisbelowit.ThesecondlinedefinestheP
element,indicatingthatithasastarttag(<P>),asshownbythedash,andanoptionalclose
tag(</P>),asindicatedbytheO.Thetypeofcontentthatisallowedtobeplacedwithina
Pelementisdefinedbytheentity%inline,whichactshereasashorthandforvariousother
elementsandcontent.Thisideaofonlyallowingsometypesofelementswithinother
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 17
elementsiscalledthecontentmodel.Ifyoufurtherexplorethespecificationtoseewhatthat
%inlineentitymapsoutto,youwillseethatitcontainsnumerousotherelements,suchas
EM,STRONG,andsoon,aswellasregulartypedtext.Thefinallinedefinestheattributesfor
PART I
a<P>tagasindicatedbytheentity%attrswhichthenexpandstoanumberofentitieslike
%core,%i18n,and%coreeventswhichfinallyexpandintoavarietyofattributeslikeid,
class,style,title,lang,dir,onclick,ondblclick,andmanymore.Thefullsyntax
ofthePelementcanbefoundinthereferenceinChapter3;theaimhereisforyouto
understandthesyntaxofSGMLinabasicsensetosupportyourunderstandingofhowWeb
browserstreatmarkup.
Asanotherexample,lookattheHTML4.01DTD’sdefinitionoftheHRelement:
<!--===================HorizontalRule================================-->
<!ELEMENTHR-OEMPTY--horizontalrule-->
<!ATTLISTHR
%attrs;--%coreattrs,%i18n,%events--
>
Fromthissyntaxfragment,notethattheHRelementhasastarttagbutdoesnotrequirea
closetag.Moreinterestingly,theelementdoesnotencloseanycontent,asindicatedbythe
EMPTYdesignation.ItturnsouttohavethesamesetofattributesasthePelement,as
definedbythe%attrsentity.
AsmentionedintheprevioussectiononthehistoryofHTML,in1999theW3Crewrote
HTMLasanapplicationofXMLandcalleditXHTML.XML,inthissituation,servesthe
samepurposeasSGML:alanguageinwhichtowritetherulesofalanguage.Infact,XMLis
insomesensejustalimitedformofSGML.XMLandSGMLcanbeusedtowritearbitrary
markuplanguages,notjustHTMLandXHTML.Thesewouldbecalledapplicationsor,maybe
moreappropriately,applicationlanguages.Numerousmarkuplanguageshavebeendefined
withSGMLandXML,andyoucouldevendefineyourownifyoulike.Therelationship
betweenthevariousmarkuptechnologiesisshownhere:
…
Example … … SOAP
Application TEI DocBook WML RSS
Languages
HTML XHTML
TheDTDdefinedinXMLfortheXHTMLlanguageisactuallyquitesimilartotheDTD
fortraditionalHTML.Forexample,considertheXHTMLDTDentriesforthetwoelements
previouslypresented:
<!--===================Paragraphs=====================================-->
<!ELEMENTp%Inline;>
<!ATTLISTp
%attrs;
>
18 Part I: Core Markup
<!--===================HorizontalRule================================-->
<!ELEMENThrEMPTY>
<!ATTLISThr
%attrs;
>
Asyoucansee,thereissomecasechanging(lowercaseelements),alackofoptionalclose
tags,andageneralcleanupofsyntax,butotherwisethingsareprettymuchthesame.
Properlyconstructed(X)HTMLdocumentsshouldreferenceaDTDofsomesortandit
isimportanttoknowwhatthismeansasbrowsersandWebqualityassurancetoolsactually
consultthedoctypedirectives.Hopefully,thisbriefintroductionhasgivenyouasenseof
theunderlyingspecificationof(X)HTMLanditsdegreeofdetail.AppendixEpresents
completecoverageofhowtoreadthe(X)HTMLDTDs.
NOTE Interestingly,HTML5doesnotuseSGMLorXMLdefinitions,butinsteadreliesonan
Englishprosespecificationcombinedwithsomeformalism.Chapter3discussesthischangeand
someotheraspectsoftheHTML5languageandspecificationthatisdifferentfromtheolder
markuplanguages.
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
indicatesthatweareusingthetransitionalvariationofHTML4.01thatstartswitharoot
elementhtml.Inotherwords,an<html>tagwillserveastheultimateparentofallthe
contentandelementswithinthisdocument.
A<!DOCTYPE>declarationmightgetabitmorespecificandspecifytheURI(Uniform
ResourceIdentifier)oftheDTDbeingusedasshownhere:
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
InthecaseofanXHTMLdocument,thesituationreallyisn’tmuchdifferent:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
However,donotethattheroothtmlelementhereislowercase,whichhintsatthecase
sensitivityfoundinXHTML.
TherearenumerousdoctypedeclarationsthatarefoundinHTMLandXHTML
documents,asshowninTable1-2.
NOTE OnoccasionyoumightseeotherHTMLdocumenttypeindicators,notablyoneforthe3.0
standardthatwasneverreallyadoptedintheWebcommunity.
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 19
PART I
HTML 3.2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
HTML 4.0 Transitional <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
HTML 4.0 Frameset <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">
HTML 4.0 Strict <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"
"http://www.w3.org/TR/html4/strict.dtd">
HTML 4.01 Transitional <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
HTML 4.01 Frameset <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">
HTML 4.01 Strict <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
HTML5 <!DOCTYPE html>
XHTML 1.0 Transitional <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
XHTML 1.0 Strict <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
XHTML 1.0 Frameset <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
XHTML 1.1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
XHTML 2.0 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 2.0//EN"
"http://www.w3.org/MarkUp/DTD/xhtml2.dtd">
XHTML Basic 1.0 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN"
"http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd">
XHTML Basic 1.1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN"
"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
Whiletherearemanydifferentversionsof(X)HTML,thegoodnewsisthattherough
documentstructuredefinedforeachisprettysimilar;ofcourse,thebadnewsisthat
littledetailswillbedifferentfromversiontoversion,soyouneedtobeprecisewithyour
syntax.
20 Part I: Core Markup
<html>
<head>
<meta http-equip="Content-Type"
content="text/html; charset=utf-8"> Head contains
<title>Page Title</title> info about page
Body
</body>
</html>
Filename: template.html
Inthisgraphicalrepresentation,the<!DOCTYPE>indicator,which,aspreviously
mentioned,showstheparticularversionofHTMLbeingused,inthiscase4.01Transitional.
Withinaroothtmlelement,thebasicstructureofadocumentrevealstwoelements:thehead
andthebody.Theheadelementcontainsinformationandtagsdescribingthedocument,such
asitstitle,whilethebodyelementhousesthedocumentitself,withassociatedmarkup
requiredtospecifyitsstructure.HTML5followsthesamecorestructurebutintroduces
differences,whichiscoveredindepthinChapter2.
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 21
ThestructureofanXHTMLdocumentisprettymuchthesamewiththeexceptionofa
different<!DOCTYPE>indicatorandanxmlns(XMLnamespace)attributeaddedtothe
htmltagsothatitispossibletointermixXMLmoreeasilyintotheXHTMLdocument:
PART I
Doctype statement indicates type of document
<html xmlns=“http://www.w3.org/1999/xhtml”>
<head>
<meta http-equip="Content-Type"
content="text/html; charset=utf-8" /> Head contains
<title>Page Title</title> info about page
</head>
Body
</body>
</html>
Filename: template.html
Alternatively,ineitherHTMLorXHTML(butnotinHTML5),wecanreplacethe
<body>tagwitha<frameset>tag,whichenclosespotentiallynumerous<frame>tags
correspondingtoindividualportionsofthebrowserwindow,termedframes.Eachframein
turnwouldreferenceanotherHTML/XHTMLdocumentcontainingeitherastandard
document,completewith<html>,<head>,and<body>tags,orperhapsyetanother
frameddocument.The<frameset>tagalsoshouldincludeanoframeselementthat
providesaversionofthepageforbrowsersthatdonotsupportframes.Withinthiselement,
22 Part I: Core Markup
a<body>tagshouldbefoundforbrowsersthatdonotsupportframes.Avisual
representationofthisideaisshownhere:
<html>
<head>
<meta http-equip="Content-Type"
content="text/html; charset=utf-8"> Head contains
<title>Page Title</title> info about page
</frameset>
<noframes>
<body>
Body
</body>
</noframes>
</html>
Filename: template.html
HTML5doesnotsupportstandardframes,thoughitdoespreserveinlineframes.
Chapter2addressesthatHTML5–specificchange;fornow,we’llconcentrateonatypical
documentstructureanddrillintoeachelementuntilwereachtheverycharactersdisplayed.
Roughlyspeaking,thestructureofanon-framed(X)HTMLdocumentbreaksoutlikeso:
HTML
HEAD BODY
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 23
Thefollowingsectionsdrillintoeachofthedocumentstructuringmarkupelementsand
explorewhat’scontainedinside.
PART I
The Document Head
Theinformationintheheadelementofan(X)HTMLdocumentisveryimportantbecauseit
isusedtodescribeoraugmentthecontentofthedocument.Theelementactslikethefront
matterorcoverpageofadocument.Inmanycases,theinformationcontainedwithinthe
headelementisinformationaboutthepagethatisusefulforvisualstyling,defining
interactivity,settingthepagetitle,andprovidingotherusefulinformationthatdescribesor
controlsthedocument.
<title>SimpleHTMLTitleExample</title>
youwillseesomethinglikethis:
Whenatitleisnotspecified,mostbrowsersdisplaytheURLpathorfilenameinstead:
Onlyonetitleelementshouldappearineverydocument,andmostuseragentswill
ignoresubsequenttaginstances.Youshouldbequitecarefulaboutmakingsureatitle
elementiswellformedbecauseomittingtheclosetagcancausemanybrowserstonotload
thedocument.ArecentversionofOperarevealswhatislikelyhappeninginthissituation:
Hereitappearsthatthemarkupandrestofthedocumentareusedasthecontentsofthe
unclosedtitleelement,andthusnothingisrenderedinthebrowser.Itshouldbenotedthat
thisparticularrenderingmayvarybecausesomebrowsersfixanunclosedtitle.
24 Part I: Core Markup
Adocumenttitlemaycontainstandardtext,butmarkupisn’tinterpretedina<title>
tag,asshownhere:
However,characterentitiessuchas©(or,alternatively,©),whichspecifiesa
copyrightsymbol,areallowedinatitle:
<title>SimpleHTMLTitleExample,©2010WebMonopoly,Inc.</title>
Foranentitytobedisplayedproperly,youneedtomakesuretheappropriatecharacter
setisdefinedandthatthebrowsersupportssuchcharacters;otherwise,youmayseeboxes
orotheroddsymbolsinyourtitle:
Tosettheappropriatecharacterset,youshouldincludea<meta>tagbeforethepage
titleeventhoughtraditionallytitleisconsideredthefirstelement.
NOTE Beyondcharactersetconcerns,thinktwicebeforeusingaspecialcharactersuchasacolon
(:),slash(/),orbackslash(\)inadocumenttitle.Anoperatingsystemmighthaveaproblem
withsuchatitleifthedocumentissavedtothelocalsystem.Forexample,thecolonisn’tallowed
withinMacintoshfilenames,andslashesgenerallyaren’tallowedwithinfilenames,becausethey
indicatedirectories.Mostmodernbrowsersremovesuchspecialcharactersandreducethemto
spacesduringtheSaveprocess.Tobeonthesafeside,usedashestodelimititemsinapagetitle.
<metahttp-equiv="Content-Type"content="text/html;charset=ISO-8859-1">
Becausemetaisanemptyelement,youwouldusethetrailing-slashsyntaxshownhere:
<metahttp-equiv="Content-Type"content="text/html;charset=ISO-8859-1"/>
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 25
MostpeoplewouldagreethatusingtheUTF-8charactersetisprobablyagoodideafor
Western-languagepageauthorsbecauseitgivesthemaccesstointernationalcharacter
glyphswhenneededwithoutcausingthemanytrouble:
PART I
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
DecidingwhichMIMEtypetouseisn’tasstraightforward.ForstandardHTML,the
MIMEtypeisalwaystext/html.However,whenXHTMLisinplay,confusionand
browserproblemsensue.NumerouspunditsbemoanthefactthatmostXHTMLisservedas
text/html,particularlybecauseitdoesn’tgiveyouthestrictparsingthatXMLtendsto
afford.IntheuseofXHTML,youmaychoosefromtext/html,text/xml,application/
xml,andapplication/xhtml+xmlaspotentialMIMEtypes.Giventhepotentialfor
compatibilityandevenrenderingproblems,forbetterorworse,theMIMEtypetext/html
willbeusedfornearlyall(X)HTMLexamplesinthisbooksothatbrowserrenderingis
ensured.Thishedgewillbeexploredabitmorelaterinthechapterwhenaddressingthe
implicationsofXHTML.Insummaryatthepointofwritingthisedition,itisrecommend
specifyingaContent-Typeoftext/htmlandtheUTF-8characterset,anddoingsoas
yourfirstelementwithinthehead,likeso:
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>Pagetitlehere</title>
</head>
NOTE ThemetaelementalsohasmanyotherusesbeyonddefiningcharactersetandMIMEtype.
Itisalsousedtosetarbitraryname-contentpairstoprovidemeta-informationaboutadocument
forpurposeslikesearchengineoptimization(forexample,<metaname="keywords"
content="Keyword1,...KeywordN">).Otherusesof<meta>tagswillbecoveredin
thereferencesectionofChapter3.
<base> A<base>tagspecifiesanabsoluteURLaddressthatisusedtoprovideserver
anddirectoryinformationforpartiallyspecifiedURLaddresses,calledrelativelinks,used
withinthedocument:
<basehref="http://htmlref.com/basexeample">
Becauseofitsglobalnature,a<base>tagisoftenfoundrightaftera<title>tagasit
mayaffectsubsequent<script>,<link>,<style>,and<object>tagreferencedURIs.
www.allitebooks.com
26 Part I: Core Markup
<link> A<link>tagspecifiesaspecialrelationshipbetweenthecurrentdocumentand
anotherdocument.Mostcommonly,itisusedtospecifyastylesheetusedbythedocument
(asdiscussedinChapter4):
<linkrel="stylesheet"media="screen"href="global.css"type="text/css">
However,the<link>taghasanumberofotherinterestingpossibleuses,suchastoset
upnavigationrelationshipsandtohinttobrowsersaboutpre-cacheablecontent.Seethe
elementreferenceinChapter3formoreinformationonthis.
<object> An<object>tagallowsprogramsandotherbinaryobjectstobedirectly
embeddedinaWebpage.Here,forexample,anonvisibleFlashobjectisbeingreferenced
forsomeuse:
<objectclassid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
width="0"height="0"id="HiddenFlash">
<paramname="movie"value="flashlib.swf"/>
</object>
Usingan<object>taginvolvesmorethanabitofcomplexity,andtherearenumerous
choicesoftechnology,includingJavaapplets,plug-ins,andActiveXcontrols.
<script> A<script>tagallowsscriptinglanguagecodetobeeitherdirectlyembedded
within,
<scripttype="text/javascript">
alert("HifromJavaScript!");
/*morecodebelow*/
</script>
or,moreappropriately,linkedtofromaWebpage:
<scripttype="text/javascript"href="ajaxtcr.js"></script>
Nearlyalways,JavaScriptisthelanguageinuse,thoughotherlanguagessuchasVBScript
arepossible.
<style> A<style>tagisusedtoenclosedocument-widestylespecifications,typically
inCascadingStyleSheet(CSS)format,relatingtofonts,colors,positioning,andother
aspectsofcontentpresentation:
<styletype="text/css"media="screen">
h1{font-size:xx-large;color:red;font-style:italic;}
/*allh1elementsrenderasbig,redanditalic*/
</style>
TheuseofthistagwillbediscussedinChapter4.
Comments Finally,commentsareoftenfoundintheheadofadocument.FollowingSGML
syntax,acommentstartswith<!--andendswith-->andmayencompassmanylines:
<!--HiIamacomment-->
<!--Author:ThomasA.Powell
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 27
Book:HTML:TheCompleteReference
Edition:5
-->
PART I
Commentscancontainjustaboutanythingexceptothercommentsandareparticularly
sensitiveto–symbols.Thus
<!------THISISN'TASYNTACTICALLYCORRECTCOMMENT!---->
NOTE Correctusageofcommentsgoeswellbeyondsyntax,becausetheymayinherentlyexpose
securityconcernsonpublic-facingsites.You’llalsofindthatcommentsareusednotonlyfor
developmentnotesbutalsotomasksometypesofcontentfrombrowsers.
Thecompletesyntaxofthemarkupallowedintheheadelementunderstrict(X)HTML
isshownhere:
head
mandatory
title
single occurrence
base
and generally early
link
style
script
object
meta
<!-- -->
FollowingisanexampleXHTMLdocumentwithaheadelementthatcontainscommon
usageofelements:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>SampleHeadElement</title>
<!--Someexamplemetatags-->
<metaname="keywords"content="Fake,HeadExample,HTMLRef"/>
<metaname="description"content="Asimpleheadexamplethatshowsanumber
oftheelementspresentedinaction."/>
<metaname="author"content="ThomasA.Powell"/>
28 Part I: Core Markup
<!--SetaglobalURIstemforallreferences-->
<basehref="http://htmlref.com/baseexample"/>
<!--Linkedanddocumentspecificstyles-->
<linkrel="stylesheet"href="screen.css"media="screen"/>
<linkrel="stylesheet"href="printer.css"media="print"/>
<styletype="text/css">
<!--
h1{font-size:xx-large;color:red;font-style:italic;}
-->
</style>
<!--Embeddedandlinkedscripts-->
<scripttype="text/javascript">
<!--
varglobalDebug=true;
//-->
</script>
<scriptsrc="ajaxtcr.js"type="text/javascript"></script>
<scriptsrc="effects.js"type="text/javascript"></script>
</head>
<body>
<p>Somebodycontenthere.</p>
</body>
</html>
Thevariousdetailsofthetagswithinthedocumentheadareallpresentedinthe
elementreferenceinChapter3;theaimherewastoshowyoutheorganizationofthehead
elementandhowitsupportsthebody.Nowlet’smoveontoseethecontentinthe
documentbodyitself.
Othermiscellaneoustypesofelements,includingthosethatreferenceotherobjectssuch
asimages(img)orinteractiveelements(object),arealsogenerallyfoundwithinblocks,
thoughinsomeversionsofHTMLtheycanstandontheirown.
PART I
Withinblockandinlineelements,youwillfindtextualcontent,unlesstheelementis
empty.Typedtextmayincludespecialcharactersthataredifficulttoinsertfromthe
keyboardorrequirespecialencoding.TousesuchcharactersinanHTMLdocument,they
mustbe“escaped”byusingaspecialcode.Allcharactercodestaketheform&code;,where
codeisawordornumericcodeindicatingtheactualcharacterthatyouwanttoput
onscreen.Forexample,whenaddingaless-thansymbol(<)youcoulduse<or<.
CharacterentitiesalsoarediscussedindepthinAppendixA.
Finally,justasinthehead,youmayincludecommentsinthebodyelement.
Avisualoverviewofalltheitemspresentedinthebodyisshownhere:
Comment
Block Elements
Inline Elements
Character Entity
30 Part I: Core Markup
Thefullsyntaxoftheelementsallowedinthebodyelementisabitmoreinvolvedthan
thefullsyntaxofthehead.Thisdiagramshowswhatisdirectlyincludedinthebody:
body
div
ul, ol
li
dl
dt, dd
pre
hr
blockquote
address
fieldset
table
noscript
script
ins
del
<!-- -->
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 31
Goingdeeperintothefullsyntaxinasinglediagramisunreasonabletopresent.Justas
anexample,takethepelementandcontinuetoexpand,keepinginmindthatthese
elementswillalsoloopbackoneachotherandexpandoutaswell:
PART I
p
a small acronym
br em sub
object q textarea*
tt kbd button*
b cite
WhileitmightbedifficulttomeaningfullypresenttheentiresyntaxofHTML
graphicallyinadiagram,thediagrampresentedhereshoulddrivehomethepointthat
HTMLisquitestructuredandthedetailsofhowelementsmaybeusedarequiteclear.Now
thatyouhavesomeinsightintothesyntaxofmarkup,thenextsectiondiscusseshow
browsersdealwithit.
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HelloHTMLWorld</title>
<!--SimplehelloworldinHTML4.01strictexample-->
</head>
<body>
<h1>WelcometotheWorldofHTML</h1>
32 Part I: Core Markup
<hr>
<p>HTML<em>really</em>isn'tsohard!</p>
<p>Soonyouwill♥usingHTML.</p>
<p>Youcanputlotsoftexthereifyouwant.
Wecouldgoonandonwithfaketextforyou
toread,butlet'sgetbacktothebook.</p>
</body>
</html>
itbuildsaparsetreetointerpretthestructureofthedocument,possiblylikethis:
DOCTYPE Legend
TITLE
BODY
H1
HR
“HTML”
EM
“Really”
“isn’t so hard!”
Theseparsetrees,oftencalledDOM(DocumentObjectModel)trees,arethebrowsers’
interpretationofthemarkupprovidedandareintegraltodetermininghowtorenderthe
pagevisuallyusingbothdefault(X)HTMLstyleandanyCSSattached.JavaScriptwillalso
PART I
usethisparsetreewhenscriptsattempttomanipulatethedocument.Theparsetreeserves
astheskeletonofthepage,somakingsurethatitiscorrectisquiteimportant,butsadly
we’llseeveryoftenitisn’t.
NOTE Thesyntaxtreespresentedearlierlookverysimilartotheparsetrees,andtheyshould,
becauseanyparticularparsetreeshouldbederivablefromtheparticularmarkuplanguage’s
contentmodel.
Browsersareactuallyquitepermissiveinwhattheywillrender.Forexample,consider
thefollowingmarkup:
<TITLE>HelloHTMLWorld</title>
<!--Simplehellomalformedworld--example-->
</head>
<body>
<h1>WelcometotheWorldofHTML</H1>
<hr/>
<p>HTML<eM>really</Em>isn'tsohard!
<P>Soonyouwill♥usingHTML.
<p>Youcanputlotsoftexthereifyouwant.
Wecouldgoonandonwithfaketextforyou
toread,<foo>but</foo>let'sgetbacktothebook.
</html>
Thisexamplemissesimportanttags,doesn’tspecifyencodingtypes,hasamalformed
comment,usesinconsistentcasing,doesn’tclosetags,andevenusessomeunknown
elementfoo.However,thiswillrenderexactlythesamevisuallyasthecorrectmarkup
previouslypresented,asshowninFigure1-3.
34 Part I: Core Markup
Well-formed
Markup
Malformed
Markup
Nowifyoulookattheparsetreeformedbythebrowser,youwillnotethatmanyofthe
mistakesappeartobemagicallyfixedbythebrowser:
PART I
Ofcourse,thenumberofassumptionsthatabrowsermaymaketofixarbitrary
syntacticalmistakesislikelyquitelargeanddifferentbrowsersmayassumedifferent
“fixes.”Forexample,giventhissmallfragmentofmarkup
<p>MakingmalformedHTML<em><strong>really<em><strong>isn'tsohard!</p>
leadingbrowserswillformtheirparsetreesabitdifferently,asshowninFigure1-4.
www.allitebooks.com
36 Part I: Core Markup
FIGURE 1-4 Same markup, different parse, as shown in Firefox 3 (above) and Internet Explorer 8 (below)
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 37
Simplyput,itisquiteimportanttoaimforcorrectmarkupasasolidfoundationfora
Webpageandtonotassumethemarkupiscorrectjustbecauseitappearstorender
correctlyinyourfavoritebrowser.
PART I
Validation
Asshownearlier,aDTDdefinestheactualelements,attributes,andelementrelationships
thatarevalidindocuments.Nowyoucantakeadocumentwrittenin(X)HTMLandthen
checkwhetheritconformstotherulesspecifiedbytheDTDused.Thisprocessofchecking
whetheradocumentconformstotherulesoftheDTDiscalledvalidation.
The<!DOCTYPE>declarationallowsvalidationsoftwaretoidentifytheHTMLDTD
beingfollowedinadocument,andverifythatthedocumentissyntacticallycorrect—in
otherwords,thatalltagsusedarepartofaparticularspecificationandarebeingused
correctly.Aneasywaytovalidateadocumentissimplytouseanonlineservicesuchasthe
W3CMarkupValidationService,athttp://validator.w3.org.Ifthemalformedexample
fromtheprevioussectionispassedtothisservice,itclearlyshowsthatthepagehaserrors:
38 Part I: Core Markup
PasstheURLtotheserviceyourselfbyusingthislinkintheaddressbar:
http://validator.w3.org/check?uri=http%3A%2F%2Fhtmlref.com%2Fch1%2Fmalforme
dhelloworld.html
Byreadingthevalidator’smessagesabouttheerrorsitdetected,youcanfindand
correctthevariousmistakes.Afterallmistakesarecorrected,thedocumentshouldvalidate
cleanly:
Webdevelopersshouldaimtostartwithabaselineofvalidmarkupbeforetryingto
addressvariousbrowserquirksandbugs.GiventhatsomanyWebpagesontheWebare
poorlycoded,somedevelopersopttoadda“quality”badgetoapagetoshoworeven
provestandardsconformance:
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 39
Whetheruserscareaboutsuchthingsisdebatable,buttheaimforcorrectnessis
appropriate.Contrastthistothetypicaleffortoftestingapagebyviewingitinvarious
browserstoseewhathappens.Thethoughtis,ifitlooksright,thenitisright.However,this
PART I
doesnotacknowledgethatthesetofsupportedorrenderablepagesabrowsermayhandle
isasupersetofthosewhichareactuallyconformingtoaparticularspecification:
Conforming
Markup
Unsupported Markup
Itisanunfortunaterealitythatbrowserssupportamultitudeofincorrectthingsand
thatdevelopersoftenuseapopularbrowserasanacceptanceenginebaseduponsomepage
renderingforbetterorworse.Suchanapproachtomarkuptestingmightseemreasonable
intheshortterm,butitwillultimatelyleadtosignificantdeveloperfrustration,particularly
asothertechnologiesareadded,suchasCSSandJavaScript,andnewerbrowsersare
introduced.Unfortunately,giventhebrowsers’currentmethodofallowinggarbageyet
preferringstandards,thereislittlereasonforsomedeveloperstocareuntilsuchapriceis
realized.
dubbedthe“doctypeswitch.”Whenabrowserseesaknownstandards-focuseddoctype
indicator,itswitchesintoastandardscompliantparse:
However,ifthe<!DOCTYPE>statementismissing,referencesaveryoldversionlike3.2,
orisunknown,thebrowserwillenterintoquirksmode.Browsersmayprovideanindication
oftherenderingmodeviaanentryinpageinfo:
DTD Missing
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 41
Inothercases,youmayneedtouseatooltodeterminetheparsemode:
PART I
Webdevelopersshouldaimforasolidmarkupfoundationthatisparsedina
predictablemanner.Thenumberofrenderingodditiesthatwillstillbeencounteredeven
withsuchasolidfootingisnotinconsequential,soit’sbestnottotemptfateandinsteadto
trytofollowthe“rules”ofmarkup.
<B>Goboldly</B>
<B>Goboldly</b>
<b>Goboldly</B>
<b>Goboldly</b>
Inthepast,developerswerehighlyopinionatedabouthowtocaseelements.Somedesigners
pointedtotheeaseoftypinglowercasetagsaswellasXHTML’srequirementforlowercase
elementsasreasonstogoalllowercase.HTML5revertsbacktocase-insensitivemarkupand
thuswemayseeareturntouppercasetagsbystandardsawaredevelopers.
42 Part I: Core Markup
<strong>Testofspaces</strong><br>
<strong>Testofspaces</strong><br>
<strong>T
es
tofspaces</strong><br>
Asshownhere,allthespaces,tabs,andreturnsarecollapsedtoasingleelement:
However,itispossibletoforcethewhitespaceissue.Ifmorespacesarerequired,itis
possibletousethenonbreakingspaceentity,or .Someconsiderthistheducttapeof
theWeb—usefulinabindwhenalittlebitofspacingisneededoranelementhastobekept
fromcollapsing.Yetusingmarkupsuchas
Look,I'mspacedout!
wouldaddspacetotheoutput,thequestionis,exactlyhowfar?Inprint,usingspacesto
formatisdangerousgivenfontsizevariability,sotextrarelylinesup.Thisisnodifferenton
theWeb.
Furthernotethatinsomesituations,(X)HTMLdoestreatwhitespacecharactersdifferently.
Inthecaseofthepreelement,whichdefinesapreformattedblockoftext,whitespaceis
preservedratherthanignoredbecausethecontentisconsideredpreformatted.Itisalso
possibletousetheCSSpropertywhite-spacetochangedefaultwhitespacehandling.
Becausebrowserswillignoremostwhitespace,Webpageauthorsoftenformattheir
documentsforreadability.However,therealityisthatbrowsersreallydon’tcareonewayor
another,nordoendusers.Becauseofthis,somesiteshaveadoptedamarkupoptimization
idea,oftencalledcrunchingorminification,tosavebandwidth.
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 43
PART I
<ul>
<p>Whatasimplewaytobreakthecontentmodel!</p>
</ul>
whichoftenisusedforsimpleindentation,actuallydoesn’tfollowthecontentmodelforthe
strict(X)HTMLspecifications.The<ul>tagisonlysupposedtocontain<li>tags.The<p>
tagisnotreallyappropriateinthiscontext.Muchofthetime,Webpageauthorsareableto
getawaywiththis,butoftentheycan’t.Forexample,insomebrowsers,the<input>tag
foundoutsidea<form>tagissimplynotdisplayed,yetinotherbrowsersitis.
<p>Thisisn'tclosed
<p>Thisis</p>
However,giventhecontentmodel,thecloseofthetopparagraphcanbeinferredsinceits
contentmodeldoesn’tallowforanother<p>tagtooccurwithinit.HTML5continuesto
allowthis,asdiscussedinChapter2.
Afewelements,likethehorizontalrule(hr)andlinebreak(br),donothaveclosetags
becausetheydonotencloseanycontent.Theseareconsideredemptyelementsandcanbe
usedasisintraditionalHTML.However,underXHTMLyoumustalwaysclosetags,so
youwouldhavetowrite<br></br>or,morecommonly,useaself-closingtagformatwith
afinal“/”character,likeso:<br/>.
<p></p><p></p><p></p>
doesthisproducenumerousblanklines?No,sincethebrowserminimizestheemptyp
elements.SomeHTMLeditorsoutputnonsensemarkupsuchas
<p> </p><p> </p><p> </p>
todealwiththis.Ifthislookslikemisusedmarkuptoyou,you’reright!
<b><i>isinerrorastagscross</b></i>
44 Part I: Core Markup
whereas
<b><i>isnotsincetagsnest</i></b>
andthusissyntacticallycorrect.Allformsofmarkup,traditionalHTML,XHTML,and
HTML5,followthisrule,andwhilecrossingtagsmayseemharmless,itdoesintroduce
someambiguityinparsetrees.Tobeawell-formedmarkup,propernestingismandatory.
<imgsrc=robot.gifheight=10width=10alt=robot>
wouldworkfineinmostbrowsersandwouldvalidate.However,thelackofquotescan
leadtotrouble,especiallywhenscriptingisinvolved.Quotesshouldbeusedunder
transitionalmarkupformsandarerequiredunderstrictformslikeXHTML;so,
<imgsrc="robot.gif"height="10"width="10"alt="robot"/>
wouldbethecorrectformofthetag.Generally,itdoesn’tmatterwhetheryouusesingleor
doublequotes,unlessotherquotesarefoundwithinthequotes,whichiscommonwith
JavaScriptorevenwithCSSwhenitisfoundinanattributevalue.Stylistically,double
quotestendtobefavored,buteitherwayyoushouldbeconsistent.
<bogus>thistextwilldisplayonscreen</bogus>
andmarkupsuchas
<pid="myPara"obviouslybadattribute="TRUE">willalsorenderfine.</p>
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 45
Browsersmakebestguessesatstructuringmalformedcontentandtendtoignorecode
thatisobviouslywrong.Thepermissivenatureofbrowsershasresultedinamassivenumber
ofmalformedHTMLdocumentsontheWeb.Oddly,frommanypeople’sperspective,this
PART I
isn’tanissue,becausethebrowsersdomakesenseoutofthe“tagsoup”theyfind.However,
suchacavalieruseofthelanguagecreatesdocumentswithshakyfoundationsatbest.Once
othertechnologiessuchasCSSandJavaScriptarethrownintothemix,brazenflauntingofthe
rulescanhaverepercussionsandmayresultinbrokenpages.Furthermore,toautomatethe
exchangeofinformationontheWeb,collectivelyweneedtoenforcestricterstructureofour
documents.Thefocusonstandards-basedWebdevelopmentandfuturedevelopmentof
XHTMLandHTML5bringssomehopeforstabilityandstructureofWebdocuments.
<b>Thisisimportant!</b>
ThissimpleapproachfitswiththeWYSIWYG(whatyouseeiswhatyouget)worldofprograms
suchasMicrosoftWord.
Logicalmarkupisalittlelessobvious;toindicatetheimportanceofthephrase,itshould
beenclosedinthelogicalstrongelement:
<strong>Thisisimportant.</strong>
Interestingly,thedefaultrenderingofthiswouldbetoemboldenthetext.Giventhe
difference,itseemsthesimpler,moreobviousapproachofusinga<b>tagisthewaytogo.
However,actuallythesemanticmeaningofstrongprovidesabitmoreflexibilityandis
preferred.Remember,the<strong>tagisusedtosaythatsomethingisimportantcontent,
nottoindicatehowitlooks.IfaCSSruleweredefinedtosaythatimportantitemsshould
bebig,red,anditalic
<style="text/css">
strong{font-size:xx-large;color:red;font-style:italic;}
</style>
confusionwouldnotnecessarilyensue,becauseweshouldn’thaveapredisposedviewof
whatstrongmeansvisually.However,ifwepresentedaCSSruletomake<b>tagsact
assuch,itmakeslesssensebecauseweassumethatthemeaningofthetagissimplyto
emboldensometext.
www.allitebooks.com
46 Part I: Core Markup
HTMLunfortunatelymixeslogicalandphysicalmarkupthinking.Evenworse,common
renderingsaresofamiliartodevelopersthattagsthatarelogicalareassumedphysical.What
doesan<h1>tagdo?MostWebdeveloperswouldsayitdefinesabigheading.However,
thatisassumingaphysicalview;itissimplysayingthattheenclosedcontentisalevelone
heading.Howsuchaheadinglooksiscompletelyarbitrary.WhilemanyofHTML’slogical
elementsarerelativelyunderutilized,others,suchasheadingsandparagraphs(<p>),are
usedregularlythoughtheyaregenerallythoughtofasphysicaltagsbymostHTMLusers.
Considerthatpeoplegenerallyconsider<h1>alargeheading,<h2>asmallerheading,and
predictthat<p>tagscausereturnsandyoucanseethat,logicalornot,thelanguageisphysical
tomostofitsusers.However,doesthathavetobethecase?No,thesearelogicalelementsand
therenderings,whilecommon,arenotrequiredandCSSeasilycanchangethem.
Thebenefitsoflogicalelementsmightnotbeobvioustothosecomfortablewithphysical
markup.Tounderstandthebenefits,it’simportanttorealizethatontheWeb,manybrowsers
renderthingsdifferently.Inaddition,predictingwhattheviewingenvironmentwillbeis
difficult.Whatbrowserdoestheuserhave?Whatishisorhermonitor’sscreenresolution?
Doestheuserevenhaveascreen?Consideringtheextremeoftheuserhavingnoscreenat
all,howwouldaspeakingbrowserrendera<b>tag?Whatabouta<strong>tag?Text
taggedwith<strong>mightbereadinafirmvoice,butboldfacedtextmightnothavean
easilytranslatedmeaningoutsidethevisualrealm.
Manyrealisticexamplesexistofthepoweroflogicalelements.Considerthe
internationalaspectsoftheWeb.Insomecountries,thedateiswrittenwiththedayfirst,
followedbythemonthandyear.IntheUnitedStates,thedategenerallyiswrittenwith
themonthfirst,andthenthedayandyear.A<date>ora<time>tag,thelatterofwhich
isactuallynowpartofHTML5,couldtagtheinformationandenablethebrowserto
localizeitfortheappropriateviewingenvironment.Inshort,separationofthelogical
structurefromthephysicalpresentationallowsmultiplephysicaldisplaystobeapplied
tothesamecontent.Thisisapowerfulideawhich,unfortunately,eventodayisrarely
takenadvantageof.
Whetheryousubscribetothephysical(specific)orlogical(general)viewpoint,
traditionalHTMLisneitherpurelyphysicalnorpurelylogical,atleastnotyet.Inother
words,currentlyusedHTMLelementscomeinbothflavors,physicalandlogical,though
usersnearlyalwaysthinkofthemasphysical.Thisislikelynotgoingtogetsettledsoon;
thebattlebetweenlogicalandphysicalmarkuppredatesHTMLbyliterallydecades.
HTML5willcertainlysurpriseanyreaderswhoarealreadylogicalmarkupfans,because
itfullypreservestraditionalpresentationaltagslike<b>and<i>,giventheircommon
use,thoughjumpsthroughsomeinterestingmentalhoopstoclaimmeaningischanged.
Further,thenewspecificationpromotesmedia-andvisual-focusedmarkuplike
<canvas>and<video>andintroducestremendouslypowerfulnavigationaland
sectioninglogical-focusedtags.Ifrecenthistoryisanyguide,thenHTML5islikelygoing
topickupmanyfans.
littletochangethisthinking,withthelatestbrowserhacksandfiltersaspopularasthepixel
tricksandtablehacksofthegenerationbefore.Developerstendtofavorthatwhichiseasy
andseemstowork,sowhybothertoputmoretimein,particularlyifbrowsersrenderthe
PART I
almostrightmarkupwithlittlecomplaintandnotice?
Obviously,this“goodenough”approachsimplyisn’tgoodenough.Withoutstandards,
themodernworldwouldn’tworkwell.Forexample,imagineaworldofconstructionin
whicheverynutandboltmightbeaslightlydifferentsize.Standardsprovideneeded
consistency.TheWebneedsstandards,butstandardshavetoacknowledgewhatpeople
actuallydo.DeclaringthatWebdevelopersreallyneedtovalidate,uselogicalmarkup,and
separatethelookfromthestructureofthedocumentisgreatbutitdoesn’tgetthemtodo
so.Standardsareespeciallypointlessiftheyareneverwidelyimplemented.
WebtechnologiestodayarelikeEnglish—widelyunderstoodbutpoorlyspoken.However,
atthesametimetheyaretheLatinoftheWeb,providingastrongfoundationfordevelopment
andintersectingwithnumeroustechnologies.Webstandardsanddevelopmentpractices
provideaninterestingstudyofthedifferencebetweenwhattheoristssayandwhatpeople
wantanddo.HTML5seemsastepintherightdirection.Thespecificationacknowledgesthat,
forbetterorworse,traditionalHTMLpracticesareherefornow,andthusattemptstomake
themsolidwhilecontinuingtomovetechnologyforwardandencouragecorrectusage.
ofthosethatare,aredoneincorrectly.Poordevelopereducation,themorestringentsyntax
requirements,andultimatelythelackofobvioustangiblebenefitmayhavekeptmanyfrom
adoptingtheXMLvariantofHTML.
Myth: (X)HTML Is the Most Important Technology Needed to Create Web Pages
Whereas(X)HTMListhebasisforWebpages,youneedtoknowalotmorethanmarkupto
buildusefulWebpages(unlessthepageisverysimple).However,don’tunderestimate
PART I
markup,becauseitcanbecomeabitofachallengeitself.Basedonthesimpleexamples
presentedinthischapter,youmightsurmisethatmasteringWebpagecreationismerelya
matteroflearningthemultitudeofmarkuptags,suchas<h1>,<p>,<em>,andsoon,that
specifythestructureofWebdocumentstobrowsers.Whilethiscertainlyisanimportant
firststep,itwouldbesimilartobelievingyoucouldmastertheartofwritingbysimply
understandingthevariouscommandsavailableinMicrosoftWord.Thereisatremendous
amounttoknowinthefieldofWebdesignanddevelopment,includinginformation
architecture,visualdesign,client-andserver-sideprogramming,marketingandsearch
engines,Webserversanddelivery,andmuch,muchmore.
<?xmlversion="1.0"encoding="utf-8"?>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/xml;charset=utf-8"/>
<title>HelloXHTMLWorld</title>
<!--SimplehelloworldinXHTML1.0strictexample-->
</head>
50 Part I: Core Markup
<body>
<h1>WelcometotheWorldofXHTML</h1>
<hr/>
<p>XHTML<em>really</em>isn'tsohardeither!</p>
<p>Soonyouwill♥usingXHTMLtoo.</p>
<p>TherearesomedifferencesbetweenXHTML
andHTMLbutwithsomeprecisemarkupyou'll
seesuchdifferencesareeasilyaddressed.</p>
</body>
</html>
O NLINE http://htmlref.com/ch1/xhtmlasxml.html
http://htmlref.com/ch1/xhtmlasxml.xml
Interestingly,mostbrowsers,saveInternetExplorer,willnothaveaproblemwiththis.
InternetExplorerwilltreattheapparentXMLactingasHTMLasnormalHTMLmarkup,
butifweforcetheissue,itwillparseitasXMLandthenrenderanXMLtreeratherthana
defaultrendering:
TogetthebenefitofusingXML,weneedtoexploreifsyntaxcheckingisreallyenforced.
TurnsoutthatworksifthebrowserbelievesmarkuptobeXML,butnotifthebrowsergets
theslightestideathatwemeanforcontenttobeHTML.Seeforyourselfwhenyoutrythe
examplesthatfollow.YoushouldnoteitproperlyfailswhenitassumesXMLandnotwhen
itsuspectsHTML.
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 51
O NLINE http://htmlref.com/ch1/xhtmlasxmlmalformed.html
http://htmlref.com/ch1/xhtmlasxmlmalformed.xml
PART I
NOTE TheexamplepresentedisquitesimpleandmeanttoshowthepossibilityofXHTMLifit
werefullyrealized.NotethatassoonasyoustartaddingmarkupwithinternalCSSand
JavaScript,theamountofworktogetrenderingworkinginbrowsersincreasessubstantially.
Insummary,ifabrowserreallybelievesitisgettingXML,itwillenforceparsingrules
andforcewell-formedness.Regardlessofwhetherrulesareenforcedornot,without
InternetExplorerrenderingmarkupvisually,itwouldappearthatwehavetodeliver
XHTMLasstandardHTML,asmentionedearlierinthechapter,whichprettymuchmakes
themovetoanXMLworldpointless.
NOTE Asthiseditionofthebookwaswrappedup,thefutureofXHTML2becamemurkybecause
theW3CannouncedthatitwaslettingtheXHTML2WorkingGroup’scharterexpire.This,
however,shouldnotbetakentoindicatethatXMLappliedtoHTMLisdead;itdoesindeedlive
onunderHTML5.
52 Part I: Core Markup
NOTE WhileHTML5stabilizedsomewhataroundOctober2009,withaW3Cfinalcandidate
recommendationgoalof2012,youaredulywarnedthatthestatusofHTML5maychange.
Becauseoftheearlynatureofthespecification,specificdocumentationofHTML5focusesmoreon
whatworksnowthanonwhatmaymakeitintothespecificationlater.
HTML5ismeanttorepresentanewversionofHTMLalongtheHTML4path.The
emergingspecificationalsosuggeststhatitwillbeareplacementforXHTML,yetitendsup
supportingmostofthesyntaxthatendusersactuallyuse,particularlyself-identifying
emptyelements(forexample,<br/>).Italsoreversessomeofthetrends,suchascase
sensitivity,thathaveenteredintomarkupcircles,soitwouldseemthattheHTMLstylesof
thepastwillbefineinthefuture.Inmostways,HTML5doesn’tpresentmuchofa
difference,asyousawearlierinthechapter’sintroductoryexample,shownagainhere:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HelloHTMLWorld</title>
<!--SimplehelloworldinHTML5example-->
</head>
<body>
<h1>WelcometotheFutureWorldofHTML5</h1>
<hr>
<p>HTML5<em>really</em>isn'tsohard!</p>
<p>Soonyouwill♥usingHTML.</p>
<p>Youcanputlotsoftexthereifyouwant.
Wecouldgoonandonwithfaketextforyou
toread,butlet'sgetbacktothebook.</p>
</body>
</html>
O NLINE http://htmlref.com/ch1/helloworldhtml5.html
Chapter 1: Tr a d i t i o n a l H T M L a n d X H T M L 53
Allthatisdifferentinthisexampleisthatthe<!DOCTYPE>statementismuchsimpler.In
fact,thespecificideaofusingSGMLandperformingvalidationdoesnotapplytoHTML5.
However,thesyntaxcheckingbenefitsofvalidationlivesonandisnowbeingcalled
PART I
conformancecheckingandforallintentsandpurposesisthesame.Interestingly,because
ofthestatementinitsshortenedform,browserswillcorrectlyenterintoastandards
compliancemodewhentheyencounteranHTML5document:
Inthenextchapter,we’llseethatHTML5isquiteabitdifferentthanHTML4despitewhat
our“helloworld”examplesuggests.Therearemanynewtagsandthereisatremendous
emphasisoninteractivityandWebapplicationdevelopment.However,probablythemost
interestingaspectofHTML5isthefocusondefiningwhatbrowsers—or,morewidely,user
agentsingeneral—aresupposedtodowhentheyencounterill-formedmarkup.HTML5,by
definingknownoutcomes,makesitmuchmorelikelythattoday’s“tagsoup”willbeparsed
predictablybytomorrow’sbrowsers.Unfortunately,readanotherway,itprovidesyetmore
reasonsforthosewhocreatesuchamessofmarkupnottochangetheirbadhabits.
Likely,thefutureofmarkuphasmorethanonepossibleoutcome.Myopinionisthat
thosewhoproduceprofessional-grademarkuporwhowritetoolstodosowillcontinueto
embracestandards,XMLornot,whilethosewhodabblewithcodeandhavefunwill
continuetoworkwithlittleunderstandingoftherulestheybreakandwillhavenoworries
aboutdoingso.TheforgivenessthatHTMLallowsisboththekeytoitspopularityand,
ultimately,thecurseoftheunpredictabilityoftenassociatedwithit.
Summary
HTMListhemarkuplanguageforbuildingWebpagesandtraditionallyhascombined
physicalandlogicalstructuringideas.Elements—intheformoftagssuchas<em>and
</em>—areembeddedwithintextdocumentstoindicatetobrowsershowtorenderpages.
TherulesforHTMLarefairlysimpleandcompliancecanbecheckedwithaprocesscalled
validation.Unfortunately,theseruleshavenotbeenenforcedbybrowsersinthepast.
Becauseofthislooseness,therehasbeenagreatdealofmisunderstandingaboutthe
purposeofHTML,andagoodportionofthedocumentsontheWebdonotconformtoany
particularofficialspecificationofHTML.StricterformsofHTML,andespeciallythe
introductionofXHTML,attempttoimposeamorerigidsyntax,encouragelogicalmarkup,
andleavepresentationaldutiestoothertechnologiessuchasCascadingStyleSheets.While
verywidespread,useofstrictmarkuphasyettooccurontheWeb.Webdevelopersshould
aimtomeetstandardstofuture-prooftheirdocumentsandmoreeasilyaddressallthe
variousissuesthatwillcertainlyariseingettingbrowserstorenderthemproperly.
This page intentionally left blank
CHAPTER
2
Introducing HTML5
T
heHTML5specificationnotonlyembracesthepast,bysupportingtraditional
HTML-andXHTML-stylesyntax,butalsoaddsawiderangeofnewfeatures.
AlthoughHTML5movesforwardfromHTML4,italsoissomewhatofaretreatand
anadmissionthattryingtogeteveryWebdeveloperontheInternettowritetheirmarkup
properlyisafutileeffort,particularlybecausefewWebdevelopersareactuallyformally
trainedinthetechnology.HTML5triestobringordertochaosbycodifyingcommon
practices,embracingwhatisalreadyimplementedinbrowsers,anddocumentinghow
theseuseragents(browsersorotherprogramsthatconsumeWebpages)shoulddealwith
ourimperfectmarkup.
HTML5’sgoalsaregrand.Thespecificationissprawlingandoftenmisunderstood.
Giventheconfusion,thegoalsofthischapterarenotonlytosummarizewhatisnewabout
HTML5andprovidearoadmaptotheelementreferencethatfollows,buttoalsoexpose
someofthemythsandmisconceptionsaboutthisexcitingnewapproachtomarkup.
NOTE Perhapsjusttobenew,HTML5omitsthespacefoundcommonlybetween(X)HTMLandits
versionnumber,asinHTML4orXHTML1.Wefollowthisstylegenerallyinthebook,butnote
eventhespecificationhasnotbeenstringentonthispoint.
Hello HTML5
ThesyntaxofHTML5shouldbemostlyfamiliar.Asshowninthepreviouschapter,asimple
HTML5documentlookslikethis:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HelloHTML5World</title>
</head>
<body>
<h1>HelloHTML5</h1>
<p>Welcometothefutureofmarkup!</p>
</body>
</html>
55
56 Part I: Core Markup
O NLINE http://htmlref.com/ch2/helloworld.html
Forallpracticalpurposes,allthatisdifferentfromstandardHTMLinthisexampleis
the<!DOCTYPE>statement.Givensuchminimalchanges,ofcourse,basicHTML5will
immediatelyrendercorrectlyinbrowsers,asdemonstratedinFigure2-1.
Asindicatedbyitsatypical<!DOCTYPE>statement,HTML5isnotdefinedasanSGML
orXMLapplication.Becauseofthenon-SGML/XMLbasisforHTML,thereisnoconceptof
validationinHTML5;instead,anHTML5documentischeckedforconformancetothe
specification,whichprovidesthesamepracticalvalueasvalidation.Sothelackofaformal
DTDissomewhatmoot.Asanexample,considerthefollowingflawedmarkup:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HelloMalformedHTML5World</title>
</head>
<body>
<!--notebadclosetagbelow-->
<h1>HelloMalformedHTML5<h1>
<!--unknowntagfoundhere-->
<p>Welcometothe<danger>future</danger>ofmarkup!</p>
<!--missing</body>-->
</html>
O NLINE http://htmlref.com/ch2/conformancecheck.html
WhencheckedwithanHTML5conformancechecker,suchastheW3CMarkup
PART I
ValidationServiceusedinthischapter(availableathttp://validator.w3.org),youseethe
expectedresult:
Later,witherrorscorrected,acleancheckispossible:
58 Part I: Core Markup
NOTE GiventhecurrentlyfluidnatureofHTML5,developersarewarnedthat,atleastfornow,
HTML5conformancemaybeabitofamovingtarget.
Ifyouarewonderingwhatmodethebrowserentersintobecauseofthedivergent
<!DOCTYPE>usedbyHTML5,apparentlyitisthemorestandards-orientedmode:
Employingthemorestandards-orientedparsingmodemightseemappropriate,butitis
somewhatoddgiventhepointofthenextsection.
<!DOCTYPEhtml>
<!--Ihavenohtml,head,orbodyastheyareactuallyoptional-->
<metahttp-equiv=Content-Typecontent="text/html;charset=utf-8">
<title>HTML5TagSoupTest</title>
<h1title="moresloppymarkupahead!">HTML5</H1>
<pid=p1>Backtothefutureofloosemarkup!?
<p>Yesitlooksthatway
<ul>
<li>optionalelements
<LI>caseisnoproblem
<liid=noquotes>quotesoptionalinmanycases
<li>inferredclosetags
</UL>
<p>Ohmy
<br>
<br/>
<p>Intermixingmarkupstyles!
<!--okthat'senoughlet'sstopnow-->
O NLINE http://htmlref.com/ch2/loosesyntax.html
Chapter 2: Introducing HTML5 59
Thisexample,atleastcurrently,conformstotheHTML5specification:
PART I
DonotinterpretthepreviousexampletomeanthatHTML5allowsamarkupfree-for-all.
Understandthatthese“mistakes”areactuallyallowedundertraditionalHTMLandthus
areallowedunderHTML5.ToensurethatyouconformtotheHTML5specification,you
shouldbeconcernedprimarilyaboutthefollowing:
• Makesuretonestelements,notcrossthem;so
<b><i>isinerrorastagscross</b></i>
whereas
<b><i>isnotsincetagsnest</i></b>.
• Quoteattributevalueswhentheyarenotordinalvalues,particularlyiftheycontain
specialcharacters,particularlyspaces;so
<pid=p1>Finewithnoquotes</p>
becauseitisasimpleattributevalue,whereas
<ptitle=troubleherewithnoquotes>Notokwithoutquotes</p>
isclearlymessedup.
• Understandandfollowthecontentmodel.Justbecauseonebrowsermayletyou
usealistitemanywhereyoulike,
<li>Ishouldbeinalist!</li>
itisn’tcorrect.Elementsmustrespecttheircontentmodel,sotheexampleshould
readinsteadas
<ul><li>AlliswellIaminalist!</li></ul>
becauseitfollowsHTML5’scontentmodel.
60 Part I: Core Markup
• Donotuseinventedtagsunlesstheyareincludedviasomeothermarkuplanguage:
<p>I<danger>shouldn't</danger>conformunlessIamdefinedin
anotherspecificationanduseanamespace</p>
• Encodespecialcharacters,particularlythoseusedintags(<>),eitherasanentity
ofanamedform,suchas<,orasanumericvalue,suchas<.AppendixA
coversthistopicinsomedepth.
Thisbrieflistofwhatyoushoulddomightseemfamiliar;itisprettymuchthelistof
recommendationsforcorrectmarkupfromthepreviouschapterreturnedtothetraditional
markupstylesofHTML.Whatthismeansisthatifyouhavebeenwritingmarkupcorrectly
inthepast,HTML5isn’tgoingtopresentmuchofachange.Infact,inmanycases,justby
changingavaliddocument’sdoctypetothenewsimpleHTML5<!DOCTYPEhtml>,the
resultshouldbeanHTML5–conformingdocument.
XHTML5
ForthosewithaheavyinvestmentinastrictXHTMLsyntaxworldview,HTML5might
seemlikeaslapintheface.However,suchareactionisabitpremature;HTML5neither
makesthecleanmarkupyouwritenon-conformingnorsuggeststhatyoushouldn’tauthor
markupthisway.Ifyouwanttopursuean“XMLish”approachtoyourdocument,HTML5
allowsit.Consider,forexample,astrictXHTMLexamplethatisnowHTML5:
<?xmlversion="1.0"encoding="UTF-8"?>
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HelloXHTML5World</title>
<!--SimplehelloworldinXHTML5-->
</head>
<body>
<h1>WelcometotheWorldofXHTML5</h1>
<hr/>
<p>XHTML5<em>really</em>isn'tsohardeither!</p>
<p>HTML5likesXMLsyntaxtoo.</p>
<p>MakesuretoserveitwiththecorrectMIMEtype!</p>
<!--IEusersyouwillgetarendererror.
Pleasereadontolearnwhy.-->
</body>
</html>
O NLINE http://htmlref.com/ch2/xhtml5helloworld.xhtml
NOTE WhenusingXMLsyntaxwithHTML5accordingtoHTML5specification,thisshouldbe
termedXHTML5.
Chapter 2: Introducing HTML5 61
Noticethatthepreviousexampleusesan.xhtmlfileextension.XHTML5usageclearly
indicatesthatanHTML5documentwrittentoXMLsyntaxmustbeservedwiththeMIME
typeapplication/xhtml+xmlorapplication/xml.Thepreviousexamplewasserved
PART I
withtheformerMIMEtype.YoucanfindthesameexampleservedwithlatterXMLMIME
typeathttp://htmlref.com/ch2/xhtml5helloworld.xml.
Unfortunately,althoughHTML5supportsXML,therealvalueofXHTML—thetrue
strictnessofXML—hasnotbeenrealized,atleastsofar,becauseofalackofbrowser
support.Asofthisedition’swriting,InternetExplorerbrowsers(uptoversion8)willnot
renderXHTMLservedwiththeappropriateapplication/xhtml+xmlMIMEtypeand
willtaketherawXMLformandrenderitasaparsetree.Otherbrowsers,fortunately,don’t
dothis(seeFigure2-2),whichislittlesolacegivenInternetExplorer’swidespreadusage.
YoucanwriteXMLishmarkupandserveitastext/htmlbutitwon’tprovidethe
benefitofstrictsyntaxconformance.Inshort,HTML5certainlyallowsyoutotryto
continueapplyingtheintentofXHTMLinthehopesthatsomedayitbecomesviable.
Interestingly,Googlehasevenlargerstudies,andwhiletheydon’tfocusspecificallyon
validation,whattheyindicateontagusageindicatesclearlythatnomatterthesamplesize,
cleanmarkupismoretheexceptionthantherule.
Yetdespitethemarkupmadness,theWebcontinuestowork.Infact,somemightsaythe
permissivenatureofbrowsersthatparsejunkHTMLactuallyhelpstheWebgrowbecauseit
lowersthebarriertoentryfornewWebpageauthors.Certainlyashakyfoundationtobuild
upon,butthestarkrealityisthatwemustdealwithmalformedmarkup.Tothisend,HTML5
makesoneverymajorcontribution:itdefineswhattodointhepresenceofmarkupsyntax
problems.
Thepermissivenatureofbrowsersisrequiredforbrowserstofixmarkupmistakes.HTML5
directlyacknowledgesthissituationandaimstodefinehowbrowsersshouldparsebothwell-
formedandmalformedmarkup,asindicatedbythisbriefexcerptfromthespecification:
ThisspecificationdefinestheparsingrulesforHTMLdocuments,whetherthey
aresyntacticallycorrectornot.Certainpointsintheparsingalgorithmaresaid
tobeparseerrors.Theerrorhandlingforparseerrorsiswell-defined:useragents
musteitheractasdescribedbelowwhenencounteringsuchproblems,ormust
abortprocessingatthefirsterrorthattheyencounterforwhichtheydonotwish
toapplytherulesdescribedbelow.
WhileacompletediscussionoftheimplementationofanHTML5–compliantbrowser
parserisoflittleinteresttoWebdocumentauthors,browserimplementersnowhavea
commonspecificationtoconsulttodeterminewhattodowhentagsarenotnested,simply
leftopen,ormangledinavarietyofways.ThisisthepartoftheHTML5specificationthat
1
BrianWilson,“MAMAW3CValidatorResearch,”subsection“InterestingViewsofValidationRates,part2:
AlexaGlobalTop500,”Dev.Opera,October15,2008,http://dev.opera.com/articles/view/mama-w3c-
validator-research-2/?page=2#alexalist.
2
Ibid.,subsection“HowManyPagesValidated?”http://dev.opera.com/articles/view/mama-w3c-
validator-research-2/#validated.
Chapter 2: Introducing HTML5 63
willlikelyproducethemostgood,becauseobtainingconsensusamongbrowservendorsto
handlemarkupproblemsinaconsistentmannerisamorelikelypathtoanimprovedWeb
thandefiningsomestrictsyntaxandthenattemptingtoeducatedocumentauthorsaround
PART I
theworldenmassetowritegoodmarkup.
HTML5’saimtobringordertothechaosofsloppymarkupisbutoneofthegrand
aimsofthespecification.ItalsoaimstoreplacetraditionalHTML,XHTML,andDOM
specifications,andtodosoinabackward-compatiblefashion.Initsattempttodothis,the
specificationissprawling,addressingnotjustwhatelementsexistbuthowtheyareused
andscripted.HTML5embracesthefactthattheWebnotonlyiscomposedofdocuments
butalsosupportsapplications,thusmarkupmustacknowledgeandfacilitatethebuilding
ofsuchapplications.MoreofthephilosophyofHTML5willbediscussedlaterinthe
chapterwhenaddressingsomestrongopinions,myths,andmisconceptionssurrounding
thespecification;fornow,takealookatwhatmarkupfeaturesHTML5actuallychanges.
NOTE Althoughtheseelementsareremovedfromthespecificationandshouldbeavoidedinfavorof
CSS,theylikelywillcontinuetobesupportedbybrowsersforsometimetocome.Thespecification
evenacknowledgesthisfact.
LookingatTable2-1,youmightnoticethatsomeelementsthatapparentlyshouldbe
eliminatedsomehowliveon.Forexample,<small>continuestobeallowed,but<big>is
obsolete.Theideahereistopreserveelementsbutshiftmeaning.Forexample,<small>is
nolongerintendedtocorrespondtotextthatisjustreducedinsize,similarto<font
size="-1">or<spanstyle="font-size:smaller;">,butinsteadisintendedto
representtheuseofsmalltext,suchasappearsinfineprintorlegalinformation.Ifyou
thinkthisdecisionseemsabitpreposterous,jointhecrowd.Someoftheotherchangesto
elementmeaningseemevenabitmorepreposterous,suchastheclaimthata<b>tagnow
representsinlinetextthatisstylisticallyoffsetfromstandardtext,typicallyusingadifferent
typetreatment.Soapparently<b>tagsarenotnecessarilybold,butratherconveysome
sensethatthetextis“different”(whichlikelymeansbold).Unlikelytobethoughtofinsuch
amannerbymeremarkupmortals,wesimplysay<b>tagsliveon,asdoanumberofother
presentationalelements.Table2-2presentsthemeaning-changedelementsthatstayputin
HTML5andtheirnewmeaning.
Themeaningofsomeoftheseitemsmightnotbeimmediatelyclear,butdon’tworry
aboutthatnow,becauseeachwillbedemonstratedlaterinthechapterandafullreference
presentedinChapter3.
Likethestrictvariantsof(X)HTML,HTML5alsoremovesnumerouspresentation-
focusedattributes.Table2-3summarizesthesevaluesandpresentsCSSalternatives.
NOTE WhileframesaremostlyremovedfromHTML5,inlineframesliveon.Seethesection“The
UncertainFutureofFrames,”laterinthechapter,formoreinformation.
Table2-4isnotacompletelistofnon-conformingelements,justtheonesthataresupported
byrecentHTML4andXHTML1.xspecifications.Discussingthefactthatancienttagslike
<listing>and<plaintext>continuenottobesupportedorthatallthepresentationaltags
PART I
iframe, h1, h2, h3, h4, h5, cases float
h6, hr, img, input, legend,
object, p, table, tbody, td,
tfoot, th, thead, tr
alink body bodya:active{color: color-
value;}
background body background-image or background
bgcolor body, table, td, th, tr background-color
border img, object, table border-width and/or border
cellpadding table padding
cellspacing table margin
char col, colgroup, table, tbody, N/A
td, tfoot, th, thead, tr
charoff col, colgroup, table, tbody, N/A
td, tfoot, th, thead, tr
clear br clear
compact dl, menu, ol, ul margin properties
frame table border properties
frameborder iframe border properties
height td, th height
hspace img, object margin properties
link body bodya:link{color:color-
value;}
marginheight iframe margin properties
marginwidth iframe margin properties
noshade hr border-style or border
nowrap td, th overflow
rules table borderproperties
scrolling iframe overflow
size hr width
text body body{color: color-value;}
type li, ol, ul list-style-typeandlist-style
valign col, colgroup, tbody, td, vertical-align
tfoot, th, thead
vlink body bodya:visited{color:color-
value;}
width col, colgroup, hr, pre, width
table, td, th
like<font>andproprietarytagslike<spacer>,<marquee>,and<blink>shouldbeofflimits
issomewhatredundantanddoesnotbuildonthespecifications.However,thereferencein
Chapter3coverscompliancepointscompletely,sowhenindoubtchecktheappropriate
element’sentry.
PART I
such as a blog post, article, or self-continued unit of information.
aside Encloses content that is tangentially related to the other content in an enclosing
element such as section.
audio Specifies sound to be used in a Web page.
canvas Defines a region to be used for bitmap drawing using JavaScript.
command Located within a menu element, defines a command that a user may invoke.
datalist Indicates the data items that may be used as quick choices in an input element of
type="list".
details Defines additional content that can be shown on demand.
figure Defines a group of content that should be used as a figure and may be labeled by a
legend element.
footer Represents the footer of a section or the document and likely contains
supplementary information about the related content.
header Represents the header of a section or the document and contains a label or other
heading information for the related content.
hgroup Groups heading elements (h1–h6) for sectioning or subheading purposes.
mark Indicates marked text and should be used in a similar fashion to show how a
highlighter is used on printed text.
meter Represents a scalar measurement in a known range similar to what may be
represented by a gauge.
nav Encloses a group of links to serve as document or site navigation.
output Defines a region that will be used to hold output from some calculation or form
activity.
progress Indicates the progress of a task toward completion, such as displayed in a progress
meter or loading bar.
rp Defines parentheses around ruby text defined by an rt element.
rt Defines text used as annotations or pronunciation guides. This element will be
enclosed within a ruby element.
ruby This is the primary element and may include rt and rp elements. A ruby element
serves as a reading or pronunciation guide. It is commonly used in Asian languages,
such as in Japanese to present information about Kanji characters.
section Defines a generic section of a document and may contain its own header and
footer.
source Represents media resources for use by audio and video elements.
time Encloses content that represents a date and/or time.
video Includes a video (and potentially associated controls) in a Web page.
PART I
4saveaslightlydifferent<!DOCTYPE>statement.However,ifyoulookcloser,therearea
fewimportantdifferencesinHTML5thatshowthedocumentstructurehasinfactbeen
expandedquiteabit.
HTML5documentsmaycontainaheaderelement,whichisusedtosettheheader
sectionofadocumentandthusoftencontainsthestandardh1toh6headingelements:
<header>
<h1>WelcometotheFutureWorldofHTML5.</h1>
<h2>Don'tbescareditisn'tthathard!</h2>
</header>
Similarly,afooterelementisprovidedfordocumentauthorstodefinethefooter
contentofadocument,whichoftencontainsnavigation,legal,andcontactinformation:
<footer>
<p>Contentofthisexampleisnotundercopyright</p>
</footer>
Theactualcontenttobeplacedina<footer>tagis,ofcourse,uptoyouandmaybe
enclosedindiv,p,orotherblockelements,asillustratedbythissimpleexample:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HTML5headerandfooterexample</title>
</head>
<body>
<header>
<h1>WelcometotheFutureWorldofHTML5.</h1>
<h2>Don'tbescareditisn'tthathard!</h2>
</header>
<p>Somebodycontenthere.</p>
<p>Somemorebodycontenthere.</p>
<footer>
<p>Contentofthisexampleisnotundercopyright.</p>
</footer>
</body>
</html>
O NLINE http://htmlref.com/ch2/headerfooter.html
TheHTML5structuralelementwiththemostpossibleusesisthesectionelement.A
particular<section>tagcanbeusedtogrouparbitrarycontenttogetherandmaycontain
further<section>tagstocreatetheideaofsubsections.Traditionally,wearefamiliarwith
sections;justasthisbookisbrokenintochaptersandvariousmainandsecondarysections,
70 Part I: Core Markup
sotoocouldaWebdocumentbestructuredinthisway.Theexamplehereillustratesthe
basicuseofHTML5sections:
<section>
<h1>Chapter2</h1>
<p>NewHTML5elements.</p>
<section>
<h2>HTML5'ssectionElement</h2>
<p>Theseelementsareusefultocreateoutlines.</p>
<section>
<h3>NestAway!</h3>
<p>Nestyoursectionsbutasyounestyoumightwanttoindent.</p>
</section>
</section>
<p>Okthat'senoughofthat.</p>
</section>
O NLINE http://htmlref.com/ch2/section.html
Itmaynotbeobviousbutasectionelementmaycontainheaderandfooterelements
ofitsown:
<section>
<header>
<h1>IamSectionHeading</h1>
</header>
<h2>IamoutsidethesectionheaderI'mjustaplainheadline.</h2>
<p>Somemoresectioncontentmightgohere.</p>
<footer>
<p>Hifromthefooterofthissection.</p>
</footer>
</section>
HTML5usesheadingsandnewlyintroducedelementslikethesectionelementfor
outliningpurposes.Forexample,theexpandedexamplehereshowsanumberofsections
withheaders,footers,headlines,andcontent:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HTML5expandedsectionexample</title>
</head>
<body>
<header>
<h1>WelcometotheFutureWorldofHTML5</h1>
<h2>Don'tbescareditisn'tthathard!</h2>
</header>
Chapter 2: Introducing HTML5 71
<!--assumechapter1before-->
<sectionid="chapter2">
<header>
<h1>Chapter2</h1>
PART I
</header>
<p>Introtochapter2here...</p>
<sectionid="newStrucreElements">
<header>
<h2>NewStructuralElements</h2>
</header>
<h3>headerElement</h3>
<p>Discussionofheaderelement.</p>
<h3>footerElement</h3>
<p>Discussionoffooterelement.</p>
<h3>sectionElement</h3>
<p>Discussionofsectionelement</p>
</section>
<sectionid="newFormElements">
<header>
<h2>NewFormElements</h2>
</header>
<h3>inputtype=date</h3>
<p>Discussionhere...</p>
<footer>
<p>TheseideasarefromWebFormsspecification.</p>
</footer>
</section>
</section>
<sectionid="chapter3">
<header>
<h2>Chapter3</h2>
</header>
<p>Massiveelementreference...</p>
</section>
<footer>
<p>Contentofthisexampleisnotundercopyright</p>
</footer>
</body>
</html>
O NLINE http://htmlref.com/ch2/sectionoutline.html
72 Part I: Core Markup
HTML5–compliantbrowsersshouldtakethismarkupanddefineanoutlinebasedupon
theuseofheaders,likeso:
Intheory,useragentscouldtaketheoutliningsemanticsandderivemeaningoreven
provideanalternativebrowserinterface,althoughthatisquitespeculativeatthispoint.Itis
clear,however,thatifyouintroducesuchoutliningideas,issuesmayarise.Forexample,the
firstheaderreallywasnottwolevelsofsectioningbutsimplyonewithasubhead.To
addressthisoutlining,youwouldtakethismarkup
<header>
<h1>WelcometotheFutureWorldofHTML5</h1>
<h2>Don'tbescareditisn'tthathard!</h2>
</header>
andthenjointhesubheadtotheheadlinewithanhgroupelementlikeso:
<header>
<hgroup>
<h1>WelcometotheFutureWorldofHTML5</h1>
<h2>Don'tbescareditisn'tthathard!</h2>
</hgroup>
</header>
No hgroup hgroup
elements used elements used
Chapter 2: Introducing HTML5 73
Acompleteexampletoexplorecanbefoundonline,thoughyoumayfindthatabrowser
doesnotdoanythingofinterestandthatyouneedanoutlinesimulatortoseethedifference
betweenusing<hgroup>tagsornot.
PART I
O NLINE http://htmlref.com/ch2/hgroup.html
Giventhesesemantics,itisclearthatHTML5sectioningelementsarenotjusta
formalizationof<div>tagswithappropriateclassvalues.Forexample,youmight
consider
<divclass="header">
<!--headerhere-->
</div>
<divclass="section">
<divclass="header">
<h2>SectionHeading</h2>
</div>
<p>Contentofsection.</p>
</div>
<divclass="footer">
<!--footerhere-->
</div>
toberoughlythesameasthepreviouslyintroducedelements.Tosomedegreethisistrue,
butclearlythenamesoftheclassvaluesaren’tdefinedbyastandardnorisanyoutlining
algorithmdefined.
Beyondsectioning,HTML5introducesanumberofotherstructuralelements.For
example,thearticleelementisusedtodefineadiscreteunitofcontentsuchasablog
post,comment,article,andsoon.Forexample,thefollowingdefinesafewindividualblog
postsinadocument:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HTML5articleexample</title>
</head>
<body>
<header>
<hgroup>
<h1>WelcometotheFutureWorldofHTML5Blog</h1>
<h2>Don'tbescareditisn'tthathard!</h2>
</hgroup>
</header>
<sectionid="articleList">
<h2>LatestPosts</h2>
<articleid="article3">
<h2>HTML5HereToday!</h2>
<p>Articlecontenthere...</p>
</article>
74 Part I: Core Markup
<articleid="article2">
<h2>HTML5WidelyMisunderstood</h2>
<p>Articlecontenthere...</p>
</article>
<articleid="article1">
<h2>Discoveringthearticleelement</h2>
<p>Articlecontenthere...</p>
</article>
</section>
<footer>
<p>Thisfakeblogexampleisnotreal.</p>
</footer>
</body>
</html>
O NLINE http://htmlref.com/ch2/article.html
Theideaofdefiningthesediscretecontentunitsspeciallyisthatyoumightwishto
extractthemautomatically,soagain,havingdefinedelementsasopposedtosomeadhoc
useofclassnameson<div>tagsispreferred.
NOTE UnderearlyHTML5drafts,thearticleelementprovidedforciteandpubdate
attributes,whichmaymaketheusageofthecontentmoremeaningfulbyoutsidesites;however,
thesewerelaterdroppedanduseof<time>tagswasencouraged.
HTML5alsointroducesanasideelement,whichmaybeusedwithincontentto
representmaterialthatistangentialor,astheelementnamesuggests,anaside:
<p>HereweexplorethevariousHTML5elements.Iwouldwrite
somerealcontentherebutyouarebusyreadingthebookanyway.
</p>
<aside>
<h2>PointlessAside</h2>
<p>OhbythewaydidyouknowthattheauthorlivesinSanDiego?
Itiscompletelyirrelevanttothediscussionbutheseems
toliketheweatherthereasopposedtorainyNewZealand.</p>
</aside>
<p>SoaswecontinuetodiscussthevariousHTML5elementswemust
remembertostayfocusedasthereismuchtolearn.
</p>
O NLINE http://htmlref.com/ch2/aside.html
Chapter 2: Introducing HTML5 75
Youmayhavenotedthatan<h2>tagwasusedintheaside.Whilenotrequired,itis
usefulasaremindertoreadersthatasideelementsserveasoutlinesectioningelements,as
shownhere:
PART I
NOTE Ifaheadingisnotprovidedinanaside,youmayseeanoutlinemechanismadd“Untitled
Section”orpotentiallyevenmakeuponebaseduponthestartoftheelementcontent.
Adding Semantics
ManyoftheelementsthatHTML5addsthatcanbeusedrightawayaresemanticinnature.
Inthissense,HTML5continuestheappropriategoalofseparatingstructurefromstyle.In
thissection,youwillseeanumberofrepurposedelementsaswellassomethatareallnew.
Atfirstyouwon’tseemuchvalueinusingthemotherthantoaddsemantics,buttoward
theendofthechapterwewillexplorehowtomaketheelementsunderstandabletomost
modernbrowsersandhowtoapplysomesimplestylingforendusers.
Marking Text
ThenewHTML5elementmarkwasintroducedforhighlightingcontentsimilarlytohow
ahighlighterpenmightbeusedonimportanttextinabook.Thefollowingexamplewraps
afewimportantwords:
<p>Herecomes<mark>markedtext</mark>wasitobvious?</p>
Unfortunately,youwon’tnecessarilyseeanythingwithsuchanexample:
Youwouldneedtoapplyastyle.Here,inlinestylesareusedjusttoshowtheidea:
<p>ThenewHTML5specificationisintheworks.While<mark
style="background-color:red;">manyfeaturesarenotcurrently
implementedorevenwelldefined</mark>yet,<mark
style="background-color:green;">progressisbeingmade</mark>.
StaytunedtoseemorenewHTMLelementsaddedtoyourWebdocuments
intheyearstocome.</p>
O NLINE http://htmlref.com/ch2/mark.html
76 Part I: Core Markup
Afterseeingsuchanexample,youmightwonderwhatthepointisofthiselement,
becausea<span>tagormaybeevenan<em>tagcouldbeusedinstead.Again,semanticsis
thekeytothiselement.ItmakesthemeaningofHTMLdocumentsmoreobvious.
<p>Todayitis<time>2009-07-08</time>whichisaninterestingdate.</p>
aswellas
<p>Aninterestingdate/timeforSciFibuffsis<time>1999-09-13T09:15:00
</time>!</p>
wouldbothbevalid.Theelementshouldcontainadate/timevaluethatisintheformat
YYYY-MM-DDThh:mm:ssTZD,wheretheletterscorrespondtoyears,months,days,hours,
minutes,andseconds,Tistheactualletter‘T,’andZDrepresentsatimezonedesignatorof
eitherZoravaluelike+hh:mmtoindicateatimezoneoffset.However,itseemsreasonable
thatthetimeelementwouldcontainvaluesthatmaynotbeinacommonformatbutare
recognizedbyhumansasdates.Ifyoutrysomethinglike
<p>Rightnowitis<time>6:15</time>.</p>
itmaybemeaningfultoyoubutitdoesnotconformtoHTML5.Toprovidebothhuman-
andmachine-friendlydate/timecontent,theelementsupportsadatetimeattribute,which
shouldbesettothepreviouslymentioneddateformatofYYYY-MM-DDThh:mm:ssTZD.So,
thefollowingexampleismeaningfulbecauseitprovidesbothareadableformanda
machine-understoodvalue:
<p>Myfirstsonwasbornon<timedatetime="2006-01-13">Fridaythe13th
</time>soitismynewluckyday.</p>
O NLINE http://htmlref.com/ch2/time.html
Similartomark,thetimeelementhasnopredefinedrendering,thoughyoucould
certainlydefinealookusingCSS.
Inserting Figures
Itisoftennecessarytoincludeimages,graphs,compoundobjectsthatcontaintextand
images,andsooninourWebdocuments,allofwhichusuallyarecalledfigures.Longago,
HTML3triedtointroducethefigelementtorepresentsuchconstructs;HTML5
reintroducestheideawiththemoreappropriatelynamedfigureelement.Asimple
exampleillustratesthisnewelement’susage:
<figureid="fig1">
<dd>
<imgsrc="figure.png"height="100"width="100"
Chapter 2: Introducing HTML5 77
alt="Ascreencaptureofthefigureelementinaction">
<p>Thismighty<figure>taghasreturnedfromHTML3tohauntyour
dreams.</p>
</dd>
PART I
<dt>FigureEx-1</dt>
</figure>
O NLINE http://htmlref.com/ch2/figure.html
Actingasasemanticelement,figuresimplygroupsitemswithinanenclosed<dd>
tag,thoughitmayassociatethemwithacaptiondefinedbya<dt>tagasshowninthe
example.Youmaydesiretostylea<figure>tagbyplacingastrokearounditsvisual
renderingordisplayitinsomeotherappropriatemanner;ofcourse,thatisthedutyofCSS.
Youshouldalsonotethattheuseofidona<figure>willlikelybeusefultotargetusing
links,asfiguresmaybepositionedawayfromthecontentthatreferencesthem.
NOTE InearlydraftsoftheHTML5specification,the<legend>wasusedinsteadof<dt>andno
specialtagwasrequiredforcontentenclosure.
Specifying Navigation
OnenewHTML5elementthatislongoverdueisthenavelement.Thepurposeofthis
elementistoencapsulateagroupoflinksthatservesasacollectionofoffsitelinks,
documentnavigation,orsitenavigation:
<nav>
<h2>OffsiteLinks</h2>
<ahref="http://www.w3c.org">W3C</a><br>
<ahref="http://www.htmlref.com">Booksite</a><br>
<ahref="http://www.pint.com">Author'sFirm</a><br>
</nav>
Conventionally,manyWebdevelopershaveused<ul>and<li>tagstoencapsulate
navigationandthenstyledtheelementsappropriatelyasmenuitems.Thisseemsto
introducequiteabitofambiguityinmarkupbecauseitmaybedifficulttodeterminethe
differencebetweenalistthathaslinksinitandalistthatissimplynavigation.The
semanticsdefinedbyHTML5fora<nav>tageliminatethisconfusion.Interestingly,thereis
norequirementtoavoidusing<ul>and<li>tagswithinnavigation,soifyouareaCSS
aficionadowhoiscomfortablewiththatapproach,itisfinetousemarkuplikethis:
<navid="mainNav">
<ul>
<li><ahref="about.html">About</a></li>
<li><ahref="services.html">Services</a></li>
<li><ahref="contact.html">Contact</a></li>
<li><ahref="index.html">Home</a></li>
</ul>
</nav>
O NLINE http://htmlref.com/ch2/nav.html
78 Part I: Core Markup
<video>
Toinsertvideo,usea<video>tagandsetitssrcattributetoalocalorremoteURLcontaining
aplayablemovie.Youshouldalsodisplayplayblackcontrolsbyincludingthecontrols
attribute,aswellassetthedimensionsofthemovietoitsnaturalsize.Thissimpledemoshows
theuseofthenewelement:
<videosrc="http://htmlref.com/ch2/html_5.mp4"
width="640"height="360"controls>
<strong>HTML5videoelementnotsupported</strong>
</video>
Chapter 2: Introducing HTML5 79
NOTE IfyouareusingXHTML5,giventhatcontrolsisanoccurrencestyleattribute,use
controls="controls"tobeconforming.
PART I
Youshouldnotetheincludedcontentinthetagthatnonsupportingbrowsersfallback
to.ThefollowingshowsInternetExplorerdisplayingthealternativecontent:
However,evenifabrowsersupportsthevideoelement,itmightstillhaveproblems
displayingthevideo.Forexample,Firefox3.5won’tloadthisparticularmediaformatdirectly:
HTML5openvideohas,asitcurrentlystands,broughtbackthemadnessofmedia
codecsupportthatFlashsolved,albeitinalessthanstellarway.Toaddressthemedia
supportproblem,youneedtoaddinalternativeformatstousebyincludinganumberof
<source>tags:
<videowidth="640"height="360"controlsposter="loading.png">
<sourcesrc="html_5.mp4"type="video/mp4">
<sourcesrc="html_5.ogv"type="video/ogg">
<strong>HTML5videoelementnotsupported</strong>
</video>
80 Part I: Core Markup
Alsonoteintheprecedingsnippettheuseoftheposterattribute,whichissettodisplayan
imageinplaceofthelinkedobjectincaseittakesafewmomentstoload.Othervideoelement–
specificattributeslikeautobuffercanbeusedtoadvisethebrowsertodownloadmedia
contentinthebackgroundtoimproveplayback,andautoplay,whichwhenset,willstartthe
mediaassoonasitcan.Acompleteexampleofthevideoelementinactionisshownhere:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HTML5videoexample</title>
</head>
<body>
<h1>SimpleVideoExamples</h1>
<videosrc="http://htmlref.com/ch2/html_5.mp4"
width="640"height="360"controls>
<strong>HTML5videoelementnotsupported</strong>
</video>
<br><br><br>
<videowidth="640"height="360"controlsposter="loading.png">
<sourcesrc="http://htmlref.com/ch2/html_5.mp4"type="video/mp4">
<sourcesrc="http://htmlref.com/ch2/html_5.ogv"type="video/ogg">
<strong>HTML5videoelementnotsupported</strong>
</video>
</body>
</html>
O NLINE http://htmlref.com/ch2/video.html
ThereferencesectioninChapter3showsthecompletelistofattributesforthevideo
elementsupportedasoflate2009.Bewarned,though,thatifthevariousmediamarkup
effortsofthelate1990srepeatthemselves,itisquitelikelythattherewillbeanexplosionof
attributes,manyofwhichmaybespecifictoaparticularbrowserormediaformat.
<audio>
HTML5’saudioelementisquitesimilartothevideoelement.Theelementshouldsupport
commonsoundformatssuchasWAVfiles:
<audiosrc="http://htmlref.com/ch2/music.wav"></audio>
Inthismanner,theaudioelementlooksprettymuchthesameasInternetExplorer’s
proprietarybgsoundelement.Havingthefallbackcontentrelyonthatproprietarytag
mightnotbeabadidea:
<audio>
<bgsoundsrc="http://htmlref.com/ch2/music.wav">
</audio>
Chapter 2: Introducing HTML5 81
Ifyouwanttoallowtheusertocontrolsoundplay,unlessyouhaveutilizedJavaScript
tocontrolthis,youmayopttoshowcontrolswiththesamenamedattribute.Dependingon
thebrowser,thesecontrolsmaylookquitedifferent,asshownnext.
PART I
<audiosrc="http://htmlref.com/ch2/music.wav"controls></audio>
Aswiththevideoelement,youalsohaveautobufferandautoplayattributesforthe
audioelement.Unfortunately,justlikevideo,therearealsoaudioformatsupportissues,
soyoumaywanttospecifydifferentformatsusing<source>tags:
<audiocontrolsautobufferautoplay>
<sourcesrc="http://htmlref.com/ch2/music.ogg"type="audio/ogg">
<sourcesrc="http://htmlref.com/ch2/music.wav"type="audio/wav">
</audio>
Acompleteexampleisshownhere:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HTML5audioexamples</title>
</head>
<body>
<h1>SimpleAudioExamples</h1>
<h2>wavFormat</h2>
<audiosrc="http://htmlref.com/ch2/music.wav"controls></audio>
<h2>oggFormat</h2>
<audiosrc="http://htmlref.com/ch2/music.ogg"controls></audio>
<h2>MultipleFormatsandFallback</h2>
<audiocontrolsautobufferautoplay>
<sourcesrc="http://htmlref.com/ch2/music.ogg"type="audio/ogg">
<sourcesrc="http://htmlref.com/ch2/music.wav"type="audio/wav">
<!--[ifIE]>
<bgsoundsrc="http://htmlref.com/ch2/music.wav">
<![endif]-->
</audio>
</body>
</html>
O NLINE http://htmlref.com/ch2/audio.html
82 Part I: Core Markup
Media Considerations
Aninterestingconcernabout“open”mediaformatsiswhetherornottheyreallyareopen.
AstheHTML5specificationemerges,fissuresarealreadyformingintermsofhowthese
elementsareimplemented,whatcodecswillbesupportedbywhatbrowservendors,and
whetherHTML5willrequireaparticularcodectobesupportedbyallHTML5–compliant
browsers.Validconcernsaboutso-called“submarine”patentssurfacingandtorpedoingthe
openmediaeffortarerealandhotlydebated.
Unfortunately,giventhismediacodecchaos,atthetimeofthisedition’swriting,getting
anexampletoworkinallbrowserscanbequiteachoreandFlashand/orQuickTimesupport
mustbeaddedtoaddressolderbrowsers.Simplyput,forallitspossibilities,sofarHTML5
mediaisamessysolutionatbest.Thefollowingaddsinafallbackwithinthepreviousvideo
exampleforFlash:
<videowidth="640"height="360"controlsposter="loading.png">
<sourcesrc="http://htmlref.com/ch2/html_5.mp4"type="video/mp4">
<sourcesrc="http://htmlref.com/ch2/html_5.ogv"type="video/ogg">
<objectdata="html_5.swf"type="application/x-shockwave-flash"
width="640"height="360"id="player">
<paramname="movie"value="html_5.swf"/>
<strong>Error:Novideosupportatall</strong>
</object>
</video>
Giventheexample,Ithinkitisn’tmuchofastretchtoimaginea<source>tagbeingsetto
aFlashtypeeventually;makingthedirectionthisisgoingevenmoreconfusing.
Sowhilethepotentialbenefitsofopenmediaformatscanbedebatedendlessly,thereis
alsothepragmaticconcernofhowlongitwilltakebeforeHTML5’sopenmediamovement
becomesviable.GettingtothestablemediaplaybackworldprovidedbyFlashtookmany
years,anditseemsunlikelythatHTML5solutionswillmovemuchfaster.
NOTE ThecurrentstateoftheHTML5specificationbeforepresssuggeststhatnocodecisofficial.
Whiletheneutralityiswelcome,therealitythatimplementationsvaryconsiderablystillcontinues.
3
Circalate2009,themostpopularIE<canvas>emulationlibraryisexplorercanvas,availableathttp://
code.google.com/p/explorercanvas/.
Chapter 2: Introducing HTML5 83
<canvasid="canvas"width="300"height="300">
<strong>CanvasSupportingBrowserRequired</strong>
</canvas>
PART I
Notethealternativecontentplacedwithintheelementforbrowsersthatdon’tsupport
theelement.
Afteryouplacea<canvas>taginadocument,yournextstepistouseJavaScriptto
accessanddrawontheelement.Forexample,thefollowingfetchestheobjectbyitsid
valueandcreatesatwo-dimensionaldrawingcontext:
varcanvas=document.getElementById("canvas");
varcontext=canvas.getContext("2d");
NOTE 3Ddrawingiscomingto<canvas>butisnotcurrentlydefinedoutsideofextensions.
Onceyouhavethedrawingcontext,youmightemployvariousmethodstodrawonit.
Forexample,thestrokeRect(x,y,width,height)methodtakesxandycoordinatesand
heightandwidth,allspecifiedasnumbersrepresentingpixels.Forexample,
context.strokeRect(10,10,150,50);
woulddrawasimplerectangleof150pixelsby50pixelsstartingatthecoordinate10,10
fromtheoriginoftheplaced<canvas>tag.Ifyouwantedtosetaparticularcolorforthe
stroke,youmightsetitwiththestrokeStyle()method,likeso:
context.strokeStyle="blue";
context.strokeRect(10,10,150,50);
Similarly,youcanusethefillRect(x,y,width,height)methodtomakearectangle,
butthistimeinasolidmanner:
context.fillRect(150,30,75,75);
Bydefault,thefillcolorwillbeblack,butyoucandefineadifferentfillcolorbyusing
thefillColor()method.Asademonstrationthisexamplesetsalightredcolor:
context.fillStyle="rgb(218,0,0)";
YoucanusestandardCSScolorfunctions,whichmayincludeopacity;forexample,here
theopacityofthereddishfillissetto40percent:
context.fillStyle="rgba(218,112,214,0.4)";
AfullexampleusingthefirstcanvaselementandassociatedJavaScriptispresentedhere:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HTML5canvasexample</title>
<scripttype="text/javascript">
window.onload=function(){
varcanvas=document.getElementById("canvas");
84 Part I: Core Markup
varcontext=canvas.getContext("2d");
context.strokeStyle="orange";
context.strokeRect(10,10,150,50);
context.fillStyle="rgba(218,0,0,0.4)";
context.fillRect(150,30,75,75);
}
</script>
</head>
<body>
<h1>SimpleCanvasExamples</h1>
<canvasid="canvas"width="300"height="300">
<strong>CanvasSupportingBrowserRequired</strong>
</canvas>
</body>
</html>
O NLINE http://htmlref.com/ch2/canvas.html
Inasupportingbrowser,thesimpleexampledrawssomerectangles:
Unfortunately,InternetExploreruptoversion8willnotbeabletorendertheexample
withoutacompatibilitylibrary:
Chapter 2: Introducing HTML5 85
Reworkingtheexampletoaddjustsuchalibrarymakesthingsworkjustfine:
PART I
O NLINE http://htmlref.com/ch2/canvasie.html
context.beginPath();
context.lineTo(20,100);
context.lineTo(120,300);
context.lineTo(220,100);
context.stroke();
Now,ifyouweretoaddcontext.closePath()beforecontext.stroke(),theV
shapewouldturnintoatriangle,becauseclosePath()wouldconnectthelastpointand
thefirstpoint.
Also,bycallingfill()insteadofstroke(),thetrianglewillbefilledinwithwhatever
thefillcoloris,orblackifnoneisspecified.Ofcourse,youcancallbothfill()and
stroke()onanydrawnshapeifyouwanttohaveastrokearoundafilledregion.Thus,to
86 Part I: Core Markup
stylethedrawing,youcanspecifythefillStyleandstrokeStyleandmaybeeven
definethewidthofthelineusinglineWidth,asshowninthisexample:
context.strokeStyle="blue";
context.fillStyle="red";
context.lineWidth=10;
context.beginPath();
context.lineTo(200,10);
context.lineTo(200,50);
context.lineTo(380,10);
context.closePath();
context.stroke();
context.fill();
Asyousawinafewpreviousexamples,youcanchangecolorbysettingthefillColor
property.InadditiontotheCSScolorvalues,youcanalsosetthefillColortoagradient
object.AgradientobjectcanbecreatedbyusingcreateLinearGradient()or
createRadialGradient().
Thefollowingexamplecreatesasimplelineargradientthatwillbeappliedtoarectangle
usingthecreateLinearGradient(x1,y1,x2,y2)method.Thegradientispositionedat
10,150andissettogo200pixelsinbothdirections.
varlg=context.createLinearGradient(10,150,200,200);
Next,thegradientcolorsareaddedusingtheaddColorStop()method.Thisspecifies
acolorandtheoffsetpositioninthegradientwherethecolorshouldoccur.Theoffsetmust
bebetween0and1.
lg.addColorStop(0,"#B03060");
lg.addColorStop(0.75,"#4169E1");
lg.addColorStop(1,"#FFE4E1");
Ofcourse,youcouldusethergbaCSSfunctiontocreateagradientwithtransparency
aswell.Finally,thefillColorissettothegradient.Hereisthecompletecodesnippet,
followedbyavisualexample:
varlg=context.createLinearGradient(10,150,200,200);
lg.addColorStop(0,"#B03060");
lg.addColorStop(0.5,"#4169E1");
lg.addColorStop(1,"#FFE4E1");
context.fillStyle=lg;
context.beginPath();
context.rect(10,150,200,200);
context.fill();
Chapter 2: Introducing HTML5 87
PART I
Notethatbeforeyoudrawtheshape,youresetthepathtoensurethatyoudonotapply
thesechangestopreviouslyrenderedpartsofthedrawing.
TocreatearadialgradientusingcreateRadialGradient(x1,y1,r1,x2,y2,r2),you
mustsetthepositionandradiusoftwocirclestoserveasthegradient.Youaddcolorstops
inthesamemannerasthelineargradient,sothecodelooksquitesimilarotherwise:
varrg=context.createRadialGradient(350,300,80,360,250,80);
rg.addColorStop(0,"#A7D30C");
rg.addColorStop(0.9,"#019F62");
rg.addColorStop(1,"rgba(1,159,98,0)");
context.fillStyle=rg;
context.beginPath();
context.fillRect(250,150,200,200);
Thecompleteexample,drawingafewdifferentshapeswithfillsandstyles,ispresented
here:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HTML5canvaslinesandshapesexample</title>
<scripttype="text/javascript">
window.onload=function(){
varcanvas=document.getElementById("canvas");
varcontext=canvas.getContext("2d");
context.strokeStyle="blue";
context.fillStyle="red";
context.lineWidth=10;
context.beginPath();
context.lineTo(200,10);
88 Part I: Core Markup
context.lineTo(200,50);
context.lineTo(380,10);
context.closePath();
context.stroke();
context.fill();
varlg=context.createLinearGradient(10,150,200,200);
lg.addColorStop(0,"#B03060");
lg.addColorStop(0.5,"#4169E1");
lg.addColorStop(1,"#FFE4E1");
context.fillStyle=lg;
context.beginPath();
context.rect(10,150,200,200);
context.fill();
varrg=context.createRadialGradient(50,50,10,60,60,50);
rg.addColorStop(0,"#A7D30C");
rg.addColorStop(0.9,"#019F62");
rg.addColorStop(1,"rgba(1,159,98,0)");
context.fillStyle=rg;
context.beginPath();
context.fillRect(0,0,130,230);
context.beginPath();
context.lineTo(250,150);
context.lineTo(330,240);
context.lineTo(410,150);
context.stroke();
}
</script>
</head>
<body>
<h1>SimpleShapesoncanvasExample</h1>
<canvasid="canvas"width="500"height="500">
<strong>CanvasSupportingBrowserRequired</strong>
</canvas>
</body>
</html>
O NLINE http://htmlref.com/ch2/canvaslinesandshapes.html
Applying Some Perspective
Asthecontextisspecifiedas2d,itisnosurprisethateverythingyouhaveseensofarhas
beentwo-dimensional.Itispossibletoaddsomeperspectivebychoosingproperpointsand
shades.The3DcubeshowninFigure2-3iscreatedusingnothingmorethanseveral
moveTo()andlineTo()calls.ThelineTo()callisusedtocreatethreesidesofthecube,
butthepointssetarenotstraighthorizontalandverticallinesasweseewhenwemake2D
squares.Shadingisappliedtogivetheillusionofdimensionalitybecauseoftheapplication
ofalightsource.Whilethecodehereisprettysimple,youcanseethatusingcanvas
Chapter 2: Introducing HTML5 89
PART I
FIGURE 2-3 Faking 3D with perspective
properlyisoftenafunctionmoreofwhatyoumayknowaboutbasicgeometryanddrawing
thananythingelse.
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>CanvasCubeExample</title>
<styletype="text/css"media="screen">
body{background-color:#E67B34;}
</style>
<scripttype="text/javascript">
window.onload=function(){
varcontext=document.getElementById("canvas").getContext("2d");
context.fillStyle="#fff";
context.strokeStyle="black";
context.beginPath();
context.moveTo(188,38);
context.lineTo(59,124);
90 Part I: Core Markup
context.lineTo(212,197);
context.lineTo(341,111);
context.lineTo(188,38);
context.closePath();
context.fill();
context.stroke();
context.fillStyle="#ccc";
context.strokeStyle="black";
context.beginPath();
context.moveTo(341,111);
context.lineTo(212,197);
context.lineTo(212,362);
context.lineTo(341,276);
context.lineTo(341,111);
context.closePath();
context.fill();
context.stroke();
context.fillStyle="#999";
context.strokeStyle="black";
context.beginPath();
context.moveTo(59,289);
context.lineTo(59,124);
context.lineTo(212,197);
context.lineTo(212,362);
context.lineTo(59,289);
context.closePath();
context.fill();
context.stroke();
}
</script>
</head>
<body>
<h1>CanvasPerspective</h1>
<canvasid="canvas"width="400"height="400">
<strong>CanvasSupportingBrowserRequired</strong>
</canvas>
</body>
</html>
O NLINE http://htmlref.com/ch2/canvascube.html
(x,y)aswellasthecircle’sradius.Howmuchofthecircleisdrawnisdefinedby
startAngleandendAngle,inradians.ThedirectionofthecurveissetbyaBooleanvalue,
whichisthefinalparameterspecifiedbycounterclockwise.Ifitissettotrue,thecurve
PART I
willmovecounterclockwise;otherwise,itwillmoveclockwise.Ifyourmathisabitrusty,to
makeafullcircle,thestartangleshouldbesetto0andtheendangleshouldbe2π.Soto
startyourfacedrawing,usearc()todrawtheheadasacircle:
context.arc(150,150,100,0,Math.PI*2,true);
UsethequadraticCurveTo(cpx,cpy,x,y)methodtodrawthenoseandthemouth.
Thisfunctionstartsatthelastpointinthepathanddrawsalineto(x,y).Thecontrolpoint
(cpx,cpy)isusedtopullthelineinthatdirection,resultinginacurvedline.However,you
callmoveTo()firsttosetthelastpointinthepath.Inthefollowingsnippet,alinewas
drawnfrom(155,130)to(155,155).Becausethex-coordinateofthecontrolpoint(130,145)
istotheleft,thelineispulledinthatdirection.Becausethey-coordinateisinbetweenthe
y-coordinates,thepullisroughlyinthemiddle.
context.moveTo(155,130);
context.quadraticCurveTo(130,145,155,155);
context.moveTo(100,175);
context.quadraticCurveTo(150,250,200,175);
YoucallbezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y)todrawtheeyes.Thisfunction
issimilartoquadraticCurveTo()exceptthatithastwocontrolpointsandhasalinethatis
pulledtowardbothofthem.Again,moveTo()isusedtosetthestartpointoftheline:
context.moveTo(80,110);
context.bezierCurveTo(95,85,115,85,130,110);
context.moveTo(170,110);
context.bezierCurveTo(185,85,205,85,220,110);
Lastly,usearcTo(x1,y1,x2,y2,radius)todrawaframearoundtheface.Unfortunately,
foreshadowingsomeissueswiththecanvasAPI,wenotethatarcTo()isnotcurrently
supportedproperlyinallbrowsers,soitmayrenderoddly.Whenitdoeswork,itcreates
twolinesandthendrawsanarcwiththeradiusspecifiedandcontainingapointtangentto
eachofthelines.Thefirstlineisdrawnfromthelastpointinthesubpathto(x1,y1)and
thesecondlineisdrawnfrom(x1,y1)to(x2,y2).
context.moveTo(50,20);
context.arcTo(280,20,280,280,30);
context.arcTo(280,280,20,280,30);
context.arcTo(20,280,20,20,30);
context.arcTo(20,20,280,20,30);
Thecompleteexampleisshownnext.Notethat,givenlayering,youdrawandfillthe
frameandfaceandthendrawthefeatureslast.Alsonotethatyouresetthepathswiththe
beginPath()method.Commonly,peopleforgettodothis,whichcanproducesome
interestingdrawings.ArenderingofthefaceexampleisshowninFigure2-4.
92 Part I: Core Markup
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>CanvasFaceExample</title>
<scripttype="text/javascript">
window.onload=function(){
varcanvas=document.getElementById("canvas");
varcontext=canvas.getContext("2d");
context.strokeStyle="black";
context.lineWidth=5;
/*createaframeforourdrawing*/
context.beginPath();
context.fillStyle="blue";
context.moveTo(50,20);
context.arcTo(280,20,280,280,30);
context.arcTo(280,280,20,280,30);
context.arcTo(20,280,20,20,30);
context.arcTo(20,20,280,20,30);
context.stroke();
context.fill();
Chapter 2: Introducing HTML5 93
/*drawcircleforhead*/
context.beginPath();
context.fillStyle="yellow";
context.arc(150,150,100,0,Math.PI*2,true);
PART I
context.fill();
/*drawtheeyes,noseandmouth*/
context.beginPath();
context.moveTo(80,110);
context.bezierCurveTo(95,85,115,85,130,110);
context.moveTo(170,110);
context.bezierCurveTo(185,85,205,85,220,110);
context.moveTo(155,130);
context.quadraticCurveTo(130,145,155,155);
context.moveTo(100,175);
context.quadraticCurveTo(150,250,200,175);
context.moveTo(50,20);
context.stroke();
}
</script>
</head>
<body>
<h1>Smileyou'reoncanvas</h1>
<canvasid="canvas"width="300"height="300">
<strong>CanvasSupportingBrowserRequired</strong>
</canvas>
</body>
</html>
O NLINE http://htmlref.com/ch2/canvasface.html
/*scaletallandthin*/
context.scale(.5,1.5);
writeBoxes(context);
/*moveshortandwide*/
context.scale(1.75,.2);
writeBoxes(context);
94 Part I: Core Markup
O NLINE http://htmlref.com/ch2/canvasscale.html
Nextupistherotate(angle)method,whichcanbeusedtorotateadrawingina
clockwisedirectionbyanangledefinedinradians:
/*rotatetotheright*/
context.rotate(Math.PI/8);
writeBoxes(context);
/*rotatetotheleft*/
context.rotate(-Math.PI/8);
writeBoxes(context);
O NLINE http://htmlref.com/ch2/canvasrotate.html
Chapter 2: Introducing HTML5 95
Thetranslate(x,y)functionisahandyfunctiontousetochangetheoriginfrom
(0,0)toanotherlocationinthedrawing.Thefollowingexamplemovestheoriginto
(100,100).Then,whenthestartcoordinatesoftherectanglearespecifiedat(0,0),itreally
PART I
startsat(100,100).
context.translate(100,100);
context.fillRect(0,0,100,100);
Asimpleexampleofmovingsomeboxesaroundisshownhere:
O NLINE http://htmlref.com/ch2/canvastranslate.html
Allthemethodspresentedsofarareconveniencestohelpususeanunderlying
transformmatrixassociatedwithpaths.Allpathshaveanidentitymatrixastheirdefault
transform.Asanidentity,thistransformmatrixdoesnothing,butitiscertainlypossibleto
adjustthismatrixinafewways.First,itcanbedirectlymodifiedbycallingsetTransform
(m11,m12,m21,m22,dx,dy),whichresetsthematrixtotheidentitymatrixandthen
callstransform()withthegivenparameters.Oryoucandothisdirectlybyusing
transform(m11,m12,m21,m22,dx,dy),whichmultiplieswhateverthecurrentmatrixis
withthematrixdefinedby
m11m21dx
m12m22dy
001
Theproblemwiththemethodshouldbeobvious:unlessyouunderstandmorethana
bitaboutmatrixmath,thiscanbeabitdauntingtouse.Onthebrightside,withthe
method,youcandojustaboutanythingyouwant.Hereasimpleexampleskewsand
movessomesimplerectangles.TheresultisshowninFigure2-5.
96 Part I: Core Markup
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>canvastransform()Example</title>
<styletype="text/css">
canvas{border:1pxsolidblack;}
</style>
<scripttype="text/javascript">
window.onload=function(){
varcanvas=document.getElementById("canvas");
varcontext=canvas.getContext("2d");
context.fillStyle="rgba(255,0,0,.4)";
context.rect(0,0,100,100);
context.fill();
context.setTransform(1,1,1,0,0,0);
context.beginPath();
context.fillStyle="rgba(0,255,0,.4)";
context.rect(75,75,100,100);
context.fill();
context.setTransform(0,.5,1,.8,0,0);
context.beginPath();
Chapter 2: Introducing HTML5 97
context.fillStyle="rgba(0,0,255,.4)";
context.rect(50,50,100,100);
context.fill();
}
PART I
</script>
</head>
<body>
<h1>SimpleTransforms</h1>
<canvasid="canvas"width="400"height="300">
<strong>CanvasSupportingBrowserRequired</strong>
</canvas>
</body>
</html>
O NLINE http://htmlref.com/ch2/canvastransform.html
• Animagealreadyloadedonthepage
• DynamicallycreatedthroughtheDOM
• Anothercanvasobject
• Animagecreatedbysettingitssrctoadata:URL
Theimportantthingtorememberisthattheimagemustbeloadedbythetimecanvas
isreadytoaccessit.Thismayrequireuseoftheonloadfunctionfortheimage:
varimg=newImage();
img.onload=function(){
context.drawImage(img,0,0,400,400);
}
img.src="dog.jpg";
ThelastwaythatdrawImage(img,sx,sy,sw,sh,dx,dy,dw,dh)maybecalledallows
apartoftheimagetobecutoutanddrawntothecanvas.The(sx,sy)coordinatesarethe
locationontheimage,andswandsharethewidthandheight,respectively.Therestofthe
parametersprefixedwithdarethesameasinthepreviousformofthemethod.
varimg=document.getElementById("image1");
/*slicesa100pxsquarefromimage1atlocation(200,75)
Placesonthecanvasat(50,50)andstretchesitto300pxsquare.*/
context.drawImage(img,200,75,100,100,50,50,300,300);
98 Part I: Core Markup
Howeveryoudecidetoplaceit,onceanimageisonthecanvas,itisthenpossibleto
drawonit.Thefollowingexampleloadsanimageanddrawsaregioninpreparationfor
eventuallyaddingacaption:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>canvasdrawImage()Example</title>
<styletype="text/css">
canvas{border:1pxsolidblack;}
</style>
<scripttype="text/javascript">
window.onload=function(){
varcanvas=document.getElementById("canvas");
varcontext=canvas.getContext("2d");
varimg=newImage();
img.src="dog.jpg";
img.onload=function(){
context.lineWidth=5;
context.drawImage(img,0,0,400,400);
context.beginPath();
context.lineWidth=5;
context.fillStyle="orange";
context.strokeStyle="black";
context.rect(50,340,300,50);
context.fill();
context.stroke();
}
}
</script>
</head>
<body>
<canvasid="canvas"width="400"height="400">
<strong>CanvasSupportingBrowserRequired</strong>
</canvas>
</body>
</html>
O NLINE http://htmlref.com/ch2/canvasimage.html
context.fillStyle="rgb(0,0,255)";
context.strokeStyle="rgb(0,0,0)";
context.fillText("Canvasisgreat!",10,40);
context.strokeText("Canvasisgreat!",10,40);
PART I
Togetmore-customizedtext,youcanusethefontproperty,whichyousetidentically
toaCSSfontproperty.YoucanusetextAlignandtextBaselinetosetthehorizontal
andverticalalignmentofthetextstring.ThetextAlignpropertyhasthepossiblevaluesof
start,end,left,right,andcenter.ThetextBaselinepropertycanbesettotop,
hanging,middle,alphabetic,ideographic,andbottom.
context.font="bold30pxsans-serif";
context.textAlign="center";
context.textBaseline="middle";
Youcanaddshadowstoshapessimplybysettingtheshadowproperties,shadowOffsetX,
shadowOffsetY,shadowBlur,andshadowColor.Theoffsetssimplysethowfartheshadow
shouldbeoffsetfromtheimage.Apositivenumberwouldmaketheshadowgototheright
anddown.Anegativenumberwouldmakeitgototheleftandup.TheshadowBlurproperty
indicateshowblurredtheshadowwillbe,andtheshadowColorpropertyindicatesthecolor.
Thiscodefragmentdemonstratessettingashadow.
context.shadowOffsetX=10;
context.shadowOffsetY=5;
context.shadowColor="rgba(255,48,48,0.5)";
context.shadowBlur=5;
context.fillStyle="red";
context.fillRect(100,100,100,100);
Alltheconceptsfromthisandthelastsectioncanbeputtogetherasfollowstocaption
animagewithsomeshadowedtext,asshowninFigure2-6.
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>canvasTextExample</title>
<styletype="text/css">
canvas{border:1pxsolidblack;}
</style>
<scripttype="text/javascript">
window.onload=function(){
varcanvas=document.getElementById("canvas");
varcontext=canvas.getContext("2d");
varimg=newImage();
img.src="dog.jpg";
img.onload=function(){
context.lineWidth=5;
context.drawImage(img,0,0,400,400);
context.beginPath();
context.lineWidth=5;
context.fillStyle="orange";
context.strokeStyle="black";
100 Part I: Core Markup
context.rect(50,340,300,50);
context.fill();
context.stroke();
context.lineWidth=2;
context.font='40pxsans-serif';
context.strokeStyle="black";
context.fillStyle="white";
context.fillText("Canvasisgreat!",60,375);
context.shadowOffsetX=10;
context.shadowOffsetY=5;
context.shadowColor="rgba(0,48,48,0.5)";
context.shadowBlur=5;
context.strokeText("Canvasisgreat!",60,375);
}
}
</script>
</head>
<body>
<canvasid="canvas"width="400"height="400">
<strong>CanvasSupportingBrowserRequired</strong>
</canvas>
</body>
</html>
O NLINE http://htmlref.com/ch2/canvastext.html
<canvas> Conclusions
PART I
WehavejustscratchedthesurfaceofthecanvasAPI.AfulllistingoftheAPIcanbefound
inthereferenceinChapter3.However,areferenceissimplythat;bewarnedthattheuseof
thecanvaselementcangetquiteinvolved,andyoushouldnotreasonablyexpecttouseit
ifyoudon’thavesignificantJavaScriptknowledge.EvenifyouknowJavaScript,thereare
challengesaheadbecauseimplementationsvarybetweenbrowsersand,fornow,Internet
Explorerrequiresacompatibilitylibraryevenforbasicsupport.Scriptingcanvas-based
drawingsforinteractivityisabitclunky,andtextsupportisfarfromstellar.Accessibility
concernsalsoabound.However,don’tletthechallengesdissuadeyou;HTML5’scanvas
APIisquitepowerfulandwarrantsyourexploration.Thepurposeofthissectionwasto
introduceyoutotheelementandshowyouwhatispossibletoaccomplishwithit.Consult
theWebforthelatestchangesincanvassupport.
<p><label>color:<inputtype="color"name="favColor"></label></p>
Asofthetimeofthisedition’swriting,noimplementationexistedforthiscontrol,butit
mightlooksomethinglikethis:
102 Part I: Core Markup
Avarietyofdatecontrolscannowbedirectlycreatedbysettingthetypeattributeto
date,datetime,datetime-local,month,week,ortime.Severalofthesecontrolsare
demonstratedhere:
<p><label>date:
<inputtype="date"name="date">
</label></p>
<p><label>datetime:
<inputtype="datetime"name="datetime">
</label></p>
<p><label>datetime-local:
<inputtype="datetime-local"name="datetime2">
</label></p>
<p><label>time:
<inputtype="time"name="time">
</label></p>
<p><label>month:
<inputtype="month"name="month">
</label></p>
<p><label>week:
<inputtype="week"name="week">
</label></p>
Itshouldbepossibletorestrictthedateschosen,butcurrentlyanyrestrictionsmustbe
controlledwithscript.
Chapter 2: Introducing HTML5 103
Settingtypetonumbergivesyouanumericspinboxinconformingbrowsers:
<p><label>number:<inputtype="number"name="number"></label></p>
PART I
Whenunconstrained,thespinboxwillbeabletomoveupanddownarbitrarilywithno
limits.However,itispossibletodefineallowedvalues.Forexample,themaxattributecan
besettolimitthemaximumvalue,mintolimitthesmallestvalue,andevenstepto
indicatehowvaluesmaybemodified.Forexample,
<inputtype="number"name="number2"min="-5"max="25"step="5">
wouldcreateanumericspinboxthatrangesfrom–5to25inincrementsof5.
Asimilarformofcontrolcanbecreatedusingarangecontrol:
<inputtype="range"name="range"max="100"min="1"step="5">
Thiscontrolpresentsitselfasaslider,whichsofarhasavariedappearanceinbrowsers:
Likethenumberpicker,themin,max,andstepattributesallcanbesettolimitvalues:
<p><label>range(1-100step5):
<inputtype="range"name="range"max="100"min="1"step="5">
</label></p>
<p><label>range(-1000-1000step100):
<inputtype="range"name="range"max="1000"min="-1000"step="100">
</label></p>
Itisalsopossibletofurtherdefinesemanticrestrictionsbysettingan<input>tag’s
typeattributetotel,email,orurl:
<p><label>TelephoneNumber:<inputtype="tel"name="telno"></label></p>
<p><label>Email:<inputtype="email"name="email"></label></p>
<p><label>URL:<inputtype="url"name="url"></label></p>
Abrowsermaythenspecifysomeindicationsoftheappropriatedatatype:
104 Part I: Core Markup
Itisalsopossibletosettypetosearch,whichmayeventuallyhaveanassociatedpick
list.Currently,somebrowsersprovidesomecontrolsforclearingasearchfield:
<inputtype="text"name="firstname"id="firstname"required>
Abrowsermaythensetanerrorstyleonthefieldandpresentamessageifthereisa
problem:
Thepatternattributealsocanbeemployedtoforcetheentereddatatoconformtoa
suppliedregularexpression:
<labelfor="phonenum"class="required">PhoneNumber:</label>
<inputtype="text"name="phonenum"id="phonenum"required
pattern="^\(\d{3}\)\d{3}-\d{4}$">
Ifatitleisspecifiedwhenpatternsareapplied,thebrowsermaydisplaythisadvisory
information:
<labelfor="phonenum"class="required">PhoneNumber:</label>
<inputtype="text"name="phonenum"id="phonenum"required
pattern="^\(\d{3}\)\d{3}-\d{4}$"
title="Phonenumberofform(xxx)xxx-xxxxrequired">
However,insomecases,youcannotonlyapplyapatternbutalsoemploythe
appropriatesemantictypevaluelikeemail,thoughitisn’tcleariftheseelementswillapply
theirownimpliedvalidationpatternmatchessimplybysettingthemasrequired:
Chapter 2: Introducing HTML5 105
<labelfor="email"class="required">E-mail:</label>
<inputtype="text"name="email"id="email"required
pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|i
nt|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$"title="E-mailformat
PART I
required">
Thespecificationindicatesthatthepresentationoffieldsinerrorcanbecontrolledby
usingtheCSSpseudo-class:invalidinHTML5–compliantbrowsers.
AfullexampleforyoutotestoutbasicHTML5requiredandpatternusageina
browsercanbefoundatthebook’ssupportWebsite.
O NLINE http://htmlref.com/ch2/requiredpattern.html
NOTE Becausevalidationisunderbrowsercontrol,HTML5providesaformnovalidate
attributethatcanbesetoncontrolsortheformtodisablevalidation.
Autocomplete Lists
UnderHTML5,theinputelement’slistattributeisusedtosettheDOMidofa
datalistelementusedtoprovideapredefinedlistofoptionssuggestedtotheuserfor
entry:
<p><label>FavoriteDog:<inputtype="text"list="dogs"></label></p>
<datalistid="dogs">
<option>Angus</option>
<option>Tucker</option>
<option>Cisco</option>
<option>Sabrina</option>
</datalist>
Thisissimilartotheautocompleteattributediscussedinthenextsection,butitallows
youtospecifythedefaultdataratherthanrelyingonwhatmayhavebeenenteredinthe
browserpreviously.
<inputtype="text"name="firstname"id="firstname"value="Thomas">
Quiteoften,peopleputplaceholderoradvisorytexthere,likeso:
<inputtype="text"name="middlename"id="middlename"
value="Enteryourmiddlenamehere">
106 Part I: Core Markup
However,usingthevalueattributeinthismannerissomewhatinappropriate,becausethe
purposeoftheattributeisnottosupplyinstructionsforthefield’susebutrathertosupply
apotentialvaluefortheusertosubmittotheserver.HTML5introducestheplaceholder
attributetouseinsteadforthisduty:
<inputtype="text"name="firstname"id="firstname"
placeholder="Enteryournamehere">
HTML5alsointroducestheautofocusattribute,whichwhenplacedonafieldshould
causeasupportingbrowsertoimmediatelyfocusthisfieldoncethepageisloaded:
<label>Search:<inputtype="search"name="query"
id="searchBox"autofocus></label>
AlsounderHTML5,itshouldbepossibletoadvisethebrowsertodisplaythe
autocompletesuggestionsprovidedforfieldsifsimilarfieldnameshavebeenusedinthe
past:
<inputtype="text"name="firstname"id="firstname"
placeholder="Enteryournamehere"autocomplete>
Interestingly,thisparticularattributehasbeensupportedinInternetExplorerbrowsersfor
sometime.
OtherformimprovementslikelywillbeaddedtotheHTML5specification.Theaim
hereistogiveyouasenseofthechangestheHTML5specificationintendstobringto
Web-baseddatacollection.
<menutype="list"id="oldStyle">
<li>Item1</li>
<li>Item2</li>
Chapter 2: Introducing HTML5 107
<li>Item3</li>
<li>Item4</li>
</menu>
PART I
UnderHTML5themenuelementhasbeenreturnedtoitsoriginalpurpose.Anew
attribute,type,isintroducedthattakesavalueoftoolbar,context,orlist(thedefault).
ThisexamplesetsupasimpleFilemenuforaWebapplication:
<menutype="toolbar"id="fileMenu"label="File">
<li><ahref="javascript:newItem();">New</a></li>
<li><ahref="javascript:openItem();">Open</a></li>
<li><ahref="javascript:closeItem();">Close</a></li>
<hr>
<li><ahref="javascript:saveItem();">Save</a></li>
<li><ahref="javascript:saveAsItem();">Saveas...</a></li>
<hr>
<li><ahref="javascript:exitApp();">Exit</a></li>
</menu>
UsingCSSandJavaScript,thismenumightrenderlikeso:
Again,thisiscompletelyspeculativeandisjustmeanttoillustrateapossibility.
Withmenu,itwouldalsobepossibletodefineacontextmenu,usuallyinvokedbya
right-click:
<menutype="context"id="simpleMenu">
<li><ahref="javascript:add();">Add</a></li>
<li><ahref="javascript:edit();">Edit</a></li>
<li><ahref="javascript:delete();">Delete</a></li>
</menu>
Thiscouldrendersomethinglikethis:
108 Part I: Core Markup
Theglobalcontextmenuattributeisusedtodefineanelement’scontextmenu,whichis
generallythemenuinvokeduponaright-click.Theattribute’svalueshouldholdastring
thatreferencestheidofa<menu>tagfoundintheDOM.Forexample,
<divcontextmenu="simpleMenu">Widget</div>
wouldreferencethepreviouslydefinedmenuviaaright-click.Ifthereisnoelementfound
ornovalue,thentheelementhasnospecialcontextmenuandtheuseragentshouldshow
itsdefaultmenu.InternetExplorerandmanyotherbrowserssupportanoncontextmenu
attributethatcouldbeusedtoimplementtheideaofthisemergingattribute.
Again,allofthisiscompletelyspeculativeandmeanttoillustratetheconcept;sofar,no
browsernativelyimplementsthisfunctionality,thoughitwouldn’tbeastretchtohave
JavaScriptemulatethis.
command Element
Themenuelementmaycontainnotjustlinksbutalsootherinteractiveitems,includingthe
newlyintroducedcommandelement.Thisemptyelementtakesalabelandmayhave
anicondecorationaswell.Thecommandelementhasatypeattribute,whichmaybeset
tocommand,radio,orcheckbox,thoughwhenradioisemployedthereneedstobe
aradiogroupindication.Asimpleexampleherewiththerepurposedmenuelementshould
illustratethepossibleuseofthiselement:
<menutype="command"label="MainMenu">
<commandtype="command"label="Add"icon="add.png">
<commandtype="command"label="Edit"icon="edit.png">
<commandtype="command"label="Delete"icon="delete.png">
<hr>
<menutype="command"label="Skin"id="skinMenu">
<commandtype="radio"radiogroup="skin"label="Classic">
<commandtype="radio"radiogroup="skin"label="Modern"checked>
<commandtype="radio"radiogroup="skin"label="Neo">
</menu>
<hr>
<commandtype="checkbox"label="SecureMode">
</menu>
Suchamenumightlooklikethefollowing:
Butagain,thisisjustillustrativeandinthiscase,Iamsomewhatskepticalaboutthe
commandelementbecauseitseemstosharemanyoftheaspectsoftraditionalformfield
controls,sowhymoreelementsareneededisunclear.
Chapter 2: Introducing HTML5 109
PART I
mightberepresentedbyagauge.Thefollowingexampleisareadingofvelocityforsome
fantasticallyfastspacevessel:
<p>WarpDriveOutput:<metermin="0"max="10"low="3"optimum="7"high="9"
value="9.5"title="Captainshecan'ttakemuchmoreofthis!"></meter></p>
Apotentialrenderingcouldlooklike
Morelikely,itwilllooklikeasimplemeter,butthisspeculationdoesillustratejusthow
variablepresentationmaybe.Usingscript,itisprobablypossibletosimulatethiselement
rightnoweventhoughbrowsersdon’tsupportit.
Slightlydifferentfrommeteristheprogresselement,whichdefinescompletion
progressforsometask.Commonly,thiselementmightrepresentthepercentagefrom
0percentto100percentofatask,suchasloadingtobecompleted:
<p>Progress:<progressid="progressBar"max="100.00"value="33.1">
33.1%</progress></p>
Ofcourse,therangeandvaluesprovidedherearepurelyarbitraryandtherendering
shownissimilarlyjustillustrativeoftheideaoftheprogresselement.
details Element
Thenewdetailselementissupposedtorepresentsomeformofextradetails,suchas
atooltiporrevealedregionthatmaybeshowntoauser.Thedetailselementcancontain
onedtelementtospecifythesummaryofthedetailsaswellasoneddelementtosupply
theactualdetails.Theattributeopencanbesettorevealthedetailsorcanbechanged
dynamically,asshowninthisexample:
<detailsonclick="this.open='open'">
<dt>Help?</dt>
<dd>ThiscouldgiveyouhelpwithHTML5butweneedmore
implementationstoprovehowthingswillwork.</dd>
</details>
110 Part I: Core Markup
Hereisanexampleofhowthedetailselementmightappear:
output Element
Thefinalstoponthisspeculativetouristheoutputelement,whichisusedtodefinea
regionthatwillbeusedasoutputfromsomecalculationorformcontrol.HereIimagine
usingthecalendarpickerandhavingtheeventualreleasedateofHTML5beingrevealedin
anoutputelement:
<formaction="#"method="get"id="testform">
<p><inputtype="date"id="year">
<p>HTML5releasedintheyear
<outputfor="year"> </output></p>
</form>
Scriptcouldcertainlybeusedtoperformthisaction:
Inthiscase,itisdoubtfulweneedtoconcernourselvestoomuchwiththelikely
representationofthisyet-to-besupportedelement,because,asdefined,outputisjust
asemanticelementandcouldbesimulatedintraditionalHTMLusinga<div>.
4
Quotedfromhttp://www.w3.org/TR/html5-diffcirca2009.
Chapter 2: Introducing HTML5 111
HTML5proposestwonewattributesfortheiframeelement:seamlessandsandbox.
Theseamlessattributeeffectivelyrenderstheiframeasaninlineinclude,whichallows
theparentdocument’sCSStoaffectthecontentsoftheiframe:
PART I
<iframesrc="content.html"name="thisframe"width="200"
height="300"seamless">[alternatecontent]</iframe>
HereisthesameexampleusingXHTMLstylesyntax:
<iframesrc="content.htm"name="thisframe"width="200"
height="300"seamless="seamless">[alternatecontent]</iframe>
Thesandboxattribute“sandboxes”theiframe,essentiallypreventingitfrompullingin
contentfromanysourceotherthantheiframeitself.Usedwithoutattributes,sandboxhas
thefollowingeffectsontheiframe:
• Newwindowscannotbecreatedfromwithintheiframe.
• Plug-insareprohibited;embed,object,andappletwillnotfunctionin
asandboxediframe.
• Nestedinlineframesareprohibited.
• Acompletelysandboxediframeisconsidered,inessence,anewsubdomainonthe
clientside.AccesstoJavaScriptisnotallowed;cookiescan’tbereadorwritten.
• Acompletelysandboxedinlineframecannotsubmitformsorrunscripts.
Theseprohibitionscanbe“turnedoff”usinganumberofattributes:
• allow-same-originallowstheiframetopullincontentfromelsewhereinthe
samedomain.
• allow-formspermitsthesubmissionofformsinthesandboxediframe.
• allow-scriptsallowsthesandboxediframetorunscriptsfromthesamedomain.
Theseattributescanbeusedseparately,ortogetherasspace-separatedvalues.Theorderof
theattributesdoesnotaffectanyfunctionality.
<iframesrc="content.htm"sandbox="allow-same-origin
allow-formsallow-scripts">
<iframesrc="content.htm"sandbox="allow-forms">
HTML5dropspresentationaliframeattributessuchasframeborder,scrolling,
marginwidth,andmarginheight.Theattributesname,height,width,andtheall-
importantsrcremainpartofthespecification.HTML5alsoaddsglobalattributestoall
HTML5tags,including<iframe>.SeeChapter3foranin-depthdiscussionofthese
attributes.
UnderHTML5,the<iframe>tagcanalsobewrittenXHTMLstyle,withaclosingslash:
<iframesrc="content.htm"height="200"width="200"
sandbox="allow-same-origin"/>
112 Part I: Core Markup
Unfortunately,thissyntaxdoesnotallowtheinclusionofalternativecontentasshownhere:
<iframesrc="content.htm"height="200"width="200"
sandbox="allow-same-origin">
YourbrowserdoesnotsupportiframesoritsnewHTML5attributes.
Youshouldbeabletogetabrowserthatdoesthisinafewyears.
</iframe>
ItisstillpreferabletousetraditionalHTML-stylemarkuptoinsertaniframeintoan
HTML5document.
Atthetimeofthiswriting,HTML5changesto<iframe>arenotsupportedbyany
browsers;however,InternetExplorer’ssecurityattributeisquitesimilartotheintentof
HTML5’ssandboxattribute.
<divid="dragme"class="box"draggable="true">Iamadraggablediv</div>
EverythingelsemustbeconfiguredthroughJavaScript.Thereareseveralneweventsfor
draganddrop.TheseareattachedtoHTMLelementsjustasanyothereventusing
addEventListener()orattachEvent().
Thefollowingeventsareattachedtotheitemthatwillbedragged:
• dragstart Thedraghasbegun.
• drag Theelementisbeingmoved.
• dragend Thedraghascompleted.
Therestoftheeventsareattachedtothedroparea:
• dragenter Theelementisdraggedintothedroparea.
• dragover Theelementisdraggedintothedroparea.Thedefaultbehaviorhereis
tocancelthedrop,soitisnecessarytohookupthiseventandthenreturnfalseor
callpreventDefault()tocancelthedefaultbehavior.
• dragleave Theelementisdraggedoutofthedroparea.
• drop Theelementisdroppedinthedroparea.
HereweuseJavaScripttohookupsomeoftheseeventsonadraggableboxandadroparea:
vardrag=document.getElementById("dragbox");
drag.addEventListener("dragstart",dragstart,false);
drag.addEventListener("dragend",dragend,false);
Chapter 2: Introducing HTML5 113
vardrop=document.getElementById("dropzone");
drop.addEventListener("dragenter",dragenter,false);
drop.addEventListener("dragleave",dragleave,false);
drop.addEventListener("dragover",dragover,false);
PART I
drop.addEventListener("drop",drops,false);
EachoftheseeventscontainsaneweventpropertycalleddataTransfer.Thispropertyis
usedtocustomizethedraganddropandtopassdatafromthedragelementtothedrop
element.Itsupportsthefollowingpropertiesitself:
• dropEffect Indicatesthetypeofdraganddropexpectedforthedropzone.Ifit
doesnotmatchtheeffectAllowedsetinthedragelement,thenthedropwillbe
canceled.Theoptionsarenone,copy,link,andmove;forexample:
e.dataTransfer.dropEffect="copy";
• effectAllowed Indicatesthetypesofdraganddropthatthedraggingelement
willallow.IfitdoesnotmatchthedropEffectinthedropzone,thenthedropwill
becanceled.Theoptionsarenone,copy,copyLink,copyMove,link,linkMove,
move,all,anduninitialized;forexample:
e.dataTransfer.effectAllowed="move";
• types Presentsalistofcontenttypesthatthedraggabledatacontains:
if(e.dataTransfer.types.contains("text/html")){
//dosomething;
}
• clearData() Resetsthedatainthedragelement.
e.dataTransfer.clearData();
• setData(format,data) Setsdatatobesenttothedropzone.Theformatfield
expectsastringtoindicatetheformatofthedatabeingpassed.
e.dataTransfer.setData("text/plain","SimpleString");
e.dataTransfer.setData("text/html","<strong>HTMLString</strong>");
• getData(format) Fetchesthedatasetbythedragitem.Onlyreturnsthedata
thatmatchestheformattype.
e.dataTransfer.getData("text/html");//returns<strong>HTMLString</
strong>
• setDragImage(element,x,y) Whenanitemisbeingdragged,itispossiblefor
thedragshadowtobesettoanyelement.Itcanbeanelementonthepage,animage,
anewlycreatedelement,orevenacanvasdrawing.Thex,ycoordinatesindicate
wherethemouseshouldattachtotheshadow.
e.dataTransfer.setDragImage(document.getElementById("shadowimage",10,
10));
WiththemethodsandpropertiesexposedinthedataTransferproperty,thedrag
anddropisquitepowerful.Oneexceptionalfeatureistheabilitytodraganything
intoadropzoneandretrievethecontentviagetData().ThisincludesURLsfrom
theaddressbar,HTMLfromotherpages,andtextfromNotepaddocuments.
114 Part I: Core Markup
AsimpleexampleusingafewofthedraganddropAPIpropertiesandmethodscanbe
foundonlineatthebooksupportsite.
O NLINE http://htmlref.com/ch2/draggable.html
contenteditable Attribute
FirstintroducedbyInternetExplorer,theproprietarycontenteditableattributeis
supportedbymostbrowserstoday.HTML5standardizestheuseofthisattributeglobally
onallelements.Thebasicsenseoftheattributeisthatifyousetittotrue,thebrowser
shouldallowyoutomodifythetextdirectlywhenyouclicktheelement:
<pcontenteditable="true">Thisparagraphoftextiseditable.Clickit
andyouwillsee.Ofcoursethereisnosenseofsavingitwithcodeto
transmittheinformationtotheserver.Thisparagraphoftextiseditable.
Clickitandyouwillsee.Ofcoursethereisnosenseofsavingitwith
codetotransmittheinformationtotheserver.</p>
Thebrowsermayormaynotpresentastylechangetoshowyouarein“editmode.”
Style change
upon edit
versus
No style change
upon edit
ItispossibletouseJavaScripttoenablecontenteditingbychangingthecorresponding
contentEditablepropertyfortheelement.Forexample,thefollowingchangesthis
propertyandupdatestheclassnametoreflectastylechangewhenineditmode.
<pondblclick="this.contentEditable=true;this.className='inEdit';"
onblur="this.contentEditable=false;this.className='';">Thisparagraph
usessomesimplescripttobeeditable.Double-clickthetextto
beginediting.</p>
Chapter 2: Introducing HTML5 115
O NLINE http://htmlref.com/ch2/contenteditable.html
NOTE Withoutsendingthemodifiedcontenttotheserver,anytextchangedwhenineditmodewill
PART I
belostwhenthepageisexited.
spellcheck Attribute
HTML5definesaspellcheckattributegloballyforelements.Interestingly,somebrowsers
suchasFirefoxhavesupportedspellcheckingofformfieldsandelementsincontentediting
modeusingthecontenteditableattributeforsometime.HTML5makesthisattribute
standard.
Enablingthespellcheckingofelementcontentisamatterofsettingthespellcheck
attributetotrue:
<pspellcheck="true">Spellcheckon:Thereisatyyypooohere.
Didthebrowserspotit?</p>
Testinginsupportingbrowsersshowsthatindicationoncontenteditableregionsappears
whenthereisaspellingerror.However,thereisunclarityinthespecificationwhetherthe
usermustbeineditmodebeforetheindicationshouldbedisplayed.
Commonly,thisattributeisabitmoreusefulonformfields,giventheirinteractivenature:
<label>Textfield:(spellcheckon)
<inputtype="text"name="textfield"spellcheck="true"value="Thereisa
tyyypoohere.Didthebrowserspotit?"></label>
Giventheapplicationofsingle-linetextfields,itisfarmoreusefultosetthisattribute
onmultilinetextfieldsdefinedbya<textarea>tag,likeso:
<label>Textarea:(spellcheckon)<textareaname="comments"
spellcheck="true">Thereisatyyypooohere.Didthebrowserspotit?
</textarea></label>
O NLINE http://htmlref.com/ch2/spellcheck.html
NOTE Somebrowsersmayinvokespellcheckingonelements—particularlythetextarea
element—regardlessofthepresenceandvalueofaspellcheckattribute.
116 Part I: Core Markup
Internationalization Improvements
Whiletherearenotmanyinternationalization-supportingchangesintheHTML5specification,
itdoesmakestandardtheruby,rp,andrtelements,whichwereinitiallysupportedbythe
InternetExplorerbrowserstoassociateareadingtextwithabasetextforcertainEastAsian
languageslikeJapanese.Thebasetextthattheannotationisassociatedwithshouldbeenclosed
ina<ruby>tag;theannotation,enclosedina<rt>tag,willappearassmallertextabovethe
basetext,andoptionallyan<rp>tagcanbeusedtowrapcontenttodelimitrubytextfor
browsersthatdonotsupportthisformatting:
<p>
<!--TheKanjiforJapaneselanguagewiththeromanjiaboveitorwithin
parensfornonrubyawarebrowsers-->
<ruby>
日本語<rp>(</rp><rt>nihongo</rt><rp>)</rp>
</ruby>
</p>
data-X Attributes
HTML5definesastandardwaytoincludedeveloper-defineddataattributesintags,often
fortheconsumptionbyscripts.Thegeneralideaistousetheprefixdata-andthenpick
avariablenametoincludesomenon-visualdataonatag.Forexample,hereanauthor
variablehasbeendefinedascustomdata:
<pid="p1"data-author="ThomasA.Powell">Thisisadata-Xexample</p>
ThisvaluecouldthenbereadeitherbyusingthestandardDOMgetAttribute()
method,
<form>
<inputtype="button"value="ShowAuthor"onclick="alert(document.
getElementById('p1').getAttribute('data-author'));">
</form>
orbyusingnewHTML5DOMobjectsandpropertiesforaccessingsuchdata:
<form>
<inputtype="button"value="ShowAuthor"onclick="alert(document.
getElementById('p1').dataset.author);">
</form>
Chapter 2: Introducing HTML5 117
Theseattributevaluesshouldnotbeusedbyauseragenttostylethepageandare
solelyfordeveloperuse.Inmanyways,theattributeisthedirectconsequenceofpeoplejust
inventingattributesandforgoingvalidation,
PART I
<pid="p1"author="ThomasA.Powell">Thisisafakeattributeexample</p>
orusingclassvaluesinasimilarmanner:
<pid="p1"class="author-Thomas-A.-Powell">Thisisaclassdataexample</p>
Thisinappropriateuseofmarkupiscommonsinceitisoftenusefultoburyconfiguration
datainanelement.Now,withthedata-styleattributes,wehaveastandardwayofdoingthis
thatwillvalidateandhopefullyreducetheconclusionsthatoftenensuewhenoverloadingthe
classattribute.
Microdata
HTML5addstheconceptofmicrodata,whichaddstheabilitytoannotatecontentinsuch
awaythatacustomprogramwillbeabletoparsetheHTMLpageandretrieveitems
consistingofname/valuepairsofdesireddata.Tocreateanitem,theattributeitemscope
isaddedtoaparenttag:
<divitemscope>
Dog'sName:Angus<br>
Dog'sAge:7<br>
Dog'sBirthday:July22<br>
Dog'sPicture:<imgsrc="angus.jpg">
</div>
Simplycreatinganitemdoesn’tdomuchwithoutanyname/valuepairs.Theattribute
itempropisusedtocreatethename/valuepairsonthedesireddata.Theitemprop
attributeissettothenameofthepair,andthevaluedependsonwhattypeofelement
itempropisseton.Iftheelementisanaudio,embed,iframe,img,source,orvideo
element,thenthevalueissettothesrcofthattag.Iftheelementisana,area,orlinktag,
thenthevalueissettothehrefofthattag.Iftheelementisatimetag,thenthevalueisset
tothedatetimeattributeofthattag.Iftheelementisametatag,thenthevalueissettothe
contentattributeofthattag.Otherwise,thevalueissettothetextofthetag.
Asanexample,
<divitemscope>
Dog'sName:<spanitemprop="name">Angus</span><br>
Dog'sAge:<spanitemprop="age">7</span><br>
Dog'sBirthday:<timeitemprop="birthday"datetime="2002-07-22">July22</
time><br>
Dog'sPicture:<imgitemprop="picture"src="angus.jpg">
<metaitemprop="entryID"content="498274">
</div>
wouldsetthefollowingname/valuepairs:
name:Angus
age:7
birthday:2002-07-22
picture:angus.jpg
entryID:498274
118 Part I: Core Markup
Itisalsopossibletohaveanitempropbeanotheritembysettingtheitemscope
attributeinthesametagastheoneinwhichtheitempropattributeisset.Thiscreatesa
hierarchyofdata:
<divitemscope>
Dog'sName:<spanitemprop="name">Angus</span><br>
Dog'sAge:<spanitemprop="age">7</span><br>
Dog'sBirthday:<timeitemprop="birthday"datetime="2004-07-22">July22</
time><br>
Dog'sPicture:<imgitemprop="picture"src="angus.jpg"><br>
<metaitemprop="entryID"content="498274">
CurrentPoints:<br>
<divitemprop="points"itemscope>
Appearance:<spanitemprop="appearance">10</span><br>
Obedience:<spanitemprop="obedience">8</span><br>
Talent:<spanitemprop="talent">7.5</span><br>
</div>
</div>
Inthisexample,thefollowinghierarchyisadded:
points:
appearance:10
obedience:8
talent:7.5
Itisalsopossibletohavemultipleitemsatthetoplevel.Wecouldsimplycreatetwo
separateblocksofdata:
<divitemscope>
Dog'sName:<spanitemprop="name">Angus</span><br>
Dog'sAge:<spanitemprop="age">7</span><br>
Dog'sBirthday:<timeitemprop="birthday"datetime="2002-07-22">July22</
time><br>
Dog'sPicture:<imgitemprop="picture"src="angus.jpg">
<metaitemprop="entryID"content="498274">
</div>
<divitemscope>
Dog'sName:<spanitemprop="name">Kaylee</span><br>
Dog'sAge:<spanitemprop="age">13</span><br>
Dog'sBirthday:<timeitemprop="birthday"datetime="1995-11-26">November
26</time><br>
Dog'sPicture:<imgitemprop="picture"src="kaylee.jpg">
<metaitemprop="entryID"content="472391">
</div>
However,itmightbenecessarytointermingledata.Ifso,theitemrefattributecanbe
setontheparentitemtoalistofspaceseparatedIDstoindicateadditionalelementsthat
shouldbetraversedtofindname/valuepairsforthisitem.
<divid="angus"itemscopeitemref="introanguspictureangus"></div>
<divid="kaylee"itemscopeitemref="introkayleepicturekaylee"></div>
<p>Therearetwodogsinthecompetitiontoday.<br>
Chapter 2: Introducing HTML5 119
<spanid="introangus">Firstwehave<spanitemprop="name">Angus</span>who
is<spanitemprop="age">7</span>yearsold.</span><br>
<spanid="introkaylee">Next,wehave<spanitemprop="name">Kaylee</span>
whois<spanitemprop="age">13</span>yearsold.</span><br>
PART I
Photos:<br>
Angus:<imgid="pictureangus"itemprop="picture"src="angus.jpg"><br>
Kaylee:<imgid="picturekaylee"itemprop="picture"src="kaylee.jpg">
</p>
Inthepreviousexamples,thereisnowayofsayingwhattypeofitemeachitemblockis,
whichwouldpreventusefulcollectionofthedata.Inordertospecifyatype,theitemtype
attributeissetintheparentelement.ThisvaluemustbeintheformofaURL:
<divitemscopeitemtype="http://htmlref.com/dogs">
Dog'sName:<spanitemprop="name">Angus</span><br>
Dog'sAge:<spanitemprop="age">7</span><br>
Dog'sBirthday:<timeitemprop="birthday"datetime="2002-07-22">July22</
time><br>
Dog'sPicture:<imgitemprop="picture"src="angus.jpg">
<metaitemprop="entryID"content="498274">
</div>
Heretheitempropattributewasstillsettoastringaswehaveseeninallprevious
examples.However,itisalsopossibletosetthevaluetobeaURLvalue.Inthiscase,the
valuecanbecollectedoutsideoftherealmoftheitem.Thismightbeusefulinordertofetch
allemailaddressesorphonenumbersdespitewhattheitemtypeissetto.
<divitemscopeitemtype="http://htmlref.com/dogs">
Dog'sName:<spanitemprop="http://htmlref.com/name">Angus</span><br>
Dog'sAge:<spanitemprop="http://htmlref.com/age">7</span><br>
Dog'sBirthday:<timeitemprop="http://htmlref.com/importantdates/birthday"
datetime="2002-07-22">July22</time><br>
Dog'sPicture:<imgitemprop="http://htmlref.com/images/picture"
src="angus.jpg">
<metaitemprop="http://htmlref.com/contest/entryID"content="498274">
</div>
Intheseexamples,aname/valuepairhasbeenusedtosettheentryID.However,ifthe
itemisassociatedwithagloballyknownID,thisIDcanbesetusingtheitemidattribute
ontheparentelement.ThisvaluemustalsobeintheformofaURL.
<divitemscopeitemtype="http://htmlref.com/dogs"itemid="http://htmlref.
com/dogs/entries/498274">
Dog'sName:<spanitemprop="name">Angus</span><br>
Dog'sAge:<spanitemprop="age">7</span><br>
Dog'sBirthday:<timeitemprop="birthday"datetime="2002-07-22">July22</
time><br>
Dog'sPicture:<imgitemprop="picture"src="angus.jpg">
</div>
Sofar,wehavejustbeenmakingupmetadata,whichisokayaslongasyouarethe
primarytargetuserofthedata.However,foroutsideconsumption,thereareanumberof
predefinedtypesonlinethathavedefinedvocabulariessuchasvCard,vEvent,BibTeX,
120 Part I: Core Markup
andRDF.Ifoneofthesemetadatatypesisused,itisnecessarytoabidebythedefinedsetof
itempropvaluesthatcanbeused.Asanexample,thefollowingdefinesavCardinHTML5
usingmicrodataattributes:
<divitemscopeitemtype="http://microformats.org/profile/hcard">
<h2itemprop="fn">WilliamAdama</h2>
<spanitemprop="n"item>
<strong>Rank:</strong><spanitemprop="honorific-prefix">Admiral</
span><br>
<strong>Nicknames:</strong><br>
<spanitemprop="nickname">Bill</span><br>
</span>
<strong>Location:</strong>
<spanitemprop="adr"item>
<spanitemprop="region">Earth</span><br>
</span>
</div>
Itispossibletohaveduplicateentrieswiththesameitempropnameanddifferentvalues:
<divitemscopeitemtype="http://microformats.org/profile/hcard">
<h2itemprop="fn">WilliamAdama</h2>
<spanitemprop="n"item>
<strong>Nicknames:</strong><br>
<spanitemprop="nickname">Bill</span><br>
<spanitemprop="nickname">OldMan</span><br>
<spanitemprop="nickname">Husker</span><br>
</span>
</div>
Itisalsopossibletohaveanitempropwithmultiplenames:
<divitemscopeitemtype="http://microformats.org/profile/hcard">
<h2itemprop="fn">WilliamAdama</h2>
<strong>Rank:</strong><spanitemprop="titlerole">Admiral</span><br>
</div>
TheHTML5specificationdefinesextensionstotheDOMtosupportmicrodata.This
topicisoutsidethescopeofourdiscussion,butnotethattheseextensionsarenotrequired
tousemicrodatatodaybecausestandardDOMmethodsandtraversalschemesshouldbe
abletoaccessanyaddeddata.
unfortunatelyfailed.However,tobefair,pastHTMLspecificationshavenotadequately
consideredthecontextofmarkupusage.TherealityisthatWebdevelopmenttechnologies
mustlivetogether,soitmakessensethatHTML5discussestheintersectionbetweenHTML
PART I
andothertechnologies.Thissectionprovidesabriefoverviewofsomeoftheinteresting
aspectsofHTML5thatarenotlimitedtomarkup.
defer Attribute
HTML5standardizesthedeferattribute,longsupportedbyInternetExplorer,tohelp
improvepagerendering.Inthepresenceofadeferattributeonascriptelement,or
defer="defer"inthecaseofmarkupusingXML-likesyntax,asupportingbrowser
shoulddelayexecuting,andevenloading(inthecaseoflinkedscripts)toafuturetime.
Asasimpleexample,thefollowingaretwoinlinescripts,thefirstwithadeferattribute
andthesecondwithout:
<scriptdefertype="text/javascript"defer>
alert("DeferredScript");
</script>
<scripttype="text/javascript">
alert("ImmediateScript");
</script>
Insupportingbrowsers,thefirstscriptwouldactuallyfireafterthesecond.This
postponingofexecutionshouldalsoholdforexternalfilesandDOMinsertedscriptsas
well.Unfortunately,atthetimeofthisedition’swriting,theactualexecutionpatternfor
deferredscriptsisvariableinbrowsers:
NOTE ThetermDHTMLismoreofaconceptofusingJavaScriptacertainwaywithHTMLand
CSSthanaparticulartechnology.
TheDOMspecificationshavenowbeenretiredandtheDOMbindingsarespecified
insideoftheHTML5specificationitself.TheHTML5specificationintermixesthedefinition
ofanelement’smarkupwithitsscriptinterface.AllHTMLelementshaveabasicinterface
calledHTMLElement,reproducedhere:
interfaceHTMLElement:Element{
//DOMtreeaccessors
NodeListgetElementsByClassName(inDOMStringclassNames);
//dynamicmarkupinsertion
attributeDOMStringinnerHTML;
attributeDOMStringouterHTML;
voidinsertAdjacentHTML(inDOMStringposition,inDOMStringtext);
//metadataattributes
attributeDOMStringid;
attributeDOMStringtitle;
attributeDOMStringlang;
attributeDOMStringdir;
attributeDOMStringclassName;
readonlyattributeDOMTokenListclassList;
readonlyattributeDOMStringMapdataset;
//microdata
attributebooleanitemScope;
attributeDOMStringitemType;
attributeDOMStringitemId;
attributeDOMStringitemRef;
[PutForwards=value]readonlyattributeDOMSettableTokenListitemProp;
readonlyattributeHTMLPropertiesCollectionproperties;
attributeanyitemValue;
//userinteraction
attributebooleanhidden;
voidclick();
voidscrollIntoView();
voidscrollIntoView(inbooleantop);
attributelongtabIndex;
voidfocus();
voidblur();
attributeDOMStringaccessKey;
readonlyattributeDOMStringaccessKeyLabel;
attributebooleandraggable;
attributeDOMStringcontentEditable;
readonlyattributebooleanisContentEditable;
attributeHTMLMenuElementcontextMenu;
attributeDOMStringspellcheck;
//commandAPI
Chapter 2: Introducing HTML5 123
readonlyattributeDOMStringcommandType;
readonlyattributeDOMStringlabel;
readonlyattributeDOMStringicon;
readonlyattributebooleandisabled;
PART I
readonlyattributebooleanchecked;
//styling
readonlyattributeCSSStyleDeclarationstyle;
//eventhandlerDOMattributes
attributeFunctiononabort;
attributeFunctiononblur;
attributeFunctiononcanplay;
attributeFunctiononcanplaythrough;
attributeFunctiononchange;
attributeFunctiononclick;
attributeFunctiononcontextmenu;
attributeFunctionondblclick;
attributeFunctionondrag;
attributeFunctionondragend;
attributeFunctionondragenter;
attributeFunctionondragleave;
attributeFunctionondragover;
attributeFunctionondragstart;
attributeFunctionondrop;
attributeFunctionondurationchange;
attributeFunctiononemptied;
attributeFunctiononended;
attributeFunctiononerror;
attributeFunctiononfocus;
attributeFunctiononformchange;
attributeFunctiononforminput;
attributeFunctiononinput;
attributeFunctiononinvalid;
attributeFunctiononkeydown;
attributeFunctiononkeypress;
attributeFunctiononkeyup;
attributeFunctiononload;
attributeFunctiononloadeddata;
attributeFunctiononloadedmetadata;
attributeFunctiononloadstart;
attributeFunctiononmousedown;
attributeFunctiononmousemove;
attributeFunctiononmouseout;
attributeFunctiononmouseover;
attributeFunctiononmouseup;
attributeFunctiononmousewheel;
attributeFunctiononpause;
attributeFunctiononplay;
attributeFunctiononplaying;
attributeFunctiononprogress;
attributeFunctiononratechange;
attributeFunctiononreadystatechange;
124 Part I: Core Markup
attributeFunctiononscroll;
attributeFunctiononseeked;
attributeFunctiononseeking;
attributeFunctiononselect;
attributeFunctiononshow;
attributeFunctiononstalled;
attributeFunctiononsubmit;
attributeFunctiononsuspend;
attributeFunctionontimeupdate;
attributeFunctiononvolumechange;
attributeFunctiononwaiting;
};
Asyoucansee,thisinterfacedefinescommonattributeslikeid,title,lang,dir,and
soon.Italsodefinesnumerouseventhandlerslikeonclick,onscroll,onselect,andso
onthatareassociatedwithfunctions.Numerousmethodsarealsodefined.
Specificelementswillinheritthesescriptinghooksandaddtothem.Forexample,note
theinterfaceforthenewHTML5timeelement:
interfaceHTMLTimeElement:HTMLElement{
attributeDOMStringdateTime;
attributebooleanpubDate;
readonlyattributeDatevalueAsDate;
};
ThistakesallthefeaturesofHTMLElementandaddstothemdateTime,pubDate,and
valueAsDateproperties.
AsyoulookcloselyattheHTML5scriptbindings,you’llnoticethatthedifference
betweenanHTML5element’sattributesandthecorrespondingscriptpropertiesisminimal.
Ingeneral,ifanelementhasanattribute,itspropertywillbethesame,withtwoexceptions:
• IfthenameofanHTMLattributeiscomposedofmultiplewords,thefirstletterof
theallbutthefirstwordisuppercasewhenthenameisusedasascriptable
propertyname.Forexample,thetimeelementhasapubdateattribute;following
thepreviousrule,thecorrespondingDOMpropertyispubDate.
• IfthenameoftheattributeisareservedwordinJavaScript,itwillberedefined
somehow.Themostcommonattributethisruleisappliedtoistheclassattribute,
whichiswidelyused.Theword“class”can’tbeusedasascriptablepropertyname
becausekeywordclassisreservedforfutureversionsofJavaScript.Thus,to
changetheclassattributeviaJavaScript,useclassNameinstead.
Aslongasyouareawareofthesetworules,themappingsbetweenmarkupandscript
areactuallyprettystraightforward.
Wecertainlydon’texpectyoutobecomefamiliarwiththeDOMhere;asisterbook,
JavaScript:TheCompleteReference,ofnearlythesamepagecountcoversJavaScriptandits
usagewithHTMLandCSS.However,wedowanttomakeitclearthattheHTML5
specificationcombinestheDOMandmarkupspecificationstogether,sofromhereonout
thetwoideasshouldstaymoreinharmony.Thisisgenerallyagoodthing,thoughitdoes
makethespecificationquiteabitlarger.
Chapter 2: Introducing HTML5 125
PART I
JavaScriptobjectslikeNavigator,History,andmorearenotreallypartofanystandard
otherthananadhocone.Inmanycases,proprietaryJavaScriptobjects,properties,and
methodsaredocumented,butonlybytheoriginatingvendors,andotherimplementations
thatmayormaynotconformtothisproprietaryspecificationmayexist.
ProbablythemostfamousoftheproprietaryturnedcommonfeaturesinJavaScriptis
Microsoft’sinnerHTMLproperty,whichallowsforquickcreationofnewmarkupin
documents.ThispropertyiscommonlyusedbyWebdeveloperswhoacceptthatitis
widelyimplementedandquiteusefulcomparedtostandardDOMtechniques.Asa
demonstration,considerthecodeneededtoinsertthefollowingmarkup:
<p>Thisis<strong>just</strong>atest.</p>
intoanameddivelement:
<divid="div1"></div>
UsingtheDOM,thecodemightlooklikethis:
varstr1,str2,str3;
varel1,el2;
el1=document.createElement('p');
str1=document.createTextNode('Thisis');
el1.appendChild(str1);
el2=document.createElement('strong');
str2=document.createTextNode('just');
el2.appendChild(str2);
el1.appendChild(el2);
str3=document.createTextNode('atest.');
el.appendChild(str3);
document.getElementById('div1').appendChild(el1);
Usingchaining,itispossibletojamstatementstogether,butthetaskismucheasier
usingMicrosoft’sinnerHTMLproperty.Simplymakeastringlikeso
varnewElements="<p>Thisis<strong>just</strong>atest.</p>";
andthensetthecontentsofthedivtothisstring:
document.getElementById('div1').innerHTML=newElements;
BysettingtheinnerHTMLproperty,ineffect,thebrowser’sparserisinvoked,anditcreates
elementsfromthestringprovided.
GiventhewordinessofDOMmethods,manydeveloperspreferMicrosoft’sinnerHTML
schemeandthusithasbeenwidelycopiedandputintootherbrowsers.However,HTML5
doesnotcoverallofMicrosoft’sother,relatedpropertieslikeinnerTextandouterText,
thoughouterHTMLfornowappearstobecovered.
126 Part I: Core Markup
ItisinterestingthatmanydevelopersarequiteokaywiththeuseofinnerHTMLbutare
quicktoderidetheuseofJavaScript’seval()statement.Inmanyways,thesearethesame
concepts:theformerprovidesdirectaccesstothemarkupparserandthelatterprovides
directaccesstotheJavaScriptinterpreter.RegardlessoftheconsistencyofWebdevelopers’
thinkingpatterns,thecodificationofinnerHTMLisquiteawelcomechange.
TheembraceofcommonpracticesbyHTML5isn’tlimitedtoinnerHTML;thespecification
supportsallsortsoffeatures,suchasdesignModefeaturesthatallowforbrowser-based
WYSIWYGediting,commonlyusedDOMworkaroundslikeinsertAdjacentHTML(),
emergingDOMmethodslikegetElementsByClassName(),more-esotericDOM
specificationslikerangesandselections,andmore.
ThespecificationalsoprovidesAPIsforwhatitintroduces.Weexploredjustsuchan
APIearlierinthechapterwhenweexperimentedwithcanvasscripting.Similarly,elements
likeaudioandvideoexposeanumberofpropertiessuchasvolumeandmethodssuchas
play().
ThereismuchtobediscoveredwhenreadingtheHTML5specificationclosely.Consider,
forexample,howbrowsershandlerunawayscriptcode.Therereallyisnothingonlinethat
defineshoworwhenthisisdone,buttheHTML5specificationactuallystartstoaddress
suchproblems(section6.5.3.4):
Useragentsmayimposeresourcelimitationsonscripts,forexample,CPUquotas,
memorylimits,totalexecutiontimelimits,orbandwidthlimitations.Whena
scriptexceedsalimit,theuseragentmayeitherthrowaQUOTA_EXCEEDED_
ERRexception,abortthescriptwithoutanexception,prompttheuser,orthrottle
scriptexecution.
Ifyoutakethetimetoreadthespecification,youwillfindmanypassagessuchasthis
thatofferhopethatsomedaytroublingcornercasesinWebdevelopmentwillbereducedor
eveneliminated.However,youmightalsogetasensethattheaimsofthespecificationare
abittoogrand.Youcanfindbitsandpiecesofhalf-bakedideasaboutundo-redohandling;
subtlehintsaboutimportantarchitecturalchanges,suchasthemanagementofhistoryfor
supportingAjaxapplications;discussionofofflinefeaturesandstorageschemes;and
documentationofavarietyofcommunicationschemes,frominterframemessagepostingto
full-blownWebSocketcommunication.Insomecases,thesediversionAPIswillspawntheir
owndocuments,butinothercasestheyjustclutterthespecification.Thecriticsreallydo
haveapointhere.
featuresnow?Theanswerisagainyes,butthistimewithsomecaution.Todemonstrate
whycautionisrequired,thefollowingisasimpleexampleoftheuseofHTMLsectioning
elements,introducedtowardthestartofthechapter,butnowwithsomestyleappliedtothe
PART I
newHTML5elementsused:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HTML5Today?</title>
<styletype="text/css">
/*styleupafewofthenewelements*/
article,aside,figure,footer,header,
hgroup,menu,nav,section{display:block;}
body>header{background-color:#930;color:white;}
body>footer{border-top:solid5pxblack;}
h2{margin-top:0;font-style:italic;}
h3{font-variant:small-caps;}
p{margin-left:1.5em;}
section{border-top:dashed2pxblack;padding-top:1em;}
section>sectionh3{margin-left:2em;}
section>sectionp{margin-left:3em;}
body>footer>p{text-align:right;
font-style:italic;
font-size:smaller;}
</style>
</head>
<body>
<header>
<h1>WelcometotheFutureWorldofHTML5</h1>
<h2>Don'tbescareditisn'tthathard!</h2>
</header>
<!--assumechapter1before-->
<sectionid="chapter2">
<header>
<h1>Chapter2</h1>
</header>
<p>Introtochapterhere...</p>
<sectionid="newStrucreElements">
<header>
<h2>NewStructuralElements</h2>
</header>
<h3>headerElement</h3>
<p>Discussionofheaderelement.</p>
<h3>footerElement</h3>
<p>Discussionoffooterelement.</p>
<h3>sectionElement</h3>
128 Part I: Core Markup
<p>Discussionofsectionelement</p>
</section>
<sectionid="newFormElements">
<header>
<h2>NewFormElements</h2>
</header>
<h3>inputtype=date</h3>
<p>Discussionhere...</p>
<footer>
<p>TheseideasarefromWebFormsspecification.</p>
</footer>
</section>
</section>
<sectionid="chapter3">
<header>
<h2>Chapter3</h2>
</header>
<p>Massiveelementreference...</p>
</section>
<footer>
<p>Contentofthisexampleisnotundercopyright</p>
</footer>
</body>
</html>
O NLINE http://htmlref.com/ch2/html5today.html
Figure2-7showstherenderingoftheexampleintwocommonbrowsers.Notethat
InternetExplorer8andearlierhassometroublewiththenewelements.
ToaddressInternetExplorer’slackofsupport,wecanintroduceasmallscriptthat
createsthenewHTML5elementsusingtheDOMcreateElement()method.OnceIE
recognizesthemaselements,itrendersthemarkupandstylefine,asshowninFigure2-8.
<!--[ifIE]>
<scripttype="text/javascript">
varhtml5elements="abbr,article,aside,audio,canvas,datalist,details,
figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,
time,video".split(',');
for(vari=0;i<html5elements.length;i++)
document.createElement(html5elements[i]);
</script>
<![endif]-->
O NLINE http://htmlref.com/ch2/html5todayie.html
Chapter 2: Introducing HTML5 129
PART I
FIGURE 2-7 HTML5 works straightaway in many browsers, but not IE.
NOTE Becausethepreceding“shim”scriptusesconditioncommentstomakeitworkinInternet
Explorer,itwillnotvalidatewell.Therearewaysaroundthisifyouwanttousebrowser
detection.ThepointofthescriptistoillustratetheabilitytomakeHTML5workeverywhere.
Youcanexpectthatthecodewillchangeovertimeorotherhackswillbeintroduced.
WhenmovingbeyondsimpleHTML5semanticelementstointeractivefeatures,the
situationisabitdicier.CertainlyJavaScriptcanbeusedtosimulatemanyfeatures,butuntil
suchfeaturesaresolidlysupported,youshouldproceedwithcaution.
OpponentsofHTML5throwoutanestimatedfinalversiondateof2012oreven2022as
areasontoavoidthetechnologyfornow.Yes,indeed,sometimelinessuggestthatHTML5
won’tbecompletelyfinaluntilmaybe2022.Ofcourse,plentyaspectsofHTML5are
130 Part I: Core Markup
implementedtoday,anditismorelikelythatpreliminaryversionsofthespecificationwill
beacceptedatthetimeyoureadthis.Ifyouwanttoavoidusingaspecificationuntilitis
100percentcomplete,youshouldnotethatevenHTML4hassomeopenimplementation
andtestingconcerns,soyoumightwanttoheadbacktoearlierversions.Seriously,what
reallyshouldmatterwithaspecificationlikeHTML5iswhetheryoucanusemanyofits
features.Theanswertothatquestionisclearlyyes.
HTML5 as a Catch-All
HTMLispartofabiggerworld.AmodernWebsiteorapplicationreallyneedsmuchmore
thanmarkupandmustaddressstyle,script,mediaelements,networkconcerns,security
issues,usercapabilities,andmuchmore.Becauseoftheenvironmentinwhichitisfound,
Chapter 2: Introducing HTML5 131
theHTML5specificationseemstotouchallmanneroftopics.Inthissense,itscriticshavea
pointaboutits“everythingandthekitchensink”nature.However,itisimpossiblefor
markuptoliveinavacuum,sosomeoverlapandenvironmentalconsiderationsaretobe
PART I
expected.
Unfortunately,giventhatitlookslikeacatch-allspecification,manypeoplemisunderstand
thetechnologyandusetheideaofHTML5simplytorefertoanythingthatisnewinaWeb
browser.HTML5doesn’ttalkaboutCSSproperties.HTML5doesn’tdefineWebfonts.
HTML5doesn’tchangeHTTP.Whilethespecificationishuge,thereisplentyoutsideofit,
sowhyistheresuchamisconceptionthatitcoverseverything?Well,that’sthepoliticsof
theWebatwork.
TheHTML5specificationisaworkinprogress.Writingabookaboutsuchamoving
targetismorethanabitofachallenge.However,likethespecificationitself,somethinghad
tobedone.Itwilltaketoolongtofinishthespecification,andinthemeantimepeoplewant
tousesomeofthenewelementsthatarealreadysupported.
HTML5willchangetheWeb,buttheoldWebwilllikelyliveon.ThinkingthatHTML5
isgoingtotaketheworldbystorm,co-optingstandardpracticesandusurpingtechnologies
likeFlashinshortorder,isfanciful.Theoldwayswillcontinuetoliveonanditwillbequite
sometimebeforeHTML5ideasareevencommonplace.
HTML5won’tsolvealltheproblemsyouencounterasaWebdeveloper.Infact,asafe
predictionisthatitwillintroduceevenmoretrouble,particularlyaswetransitionfromthe
oldwaystothenew.Andalthoughthestandardisevolvingquickly,thereareboundtobe
fightsamongbrowservendors,multipleinterpretationsofthestandards,andthetypical
dancebetweeninnovationandspecificationconformance.
Summary
HTML5isthefuture.Workingwiththemessed-upmarkupthatdominatestheWeband
providingadefinitionofhowuseragentsshouldparsethemessisatremendous
improvementinWebdevelopment.YetHTML5doesn’tsimplyembracethepast;itextends
thelanguagewithmanymoreelementsandcontinuesthemovetomoresemanticmarkup.
WhilesomemarkuppuristsmaybemoantheresurgenceofHTMLtraditions,theXML
futureisnotdestroyedbyHTML5.Ifyouwanttouselowercase,quoteallattributes,and
self-closeemptyelements,gorightahead—thatconformstoHTML5aswell.However,
HTML5isn’tjustaboutmarkup;itisalsoaboutmetadata,media,Webapplications,APIs,
andmore.It’sasprawlingspecificationthatwillcontinuetoevolve,butmuchofitishere
today,sogetbusyandembracethefutureofmarkupnow.
CHAPTER
3
HTML and XHTML
Element Reference
T
hischapterprovidesacompletereferencefortheelementsintheHTML4.01and
XHTML1.0specifications.AllknownHTML5elementsatthetimeofthisedition’s
writingarecoveredaswell,butgiventhefluidnatureofthespecification,some
elementsmayhavebeenomittedorsyntaxmayhavechangedbythetimeofpublication.
YouareencouragedtoproceedwithcautionwhenconsideringtheHTML5information
because,againatthetimeofthiswriting,thespecificationisinfluxandfewoftheelements
discussedworknativelyinbrowsers.Proprietaryfeaturesdiscussedinthisreferencealso
shouldbetreatedwithsomecaution.Allthebrowser-specificelementsandattributes
supportedbyInternetExplorer,Firefox,Safari,Chrome,Netscape,andOperaarepresented.
Someelementspresentedinthereferencemightbedeprecated,buttheyareincluded
neverthelesseitherbecausebrowservendorscontinuetosupportthemorbecausetheymay
stillbefoundinuse.
133
134 Part I: Core Markup
PART I
Transitional application. The transitional form preserves
many of the basic presentation features of
HTML 4.0 transitional but applies the strict
syntax rules of XML to HTML.
XHTML 1.0 Strict www.w3.org/TR/xhtml1/ A reformulation of HTML 4.0 Strict using XML.
This language is rule enforcing and leaves all
presentation duties to technologies like CSS.
XHTML 1.1 www.w3.org/TR/xhtml11/ A restructuring of XHTML 1.0 that modularizes
the language for easy extension and reduction.
It is not commonly used at the time of this
writing and offers minor gains over strict
XHTML 1.0.
XHTML 2.0 www.w3.org/TR/xhtml2/ A new implementation of XHTML that will not
provide backward compatibility with XHTML 1.0
and traditional HTML. XHTML 2 will remove all
presentational tags and will introduce a variety
of new tags and ideas to the language. Beyond
this brief description, which may certainly be
wrong by the time you read it, little can be said
about XHTML 2 with certainty other than, given
HTML5, its future is somewhat questionable.
XHTML Basic 1.0 www.w3.org/TR/2000/REC- A variation of XHTML based upon the
xhtml-basic-20001219/ modularization of XHTML (1.1) designed to
work with less-powerful Web clients such as
mobile phones.
XHTML Basic 1.1 www.w3.org/TR/xhtml-basic/ An improvement to the XHTML Basic
specification that adds more features, some
fairly specific to the constrained interfaces
found in mobile devices.
class
Thisattributeindicatestheclassorclassesthataparticularelementbelongsto.Aclassname
mightbeusedbyastylesheettoassociatestyleruleswithmultipleelementsorforscript
accessusingthegetElementsByClassName()method.Asanexample,youcouldassociate
aspecialclassnamecalled“fancy”withallelementsthatshouldberenderedwitha
particularstylenamedassuchinastylesheet.Classvaluesarenotuniquetoaparticular
element,soboth<strongclass="fancy">and<pclass="fancy">couldbeusedin
thesamedocument.Italsoispossibletohavemultiplevaluesfortheclassattribute
separatedbywhitespace;<strongclass="fancyspecialexpensive">woulddefine
threeclassesfortheparticularstrongelement.
id
Thisattributespecifiesauniquealphanumericidentifiertobeassociatedwithanelement.
Naminganelementisimportanttobeingabletoaccessitwithastylesheet,alink,ora
scriptinglanguage.Namesshouldbeuniquetoadocumentandshouldbemeaningful;
althoughid="x1"isperfectlyvalid,id="Paragraph1"mightbebetter.Valuesfortheid
attributemustbeginwithaletter(A–Zora–z)andmaybefollowedbyanynumberof
letters,digits,hyphens,orperiods.However,practicallyspeaking,aperiodcharacter
shouldnotbeusedwithinanidvaluegiventheuseofthesevaluesinscriptinglanguages
andpossibleconfusionwithclassnames.
Onceelementsarenamedwithid,theyshouldbeeasytomanipulatewithascripting
language.CommonlytheyarereferencedusingtheDOMmethodgetElementById().
Liketheclassattribute,theidattributeisalsousedbystylesheetsforaccessinga
particularelement.Forexample,anelementnamedParagraph1canbereferencedbya
styleruleinadocument-widestylebyusingafragmentidentifier:
#Paragraph1{color:blue;}
Onceanelementisnamedusingid,italsoisapotentialdestinationforananchor.In
thepast,anaelementwasusedtosetadestination;now,anyelementcanbeadestination,
forexample:
<ahref="#mainContent">Skiptocontent</a>
<divid="mainContent">Thisisthecontentofthepage.</div>
Onepotentialproblemwiththeidattributeisthat,forsomeelements,particularlyform
controlsandimages,thenameattributealreadyservesitsfunction.Youshouldbecareful
whenusingbothnameandidtogether,especiallywhenusingolderelementsyntaxwith
newerstyles.Forexample,fromalinkingpointofview,thefollowingmarkupmightbe
usedtosetalinkdestination:
<aname="anchorPoint"></a>
Atsomeotherpointinthedocument,anidwiththesamenamedvaluemightexist,likeso:
<pid="anchorPoint">Iamthesamedestination?</p>
Thereissomeuncertainty,then,aboutwhatthislinkwoulddo:
<ahref="#anchorPoint">WheredoIgo?</a>
Chapter 3: HTML and XHTML Element Reference 137
Woulditgotothefirstlinkdefinedorwoulditgotothelast?Woulditfavortheelement
usingtheidoverthenameregardlessofpositioninthedocument?It’sbetternottoleave
suchissuestochancebutrathertoassumethatnameandidareinthesamenamespace,at
PART I
leastwhenlinkingisconcerned.
Withformelements,thechoiceofusingnameandidcanbemoreconfusing.Thename
attributelivesonandmustbeusedtospecifyname/valuepairsforformdata:
<inputtype="text"name="username">
However,theidattributealsoisappliedtoformcontrolsforstylepurposesandoverlap
forscriptingduties,soitisnotuncommontoseenameandidusedtogetherwiththesame
value:
<inputtype="text"name="username"id="username">
Generally,thisisanacceptablepracticeexceptwhenthepurposeofnameservessecondary
duty,suchasinthecaseofradiobuttons:
<label>Yes:
<inputtype="radio"name="yesno"id="yesno"value="yes">
</label>
<label>No:
<inputtype="radio"name="yesno"id="yesno"value="no">
</label>
Intheprecedingmarkup,theradiobuttonsmustsharethenamevalue,buttheidvalues
shouldbeuniqueforCSSandJavaScriptusage.Asimplerewritelikethismakesitwork,but
showsthatnameandidarenotquitesynonymous:
<label>Yes:
<inputtype="radio"name="yesno"id="yesno-yeschoice"value="yes">
</label>
<label>No:
<inputtype="radio"name="yesno"id="yesno-nochoice"value="no">
</label>
Givensuchchanceforconfusion,youareencouragedtopickanamingstrategyanduse
itconsistently.
style
Thisattributespecifiesaninlinestyleassociatedwithanelement,whichdeterminesthe
renderingoftheaffectedelement.Becausethestyleattributeallowsstylerulestobeused
directlywiththeelement,itgivesupmuchofthebenefitofstylesheetsthatdividethe
presentationofamarkupdocumentfromitsstructure.Anexampleofthisattribute’suseis
shownhere:
<strongstyle="font-family:Arial;
font-size:18px;">Importanttext</strong>
138 Part I: Core Markup
title
Thetitleattributeisusedtoprovideadvisorytextaboutanelementoritscontents.Given
<ptitle="HeylookIamatitletooltip!">
Thisisthefirstparagraphoftext.
</p>
thetitleattributesetssomemessageonthisfirstparagraph.Browsersgenerallydisplaythis
advisorytextintheformofatooltip,asshownhere:
Insomecases,suchaswhenappliedtotheaelement,thetitleattributecanprovide
additionalhelpinbookmarking.Likethetitleforthedocumentitself,titleattribute
valuessuchasadvisoryinformationshouldbeshort,yetuseful.Forexample,<ptitle="A
paragraph">provideslittleinformationofvalue,whereas<ptitle="HTML:The
CompleteReference-TitleExample">providesmuchmoredetail.Theattributecan
takeanarbitraryamountoftext,butthewrappingandpresentationoflargertitleswill
likelyvary.
NOTE Asofthewritingofthisedition,noformattingcanbeappliedwithinadvisorytext,though
theHTML5specificationdoesindicatethatUnicodelinefeeds(\u000A)shouldeventuallybe
supported.
Whencombinedwithscripting,thisattributecanprovidefacilitiesforautomaticindex
generation.
dir
Thedirattributesetsthetextdirectionasrelatedtothelangattribute.Theacceptedvalues
undertheHTML4.01specificationareltr(lefttoright)andrtl(righttoleft).Itshouldbe
possibletooverridewhateverdirectionauseragentsetsbyusingthisattributewiththebdo
element:
<div>
Standardtextrunninglefttorightinmostcases.
<bdodir="rtl">Napoleonneverreallysaid<q>AblewasIere
IsawElba.</q></bdo>Morestandardtext.
</div>
Chapter 3: HTML and XHTML Element Reference 139
lang
Thelangattributeindicatesthelanguagebeingusedfortheenclosedcontent.Thelanguage
isidentifiedusingtheISOstandardlanguageabbreviations,suchasfrforFrench,enfor
PART I
English,andsoon.RFC1766(www.ietf.org/rfc/rfc1766.txt)describesthesecodesandtheir
formats.
accesskey
MicrosoftappliedthisW3Cattributetoawidervarietyofelementsthanformelements.The
accesskeyattributespecifiesakeyboardnavigationacceleratorfortheelement.Pressing
ALTorasimilarkey(dependingonthebrowserandoperatingsystem)inassociationwith
thespecifiedkeyselectstheanchorelementcorrelatedwiththatkey.
Ifaccesskeysareemployed,Webpageauthorsarecautionedtobeawareofpredefined
keybindingsinthebrowsingenvironment,asamplingofwhichisdetailedinTable3-2.
NOTE Ifyoutakeintoconsiderationsomeolderandesotericbrowsers,thereareevenmorepreset
keystoavoid.
AlsonotethattheUKgovernmenthasrecommendedthat,foraccessibility,certainkey
bindingsshouldbepredefinedinUKWebsites.ThesesuggestedvaluesarefoundinTable3-3.
Pageauthorsarealsoencouragedtoconsiderstylingorprovidingscript-basedschemes
torevealaccesskeybindingsbecausetheymaynotbeobvioustousersevenwhena
conventionliketheUKbindingsisemployed.
align
Manybrowsersdefinethealignattributeonelements.Transitionalversionsof(X)HTML
doaswell.Thisattributegenerallytakesavalueofleft,right,orcenter,which
determineshowtheelementanditscontentsarepositionedinatableorthewindow.The
valueofleftisusuallythedefault.Insomecases,avalueofjustifyisalsosupported.
CSSpropertiesliketext-alignandmarginshouldbeusedinsteadofthisattributewhen
possible.
contenteditable
ThisproprietaryMicrosoftattribute,nowpartoftheHTML5specification,allowsusersto
directlyeditcontentinabrowser.Valuesarefalse,true,andinherit.Avalueoffalse
preventscontentfrombeingeditedbyusers;trueallowsediting.Thedefaultvalue,
inherit,appliesthevalueoftheaffectedelement’sparentelement.InadditiontoInternet
Explorer,allrecentmajorbrowsers,suchasFirefox3+,Safari3+,andOpera9.5+,also
supportthisattribute.
datafld
Thisattributespecifiesthecolumnnamefromthedatasourceobjectthatsuppliesthe
bounddata.ThisattributeisspecifictoMicrosoft’sdatabinding.
PART I
dataformatas
ThisInternetExplorer–specificattributeindicateswhetherthebounddataisplaintextor
HTML.
datasrc
Thisattributeindicatesthenameofthedatasourceobjectthatsuppliesthedatathatis
boundtothiselement.ThisattributeisspecifictoMicrosoft’sdatabinding.
disabled
Again,MicrosofthasappliedanexistingW3Cattributetoarangeofelementsnotassociated
withitintheW3Cspecifications.Elementswiththedisabledattributesetmayappear
fadedandwillnotrespondtouserinput.ValuesundertheMicrosoftimplementationare
trueandfalse.Whentheattributeispresent,thedefaultvalueistrue,soIE5.5and
higherwillreaddisabledas“on,”evenwithoutavaluesetfortheattribute.
height
Thisattributespecifiestheheight,inpixels,neededbyanembeddedobject,image,iframe,
applet,oranyotherembeddableitem.
hidefocus
Thisproprietaryattribute,introducedwithInternetExplorer5.5,hidesfocusonan
element’scontent.Focuswillgenerallyberepresentedwithadottedoutline,butelements
withthisattributesettotruewillnotshowsuchanindication.
hspace
Thisattributespecifiesadditionalhorizontalspace,inpixels,tobereservedoneithersideof
anembeddeditemlikeaniframe,applet,image,andsoon.
language
IntheMicrosoftimplementation,thisattributespecifiesthescriptinglanguagetobeused
withanassociatedscriptboundtotheelement,typicallythroughaneventhandlerattribute.
Possiblevaluesmightincludejavascript,jscript,vbs,andvbscript.Othervalues
thatincludetheversionofthelanguageused,suchasJavaScript1.1,mightalsobe
possible.ThereasonthisfeatureissupportedisthatitispossibleinInternetExplorerto
runmultiplescriptlanguagesatthesametime,whichrequiresthatyouindicateon
element-leveleventhandlerswhichscriptinglanguageisinplay,asdemonstratedhere:
<ponclick="alert('HifromJavaScript');"language="JavaScript">
Clickme(JavaScript)</p>
<ponclick="MsgBox('HifromVBScript')"language="VBScript">
Clickme(VBScript)</p>
142 Part I: Core Markup
tabindex
Thisattributeusesanumbertoidentifytheobject’spositioninthetabbingorderfor
keyboardnavigationusingtheTABkey.Whiletabindexisdefinedforsomeelementsas
partofW3Cstandards,IE5.5addedsupportforthisattributetoawiderrangeofelements.
UnderIE5.5orhigher,thisfocuscanbedisabledwiththehidefocusattribute.
unselectable
ThisproprietaryMicrosoftattributecanbeusedtopreventcontentdisplayedfrombeing
selected.Testingsuggeststhatthismightnotworkconsistently.Valuesareoff(selection
permitted)andon(selectionnotallowed).
vspace
Thisattributespecifiesadditionalverticalspace,inpixels,tobereservedaboveandbelow
anembeddedobject,image,iframe,applet,oranyotherembeddableitem.
width
Thisattributespecifiesthewidth,inpixels,neededbyanembeddedobject,image,iframe,
applet,oranyotherembeddableitem.
NOTE OneinterestingaspectoftheseattributesisthatwhiletheyaredefinedintheHTML5
specificationonallelements,theirmeaningisunclearorsuspectincertaincases.Forexample,
spellcheckingimagesorusinginterfaceconventionslikeacceleratorsorcontextmenuson
nonvisibleelements,particularlythoseinthehead(likemeta),simplydon’tmakesense.What
thespecsaysandwhatwillactuallybeimplementedorusedwilllikelyvary.
accesskey
UnderHTML5,theaccesskeyattributespecifiesakeyboardnavigationacceleratorforthe
element.Themaindifferencesbetweenthisandthecommonlysupportedattributearethat
itcanbeapplied,intheory,toanyelementinthespecificationandthatittakesaspace-
separatedlistofkeychoices.Forexample,
<form>
<inputtype="button"value="ShowAuthor"accesskey="tap">
</form>
Chapter 3: HTML and XHTML Element Reference 143
allowsyoutoacceleratethisbuttonsimplybypressingaspecialkeylikeALTinconjunction
withthecharactervaluespresentintheattribute.Thereissomediscussionaboutthe
attributeeventuallysupportingwordsratherthanjustindividualkeys.
PART I
contenteditable
InitiallyaproprietaryMicrosoftattribute,thisHTML5attributewhensetallowsusersto
directlyeditcontentrenderedinthebrowser.Valuesarefalse,true,andinherit.A
valueoffalsepreventscontentfrombeingeditedbyusers;trueallowsediting.The
defaultvalue,inherit,appliesthevalueoftheaffectedelement’sparentelement.
contextmenu
Thecontextmenuattributeisusedtodefineanelement’scontextmenu,whichisgenerally
themenuinvokeduponamouseright-click.Theattribute’svalueshouldholdastringthat
referencestheidvalueofa<menu>tagfoundintheDOM.Ifthereisnoelementfoundor
novalue,thentheelementhasnospecialcontextmenuandtheuseragentshouldshowits
defaultmenu.InternetExplorerandmanyotherbrowserssupportanoncontextmenu
attributethatcouldbeusedtoimplementtheideaofthisemergingattribute.
<pid="p1"data-author="ThomasA.Powell">Thisisadata-Xexample</p>
ThisvaluecouldthenbereadusingthestandardDOMgetAttribute()method,
<form>
<inputtype="button"value="ShowAuthor"onclick="alert(document.
getElementById('p1').getAttribute('data-author'));">
</form>
orusingnewHTML5DOMobjectsandpropertiesforaccessingsuchdata:
<form>
<inputtype="button"value="ShowAuthor"onclick="alert(document.
getElementById('p1').dataset.author);">
</form>
Theseattributevaluesshouldnotbeusedbyauseragenttostylewhenrenderingand
aresolelyfordeveloperuse.Inmanyways,theattributeisthedirectconsequenceofpeople
justinventingattributesandforgoingvalidation,
<pid="p1"data-author="ThomasA.Powell">Thisisafakeattributeexample</p>
144 Part I: Core Markup
orusingclassvaluesinasimilarmanner:
<pid="p1"class="author-Thomas-A.-Powell">Thisisaclassdataexample</p>
NOTE Specialcharacters,particularlycolons,shouldnotbeusedinthedata-nameshere.Youare
alsoencouragedtokeepthenameslowercaseforconsistency.
draggable
Thisattributeisusedtosetwhetherornotanelementisdraggable.Iftheattributeissetto
true,theelementisdraggable.Avalueofautosetsimagesandlinkswithanhreftobe
draggableandallotheritemstonotbedraggable.Afalsevalueturnsoffdragging.
<pdraggable="true">Dragme</p>
<pdraggable="false">Sorrynodrag</p>
RealintegrationwithelementswithdraggableattributesrequiresJavaScriptusage(see
Chapter2foranexample).
hidden
ThisattributeisaBoolean,orpresence-based,attributethatdoesnotrequireavalue.If
you’reusingXHTML5,youshouldusethevalueofhidden,asattributesmusthavevalues
withXMLsyntax.
<phidden>I'mhidden</p>
<phidden="hidden">I'mhiddenXMLsyntaxstyle</p>
Whenthisattributeisspecifiedonanelement,theelementisnotcurrentlyrelevantand
thustheuseragentshouldnotrenderit.Theexactmeaningoftheattributeisabitunclear.
ItwouldappeartobesimilartothesemanticsoftheCSSpropertydisplay:none,butthe
specificationhintsthatelementsthatarehiddenareactiveandthusitalsoissomewhat
differentfromthiscommonconstruct.Oncebrowsersimplementthisattribute,themeaning
maybeclarified.ThisattributewasinitiallycalledirrelevantinearlierHTML5drafts.
itemid
Thisattributeisusedtosetaglobalidentifierforamicrodataitem.Thisisanoptional
attribute,butifitisused,itmustbeplacedinanelementthatsetsboththeitemscopeand
itemtypeattributes.ThevaluemustbeintheformofaURL.
<divitemscopeitemtype="http://ssa.gov/People"
itemid="http://ssa.gov/SSN/123456789">
<spanitemprop="firstname">Joe</span>
<spanitemprop="lastname">Smith</span>
</div>
itemprop
Thisattributeisusedtoaddaname/valuepairtoamicrodataitem.Anychildofatagwith
anitemscopeattributecanhaveanitempropattributesetinordertoaddapropertyto
Chapter 3: HTML and XHTML Element Reference 145
thatitem.Thenameofthepropertyisthevaluesetfortheitempropattribute.Thevalue
dependsonwhattypeofelementtheattributeisaddedto.Iftheelementisanaudio,
embed,iframe,img,source,orvideotag,thenthevalueissettothesrcofthattag.
PART I
Iftheelementisana,area,orlinktag,thenthevalueissettothehrefofthattag.If
theelementisatimetag,thenthevalueissettothedatetimeattributeofthattag.Ifthe
elementisametatag,thenthevalueissettothecontentattributeofthattag.Otherwise,
thevalueissettothetextContentofthetag.Abriefexampleisshownhere.
<divitemscope>
<timeitemprop="gameday"datetime="2010-06-22">June22</time>:
The<spanitemprop="visitor">Giants</span>at
<spanitemprop="home">A's</span>.<br>
<metaitemprop="city"content="Oakland">
</div>
Iftheitemissettooneofthepredefinedtypes,thenthereisaspecificsetofvaluesthatis
allowedfortheitemprop.
itemref
Thisattributeissettoindicatewhatadditionalelementsshouldbetraversedtolookfor
name/valuepairsfortheitem.Bydefault,onlythechildrenaresearched.However,
sometimesitdoesnotmakesensetohaveasingleparentitemifthedataisintermingled.
Inthiscase,itemrefcanbesettoaspace-separatedlistofadditionalelementstotraverse:
<divitemscopeitemref="parentnameparentfood"></div>
<divitemscopeitemref="childnamechildfood"></div>
<spanid="parentname"><spanitemprop="name">Thomas</span></span>hasa
daughternamed<spanid="childname"><spanitemprop="name">Olivia</span>
</span>.
Thomas'favoritefoodis<spanid="parentfood"><spanitemprop="food">sushi
</span></span>andOlivia'sis<spanid="childfood"><span
itemprop="food">FrenchFries</span>!
itemscope
Thisattributeisusedtosetanelementasanitemofmicrodata(seeChapter2formore
informationonmicrodata).Anelementwithanitemscopeattributecreatesanewitemthat
containsagroupofname/valuepairsdefinedbyenclosedelementswithitemprop
attributes.Forexample,
<divitemscope>
<spanitemprop="firstname">Thomas</span>
<spanitemprop="lastname">Powell</span>
</div>
setsname/valuepairsoffirstname:Thomasandlastname:Powellfortheitem
declaredinthe<div>.
146 Part I: Core Markup
itemtype
Thisattributeisusedinconjunctionwiththeitemscopeattributeinordertodefineatype
forthemicrodataitem.Thisisanoptionalattribute,butifused,itmustbeplacedinthe
sameelementthatsetstheitemscopeattribute.ThevaluemustbeintheformofaURL:
<divitemscopeitemtype="http://scores.sports.com/baseball"></div>
<spanitemscopeitemtype="http://purl.org/vocab/frbr/core#Work"></span>
spellcheck
Thisattributeissettoeithertrueorfalseandindicateswhetherthecontentenclosedby
theelementshouldbespellingandgrammarchecked:
<pspellcheck="true">Howdoyouspellpotatoe?AmannamedDanmaynever
know.</p>
Ifithasnovalue,theassumedvalueistrueunlessitinheritsfalsefromanenclosing
parent.Theattributeismeaningfulonelementsthatareinteractivefortextentry,suchas
formfields,orelementsthathavecontenteditable=true.
tabindex
Thisattribute,likethetabindexattributeinitiallydefinedbyInternetExplorer,usesa
numbertoidentifytheobject’spositioninthetabbingorderforkeyboardnavigationusing
theTABkey.Theattributeshouldbesettoanumericvalue.Useragentswillgenerallymove
throughfieldswithtabindexsetinincreasingnumericorder,skippinganyelementswith0
oranegativevalue.Aftermovingoveralltabindexvalues,any0valuedfieldswillbe
navigatedinorder,butnegativevalueswillcontinuetobeskipped.Nonnumericvalueswill
generallyresultinthebrowserapplyingitsnormalfocusingalgorithm.
HTML5 Events
TheeventmodeldefinedbyHTML5isstillemerging,butthecommonevent-handling
attributesarefairlyclearandmatchmostoftheHTML4events,withsomeinterestingnew
Chapter 3: HTML and XHTML Element Reference 147
PART I
another element, typically either by clicking the mouse or tabbing.
onchange Signals that the form control has lost user focus and its value has been modified
during its last access.
onclick Indicates that the element has been clicked.
ondblclick Indicates that the element has been double-clicked.
onfocus Indicates that an element has received focus; namely, it has been selected for
manipulation or data entry.
onkeydown Indicates that a key is being pressed down with focus on the element.
onkeypress Describes the event of a key being pressed and released with focus on the
element.
onkeyup Indicates that a key is being released with focus on the element.
onload Indicates the event of a window or frame set finishing the loading of a document.
onmousedown Indicates the press of a mouse button with focus on the element.
onmousemove Indicates that the mouse has moved while over the element.
onmouseout Indicates that the mouse has moved away from an element.
onmouseover Indicates that the mouse has moved over an element.
onmouseup Indicates the release of a mouse button with focus on the element.
onreset Indicates that the form is being reset, possibly by the click of a reset button.
onselect Indicates the selection of text by the user, typically by highlighting the desired text.
onsubmit Indicates a form submission, generally by clicking a submit button.
onunload Indicates that the browser is leaving the current document and unloading it from
the window or frame.
additions.SomeofthenewerfeaturesarealreadyimplementinInternetExplorerorother
browsersbutmanyarenot.Table3-5summarizesalltheeventsyoumayseeonthevarious
previewedHTML5elementsinthischapter.AsallthingsconcerningHTML5,the
specification(www.w3.org/TR/html5)isthebestplacetogoforthelatestinformation.
PART I
selected for manipulation or data entry.
onformchange Fires when any element of the form changes.
onforminput Fires when input is made in a form element.
onhashchange Fires when the URL’s hash identifier value changes. Changing this value is
commonly performed in Ajax applications to indicate a state change and
support browser back-button activity.
oninput Fires when input is made to form elements.
oninvalid Fires when a form field is specified as invalid according to validation rules
set via HTML5 attributes such as pattern, min, and max.
onkeydown Indicates that a key is being pressed down with focus on the element.
onkeypress Describes the event of a key being pressed and released with focus on
the element.
onkeyup Indicates that a key is being released with focus on the element.
onload Indicates the event of a window or frame set finishing the loading of a
document.
onloadeddata Fires when the user agent can play back the media data at the current
play position for the first time.
onloadedmetadata Fires when the user agent has the media’s metadata describing the
media’s characteristics.
onloadstart Fires when the user agent begins to fetch media data, which may include
the initial metadata.
onmessage Fires when a message hits an element. HTML5 defines a message
passing system between client and server as well as between documents
that this handler can monitor.
onmousedown Indicates the press of a mouse button with focus on the element.
onmousemove Indicates that the mouse has moved while over the element.
onmouseout Indicates that the mouse has moved away from an element.
onmouseover Indicates that the mouse has moved over an element.
onmouseup Indicates the release of a mouse button with focus on the element.
onmousewheel Fires when the mouse wheel is used on the element or bubbles up from
some descendent element.
onoffline Fires when the user agent goes offline. Found only on the body element.
ononline Fires when the user agent goes back online. Found only on the body
element.
onpagehide Fires when a page is suspended though not necessarily fully unloaded.
PART I
onunload Indicates that the browser is leaving the current document and unloading
it from the window or frame. There may be another possible use for this
event when elements bind to remote data sources and unload.
onvolumechange Fires when the volume attribute or mute attribute value of a media
element like audio or video changes generally via script or the user’s
interaction with any shown controls.
onwaiting Fires when media element play stops but new data is expected shortly.
justbeforeoraftertheyhappen.Table3-6brieflysummarizesthebasicmeaningofthe
variousextendedeventattributesmostlyfoundinInternetExplorerbutcommonlypartially
implementedinotherbrowsers.
C AUTION Witheventsdocumentation,errorsmightexist.Theeventmodelchangesrapidly,and
thebrowservendorshavenotstoppedinnovatinginthisarea.Whiletheeventsweretestedfor
accuracy,butforthelatest,up-to-dateeventmodelforInternetExplorerinparticular,visitthe
MicrosoftDeveloperNetwork(MSDN),athttp://msdn.microsoft.com.
PART I
onfocusin Fires just before an object receives focus.
onfocusout Fires when an object is losing focus.
onhashchange Fires when the current document’s URL changes its hash value. Commonly
used for addressing state changes in Ajax applications. Also will be defined
under HTML5.
onhelp Triggered when the user presses the F1 key or a similar help button in the
user agent.
onlayoutcomplete Fires when the print or print preview process finishes.
onlosecapture Fires when the object loses mouse capture.
onmouseenter Fires when the user moves the mouse pointer into the object.
onmouseleave Fires when the user moves the mouse pointer away from the object.
onmousewheel Fires when the mouse scroll wheel is used.
onmove Triggered when the user moves a window.
onmoveend Fires when an object stops moving.
onmovestart Fires when an object starts moving.
onpaste Fires when selected content is pasted into a document.
onprogress Fires to indicate that some data is available for consumption. Generally
used in Ajax requests to access responses in progress.
onpropertychange Fires when a property changes on an object.
onreadystatechange Fires whenever the ready state for an object has changed. May move
through various states as network-fetched data is received.
onresize Triggered whenever an object is resized.
onresizeend Fires when the user finishes changing the dimensions of an object.
onresizestart Fires when the user begins to change the dimensions of an object.
onrowenter Indicates that a bound data row has changed and new data values are
available.
onrowexit Fires just prior to a bound datasource control changing the current row.
onrowsdelete Fires when dataset rows are about to be deleted.
onrowsinserted Fires when dataset rows are inserted.
onscroll Fires when a scrolling element is repositioned.
onselectionchange Fires when the selection state of a document changes.
onselectstart Fires when the user begins to select information by highlighting.
• Briefsummary Briefsummaryoftheelement’spurpose
• Standardsyntax HTML4.01,HTML5,orXHTML1.0syntaxfortheelement,
includingattributesandeventhandlersdefinedbytheW3Cspecification
• Attributesdefinedbybrowser Additionalsyntaxdefinedbydifferentbrowsers
• Standardevents Descriptionsofeventhandlerattributesfortheelement
• Eventsdefinedbybrowser Additionaleventattributesintroducedbyother
browsers,primarilybyInternetExplorer
• Examples Examplesusingtheelement
• Compatibility Theelement’sgeneralcompatibilitywithHTMLandXHTML
specificationsandbrowserversions
• Notes Additionalinformationabouttheelement
Allattributesthatarenotdefinedinaparticularlistingarecommonattributesthatcan
befoundintheprevioussections.
NOTE Listingsofattributesandeventsdefinedbybrowserversionsassumethattheseattributes
andeventsgenerallyremainassociatedwithlaterversionsofthatbrowser.Forexample,
attributesdefinedbyInternetExplorer4arevalidforInternetExplorer5andhigher,and
attributesdefinedforNetscape4remainvalidforNetscapebrowsersaswellasFirefox.Safari
informationfocusesonSafari2and3.TheGoogleChromebrowserisnotalwaysdirectlycalled
outinthisbook,but,givenitsrelianceontheWebKitengine,youshouldassumeSafarientries
willapplytothisbrowser.Compatibilitypre-Opera4isdeterminedviaresearchnottesting;in
casesofuncertainityweassumesupportfromOpera4.Ofcourse,reasonablythisismorefor
historicalaccuracyandwillsimplynotaffectmodernWebdevelopers.
Chapter 3: HTML and XHTML Element Reference 155
TIP Thesupportsitewww.htmlref.comhasthisreferenceonlineandmayhaveupdatesorfixesto
thisinformation.
PART I
<!-- ... --> (Comment)
Thisconstructenclosestextcommentsthatwillnotbedisplayedbythebrowser.Itmaybe
usedforinformationalmessagesfordevelopersaswellastomaskcontentfromuseragents
thatdonotsupportaparticulartechnology.Noattributesoreventsareassociatedwiththis
construct.
Standard Syntax
<!--...-->
Examples
<!--Thisisaninformationalcommentthatcanoccur
anywhereinanHTMLdocument.Thenextfewexamples
showhowstylesheetsandscriptsare"commentedout"toprevent
olderbrowsersfrommisinterpretingthecontent.
-->
<styletype="text/css">
<!--
h1{color:red;font-size:40px;}
-->
</style>
<scripttype="text/javascript">
<!--
document.write("helloworld");
//-->
</script>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• Commentsoftenareusedtoexcludecontentfromolderbrowsers,particularlythose
thatdonotunderstandclient-sidescriptingorstylesheets.
• Pagedevelopersshouldbecarefulwhencommentingmarkuptoensurethatother
commentsarenotincludedorthattwodashes(--)arenotembeddedinthecontent
commented.
Standard Syntax
Hidecontentifnotsupported:
<!--[ifexpression]>HTML<![endif]-->
Showcontentifnotsupported:
<![ifexpression]>HTML<![endif]>
Theexpressionlanguagesupportedbyconditionalcommentsisrelativelysimple,consisting
ofbrowsertypeandversionidentifier,less-thanandgreater-thanoperators,andbasic
Booleanoperators.ThesyntaxisbrieflyoverviewedinTable3-7.
Examples
<!--[ifIE5]>
<linkrel="stylesheet"href="ie5.css"type="text/css"media="screen">
<![endif]-->
<!--[ifltIE7]<p>YouareusinganoldIE!Pleaseupgrade.</p><![endif]-->
<!--[ifgteIE7]><p>Great,youareusingIE7orgreater.</p><![endif]-->
Item Description
IE The only currently available value to match is the string "IE", corresponding to Internet
Explorer.
number An integer or floating-point value corresponding to the version of the browser.
true The Boolean constant value of true.
false The Boolean constant value of false.
lt Less-than operator; returns true if the first argument is less than the second argument.
lte Less-than or equal operator; returns true if the first argument is less than or equal to the
second argument.
gt Greater-than operator; returns true if the first argument is greater than the second
argument.
gte Greater-than or equal operator; returns true if the first argument is greater than or equal
to the second argument.
() Subexpression operators; used to put in parentheses individual components of a more
complex expression that uses Boolean operators.
& The Boolean AND operator returns true if all subexpressions evaluate to true.
| The Boolean OR operator returns true if any of the subexpressions evaluates to true.
! Not operator reverses the Boolean meaning of any expression.
Compatibility
No standards support Internet Explorer 5+
PART I
Note
• ConditionalcommentsareoftenusedtolinkspecialInternetExplorer–specificstyle
sheetsortoincludescriptssolelyforthesebrowsers.
Standard Syntax
<!DOCTYPE"DTDIDENTIFIER">
Examples
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01TRANSITIONAL//EN">
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDXHTML1.0TRANSITIONAL//EN">
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www
.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.1//EN""xhtml11.dtd">
<!DOCTYPEhtml>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• The<!DOCTYPE>statementshouldbeusedasthefirstlineofalldocuments.
• Validationprogramsmightusethisconstructwhendeterminingthecorrectnessof
anHTMLdocument.
• WhileHTML5doesnotfollowtheSGML/XMLconceptofvalidation,the
<!DOCTYPE>isstillused.HTML5doeshoweverprovideforsyntaxchecking
currentlydubbedconformancechecking.Notethoughthatconformancechecking
doesnotrelyonXML/SGMLgrammar.
• Modernbrowsersmaydeterminewhatrenderingmodetousedependingonthe
<!DOCTYPE>statement.Thisisdubbedthedoctypeswitch.Anincorrect<!DOCTYPE>
thatdoesnotcorrespondtoappropriatemarkupusagemayresultininaccurate
display.
158 Part I: Core Markup
<a> (Anchor)
Thiselementdefinesahyperlink,thenamedtargetdestinationforahyperlink,orboth.
Standard Syntax
<a
accesskey="key"
charset="charactercodeforlanguageoflinked
resource"
class="classname(s)"
coords="comma-separatedlistofnumbers"
dir="ltr|rtl"
href="URL"
hreflang="languagecode"
id="uniquealphanumericidentifier"
lang="languagecode"
name="nameoftargetlocation"
rel="comma-separatedlistofrelationshipvalues"
rev="comma-separatedlistofrelationshipvalues"
shape="default|circle|poly|rect"
style="styleinformation"
tabindex="number"
target="frameorwindowname|_blank|_parent|_self|_top"
title="advisorytext"
type="contenttypeoflinkeddata">
</a>
hidefocus="true|false"(5.5)
language="javascript|jscript|vbs|vbscript"(4)
methods="http-method"(4)
unselectable="off|on"(5.5)
PART I
urn="URNstring"(4)
Element-Specific Attributes
charset Thisattributedefinesthecharacterencodingofthelinkedresource.Thevalueisa
space-and/orcomma-delimitedlistofcharactersetsasdefinedinRFC2045.
coords Forusewithobjectshapes,thisattributeusesacomma-separatedlistofnumbersto
definethecoordinatesoftheobjectonthepage.
href Thisisthesinglerequiredattributeforanchorsdefiningahypertextsourcelink.It
indicatesthelinktarget—eitheraURLoraURLfragment,whichisanameprecededbya
hashmark(#)specifyinganinternaltargetlocationwithinthecurrentdocument.URLsare
notrestrictedtoWeb-based(http)documents.URLsmightuseanyprotocolsupportedby
thebrowser.Forexample,file,ftp,andmailtoworkinmostuseragents.
hreflang Thisattributeisusedtoindicatethelanguageofthelinkedresourceandshould
besettowhicheverlanguageisspecifiedinthecorelangattribute.Browserswilllikelynot
annotatelinksappropriatelywithlanguageinformation,butstylesheetrulesusingattribute
selectorscouldbeusedtodothis.
160 Part I: Core Markup
media ThedraftHTML5specificationsuggeststhevalueshouldbeusedtoindicate
whetheradestinationisappropriateforscreen,print,PDA,andsoon.Thisisanadvisory
propertyanddoesnotrestrictaction.
methods Thevalueofthisattributeprovidesinformationaboutthefunctionsthatmightbe
performedonanobject.ThevaluesgenerallyaregivenbytheHTTPprotocolwhenitis
used;asforthetitleattribute,itmightbeusefultoincludeadvisoryinformationin
advanceinthelink.Forexample,thebrowsermightchooseadifferentrenderingofalinkas
afunctionofthemethodsspecified;somethingthatissearchablemightgetadifferenticon,
oranoutsidelinkmightrenderwithanindicationofleavingthecurrentsite.Thisattribute
isneitherwellunderstoodnorsupported,evenbythedefiningbrowser,InternetExplorer.
name Thisattributeisrequiredinananchordefiningatargetlocationwithinapage.Avalue
fornameissimilartoavaluefortheidcoreattribute,anditshouldbeanalphanumeric
identifieruniquetothedocument.UndertheHTMLandXHTMLspecifications,idandname
bothcanbeusedwithan<a>tagaslongastheyhaveidenticalvalues.HTML5directlystates
pageauthorsshouldnotusenameeventhoughitmaybesupportedinbrowsersandid
valuesshouldbeusedinstead.
ping ThisHTML5–specificattributeisusedtospecifytheURL(s)thatwillbenotified
whenalinkisactivated.IfmorethanasingleURLisspecified,theaddressesshouldbe
separatedbyspaces.DespitesomeearlyFirefoxdablingswiththisattributebylate2009,no
browserimplementsthisfeature,andprivacyconcernsaboutthisattributemaykeepit
fromeverbeingwidelyadopted.
rel Foranchorscontainingthehrefattribute,thisattributespecifiestherelationshipofthe
targetobjecttothelinkobject.Thevalueisacomma-separatedlistofrelationshipvalues.
Thevaluesandtheirsemanticswillberegisteredbysomeauthoritythatmighthave
meaningtothedocumentauthor.Thedefaultrelationship,ifnootherisgiven,isvoid.The
relattributeshouldbeusedonlywhenthehrefattributeispresent.Table3-8listspossible
relvaluesdefinedinHTML5for<a>tags.
rev Thisattributespecifiesareverselink,theinverserelationshipoftherelattribute.Itis
usefulforindicatingwhereanobjectcamefrom,suchastheauthorofadocument.
shape Thisattributeisusedtodefineaselectableregionforhypertextsourcelinks
associatedwithafigureinordertocreateanimagemap.Thevaluesfortheattributeare
circle,default,polygon,andrect.Theformatofthecoordsattributedependsonthe
valueofshape.Forcircle,thevalueisx,y,r,wherexandyarethepixelcoordinatesfor
thecenterofthecircleandristheradiusvalueinpixels.Forrect,thecoordsattribute
shouldbex,y,w,h.Thex,yvaluesdefinetheupper-leftcorneroftherectangle,whilewandh
definethewidthandheight,respectively.Avalueofpolygonforshaperequires
x1,y1,x2,y2,…valuesforcoords.Eachofthex,ypairsdefinesapointinthepolygon,with
successivepointsbeingjoinedbystraightlinesandthelastpointjoinedtothefirst.Thevalue
ofdefaultforshaperequiresthattheentireenclosedarea,typicallyanimage,beused.
NOTE Itisadvisabletousetheusemapattributefortheimgelementandtheassociatedmap
elementtodefinehotspotsinsteadoftheshapeattribute.
Chapter 3: HTML and XHTML Element Reference 161
Relationship
Value Explanation Example Notes
PART I
alternate The link references an <ahref="frenchintro.html"
alternate version of the rel="alternate"
document that the link lang="fr">
is in. For example, this VersionFrancais</a>
might be a translated
version of the document,
as suggested by the
lang attribute.
archives The link provides <ahref="/history.php"
a reference to rel="archives">
document(s) of DocumentHistory</a>
historical interest.
author The link provides a <ahref="/tap.html"
reference to information rel="author">
about the document’s ThomasPowell</a>
author.
bookmark The link references a <ahref="index.html"
document that serves as rel="bookmark"
a bookmark; the title title="permalink">
attribute can be used to SectionPermalink</a>
name the bookmark.
external The link indicates the <ahref="http://ajaxref Likely such links
referenced document .com/" need visual
is not local to the rel="externalauthor"> indication as well
current document, AjaxBook(offsite)</a> to indicate they
organizationally or are off site.
server-wise.
first The link is a reference to <ahref="page1.html"
the first document in a rel="first">Start</a>
collection.
help The link references a <ahref="help.html"
help document for the rel="help">Help</a>
current document or
site.
index The link references a <linkhref="docindex.html"
page that provides an rel="index"/>
index for the current
document.
Relationship
Value Explanation Example Notes
last The link is a reference to <ahref="page10.html"
the last document in a rel="last">Last</a>
collection.
license The link is a reference <ahref="/legal.html"
to the legal or copyright rel="license">
information for the LegalTerms</a>
current document’s
content. Similar to the
copyright value.
next The link references the <ahref="page2.html"
next document to visit rel="next">NextPage</a>
in a linear collection
of documents. It can
be used, for example,
to “prefetch” the next
page, and is supported
in some browsers such
as MSN TV and Mozilla-
based browsers.
nofollow This value provides an <ahref="legal.html"
indication that the link rel="nofollowlicense">
should not be followed LegalInfo</a>
by automatically
traversing user agents
such as search bots.
noreferrer This value indicates the <ahref="https://bank.com" Would require
browser should not send rel="noreferrer"> browser support.
the Referrer header Banking</a>
when following this link.
prev The link references the <ahref="page1.html"
previous document in rel="previous">
a linear collection of Previous</a>
documents.
search This value indicates that <ahref="search/"
the link references a rel="search">Search
search facility used in Site</a>
a site.
Relationship
Value Explanation Example Notes
PART I
sidebar This value specifies <ahref="instructions Assumes that
a URL that should be .html" browsers support
displayed in a browser rel="sidebar"> this interface
sidebar. LoadInstructions style.
(Sidebar)</a>
tag This value specfies a <ahref="html5.html" Specification
tag that applies to the rel="tag">HTML5</a> unclear on usage.
document. Current read
suggests tag
word used within
“tagcloud.”
up This value provides <ahref="/main/index.html"
a link to a document rel="up">IndexPage</a>
or section “up” from
the current document,
usually the parent or
index document for the
current URL.
target Thisattributespecifiesthetargetwindowforahypertextsourcelinkthatreferences
frames.Theinformationlinkedtotargetwillbedisplayedinthenamedwindow.Frames
andwindowsmustbenamedtobetargetediftheydonotcorrespondtoaspecialname
value,whichinclude_blank,whichindicatesanewwindow;_parent,whichindicatesthe
parentframesetcontainingthesourcelink;_self,whichindicatestheframecontainingthe
sourcelink;and_top,whichindicatesthefullbrowserwindow.
type ThisattributespecifiesthemediatypeintheformofaMIMEtypeforthelinktarget.
Generally,thisisprovidedstrictlyasadvisoryinformation;however,inthefutureabrowser
mightaddasmalliconformultimediatypes.Forexample,abrowsermightaddasmall
speakericonwhentypeissettoaudio/wav.ForacompletelistofrecognizedMIMEtypes,
seewww.w3.org/TR/html4/references.html#ref-MIMETYPES.
urn ThissupposedlyInternetExplorer–supportedattributehassomeoriginsinHTML3.2
anditrelatesauniformresourcename(URN)withthelink.Whileitisbasedonstandards
workgoingyearsback,themeaningofURNsisstillnotwelldefinednorhasitbeen
demonstratedthatthisattributedoesanythingdespiteitsoccurrenceinMSDN
documentation.
164 Part I: Core Markup
Examples
<!--anchorlinkingtoexternalfile-->
<ahref="http://www.democompany.com/">ExternalLink</a>
<!--anchorlinkingtofileonlocalfilesystem-->
<ahref="file:/c:\html\index.html">localfilelink</a>
<!--anchorinvokinganonymousFTP-->
<ahref="ftp://ftp.democompany.com/freestuff">AnonymousFTP
link</a>
<!--anchorinvokingFTPwithpassword-->
<ahref="ftp://joeuser:secretpassword@democompany.com/path/file">
FTPwithpassword</a>
<!--anchorinvokingmail-->
<ahref="mailto:fakeid@democompany.com">Sendmail</a>
<!--anchorusedtodefinetargetdestinationwithindocument-->
<aname="jump">Jumptarget</a>
<!--anchorlinkinginternallytoprevioustargetanchor-->
<ahref="#jump">Localjumpwithindocument</a>
<!--anchorlinkingexternallytoprevioustargetanchor-->
<ahref="http://www.democompany.com/document#jump">
Remotejumptoapositionwithinadocument</a>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• Ifyouusetheaccesskeyattributewiththiselementpage,bewaryofreserved
bindings.Seethesection“accesskey”under“OtherCommonAttributesReference”
earlierinthechapterforafulldiscussionofthisconcern.
• Thetargetattributeisnotdefinedinbrowsersthatdonotsupportframes,suchas
Netscape1–generationbrowsers.Furthermore,targetisnotallowedunderstrict
variantsofXHTMLbutinsteadislimitedtoframesetortransitionalform.This
attribute,however,doesregainitsfunctionalityunderHTML5.
• SeeAppendixDforacompletediscussionoftheURLsyntax,whichisusedasthe
valueofthesrcattribute.
<abbr> (Abbreviation)
Thiselementallowsauthorstoclearlyindicateasequenceofcharactersthatdefinesan
abbreviationforaword(suchasMr.insteadofMister,orCalifinsteadofCalifornia).
Chapter 3: HTML and XHTML Element Reference 165
Standard Syntax
<abbr
class="classname(s)"
PART I
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</abbr>
Examples
<p><abbrtitle="California">Calif</abbr></p>
<p>Isn't<abbr>WWW</abbr>anacronym?Ohwhattrouble!</p>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 7+,
XHTML 1.0, 1.1, Basic Netscape 6+, Opera 6+, Safari 1+
Notes
• Thistagiscommonlyconfusedwith<acronym>.Debateaboutjustwhatconstitutes
anacronymascomparedwithanabbreviationiscommonamongverydetail-oriented
Webstandardsexperts.WhileWebdevelopersappeartousean<acronym>tagmore
oftenthanan<abbr>tag,theformerisdeprecatedunderHTML5!Theconfusion
continues.
• Whenthetitleattributeissetonthiselement,browsersmayrenderadotted
underline,whichisusefultoindicatethepresenceofatooltipthatmightcontainthe
expansionfortheabbreviation.
• AccordingtotheHTML5specification,thetitleattributeshouldbesettothe
expansionoftheabbreviation.
• ThedisabledattributeisnotcurrentlydocumentedforthiselementatMSDN,
thoughitcontinuestoworkinInternetExplorerbrowsers.
• TheMSDNdocumentationforthiselementmayhaveerrorsregardingtheextentof
itseventsupport,becausemanyeventsthatarenotlistedassupportedactually
workedwhentested.
• Becausethereistypicallynomarkup-orientedpresentationforthiselement,itis
primarilyusedinconjunctionwithstylesheetsandscripts.
<acronym> (Acronym)
Thiselementallowsauthorstoclearlyindicateasequenceofcharactersthatcomposesan
acronym(XML,WWW,andsoon).
Chapter 3: HTML and XHTML Element Reference 167
Standard Syntax
<acronym
class="classname(s)"
PART I
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</acronym>
Examples
<p><acronymtitle="ExtensibleMarkupLanguage">XML</acronym>
<acronymlang="fr"title="SociétéNationaledeCheminsde
Fer">SNCF</acronym></p>
Compatibility
HTML 4, 4.01 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1, Basic Netscape 6+, Opera 6+, Safari 1+
Notes
• Thistagisoftenconfusedwith<abbr>andisnotincludedinHTML5asoflate2009.
• Aswithan<abbr>tag,mostbrowserswillrenderadottedunderlinewhenthetitle
attributeispresent.
• ErrorsmayoccurintheMSDNdocumentationforthiselement;forexample,
disabledcontinuestobesupportedandmanyeventsnotdocumentedwillwork.
168 Part I: Core Markup
<address> (Address)
Thisblockelementmarksuptextindicatingauthorshiporownershipofinformation.It
generallyoccursatthebeginningorendofaWebdocumentandusuallyisrenderedin
italicsintheabsenceofCSS.
Standard Syntax
<address
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</address>
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
PART I
onsuspend,ontimeupdate,onvolumechange,onwaiting
Example
<address>PINT,Inc.<br>
2105GarnetAve.<br>
SanDiego,CA92109<br>
U.S.A.</address>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• UnderHTML2.0and3.2,therearenoattributesfor<address>.
• An<address>tagmaynotcontainanother<address>tag.
style="styleinformation"
title="advisorytext"
vspace="pixels"
width="pixels">
</applet>
Element-Specific Attributes
alt Thisattributecausesadescriptivetextalternativetobedisplayedinbrowsersthatdo
notsupportJava.Webdesignersshouldalsorememberthatcontentenclosedwithinan
<applet>tagmayalsoberenderedasalternativetext.
archive ThisattributereferstotheURLofanarchivedorcompressedversionoftheapplet
anditsassociatedclassfiles,whichmighthelpreducedownloadtime.
code ThisattributespecifiestheURLoftheapplet’sclassfiletobeloadedandexecuted.
Appletfilenamesareidentifiedbya.classfilenameextension.TheURLspecifiedbycode
mightberelativetothecodebaseattribute.
codebase ThisattributegivestheabsoluteorrelativeURLofthedirectorywhereapplets’
.classfilesreferencedbythecodeattributearestored.
mayscript IntheNetscapeimplementation,thisattributeallowsaccesstoanappletbya
scriptinglanguage.
Chapter 3: HTML and XHTML Element Reference 171
name Thisattributeassignsanametotheappletsothatitcanbeidentifiedbyother
resources,particularlyscripts.
PART I
object ThisattributespecifiestheURLofaserializedrepresentationofanapplet.
src AsdefinedforInternetExplorer4andhigher,thisattributespecifiesaURLforan
associatedfilefortheapplet.ItsmeaninganduseareunclearanditisnotpartoftheHTML
standard.
Example
<appletcode="atarigame.class"align="left"archive="game.zip"
height="250"width="350">
<paramname="difficulty"value="easy">
<strong>Sorry,youneedJavatoplaythisgame.</strong>
</applet>
Compatibility
HTML 2, 3.2, 4, 4.01 (transitional) Firefox 1+, Internet Explorer 4+,
XHTML 1.0 (transitional) Netscape 2+, Opera 4+, Safari 1+
Notes
• TheW3Cspecificationdoesnotencouragetheuseof<applet>andpreferstheuse
ofthe<object>tag.UnderthestrictdefinitionofHTML4.01,thiselementis
deprecatedanditiscitedasobsoleteunderHTML5,thoughcurrentlyitstillappears
inmanyversionsofthespecification.Despitethestrongdesireofstandardbodiesto
removethisfromcommonuse,itisstilloftenused.
• TheHTML4specificationdoesnotshowevent-handlingattributesforthiselement,
thoughyoumayfindthattheywork.However,giventhatanappletmayincludean
interactiveobject,thesenseofcapturingeventswithitascomparedtowithinthe
appletcanbeabitconfusing.
Standard Syntax
<area
accesskey="character"
alt="alternativetext"
class="classname(s)"
coords="comma-separatedlistofvalues"
dir="ltr|rtl"
href="URL"
id="uniquealphanumericidentifier"
lang="languagecode"
nohref="nohref"
shape="circle|default|poly|rect"
172 Part I: Core Markup
style="styleinformation"
tabindex="number"
target="frameorwindowname|_blank|_parent|_self|
_top"(transitionalorframesetonly)
title="advisorytext">
onhelp,onkeydown,onkeypress,onkeyup,onlosecapture,onmouseenter,
onmousedown,onmouseleave,onmousemove,onmouseout,onmouseover,onmouseup,
onmousewheel,onmove,onmoveend,onmovestart,onpaste,onpropertychange,
onreadystatechange,onresizeend,onresizestart,onselectstart,ontimeerror
PART I
Element-Specific Attributes
alt Thisattributecontainsatextstringalternativetodisplayinbrowsersthatcannot
displayimages.
coords Thisattributecontainsasetofvaluesspecifyingthecoordinatesofthehotspot
region.Thenumberandmeaningofthevaluesdependuponthevaluespecifiedforthe
shapeattribute.Forarectorrectangleshape,thecoordsvalueistwox,ypairs:left,
top,right,andbottom.Foracircorcircleshape,thecoordsvalueisx,y,r,wherex,y
isapairspecifyingthecenterofthecircleandrisavaluefortheradius.Forapolyor
polygonshape,thecoordsvalueisasetofx,ypairsforeachpointinthepolygon:
x1,y1,x2,y2,x3,y3,andsoon.
href Thisattributespecifiesthehyperlinktargetforthearea.ItsvalueisavalidURL.
Eitherthisattributeorthenohrefattributemustbepresentintheelement.
hreflang Thisattribute,introducedbyHTML5,isusedtoindicatethelanguageofthe
linkedresourceinanimagemapandshouldbesettowhicheverlanguageisspecifiedin
thecorelangattribute.Browserswilllikelynotannotatelinksappropriatelywithlanguage
information,butstylesheetrulesusingattributeselectorscouldbeusedtodothis.The
absenceofthisattributeinpreviousHTMLversionsisaclearoversight.
media ThisHTML5attributespecifiesthemediaformatthelinkdestinationwasdefined
for.Itisadvisoryinformation,andthevalueshouldbeusedtosuggestifadestinationis
appropriateforscreen,print,PDA,andsoon.
name Thisattributeisusedtodefineanamefortheclickableareasothatitcanbescripted
byolderbrowsers.
nohref Thisattributeindicatesthatnohyperlinkexistsfortheassociatedarea.Eitherthis
attributeorthehrefattributemustbepresentintheelement.UnderXHTML,thisattribute
willhaveavalueof"nohref";understandardHTML,novalueisrequired.
ping ThisHTML5–specificattributeisusedtospecifytheURL(s)thatwillbenotified
whenalinkisactivated.IfmorethanasingleURLisspecified,theaddressesshouldbe
separatedbyspaces.Circaearly2009,nobrowserimplementsthisfeature,andprivacy
concernsaboutthisattributemaykeepitfromeverbeingwidelyadopted.
rel HTML5introducesthisattributetospecifylinkrelationshipsonimagemaps.Thelack
ofthisattributeinpreviousspecificationswasclearlyanoversight.Forimagemapareas
containingthehrefattribute,thisattributespecifiestherelationshipofthetargetobjecttothe
linkobject.Thevalueisacomma-separatedlistofrelationshipvalues.Thevaluesandtheir
semanticswillberegisteredbysomeauthoritythatmighthavemeaningtothedocument
author.Thedefaultrelationship,ifnootherisgiven,isvoid.Therelattributeshouldbeused
onlywhenthehrefattributeispresentbecauseitmakesnosensewithnohref.
174 Part I: Core Markup
NOTE HTML5definesanumberofrelvaluesfor<area>.Seetheearlier“<a>(Anchor)”section
foralistofthevaluesusedwiththerelattribute.
shape Thisattributedefinestheshapeoftheassociatedhotspot.HTML4definesthe
valuesrect,whichdefinesarectangularregion;circle,whichdefinesacircularregion;
poly,whichdefinesapolygon;anddefault,whichindicatestheentireregionbeyondany
definedshapes.Manybrowsers,notablyInternetExplorer4andhigher,supportalternate
valuesforshapes,includingcirc,polygon,andrectangle.
target Thisattributespecifiesthetargetwindowforhyperlink-referencingframes.The
valueisaframenameoroneofseveralspecialnames.Avalueof_blankindicatesanew
window.Avalueof_parentindicatestheparentframesetcontainingthesourcelink.
Avalueof_selfindicatestheframecontainingthesourcelink.Avalueof_topindicates
thefullbrowserwindow.
type ThisattributespecifiesthemediatypeintheformofaMIMEtypeforthelinktarget.
Generally,thisisprovidedstrictlyasadvisoryinformation;however,inthefutureabrowser
mightaddasmalliconformultimediatypes.Forexample,abrowsermightaddasmall
speakericonwhentypeissettoaudio/wav.ForacompletelistofrecognizedMIMEtypes,
seewww.w3.org/TR/html4/references.html#ref-MIMETYPES.Theattributeiscommonly
understoodfortheaelementbutwasintroducedbyHTML5toimagemaps.
Examples
<mapid="primary"name="primary">
<areashape="circle"coords="200,250,25"href="another.html">
<areashape="default"nohref>
</map>
<!--XHTMLsyntax-->
<mapid="secondary"name="secondary">
<areashape="rect"coords="10,10,100,100"href="another.html"/>
<areashape="default"nohref="nohref"/>
</map>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1 Netscape 1+, Opera 4+, Safari 1+
Notes
• AsanemptyelementunderXHTMLorwhenusingXML-stylesyntaxforHTML5,
atrailingslashisrequiredforthiselement:<area/>.
• HTML5doesnotdefinerevattributefor<area>tags.
• Netscape1–levelbrowsersdonotunderstandthetargetattributeasitrelatesto
frames.
• HTML3.2definesonlyalt,coords,href,nohref,andshape.
Chapter 3: HTML and XHTML Element Reference 175
<article> (Article)
ThisHTML5blockelementdefinesasubsetofadocument’scontentthatformsan
independentpartofthedocument,suchasablogpost,article,orotherself-contained
PART I
unitofinformation,thatmaybelinkedtoorincludedinsomeothercontentbody.
Example
<p>Thereareotherthingsinthispage.</p>
<articleid="article1">
<header>
<h1>HTML5isComingSoon!</h1>
<p><timepubdatedatetime="2009-10-31T12:30-11:00"></time></p>
</header>
176 Part I: Core Markup
<p>ThenewHTML5specificationisintheworks.Whilemanyfeaturesare
notcurrentlyimplementedorevenwelldefinedyet,progressisbeingmade.
StaytunedtoseemorenewHTMLelementsaddedtoyourWebdocumentsinthe
yearstocome.</p>
</article>
<p>Thereareotherthingsinthispage.</p>
Compatibility
HTML5 Not currently supported by any browser, but can be addressed with a custom element.
Notes
• Earlyversionsofthistagsupportedpubdateandciteattributesbutthesewere
removedlaterinfavorofnested<time>tags.
• Itispossibletonest<article>tagsandtherelationshipshouldlogicallyrelateto
theparent<article>subjectmatter.
• Thiselementisnotdirectlyimplementedinanybrowser.However,giventhatmost
browserscanhandlecustomelements,itiseasyenoughtosimulatetheideaofit
andevenapplyaCSSdisplaypropertyforit.
<aside> (Aside)
ThisHTML5elementdefinesasectionofadocumentthatenclosescontentthatis
tangentiallyrelatedtotheothercontenttheelementmaybeassociatedwith.Asimple
exampleofthiselementinactionmightbetospecifysidebarcontent.
PART I
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Example
<p>ThisisthemainpointIamtryingtomake.</p>
<aside>ThisisanasideIdon'treallyknowhowimportantitistomake,
butIlovetomakeasides.</aside>
<p>OknowbacktothepointIwasmaking.</p>
Compatibility
HTML5 Not currently supported by any browser, but can be addressed with a custom element.
Notes
• Thiselementisnotyetdirectlyimplementedinanybrowser.However,giventhat
mostbrowserscanhandlecustomelements,itiseasyenoughtosimulatetheideaof
itandevenapplyaCSSdisplaypropertyforit.
• ThiselementwillaffectHTML5’soutliningalgorithm;seeChapter2foranexample
ofthisscheme.
<audio> (Audio)
ThisHTML5elementincludesaudioinadocument.
itemtype="microdatatypeinURLformat"
lang="languagecode"
loop="loop"
spellcheck="true|false"
src="URLofaudio"
style="styleinformation"
tabindex="number"
title="advisorytext">
</audio>
Element-Specific Attributes
autobuffer ThisBooleanattributeindicateswhetherornotthebrowsershouldbegin
bufferingaudiorightaway.Itisoftensetwhenitisbelievedthattheaudiowillbeplayed.
Thisisvaluablewhenautoplayisnotset,buttheattributehasnomeaningifautoplayis
setsincethebrowserwillplaytheaudioassoonasitcan.
autoplay ThisBooleanattributeindicatesthebrowsershouldbeginplayingtheaudioas
soonafterpageloadonceithasloadedenoughoftheaudiotoavoidpausing.
controls ThisBooleanattributeissettoindicatewhetherornotthebrowsershouldpresent
thecontrolsforaudio,suchasplayback,pause,volume,andseek.Ifnotpresent,nocontrols
willbeshownanditwillbeuptothedevelopertoscriptthecontrolofthemediaplayback.
Whennocontrolsarepresent,theaudioelementwillnotbevisuallypresented.
loop ThisBooleanattribute,ifpresent,indicatesthattheaudioshouldloop.
src ThisattributeissettotheURLoftheaudiotoshow.
Examples
<audiosrc="music.ogg"autoplay>
<p>NosupportforHTML5<code>audio</code>element.</p>
</audio>
<audiosrc="music.ogg"loopcontrols>
<p>NosupportforHTML5<code>audio</code>element.</p>
</audio>
Chapter 3: HTML and XHTML Element Reference 179
<audioid="audio3">
<sourcesrc="music.ogg"type="audio/ogg">
<sourcesrc="music.mp3">
<p>NosupportforHTML5<code>audio</code>element.</p>
PART I
</audio>
<!--TricktomakesoundinIEbrowsers-->
<audiosrc="music.wav">
<bgsoundsrc="music.wav">
</audio>
Compatibility
HTML5 Firefox 3.5+, Safari 3.1+
Notes
• Alternatecontentshouldbeplacedinsideoftheaudioelementforbrowsersthatdo
notsupportit.
• HavingthecorrectMIMEtypesonhostedmediafilesiskeyforplayback.You
shouldalsomakesurethemediatypesusedworkinthebrowserstargeted,because
currentlythisvariesevenwhentheaudioelementissupported.
• Flashwilloftenbeusedtoavoidcross-browseraudioconcerns.Untilthiselementis
widelysupported,developersareadvisedtocontinuetouseFlashortorelyon
elementslikebgsound.
<b> (Bold)
Thisinlineelementindicatesthattheenclosedtextshouldbedisplayedinboldface.
Standard Syntax
<b
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</b>
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
Example
<p>Thistextis<b>bold</b>forsomereason.</p>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1 Netscape 1+, Opera 2.1+, Safari 1+
Chapter 3: HTML and XHTML Element Reference 181
Notes
• HTML2and3.2donotdefineanyattributesforthiselement.
• Modernmarkupspecificationsencouragedeveloperstousea<strong>tag
PART I
insteadof<b>.
Standard Syntax
<base
href="URL"
target="frameorwindowname|_blank|_parent|_self|
_top"(transitionalonly)>
Element-Specific Attributes
href ThisattributespecifiesthebaseURLtobeusedthroughoutthedocumentforrelative
URLaddresses.
target Fordocumentscontainingframes,thisattributespecifiesthedefaulttargetwindow
foreverylinkthatdoesnothaveanexplicittargetreference.Asidefromnamedframesor
windows,severalspecialvaluesexist.Avalueof_blankindicatesanewwindow.Avalue
of_parentindicatestheparentframesetcontainingthesourcelink.Avalueof_self
indicatestheframecontainingthesourcelink.Avalueof_topindicatesthefullbrowser
window.
Examples
<!--standardHTMLsyntax--->
<basehref="http://www.htmlref.com/">
<--XHTMLsyntax-->
<basehref="http://www.htmlref.com/"/>
<!--withframes-->
<basetarget="_blank"href="http://www.htmlref.com/">
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• Thiselementshouldonlyoccurwithintheheadelement.
• HTML2.0and3.2defineonlythehrefattribute.
• UnderXHTMLvariantsandHTML5usingXML-syntax,thisemptyelementrequires
atrailingslash:<base/>.
• HTML5’scurrentdraftspecificationspecifiesallcommonattributesandevents,but
franklymanyofthesemakelittlesenseforthiselement.HTML4didnotdefine
themforgoodreason,soitislikelythismaybemodifiedbacktoasyntaxcloserto
thatoftheHTML4specification.
PART I
Events Defined by Internet Explorer
onlayoutcomplete,onmouseenter,onmouseleave,onreadystatechange
Element-Specific Attributes
color Thisattributesetsthetextcolorusingeitheranamedcolororacolorspecifiedinthe
hexadecimal#RRGGBBformat.
face Thisattributecontainsalistofoneormorefontnames.Thedocumenttextinthe
defaultstyleisrenderedinthefirstfontfacethattheclient’sbrowsersupports.Ifnofont
listedisinstalledonthelocalsystem,thebrowsertypicallydefaultstotheproportionalor
fixed-widthfontforthatsystem.
size Thisattributespecifiesthefontsizeaseitheranumericorrelativevalue.Numeric
valuesrangefrom1to7,with1beingthesmallestand3thedefault.Relativevaluesstart
with+or–,followedbyadigit,andmodifythecurrentsizeappropriately.Resultingvalues
above7become7andbelow1become1.
Example
<!--StandardHTMLsyntax-->
<basefontcolor="#ff0000"face="Helvetica"size="+2">
<!--XHTMLstylesyntax-->
<basefontcolor="#ff0000"face="Helvetica"size="+2"/>
Compatibility
HTML 2, 3.2, 4, 4.01 (transitional) Firefox 1+, Internet Explorer 2+,
XHTML 1.0 (transitional) Netscape 1+, Opera 4+, Safari 1+
Notes
• HTML3.2supportsthebasefontelementbutonlywiththesizeattribute.
• The(X)HTMLstrictandHTML5specificationsdonotsupportthiselement.
• ThiselementcanbeimitatedwithaCSSruleonthebodyelement.
• TransitionalXHTML1.0requiresatrailingslashforthisemptyelement:
<basefont/>.
Standard Syntax
<bdo
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</bdo>
PART I
onblur,oncellchange,oncontextmenu,oncontrolselect,onclick,oncopy,
oncut,ondblclick,ondeactivate,ondrag,ondragend,ondragenter,
ondragleave,ondragover,ondragstart,ondrop,onerrorupdate,onfilterchange,
onfocus,onfocusin,onfocusout,onhelp,onkeydown,onkeypress,onkeyup,
onlosecapture,onmousedown,onmouseenter,onmouseleave,onmousemove,
onmouseout,onmouseover,onmouseup,onmousewheel,onmove,onmoveend,
onmovestart,onpaste,onpropertychange,onreadystatechange,onresizeend,
onresizestart,onscroll,onselectstart
Example
<!--Switchtextdirection-->
<p>Someothertexthere<bdodir="rtl">Thistextwillgorighttoleftin
abrowserthatsupportsthiselement</bdo>somemoretexthere.</p>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 5+,
XHTML 1.0, 1.1 Netscape 6+, Opera 7+, Safari 2+
Note
• TheHTML4specificationdidnotspecifyeventsforthiselement;theywereadded
later,sothislikelywassimplyanoversight.
Element-Specific Attributes
balance Thisattributedefinesanumberbetween–10,000and+10,000thatdetermineshow
thevolumewillbedividedbetweenthespeakers.
loop Thisattributeindicatesthenumberoftimesasoundistobeplayedandhaseithera
positivenumericvalueor–1tospecifythatitwillcontinuouslyloop.Thekeyword
infiniteisalsosupportedinmanyInternetExplorerimplementations.
186 Part I: Core Markup
src ThisattributespecifiestheURLofthesoundfiletobeplayed,whichmustbeoneof
thefollowingtypes:.wav,.au,or.mid.
volume Thisattributedefinesanumberbetween–10,000and0thatdeterminesthe
loudnessofapage’sbackgroundsound.Oddly,0isfullvolumeand–10,000isnone.
Examples
<!--assumeexamplesareindifferentpages-->
<bgsoundsrc="sound1.mid">
<bgsoundsrc="sound2.au"loop="infinite">
<bgsoundsrc="sound3.wav"loop="3"volume="-2000">
Compatibility
No standards support Internet Explorer 2+, Opera 4+
Notes
• SimilarfunctionalitycanbeachievedinolderversionsofNetscapeusingthe
<embed>tagtoinvokeanaudioplayeraswellasusingHTML5’s<audio>tagin
supportingbrowsers.
• Youcouldwritebgsoundwithaself-closingtag<bgsound/>.However,sincethis
elementisnotpartofastandard,makingitXHTML-likewillnotmakeitvalidate.
Standard Syntax
<big
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</big>
PART I
Events Defined by Internet Explorer
onactivate,onbeforeactivate,onbeforecopy,onbeforecut,onbeforedeactivate,
onbeforeeditfocus,onbeforepaste,onblur,onclick,oncontextmenu,
oncontrolselect,oncopy,oncut,ondblclick,ondeactivate,ondrag,
ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,
onfocus,onfocusin,onfocusout,onhelp,onkeydown,onkeypress,onkeyup,
onlosecapture,onmousedown,onmouseenter,onmouseleave,onmousemove,
onmouseout,onmouseover,onmouseup,onmousewheel,onmove,onmoveend,
onmovestart,onpaste,onpropertychange,onreadystatechange,onresize,
onresizeend,onresizestart,onselectstart,ontimeerror
Example
<p>Thistextisregularsize.<big>Thistextislarger.</big>Nowbackto
regularsize.</p>
Compatibility
HTML 3, 3.2, 4, 4.01 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1.1+, Opera 2.1+, Safari 1+
Notes
• ThiselementwasoriginallyintroducedinHTML3andmovedtoHTML3.2.
• TheeffectofthiselementiseasilymimickedusingtheCSSrulefont-size:
largerorunderolderbrowsersusing<fontsize="+1">.
• AlthoughHTML5marksthiselementasobsolete,interestingly,itcurrentlydoesn’t
markthesmallelementassuchbutratherrecastsitsmeaninginstead.Withthe
strict(X)HTMLvariantssupportingthiselement,thiselement’sstatusmaychange.
Example
<blink>Annoying,isn'tit?</blink>
188 Part I: Core Markup
Compatibility
No standards support Firefox 1+, Netscape 1+, Opera 7+
Notes
• Theattributesclass,id,andstylewereaddedduringtheNetscape4release;
langwasaddedfromNetscape6.
• Browserswillgenerallysupporttheinclusionoftheelementandallowcore
attributesforapplyingstyleandscriptingthiselementregardlessofthelackof
blinkingtext.
Standard Syntax
<blockquote
cite="URLofsourceinformation"
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</blockquote>
PART I
HTML5 Event Attributes
onabort,onblur,oncanplay,oncanplaythrough,onchange,onclick,
oncontextmenu,ondblclick,ondrag,ondragend,ondragenter,ondragleave,
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Element-Specific Attributes
cite ThevalueofthisattributeshouldbeaURLforthedocumentinwhichtheinformation
citedcanbefound.
Example
<blockquotecite="http://www.loc.gov/rr/program/bib/ourdocs/DeclarInd.html">
Weholdthesetruthstobeself-evident,thatallmenarecreatedequal,
thattheyareendowedbytheirCreatorwithcertainunalienablerights,
thatamongthesearelife,libertyandthepursuitofhappiness.
</blockquote>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Notes
• HTML2.0and3.2donotsupportanyattributesforthiselement.
• SomearchaicbrowserslikeWebTVunderstandthe<bq>shorthandnotation.
190 Part I: Core Markup
Standard Syntax
<body
alink="colorname|#RRGGBB"(transitionalonly)
background="URLofbackgroundimage"(transitionalonly)
bgcolor="colorname|#RRGGBB"(transitionalonly)
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
link="colorname|#RRGGBB"(transitionalonly)
style="styleinformation"
text="colorname|#RRGGBB"(transitionalonly)
title="advisorytext"
vlink="colorname|#RRGGBB">(transitionalonly)
</body>
PART I
HTML 4 Event Attributes
onclick,ondblclick,onkeydown,onkeypress,onkeyup,onload,onmousedown,
onmousemove,onmouseout,onmouseover,onmouseup,onunload
Element-Specific Attributes
alink Thisattributesetsthecolorforactivelinkswithinthedocument.Activelinks
representthestateofalinkasitisbeingclicked.Thevalueoftheattributecanbeeithera
namedcolorlikeredoracolorspecifiedinthehexadecimal#RRGGBBformatlike
#FF0000.TheCSSpseudo-classa:activeshouldbeusedinstead.
background ThisattributecontainsaURLforanimagefile,whichwillbetiledtoprovide
thedocumentbackground.TheCSSbackground-imagepropertyshouldbeusedinstead.
bgcolor Thisattributesetsthebackgroundcolorforthedocument.Itsvaluecanbeeithera
namedcolorlikeredoracolorspecifiedusingthehexadecimal#RRGGBBformatlike
#FF0000.TheCSSbackground-colorpropertyshouldbeusedinstead.
bgproperties Thisattribute,firstintroducedinInternetExplorer2,hasonevalue,fixed,
whichcausesthebackgroundimagetoactasafixedwatermarkandnottoscroll.TheCSS
propertybackground-attachmentprovidessimilarfunctionality.
192 Part I: Core Markup
bottommargin Thisattributespecifiesthebottommarginfortheentirebodyofthepageand
overridesthedefaultmargin.Whensetto0or"",thebottommarginisthebottomedgeof
thewindoworframethecontentisdisplayedin.CSSmarginpropertiesshouldbeused
instead.
leftmargin ThisInternetExplorer–specificattributesetstheleftmarginforthepage,in
pixels,overridingthedefaultmargin.Whensetto0or"",theleftmarginistheleftedgeof
thewindowortheframe.CSSmarginpropertiesshouldbeusedinstead.
link Thisattributesetsthecolorforhyperlinkswithinthedocumentthathavenotyetbeen
visited.Itsvaluecanbeeitherabrowser-dependentnamedcolororacolorspecifiedusing
thehexadecimal#RRGGBBformat.TheCSSpseudo-classa:linkshouldbeusedinstead.
marginheight ThisNetscape-specificattributesetsthetopmarginforthedocument,in
pixels.Ifsetto0or"",thetopmarginwillbeexactlyonthetopedgeofthewindowor
frame.ItisequivalenttocombiningtheInternetExplorerattributesbottommarginand
topmargin.CSSmarginpropertiesshouldbeusedinstead.
marginwidth ThisNetscape-specificattributesetstheleftandrightmarginsforthepage,in
pixels,overridingthedefaultmargin.Whensetto0or"",theleftmarginistheleftedgeof
thewindowortheframe.ItisequivalenttocombiningtheInternetExplorerattributes
leftmarginandrightmargin.CSSmarginpropertiesshouldbeusedinstead.
nowrap ThisInternetExplorer–specificattributeisusedtocontrolthewrappingoftext
bodywidth.Ifsettoyes,textshouldnotwrap.Thedefaultisno.
rightmargin ThisInternetExplorer–specificattributesetstherightmarginforthepagein
pixels,overridingthedefaultmargin.Whensetto0or"",therightmarginistherightedge
ofthewindowortheframe.CSSmarginpropertiesshouldbeusedinstead.
scroll ThisInternetExplorer–specificattributeturnsthescrollbarsonoroff.Thedefault
valueisyes.
text Thisattributesetsthetextcolorforthedocument.Itsvaluecanbeeitheranamed
colorlikeredoracolorspecifiedusingthehexadecimal#RRGGBBformat.TheCSS
propertycolorshouldbeusedonthebodyelementinsteadofthisattribute.
topmargin ThisInternetExplorer–specificattributesetsthetopmarginforthedocument,in
pixels.Ifsetto0or"",thetopmarginwillbeexactlyonthetopedgeofthewindowor
frame.CSSmarginpropertiesshouldbeusedinstead.
vlink Thisattributesetsthecolorforhyperlinkswithinthedocumentthathavealready
beenvisited.Itsvaluecanbeeitherabrowser-dependentnamedcolororacolorspecified
usingthehexadecimal#RRGGBBformat.TheCSSpseudo-classa:visitedshouldbeused
instead.
Examples
<bodybackground="checkered.gif"
bgcolor="white"
alink="red"
Chapter 3: HTML and XHTML Element Reference 193
link="blue"
vlink="red"
text="black">...</body>
PART I
<bodyonload="myLoadFunction()">...</body>
<body>...</body>
Compatibility
HTML 2, 3.2, 4, 4.01, 5+ Firefox 1+, Internet Explorer 2+
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Notes
• Whendefiningtextcolors,itisimportanttobecarefultospecifybothforeground
andbackgroundexplicitlysothattheyarenotmaskedoutbybrowserdefaultsset
bytheuser.
• UnderthestrictHTMLandXHTMLdefinitionsaswellasHTML5,CSSshouldbe
usedinplaceofpresentationattributeslikealink,background,bgcolor,link,
text,andvlink.
• Thiselementmustbepresentinalldocumentsexceptthosedeclaringaframeset.
• UnderXHTML,theclosing</body>tagismandatory.
• HTML5returnstotheoldstyleofmakingtheelementoptional.
• HTML5currentlydefinesallcommonattributesforthiselement,thoughthemeaning
ofsomeinthecontextoftheentiredocumentisabitunclear.
Standard Syntax
<br
class="classname(s)"
clear="all|left|none|right"(transitionalonly)
id="uniquealphanumericidentifier"
style="styleinformation"
title="advisorytext">
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
Element-Specific Attributes
clear Thisattributeforcestheinsertionofverticalspacesothatthetaggedtextcanbe
positionedwithrespecttoimages.Avalueofleftclearstextthatflowsaroundleft-aligned
imagestothenextfullleftmargin;avalueofrightclearstextthatflowsaroundright-aligned
imagestothenextfullrightmargin;andavalueofallclearstextuntilitcanreachbothfull
margins.ThedefaultvalueaccordingtothetransitionalHTMLandXHTMLspecificationsis
none,butitsmeaninggenerallyissupportedasjustintroducingareturnandnothingmore.
TheCSSclearpropertyispreferredoverusingthisattribute.
Examples
<p>Thistextwillbebrokenhere<br>andcontinuedonanewline.</p>
<p>XHTML<br/>syntax!</p>
<address>
PINTInc.<br>
2105GarnetAve<br>
SanDiego,CA92109<br>
</address>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Notes
• Thisisanemptyelement.AclosingtagisillegalunderallHTMLspecifications.For
XHTMLcompatibility,aclosingslashisrequired:<br/>.
• Underthestrict(X)HTMLspecificationsandHTML5,theclearattributeisnotvalid.
TheCSSpropertyclearprovidesthesamefunctionalityastheclearattribute.
Chapter 3: HTML and XHTML Element Reference 195
• HTML5currentlydefinescommonattributesforthiselementthatarenotdefinedin
HTML4andmakelittlesensegiventhatitisempty.Consultthelatestspecification
forclarity.
PART I
• Manydevelopersopttousemargin-relatedCSSpropertiestoperformthecourse
formattingdutiesthatthiselementperformed.Itisarguablethatdegradationinthe
absenceofstylesheetsmayactuallyfavorthebrelement’scontinueduse.
Standard Syntax
<button
accesskey="key"
class="classname(s)"
dir="ltr|rtl"
disabled="disabled"
id="uniquealphanumericidentifier"
lang="languagecode"
name="buttonname"
style="styleinformation"
tabindex="number"
title="advisorytext"
type="button|reset|submit"
value="buttonvalue">
</button>
Element-Specific Attributes
autofocus ThisHTML5Booleanattributeisusedtoindicatethattheuseragentshould
immediatelyfocusthisformitemonceitscontainingwindowobject(usuallythedocument)
ismadeactive.IttakesanattributevalueofautofocuswhenusingtheXML-stylesyntax
forXHTML5.
form ThisHTML5attributeshouldbesettoastringthatcorrespondstotheidoftheform
elementthatthebuttonisassociatedwith.Thisallowsformelementsinoneformtotrigger
actionsinothers.
formaction ThisHTML5attributespecifiesaURLtotargetwhenthebuttonisclicked,
similartotheuseoftheactionattributeonaformelement.
formenctype UnderHTML5thisattributeissettotheMIMEtypeforhowdatashouldbe
transmittedtotheURLspecifiedintheactionattribute.Commonvaluesinclude
Chapter 3: HTML and XHTML Element Reference 197
application/x-www-form-urlencoded(thedefaultvaluewhennotspecified),
multipart/formdata,andtext/plain.
formmethod ThisHTML5attributeindicateshowforminformationshouldbetransferred
PART I
totheserverusingaparticularHTTPmethod.Agetvalueintheattributeindicatesthat
formdatashouldbeappendedtotheURLspecifiedbytheactionattributecreatinga
querystring.Thisapproachisquitesimplebutimposesasizelimitationthatisdifficultto
gauge(maybeaslowas2kilobytesoreven~300charactersinrealsituations).Avalueof
postforthisattributetransfersthedataoftheforminthemessagebodyusingtheHTTP
POSTmethod,whichimposesnodatasizelimitation.BrowsersmayallowforotherHTTP
methodslikedeleteorput,assuggestedbytheHTML5specification,butsofarsuch
usageisrare.Thepostvaluemustbeusedwhenfileattachmentsareusedinaform.
formnovalidate ThisHTML5Booleanattributeisusedtoindicateaformshouldnotbe
validatedduringsubmission.Itisfalsebydefaultbutmaybecontrolledeitheronthe
buttondirectlyoronacontainingorrelatedform.Initiallythiswassimplyknownas
novalidate.
formtarget ThisHTML5attributeissettothenameofawindoworframethatthebutton
actionwilltargettheresultofaction,similartothetargetattributeon<a>and<form>
tags.Initially,thisattributewassimplytargetinearlydraftsofHTML5.
name Thisattributeisusedtodefineanameforthebuttonsothatitcanbescriptedby
olderbrowsersorusedtoprovideanameforsubmitbuttonswhenapagehasmorethan
one.Theidattributeispreferredforscriptingpurposes.
type Thisattributedefinestheactionofthebutton.Possiblevaluesincludebutton,reset,
andsubmit,whichareusedtoindicatethatthebuttonisaplainbutton,formresetbutton,
orformsubmissionbutton,respectively.TheXHTMLspecificationindicatessubmitisthe
default,butbrowsersmaynotenforcethisinpractice.
value
Thisattributedefinesthevaluethatissenttotheserverwhenthebuttonisclicked.This
mightbeusefulwhenusingmultiplesubmitbuttonsthatperformdifferentactions,to
indicatetothehandlingserver-sideprogramwhichbuttonwasclicked.
Examples
<buttonname="Submit"
value="Submit"
type="Submit">SubmitRequest</button>
<buttontype="button"
onclick="doSomething();">ClickThisButton</button>
<buttontype="button">
<imgsrc="polkadot.gif"alt="Polkadot"></button>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1 Netscape 6+, Opera 5+, Safari 1+
198 Part I: Core Markup
Notes
• Itisnotappropriatetoassociateanimagemapwithan<img>tagthatappearsas
thecontentofabuttonelement.
• HTML5mayeventuallyaddnewvaluestothetypeattribute.Alreadymanynew
typevalueshavebeenproposedindifferentforums,suchasadd,remove,move-up,
andmove-down.Thesemayproducepredefinedbuttonstyles,includingiconsin
someuseragents,butsofartheirinclusionisfarfromcertain.
• TheHTML4.01specificationreservesthedata-bindingattributesdatafld,
dataformatas,anddatasrcforfutureuse.InternetExplorerdoessupportthem.
• Thedefaulttypeofa<button>issubmitunderInternetExplorer8’sstandards
mode,andisbuttonunderIE8’scompatibilitymode.
• UnderInternetExplorer8,thevalueofasubmittedbuttondependsonthe
compatibilitymodeofthebrowser.InIE8standardsmode,thecontentsofthe
attributevalueissent,ascomparedtoIE8compatibilitymode,wherethe
innerTextvalueofthe<button>tagusedissent.
PART I
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
API Reference
AbriefoverviewofthecanvasscriptingAPIisprovidedinTables3-9through3-21.Selected
examplesofusecanbefoundinChapter2.
Example
<canvasid="canvas1"height="400"width="400">
<pclass="error">Canvas-SupportingBrowserRequired</p>
</canvas>
<scripttype="text/javascript">
varcanvas=document.getElementById("canvas1");
varcontext=canvas.getContext("2d");
/*drawsimplefigureofredandgreensquares*/
context.fillStyle="rgb(255,0,0)";
context.fillRect(0,0,100,100);
context.fillStyle="rgb(0,255,0)";
context.fillRect(25,25,50,50);
</script>
PART I
all fills and strokes. Value
must be between 0 and 1.
The default is 1.0.
globalCompositeOperation Sets how shapes and context.
images are written to the globalCompositeOperation
canvas. See Table 3-14 for ="destination-over";
the various options. A is the
object being written (source)
and B is the current canvas
drawing (destination). The
default is source-over.
PART I
choices are butt, round, and square. A value "round";
of butt indicates that there is a flat edge at the
end of the specified line. A value of round adds
a semicircle with a diameter the width of the line
to the end of the line. A value of square adds a
rectangle with a width half of the line’s width and
a length equal to the line’s width at the end of the
line. The default is butt.
lineJoin Sets the type of corners that occur when two context.lineJoin=
lines meet. The choices are miter, bevel, and "round";
round. On all joins, a filled triangle connecting the
two lines is connected. A value of bevel uses only
this filled triangle. A value of miter indicates that
in addition to the triangle, a second filled triangle
is created. The second triangle consists of a line
that connects the two lines as well as the two lines
themselves extended until they meet. A value of
round indicates that corners should be rounded
when lines meet. The arc has a diameter equal to
the width of the line. The default is miter.
lineWidth Sets the width of the lines. The default value is 1. context.lineWidth=5;
miterLimit Sets the max length that a line will be extended if context.miterLimit=1;
lineJoin is set to miter. If the length necessary
to join the lines is greater than the miterLimit,
the join will not occur. The default is 10.
PART I
paths set and undrawn at this
point will not be displayed.
bezierCurveTo Connects the last point in context.moveTo(50,50);
(cp1x,cp1y,cp2x, the subpath to (x,y) using context.bezierCurveTo(65,
cp2y,x,y) (cp1x,cp1y) and (cp2x, 25,85,25,100,50);
cp2y) as control points for a
cubic Bézier curve.
clip() Creates a new clipping region context
by intersecting the current .arc(150,150,100,0,Math
clipping region with the area .PI*2,true);
defined in the current path. context.clip();
closePath() Closes the last subpath and context.closePath();
creates a new subpath that
has the previous subpath’s
last point as its first point.
fill() Fills any open subpaths and context.lineTo(100,100);
then closes them. Uses the context.lineTo(0,200);
fillStyle to determine how context.lineTo(100,300);
the fill should appear. context.fill();
lineTo(x,y) Draws a line from the last point context.lineTo(100,100);
in the subpath to the point
defined by (x,y).
moveTo(x,y) Creates a new subpath with context.moveTo(150,50);
the point (x,y) added to it.
quadraticCurveTo Connects the last point in context.moveTo(50,150);
(cpx,cpy,x,y) the subpath to (x,y) using context
(cpx,cpy) as the control .quadraticCurveTo(125,
point for a quadratic Bézier 225,200,150);
curve.
rect(x,y,w,h) Creates a new subpath context.rect(50,50,100,
containing the rectangle 100);
defined by starting point (x,
y) with width w and height h.
stroke() Draws the strokes of the context.moveTo(50,250);
current path and display based context.lineTo(0,200);
on the settings specified context.lineTo(50,150);
by lineWidth, lineCap, context.lineTo(0,100);
lineJoin, miterLimit, and context.lineTo(50,50);
strokeStyle. context.stroke();
PART I
createImageData ImageData object with the (100,200);
(imagedata) width w and height h or with
the same dimensions as
imagedata.
drawImage(image,dx,dy) Draws an image specified by context.drawImage
drawImage(image,dx,dy, image onto the canvas. The (img,200,75,100,100,50,
dw,dh) image is placed at (dx,dy). 50,300,300);
drawImage(image,sx,sy, If dw and dh are specified, the context.drawImage
sw,sh,dx,dy,dw,dh) image will have that width and (img,0,0,400,400);
height, respectively. In the last
case, the section of the image
to be placed on the canvas
is specified by the rectangle
defined by sx, sy, sw, and sh.
getImageData(sx,sy, Returns an ImageData object varimg=context
sw,sh) that contains the pixel data .getImageData(0,0,
for the rectangle that starts at 100,100);
(sx,sy) with a width sw and
height sh.
putImageData(imagedata, Writes the specified ImageData context.putImageData
dx,dy[,dirtyX, to the canvas. (img,75,75);
dirtyY,dirtyWidth,
dirtyHeight])
data Represents the pixels in the alert(img.data.length);
image.
height Height of the image in pixels. alert(img.height);
width Width of the image in pixels. alert(img.width);
Compatibility
HTML5 Firefox 1.5+,
Opera 9+, Safari 2+
Notes
• Whenthiselementwasinitiallyintroducedin2004byApple,itcausedsomedegree
ofcontroversyintheWebcommunitybecausedevelopersassumedthatitwould
openthefloodgatestovendor-specificextensions.
• UndersomeSafariimplementations,theclose</canvas>tagisnotrequiredor
understood.
208 Part I: Core Markup
• Useragentsthatdonotunderstand<canvas>shouldrenderthecontentsofthe
elementinstead.
• Itispossibletosimulatethe<canvas>tagunderInternetExplorerusingoneof
numerouslibrariessuchasGoogle’sExplorerCanvas(http://excanvas.sourceforge
.net/).SuchlibrariesrelyontheuseofIE’sproprietaryVML(VectorMarkup
Language)technologyandarelikelygoingtooperateslowlygiventherequired
translationascomparedtoanative<canvas>implementation.
• Chapter2hasadiscussionof<canvas>anditsusewithJavaScript.
Standard Syntax
<caption
align="bottom|left|right|top"(transitionalonly)
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</caption>
PART I
HTML5 Event Attributes
onabort,onblur,oncanplay,oncanplaythrough,onchange,onclick,
oncontextmenu,ondblclick,ondrag,ondragend,ondragenter,ondragleave,
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Element-Specific Attributes
align Thisattributespecifiesthealignmentofthecaption.HTML4definesbottom,left,
right,andtopaslegalvalues.InternetExploreralsosupportscenter.Becausethis
attributedoesnotprovidethepossibilitytocombineverticalandhorizontalalignments,
Microsofthasintroducedthevalignattributeforthecaptionelement.
valign ThisInternetExplorer–specificattributespecifieswhetherthetablecaptionappears
atthetoporbottom.Thedefaultistop.
Example
<tableborder="1">
<captionalign="top">OurHigh-PricedMenu</caption>
<tr>
<td>Escargot</td>
<td>FiletMignon</td>
<td>BigMac</td>
</tr>
</table>
Compatibility
HTML 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1, Basic Netscape 3+, Opera 4+, Safari 1+
210 Part I: Core Markup
Notes
• Thereshouldbeonlyonecaptionpertable.
• HTML3.2definesonlythealignattributewithvaluesofbottomandtop.No
otherattributesaredefinedpriortoHTML4.
Examples
<center>Thisisinthecenterofthepage.</center>
PART I
<center>
<p>Larry</p>
<p>Curly</p>
<p>Moe</p>
</center>
Compatibility
HTML 3.2, 4, 4.01 (transitional) Firefox 1+, Internet Explorer 2+,
XHTML 1.0 (transitional) Netscape 1+, Opera 4+, Safari 1+
Notes
• ThecenterelementdefinedbytheW3Cisashorthandnotationfor<div
align="center">.Thecontentmodelforthiselementisodd,asthe<center>tag
isoftenfoundenclosinglargesectionsofcontentorfragments.Typically,ithasbeen
notedthatpageauthorswhotendtousetheelementdon’tcareaboutthecontent
modelandusetagsoutofcontextfreely.
• ThestrictversionsofHTMLandXHTMLdonotincludethecenterelement,butit
iseasilyimitatedwiththetext-alignCSSproperty.
• HTML5definesthecenterelementasobsolete.
• HTML3.2doesnotsupportanyattributesforthiselement.
<cite> (Citation)
Thiselementindicatesacitationfromabookorotherpublishedsourceandusuallyis
renderedinitalicsbyabrowser.
Standard Syntax
<cite
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</cite>
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
Example
<p>Thisexampleistakenfrom<cite>HTML&CSS:TheComplete
Reference</cite>abookbyThomasPowell.</p>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Chapter 3: HTML and XHTML Element Reference 213
Note
• HTML2and3.2donotindicateanyattributesforthiselement.
PART I
<code> (Code Listing)
Thiselementindicatesthattheenclosedtextissourcecodeinaprogramminglanguage.
Usuallyitisrenderedinamonospacedfont.
Standard Syntax
<code
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</code>
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Example
<p>Toincrementavariable<var>count</var>,use
<code>count++</code>or<code>count=count+1</code>.</p>
Compatibility
HTML 2, 3.2, 4, 4.01,5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• Thiselementisbestusedforshortcodefragmentsbecauseitdoesnotpreserve
whitespace.
• HTML2.0and3.2donotsupportanyattributesforthiselement.
• InternetExplorerdocumentationdoesnotlistaccesskeyortabindexforthis
element.Thisislikelyanoversight,asitisfoundonnearlyallotherelementsinthe
IEobjectmodel.
Standard Syntax
<col
align="center|char|justify|left|right"
char="character"
charoff="number"
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
span="number"
style="styleinformation"
Chapter 3: HTML and XHTML Element Reference 215
title="advisorytext"
valign="baseline|bottom|middle|top"
width="columnwidthspecification">
PART I
Attributes Introduced by HTML5
accesskey="spacedlistofacceleratorkey(s)"
contenteditable="true|false|inherit"
contextmenu="idofmenu"
data-X="user-defineddata"
draggable="true|false|auto"
hidden="hidden"
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
Element-Specific Attributes
bgcolor ThisInternetExplorer–specificattributesetsthebackgroundcolorforthecolumn.
Itsvaluecanbeeitherabrowser-dependentnamedcolororacolorspecifiedusingthe
hexadecimal#RRGGBBformat.
char Thisattributeisusedtosetthecharacteronwhichthecellsinacolumnshouldbe
aligned.Atypicalvalueforthisisaperiod(.)foraligningnumbersormonetaryvalues.
216 Part I: Core Markup
charoff Thisattributeisusedtoindicatethenumberofcharactersbywhichthecolumn
datashouldbeoffsetfromthealignmentcharactersspecifiedbythecharvalue.
span Whenpresent,thisattributeappliestheattributesofthecolelementtoadditional
consecutivecolumns.
valign Thisattributespecifiestheverticalalignmentofthetextwithinthecell.Possible
valuesforthisattributearebaseline,bottom,middle,andtop.
width Thisattributespecifiesadefaultwidthforeachcolumninthecurrentcolumngroup.
Inadditiontothestandardpixelandpercentagevalues,thisattributemighttakethespecial
form0*,whichmeansthatthewidthofeachcolumninthegroupshouldbetheminimum
widthnecessarytoholdthecolumn’scontents.Relativewidths,suchas0.5*,alsocanbe
used.
Example
<tableborder="1"width="400">
<colgroup>
<colalign="center"width="150"/>
<colalign="right"/>
</colgroup>
<td>Thiscolumnisalignedtothecenter.</td>
<td>Thisoneisalignedtotheright.</td>
</td>
<tr><td>!</td><td>?</td></tr>
<tr><td>!</td><td>?</td></tr>
</table>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1 Netscape 6+, Opera 7+, Safari 1+
Notes
• UnderXHTML1.0andXHTML5,<col>requiresatrailingslash:<col/>.
• Thiselementshouldappearwithinacolgroupelement,and,likethatelement,itis
somewhatofaconveniencefeatureusedtosetattributeswithoneormoretable
columns.Inpractice,fewdevelopersseemtouseit.
Standard Syntax
<colgroup
align="center|char|justify|left|right"
char="character"
Chapter 3: HTML and XHTML Element Reference 217
charoff="number"
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
PART I
lang="languagecode"
span="number"
style="styleinformation"
title="advisorytext"
valign="baseline|bottom|middle|top"
width="columnwidthspecification">
colelementsonly
</colgroup>
Element-Specific Attributes
align Thisattributespecifieshorizontalalignmentofthecontentsofthecellsinthecolumn
group.Thevaluesofcenter,left,andrighthaveobviousmeanings.Avalueofjustify
fortheattributeattemptstojustifyallthecolumn’scontents.Avalueofcharattemptsto
alignthecontentsbasedonthevalueofthecharattributeinconjunctionwithcharoff.
bgcolor ThisInternetExplorer–specificattributesetsthebackgroundcolorforthecolumns
inthecolumngroup.Itsvaluecanbeeitherabrowser-dependentnamedcolororacolor
specifiedusingthehexadecimal#RRGGBBformat.
char Thisattributeisusedtosetthecharacteronwhichthecellsinacolumnshouldbe
aligned.Atypicalvalueforthisattributeisaperiod(.)foraligningnumbersormonetary
values.
charoff Thisattributeisusedtoindicatethenumberofcharactersbywhichthecolumn
datashouldbeoffsetfromthealignmentcharactersspecifiedbythecharvalue.
span Whenpresent,thisattributespecifiesthedefaultnumberofcolumnsinthisgroup.
Browsersshouldignorethisattributeifthecurrentcolumngroupcontainsoneormore
<col>tags.Thedefaultvalueofthisattributeis1.
valign Thisattributespecifiestheverticalalignmentofthecontentsofthecellswithinthe
columngroup.
width Thisattributespecifiesadefaultwidthforeachcolumnanditscellsinthecurrent
columngroup.Inadditiontothestandardpixelandpercentagevalues,thisattributecan
takethespecialform0*,whichmeansthatthewidthofeachcolumninthegroupshouldbe
theminimumwidthnecessarytoholdthecolumn’scontents.
Examples
<colgroupspan="2"align="char"char=":"valign="center">
<col/><col/><col/>
</colgroup>
<colgroupstyle="background-color:green;">
<colalign="left"/>
<colalign="center"/>
</colgroup>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1 Netscape 6+, Opera 7+, Safari 1+
Notes
• Eachcolumngroupdefinedbya<colgroup>tagcancontainzeroormore<col>
tags.
• UnderXHTML1.0,theclosing</colgroup>tagismandatory.
Chapter 3: HTML and XHTML Element Reference 219
<command> (Command)
ThisHTML5elementrepresentsacommandausercaninvokeandisfoundwithinamenu
element.Commandsmaybesimpleactionsortogglesamongvariousstatesoroptions.
PART I
HTML5 Standard Syntax
<command
accesskey="spacedlistofacceleratorkey(s)"
class="classname(s)"
contenteditable="true|false|inherit"
contextmenu="idofmenu"
data-X="user-defineddata"
default="default"
dir="ltr|rtl"
disabled="disabled"
draggable="true|false|auto"
hidden="hidden"
icon="URLforimagetousewithcommand"
id="uniquealphanumericidentifier"
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
label="descriptivestringforcommand"
lang="languagecode"
radiogroup="radiogroupname"
spellcheck="true|false"
style="styleinformation"
tabindex="number"
title="advisorytextdescribingcommand"
type="checkbox|command|radio">
Example
<menu>
<commandlabel="Add"type="Command"icon="plus.png">
<commandlabel="Edit"type="Command"default>
<commandlabel="Delete"type="Command"disabled>
<hr>
<commandlabel="SortAscending"type="radio"radiogroup="sort">
<commandlabel="SortDescending"type="radio"radiogroup="sort">
</menu>
220 Part I: Core Markup
Compatibility
HTML5 Not currently supported by any browser, but addressed with
a custom element combined with JavaScript.
Note
• Thiselementiscurrentlyinextremelyrawformandwithoutimplementationsits
usageshouldbeconsideredspeculative.
Element-Specific Attribute
data ThisattributereferencesaURLthatcontainsthecommentinformation.
Example
<comment>Thisisnottheproperwaytoform
comments!!!</comment>
Compatibility
No standards support Internet Explorer 4, 5, 5.5, 6
Notes
• Itisbettertousestandard<!--...-->commentratherthanthistag.
• Becausethecommentelementisnotsupportedbyallbrowsers,commentedtext
doneinthisfashionwillappearinotherbrowsers.
PART I
class="classname(s)"
contenteditable="true|false|inherit"
contextmenu="idofmenu"
data-X="user-defineddata"
dir="ltr|rtl"
draggable="true|false|auto"
hidden="hidden"
id="uniquealphanumericidentifier"
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
lang="languagecode"
spellcheck="true|false"
style="styleinformation"
tabindex="number"
title="advisorytext">
optionelementsonly
</datalist>
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>DatalistTest</title>
</head>
<body>
<formaction="#"method="get">
<p><label>Drinks:<inputlist="soda"></label></p>
<datalistid="soda">
<option>Coke</option>
<option>Pepsi</option>
<option>Dr.Pepper</option>
222 Part I: Core Markup
<option>Mr.Pibb</option>
<option>Mt.Dew</option>
<option>7-Up</option>
</datalist>
</form>
</body>
</html>
Compatibility
HTML5 Opera 9.5+
Note
• Thiselementcouldbesimulatedwithotherbrowsersusingscript,customelements,
andcarefuluseofCSS.
Standard Syntax
<dd
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</dd>
PART I
disabled="false|true"(5.5)
hidefocus="true|false"(5.5)
language="javascript|jscript|vbs|vbscript"(4)
nowrap="no|yes"(4)
tabindex="number"(5.5)
unselectable="on|off"(5.5)
Element-Specific Attribute
nowrap ThisInternetExplorer–specificattributeisusedtocontrolthewrappingoftext
withina<dd>tag.Ifsettoyes,textshouldnotwrap.Thedefaultisno.CSSrulesshouldbe
usedinsteadofthisattribute.
Examples
<dl>
<dt>DOG</dt>
<dd>Adomesticatedanimalthatcravesattentionallthetime</dd>
<dt>CAT</dt>
<dd>Ananimalthatwouldjustassoonignoreyouuntilit
getshungry</dd>
</dl>
224 Part I: Core Markup
<!--HTML5Example-->
<details>
<dt>ImportantNote</dt>
<dd>ThistagseemstobereusedtoomuchunderHTML5!<dd>
</details>
<figure>
<dt>MooseBaby!</dt>
<dd>
<imgsrc="desmond.jpg"alt="DesmondBaby"height="320"width="150">
<p>AphotoofDesmondcirca2010.</p>
</dd>
</figure>
Compatibility
HTML 2, 3.2, 4, 4.01,5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Notes
• UnderHTMLspecifications,includingHTML5,theclosingtagforthiselementis
optional,thoughusingitisencouragedwhenitwillhelpmakethelistmore
understandable.
• UnderXHTML1.0,theclosing</dd>tagismandatory.
• Thiselementoccurswithinalistofdefinedtermsenclosedbya<dl>tag.Typically
associatedwithitisthetermitdefines,indicatedbythe<dt>tagthatprecedesit,
thoughitdoesn’thavetomatchbecausetherearenotcorrespondencerequirements
fordefinitionlists.
• UnderHTML5,thiselementhasanoverloadedmeaningandmayalsobeusedto
enclosethecontentwithin<details>and<figure>tags.
• InearlyversionsofHTML5,thiselementoccurredwithina<dialog>tagfor
indicationofdialog.
• HTML2and3.2definenoattributesforthiselement.
Standard Syntax
<del
cite="URL"
class="classname(s)"
datetime="date"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
Chapter 3: HTML and XHTML Element Reference 225
lang="languagecode"
style="styleinformation"
title="advisorytext">
PART I
</del>
NOTE MSDNdocumentationforthiselementappearsincorrectforeventhandlers.Notallcore
eventsarelisted,butduringtestingtheyallworked.Otherextendedeventslikeonbeforecopy,
oncopy,oncontextmenu,andmorewerealsoverifiedasfunctionalunderInternetExplorer8.
Element-Specific Attributes
cite ThevalueofthisattributeisaURLthatdesignatesasourcedocumentormessagethat
mightexplainwhytheinformationwasdeleted.
datetime Thisattributeisusedtoindicatethedateandtimethedeletionwasmade.Thevalue
oftheattributeisadateinaspecialformatasdefinedbyISO8601.Thebasicdateformatis
YYYY-MM-DDThh:mm:ssTZD
wherethefollowingistrue:
YYYY=four-digityearsuchas1999
MM=two-digitmonth(01=January,02=February,andsoon.)
DD=two-digitdayofthemonth(01through31)
hh=two-digithour(00to23)(24-hourclock,notAMorPM)
mm=two-digitminute(00through59)
ss=two-digitsecond(00through59)
TZD=timezonedesignator
ThetimezonedesignatoriseitherZ,whichindicatesUniversalTimeCoordinateor
coordinateduniversaltimeformat(UTC),or+hh:mm,whichindicatesthatthetimeisalocal
timethatishhhoursandmmminutesaheadofUTC.Alternatively,theformatforthetime
zonedesignatorcouldbe–hh:mm,whichindicatesthatthelocaltimeisbehindUTC.Note
thattheletterTactuallyappearsinthestring,alldigitsmustbeused,and00valuesfor
minutesandsecondsmightberequired.Anexamplevalueforthedatetimeattribute
mightbe1999-10-6T09:15:00-05:00,whichcorrespondstoOctober6,1999,9:15A.M.,
U.S.EasternStandardTime.
Example
<p><delcite="http://www.democompany.com/changes/oct.html"
datetime="2008-10-06T09:15:00-05:00">
Thepenaltyclauseappliestoclientlatenessaswell.
</del><ins>Nomorepenalties</ins></p>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1 Netscape 6+, Opera 7+, Safari 1+
Notes
• Browserscanrenderdeleted(<del>)textinadifferentstyletoshowthechanges
thathavebeenmadetothedocument.InternetExplorerrendersthedeletedtextas
strikethroughtext.Eventually,abrowsercouldhaveawaytoshowarevision
historyonadocument.
Chapter 3: HTML and XHTML Element Reference 227
• Useragentsthatdonotunderstand<del>or<ins>willshowtheinformation
anyway,sothereisnoharminaddinginformation—onlyindeletingit.Becauseof
thefactthat<del>-enclosedtextmightshowup,itmightbewisetocommentitout
PART I
withintheelement,asshownhere:
<del>
<!--Thisisoldinformation.-->
</del>
Element-Specific Attribute
open ThisBooleanattributeindicateswhetherdetailsshouldbeshowntotheuser.Ifnot
theyarenotshown,andwouldlikelybeexposedviaascriptevent.
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Example
<detailsonclick="this.open='open';">
<dt>Help?</dt>
<dd>
<p>ThiscouldgiveyouhelpwithHTML5butweneedmoreimplementationsto
provehowthingswillwork.</p>
</dd>
</details>
Compatibility
HTML5 Not currently supported by any browser, but addressed with a custom element.
Notes
• Thiselementmaycontainonedtelementdescribingthecaptionofthedetailed
content,andoneddelement,whichcontainsthecontenttoshow.
• InearlydraftsofHTML5specification,thelegendelementwasusedinsteadofthe
dtandddelementsaddedlater.
<dfn> (Definition)
Thisinlinelogicalelementenclosesthedefininginstanceofaterm.Itusuallyisrenderedas
boldorbolditalictext.
Standard Syntax
<dfn
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</dfn>
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
PART I
tabindex="number"
Example
<p>The<dfn>dfn</dfn>elementisanelementwhichisusedtosetoffthe
defininginstanceofaterm.Nowthat'saself-containedexample!</p>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 6+, Opera 4+, Safari 1+
230 Part I: Core Markup
Notes
• HTML2and3.2definednoattributesforthiselement.
• HTML5suggeststhatthesectionorcontentgroupingnearestanoccurrenceofadfn
elementmustcontaintheactualdefinition.
Element-Specific Attribute
compact Thisattributereducesthewhitespacebetweenlistitems.
PART I
Example
<dir>
<li>HeaderFiles</li>
<li>CodeFiles</li>
<li>CommentFiles</li>
</dir>
Compatibility
HTML 2, 3.2, 4, 4.01 (transitional) Firefox 1+, Internet Explorer 2+,
XHTML 1.0 (transitional) Netscape 1+, Opera 2.1+, Safari 1+
Notes
• Becausethe<dir>tagissupposedtobeusedwithshortlists,theitemsinthelist
shouldhaveamaximumwidthof20characters.Thisisrarelyifeverrespected.
• TheHTMLandXHTMLstrictspecificationsdonotsupportthiselement,andthe
HTML5specificationhasmarkeditasobsoleteandsuggestsusinga<ul>tag
instead.
• Mostbrowserswillnotrendera<dir>taganydifferentlyfromthe<ul>tag.
• HTML2and3.2defineonlythecompactattribute.
• Mostbrowserswillnotrenderthecompactliststyle.
• ForXHTMLtransitionalcompatibility,thecompactattributemusthaveavalue:
<dircompact="compact">.
<div> (Division)
Thiselementindicatesagenericblockofcontentthatshouldbetreatedasalogicalunitfor
scriptingorstylingpurposes.
Standard Syntax
<div
align="center|justify|left|right"(transitionalonly)
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</div>
data-X="user-defineddata"
draggable="true|false|auto"
hidden="hidden"
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
Element-Specific Attribute
nowrap ThisInternetExplorer–specificattributeisusedtocontrolthewrappingoftext
PART I
withina<div>tag.Ifsettoyes,textshouldnotwrap.Thedefaultisno.CSSrulesshould
beusedinsteadofthisattribute.
Examples
<divalign="justify">
<!--IEsyntax-->
Alltextwithinthisdivisionwillbejustified
</div>
<divclass="special"id="div1"style="background-color:yellow;">
Divsareusefulforsettingarbitrarystyle
</div>
<divclass="container">
<divclass="wrapper">
<divclass="content"><p>Ihavedivitis</p></div>
</div>
</div>
Compatibility
HTML 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 2+, Opera 4+, Safari 1+
Notes
• A<div>tagisagenericblocktagandisveryusefulforbindingscriptsorstylesto
anarbitrarysectionofadocument.Itcomplements<span>,whichisusedinline.
• Excessiveuseof<div>tagsisalmostasbadasexcessiveuseoftables,particularly
whenstructuringpagecontent.
• TheHTML4specificationspecifiesthatthedatafld,dataformatas,anddatasrc
attributesarereservedfor<div>andmightbesupportedinthefuture.Theywere
removedfromXHTML,butInternetExplorersupportsthemfordatabinding.
• UndertheHTML4.01strictspecification,thealignattributeisnotsupported.
• HTML3.2supportsonlythealignattribute.
Standard Syntax
<dl
class="classname(s)"
compact="compact"(transitionalonly)
234 Part I: Core Markup
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
dtandddelementsonly
</dl>
PART I
oncontrolselect,oncopy,oncut,ondblclick,ondeactivate,ondrag,
ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,
onfocus,onfocusin,onfocusout,onhelp,onkeydown,onkeypress,onkeyup,
onlosecapture,onmousedown,onmouseenter,onmouseleave,onmousemove,
onmouseout,onmouseover,onmouseup,onmousewheel,onmove,onmoveend,
onmovestart,onpaste,onpropertychange,onreadystatechange,onresize,
onresizeend,onresizestart,onselectstart,ontimeerror
Element-Specific Attribute
compact Thisattributereducesthewhitespacebetweenlistitems.
Examples
<dl>
<dt>Cat</dt>
<dd>Adomesticanimalthatlikesfish.</dd>
<dt>Skunk</dt>
<dd>Awildanimalthatneedsdeodorant.</dd>
</dl>
<!--Termsdefinitionsdon'thavetopairmatch-->
<dl>
<dt>Cat</dt>
<dt>Fritz</dt>
<dt>Sylvester</dt>
<dd>Adomesticanimalthatlikesfish.</dd>
<dt>Skunk</dt>
<dt>PepeLePew</dt>
<dd>Awildanimalthatneedsdeodorant.</dd>
<dt>TasmanianDevil</dt>
</dl>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Notes
• Theitemsinthelistcomprisetwoparts:theterm,indicatedbythedtelement,and
itsdefinition,indicatedbytheddelement.However,thereisnorequirementto
matchtheseelements,alternatethem,oranythingelse,atleastsyntax-wise.
• Somepagedesignersmightusea<dl>tagor<ul>tagtocreatetextindention.
AlthoughthisisacommonpracticeontheWeb,itisnotadvisablebecauseit
confusesthemeaningoftheelementbymakingitaphysicallayoutdevicerather
thanalist.ACSSpropertylikemarginorpositionshouldbeusedinstead.
236 Part I: Core Markup
• HTML2and3.2supportonlythecompactattributeforthiselement.
• ForXHTMLcompatibility,thecompactattributemustbeexpanded:
<dlcompact="compact">underthetransitionalform.Itisdeprecatedunderthe
strictspecification.Inpractice,regardlessofwhetheritisindicated,thecompact
attributegenerallyhasnoeffect.
Standard Syntax
<dt
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</dt>
PART I
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Element-Specific Attribute
nowrap ThisInternetExplorer–specificattributeisusedtocontrolthewrappingoftext
withina<dt>tag.Ifsettoyes,textshouldnotwrap.Thedefaultisno.CSSproperties
shouldbeusedinsteadofthisattribute.
Examples
<!--Typicaldefinitionlistusage-->
<dl>
<dt>Vole</dt>
<dd>Smallcreaturerelatedtotheweasel</dd>
<dt>Weasel</dt>
<dd>Smallcreaturerelatedtothevole</dd>
</dl>
<!--HTML5examples-->
<details>
<dt>ImportantNotes</dt>
<dd>ThistagseemstobereusedtoomuchunderHTML5!<dd>
</details>
<figure>
<dt>MooseBaby!</dt>
<dd>
<imgsrc="desmond.jpg"alt="DesmondBaby"height="320"width="150">
<p>AphotoofDesmondcirca2010.</p>
</dd>
</figure>
238 Part I: Core Markup
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Notes
• Traditionally,thiselementoccurswithinalistofdefinedtermsenclosedbya<dl>
tag.Itisgenerallyusedinconjunctionwitha<dd>tag,whichindicatesits
definition.However,<dt>tagsdonotrequireaone-to-onecorrespondencewith
<dd>tags.
• HTML5overloadsthemeaningofthiselementsothatitalsoservesasthecaptionof
contentenclosedwithin<details>and<figure>tags.
• UnderearlydraftsofHTML5,thiselementisalsofoundwithin<dialog>tagsand
definesthespeakersofparticularstatements.Whenusedwithinsuchtags,itmust
bepairedwith<dd>tagsinaone-to-onefashion.Thatsyntaxwaseventually
dropped.
• TheclosetagfortheelementisoptionalunderolderversionsofHTMLaswellas
HTML5,butincludingitissuggested,especiallywhenitwillmakethingsclearer,
particularlywithmultiple-linedefinitions.
• UnderXHTML1.0,theclosing</dt>tagismandatory.
• HTML2and3.2supportnoattributesforthiselement.
<em> (Emphasis)
Thisinlineelementindicatesemphasizedtext,whichmanybrowserswilldisplayasitalictext.
Standard Syntax
<em
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</em>
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
PART I
tabindex="number"
Example
<p><em>Thisistheimportantpoint</em>toconsider,notthisotherless
excitingpoint.</p>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
240 Part I: Core Markup
Notes
• Asalogicalelement,emisaprimecandidatetobindstyleinformationto.For
example,todefineemphasistomeanalargerfontsizeintheImpactfontinsteadof
italics,youmightuseaCSSrulelikethefollowinginadocument-widestylesheet:
em{font-size:larger;font-family:Impact;font-style:normal;}
• HTML2and3.2supportnoattributesforthiselement.
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
PART I
HTML5 Event Attributes
onabort,onblur,oncanplay,oncanplaythrough,onchange,onclick,
oncontextmenu,ondblclick,ondrag,ondragend,ondragenter,ondragleave,
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Element-Specific Attributes
align Thisattributecontrolsthealignmentofadjacenttextwithrespecttotheembedded
object.Thedefaultvalueisleft.
alt Thisattributeindicatesthetexttobedisplayediftheembeddedobjectcannotbe
executed.
border Thisattributespecifiesthesize,inpixels,oftheborderaroundtheembedded
object.
code ThisattributespecifiesthenameofthefilecontainingthecompiledJavaclassifthe
embedelementisusedtoincludeaJavaapplet.ThisisastrangealternativeformofJava
inclusiondocumentedbyMicrosoft.
codebase ThisspecifiesthebaseURLfortheplug-inorpotentialappletinthecaseofthe
alternativeformunderInternetExplorer.
name Thisattributespecifiesanamefortheembeddedobject,sothatitcanbereferenced
byclient-sideprogramsinanembeddedscriptinglanguage.
palette ThisattributeisusedonlyonWindowssystemstoselectthecolorpaletteusedfor
theplug-inandmightbesettobackgroundorforeground.Thedefaultisbackground.
pluginspage ThisattributecontainstheURLofinstructionsforinstallingtheplug-in
requiredtorendertheembeddedobject.
242 Part I: Core Markup
src ThisattributespecifiestheURLofsourcecontentfortheembeddedobject.
type ThisattributespecifiestheMIMEtypeoftheembeddedobject.Itisusedbythe
browsertodetermineanappropriateplug-inforrenderingtheobject.Itcanbeusedinstead
ofthesrcattributeforplug-insthathavenocontentorthatfetchitdynamically.
units ThisNetscape4+–specificattributeisusedtosettheunitsformeasurementforthe
embeddedobjectinpixelsorasarelativeemvalue.
vspace Thisattributespecifies,inpixels,thesizeofthetopandbottommarginsbetween
theembeddedobjectandsurroundingtext.
Example
<!--embedwithaclosetag-->
<embedsrc="testmovie.mov"height="150"width="150">
<noembed>
<imgsrc="testgif.gif"height="150"width="150"alt="TestImage">
</noembed>
</embed>
Compatibility
No standard initially, but widely supported Firefox 1+, Internet Explorer 4+,
HTML5 Netscape 2+, Opera 4+, Safari 1+
Notes
• Historically,ithasbeenunclearwhetherornottheclosetagfor<embed>isrequired.
Manysitestendednottouseit,anddocumentationisnotconsistent.Aclose</embed>
tagshouldberequiredandshouldsurroundanyalternativecontentinanoembed
element.
• Thiselementwassupposedtobephasedoutinfavoroftheobjectelement,butso
faritsusageseemstohavediminishedonlyslightly.
• TheembedelementisnotfavoredbytheW3Candwasdroppedby(X)HTML
specificationsprevioustoHTML5.
• Embeddedobjectsaremultimediacontentfilesofarbitrarytypethatarerenderedby
browserplug-ins.Thetypeattributeusesafile’sMIMEtypetodeterminean
appropriatebrowserplug-in.Anyattributesnotdefinedaretreatedasobject-specific
parametersandarepassedthroughtotheembeddedobject.Consulttheplug-inor
objectdocumentationtodeterminethese.
Standard Syntax
<fieldset
class="classname(s)"
dir="ltr|rtl"
Chapter 3: HTML and XHTML Element Reference 243
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
PART I
</fieldset>
Example
<fieldset>
<legend>CustomerIdentification</legend>
<br>
<label>CustomerName:
<inputtype="text"id="CustName"size="25">
</label>
</fieldset>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1 Netscape 6+, Opera 4+, Safari 1+
Notes
• Groupingcontrolsmakesiteasierforuserstounderstandthepurposesofthe
controlswhilesimultaneouslyfacilitatingtabbingnavigationforvisualuseragents
andspeechnavigationforspeech-orienteduseragents.Theproperuseofthis
elementmakesdocumentsmoreaccessibletouserswithdisabilities.
• Thefullsetofdata-bindingattributeslikelyneedstobeboundtothiselementbutis
missingfromMSDNdocumentation.
• Thecaptionfora<fieldset>tagcanbedefinedbythelegendelement.There
shouldonlybeasinglelegendelementwithintheelement.
<figure> (Figure)
ThisHTML5elementrepresentsagroupofcontentenclosedinaddelement,oftenwitha
captiondefinedbyadtelement,thatcanbemovedawayfromthemainflowofthe
document.Thewayinwhichthiselementisimplementedissimilartohowthefiguresin
thisbookarepresented—notnecessarilydirectlyadjacenttothetextdiscussingthem.
draggable="true|false|auto"
hidden="hidden"
id="uniquealphanumericidentifier"
itemid="microdataidinURLformat"
PART I
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
lang="languagecode"
spellcheck="true|false"
style="styleinformation"
tabindex="number"
title="advisorytext">
</figure>
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>FigureItOut</title>
</head>
<body>
<header><h1>WelcometotheExample</h1></header>
<p>Yesitisanotherboringexample.Inthiscasewewouldlikeyou
toreview<ahref="#fig1">FigureEx-1</a></p>
<p>Moreandmoretextisfounduntileventuallythefigureis
located.</p>
<figure>
<dd>
<imgsrc="screensnap.png"
alt="AscreencaptureoftheFigureElementinaction">
<p>ThemightyfigtaghasreturnedfromHTML3asfiguretohaunt
yourdreams.</p>
</dd>
<dt>FigureEx-1</dt>
</figure>
<p>Maybesomemorecontenthere.</p>
</body>
</html>
246 Part I: Core Markup
Compatibility
HTML5 Not currently supported by any browser, but addressed with a custom element.
Notes
• Whilethiselementisnotyetsupported,itiseasilysimulatedbyusingacustomtag
orusinga<div>tagwithaspecialclass.
• EarlydraftsofHTML5suggestedusinga<legend>tagforcaptioning;later,the
<dt>and<dd>tagswereintroducedforcontainingfigurecaptionandfigure
content,respectively.
Element-Specific Attributes
color Thisattributesetsthetextcolorusingeitherabrowser-dependentnamedcolorora
PART I
colorspecifiedinthehexadecimal#RRGGBBformat.
face Thisattributecontainsalistofoneormorefontnamesseparatedbycommas.The
useragentlooksthroughthespecifiedfontnamesandrendersthetextinthefirstfontthat
issupported.
point-size ThisNetscape4–specificattributespecifiesthepointsizeoftextandisusedwith
downloadablefonts.Itislistedforhistoricalpurposesonlyandiseasilymimickedusingthe
font-sizeCSSproperty.
size Thisattributespecifiesthefontsizeaseitheranumericorrelativevalue.Numeric
valuesrangefrom1to7,with1beingthesmallestand3thedefault.Therelativevalues,+
and-,incrementordecrementthefontsizerelativetothecurrentsize.Thevaluefor
incrementordecrementshouldrangeonlyfrom+1to+6or-1to-6.
weight UnderNetscape4,thisattributespecifiestheweightofthefont,withavalueof100
beinglightestand900beingheaviest.Thisislistedprimarilyforhistoricalpurposes;such
visualchangesarebestimplementedusingthefont-weightCSSproperty.
Example
<p><fontcolor="#FF0000"face="Helvetica,TimesRoman"size="+1">
RelativelylargeredtextinHelveticaorTimes.
</font></p>
Compatibility
HTML 3.2, 4, 4.01 (transitional) Firefox 1+, Internet Explorer 2+,
XHTML 1.0 (transitional) Netscape 1.1+, Opera 4+, Safari 1+
Notes
• Useofthiselementisnotencouraged,asitisnotpartofstrictHTMLandXHTML
specifications.HTML5definesthiselementasobsolete.CSSpropertieslike
font-face,color,andfont-sizeprovidearicherwayofprovidingthesame
functionalityasthiselement.
• Interestingly,thetransitionalspecificationforsomereasondoesnotdefinecore
eventsforthiselement.Inpractice,theyaresupportedbymajorbrowsers.
• Thedefaulttextsizeforadocumentcanbesetusingthesizeattributeofthe
basefontelement.
• TheHTML3.2specificationsupportsonlythecolorandsizeattributesforthis
element.
• HTML5appearstodefineallthecommonattributesforthiselement,butdoesnot
definethosewhichareimportanttoperformitsstatedtask.
248 Part I: Core Markup
<footer> (Footer)
ThisHTML5elementrepresentsthefootersectionofadocumentorasectionelementitis
containedwithin.Likeatypicaldocumentfooterinprint,itshouldcontainsupplementary
informationabouttherelatedcontent.
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>DocumentFooter</title>
</head>
<body>
<header><h1>WelcometotheExample</h1></header>
<p>Yesitisanotherboringexample.</p>
<footer><p>©2010BoringExamples,Inc.</p></footer>
Chapter 3: HTML and XHTML Element Reference 249
</body>
</html>
<!--Simplesectionfooter-->
PART I
<section>
<header>
<h1>SectionHeading</h1>
</header>
<p>SectionBody</p>
<p>MoreBody</p>
<footer>
<p>BoringExample©2010</p>
</footer>
</section>
Compatibility
HTML5 Not currently supported by any browser, but addressed with a custom element.
Notes
• Whilethiselementisnotyetsupported,itiseasilysimulatedbyusingacustomtag
orusinga<div>tagwithaspecialclass.
• AfooterelementshouldbeincludedintheHTML5outliningprocess.
Standard Syntax
<form
accept-charset="listofsupportedcharactersets"
action="URL"
class="classname(s)"
dir="ltr|rtl"
enctype="application/x-www-form-urlencoded|
multipart/form-data|text/plain|
MediaTypeasperRFC2045"
id="uniquealphanumericidentifier"
lang="languagecode"
method="get|post"
name="form'snameforscripting"
style="styleinformation"
target="_blank|framename|_parent|_self|
_top"(transitionalonly)
title="advisorytext">
</form>
250 Part I: Core Markup
Element-Specific Attributes
accept-charset Thisattributespecifiesthelistofcharacterencodingsforinputdatathat
PART I
mustbeacceptedbytheserverprocessingtheform.Thevalueisaspace-orcomma-
delimitedlistofcharactersetsasdefinedinRFC2045.Thedefaultvalueforthisattributeis
thereservedvalueunknown.
action ThisattributecontainstheURLoftheserverprogramthatwillprocessthecontents
oftheform.SomebrowsersalsomightsupportamailtoURL,whichcanmailtheresultsto
thespecifiedaddress.Otherwise,thedeliveryofthedataintheformisdefinedbythe
methodattribute.
autocomplete ThisMicrosoftproprietaryattribute,introducedinInternetExplorer5.0and
redefinedunderHTML5,willautomaticallyfinishfillingininformationthattheuserhas
previouslyinputintoaninputfield.Auto-filledinformationwilllikelybestoredlocallyon
theend-user’ssystembysomeprogram,typicallythebrowseritself.
enctype Thisattributeindicateshowformdatashouldbeencodedbeforebeingsenttothe
server.Thedefaultisapplication/x-www-form-urlencoded.Thisencodingreplaces
blankcharactersinthedatawithapluscharacter(+)andallothernonprintingcharacters
withapercentsign(%)followedbythecharacter’sASCIIHEXrepresentation.The
multipart/form-dataoptiondoesnotperformcharacterconversionandtransfersthe
informationasacompoundMIMEdocument.Thismustbeusedwhenusing<input
type="file">.Italsomightbepossibletouseanotherencoding,suchastext/plain
withamailedform,butingeneralyoushouldbecautiousaboutchangingtheenctype.
method Thisattributeindicateshowforminformationshouldbetransferredtotheserver
usingaparticularHTTPmethod.Agetvalueintheattributeindicatesthatformdata
shouldbeappendedtotheURLspecifiedbytheactionattribute,thuscreatingaquery
string.Thisapproachisquitesimplebutimposesasizelimitationthatisdifficulttogauge
(maybeaslowas2kilobytesinrealsituations).Avalueofpostforthisattributetransfers
thedataoftheforminthemessagebodyusingtheHTTPPOSTmethodwhichimposesno
datasizelimitation.BrowsersmayallowforotherHTTPmethodslikedeleteorputas
suggestedbytheHTML5specification,butsofarsuchusageisrare.ThePOSTmethodmust
beusedwhenfileattachmentsareusedinaform.
name ThisattributespecifiesanamefortheformandwastraditionallyusedbyJavaScript
orotherclient-sideprogrammingtechnologiestoreferenceformsandtheircontained
elements.SinceHTML4,thecoreidattributecanbeusedinsteadwithDOMmethodssuch
asdocument.getElementById().
novalidate ThisHTML5Booleanattributedetermineswhetherornotformvalidation
shouldbeappliedontheelementswithin.Bydefault,validationisenforcedunless
overriddenbythisattributeontheformleveloraformnovalidateattributeisfoundona
formelement.
target Indocumentscontainingframes,thisattributespecifiesthetargetframethatwill
displaytheresultsofaformsubmission.Inadditiontonamedframes,severalspecial
valuesexist.The_blankvalueindicatesanewwindow.The_parentvalueindicates
252 Part I: Core Markup
theparentframesetcontainingthesourcelink.The_selfvalueindicatestheframe
containingthesourcelink.The_topvalueindicatesthefullbrowserwindow.HTML5may
allowfortargetingofnonframedregionsofthepage.
Example
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN""http://www.w3.org/TR/
html4/strict.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>FormTest</title>
</head>
<body>
<formaction="dosomething.php"
method="post"name="testform"onsubmit="returnvalidate();">
<div>
<label><strong>Username:</strong>
<inputtype="text"name="username">
</label>
<br>
<label><strong>Comments:</strong>
<textareaname="comments"cols="30"rows="8"></textarea>
</label>
<br>
<inputtype="submit"value="send">
<inputtype="reset"value="clear">
</div>
</form>
</body>
</html>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• Formcontentisdefinedusingthe<button>,<input>,<select>,and<textarea>
tags,aswellasotherHTMLformattingandstructuringelements.However,they
maynotcontainotherformelements.
• Specialgroupingelements,suchasfieldset,label,andlegend,areprovidedto
structureformfields,butmoreoftentagslike<div>and<table>areusedto
improveformlayout.
• HTML2and3.2supportonlytheaction,enctype,andmethodattributesforthe
formelement.
Standard Syntax
<frame
class="classname(s)"
PART I
frameborder="0|1"
id="uniquealphanumericidentifier"
longdesc="URLofdescription"
marginheight="pixels"
marginwidth="pixels"
name="framename"
noresize="noresize"
scrolling="auto|no|yes"
src="URL"offramecontents"
style="styleinformation"
title="advisorytext">
Element-Specific Attributes
allowtransparency ThisInternetExplorer–specificattributedetermineswhetherthecontents
ofthe<frame>istransparentoropaque.Thedefaultvalueisfalse,whichmeansitis
opaque.
application ThisInternetExplorer–specificattributeisusedtoindicatewhetherthecontent
ofa<frame>istobeconsideredanHTMLapplication(HTA).HTAsareapplicationsthat
useHTML,JavaScript,andInternetExplorer,butarenotlimitedtothetypicaltypeof
254 Part I: Core Markup
securityconsiderationsofaWebpage.Givenitssecurityimplications,thisattributeshould
onlybesetifthedeveloperisfamiliarwithHTAs.
bordercolor Thisattributesetsthecoloroftheframe’sborderusingeitheranamedcoloror
acolorspecifiedinthehexadecimal#RRGGBBformat.
frameborder Thisattributedetermineswhethertheframeissurroundedbyanoutlined
three-dimensionalborder.TheHTMLspecificationpreferstheuseof1fortheframeborder
on,and0foroff;mostbrowsersalsoacknowledgetheuseofnoandyes.
longdesc ThisattributespecifiestheURLofadocumentthatcontainsalongdescriptionof
theframe’scontent.Thisattributeshouldbeusedinconjunctionwiththetitleelement.
marginheight Thisattributesetstheheight,inpixels,betweentheframe’scontentandits
topandbottomborders.
marginwidth Thisattributesetsthewidth,inpixels,betweentheframe’scontentanditsleft
andrightborders.
name Thisattributeassignsanametotheframesothatitcanbethetargetdestinationof
hyperlinksaswellasapossiblecandidateformanipulationviaascript.
noresize Thisattributeoverridesthedefaultabilitytoresizeframesandgivestheframea
fixedsize.
scrolling Thisattributedetermineswhethertheframehasscrollbars.Ayesvalueforces
scrollbars,anovalueprohibitsthem,andanautovalueletsthebrowserdecide.Whennot
specified,thedefaultvalueofautoisused.Authorsarerecommendedtoleavethevalueas
auto.Ifyouturnoffscrollingandthecontentsendupbeingtoolargefortheframe(dueto
renderingdifferences,windowsize,andsoforth),theuserwillnotbeabletoscrolltosee
therestofthecontents.Ifyouturnscrollingonandthecontentsallfitintheframe,the
scrollbarswillneedlesslyconsumescreenspace.Withtheautovalue,scrollbarsappear
onlywhenneeded.
security Thisattributesetsthevalueindicatingwhetherthesourcefileofaframehas
securityrestrictionsapplied.Theonlyallowedvalueisrestricted.
src ThisattributecontainstheURLofthecontentstobedisplayedintheframe.Ifitis
absent,nothingwillbeloadedintheframe.
Example
<framesetrows="20%,80%">
<framesrc="controls.html"name="controls"noresizescrolling="no">
<framesrc="content.html"name="body">
<noframes>
<p>Error:Noframesupport</p>
</noframes>
</frameset>
Chapter 3: HTML and XHTML Element Reference 255
Compatibility
HTML 4, 4.01 Firefox 1+, Internet Explorer 2+,
PART I
XHTML 1.0 (frameset DTD only) Netscape 2+, Opera 4+, Safari 1+
Notes
• XHTML1.0requiresatrailingslashforthiselement:<frame/>.
• Aframemustbedeclaredaspartofaframeset,assetbyusingthe<frameset>tag,
whichspecifiestheframe’srelationshiptootherframesonapage.Aframeset
occursinaspecialHTMLdocument,inwhichtheframesetelementreplacesthe
bodyelement.Anotherformofframescalledindependentframes,orfloatingframes,
alsoissupported.Floatingframescanbedirectlyembeddedinadocumentwithout
belongingtoaframeset.Thesearedefinedwiththeiframeelement.
• Manybrowsersdonotsupportframesandrequiretheuseofthe<noframes>tag.
• Framesintroducepotentialnavigationdifficulties;theiruseshouldbelimitedto
instancesinwhichtheycanbeshowntohelpnavigationratherthanhinderit.
• HTML5currentlydoesnotincludesupportforframesbeyond<iframe>tags,but
evenifthespecificationcontinuestoavoidthem,developersundoubtedlywill
continuetousethem.
Standard Syntax
<frameset
class="classname(s)"
cols="listofcolumns"
id="uniquealphanumericidentifier"
rows="listofrows"
style="styleinformation"
title="advisorytext">
</frameset>
Standard Events
onload,onunload
Element-Specific Attributes
border Thisattributesetsthewidth,inpixels,offrameborderswithintheframeset.
Settingthevalueto0eliminatesallframeborders.ThisattributeisnotdefinedintheHTML
orXHTMLspecificationbutiswidelysupported.
bordercolor Thisattributesetsthecolorforframeborderswithintheframesetusingeither
anamedcolororacolorspecifiedinthehexadecimal#RRGGBBformat.
cols Thisattributecontainsacomma-delimitedlistthatspecifiesthenumberandsizeof
columnscontainedwithinasetofframes.Listitemsindicatecolumnsfromlefttoright.
Columnsizeisspecifiedinthreeformats,whichmightbemixed.Acolumncanbeassigned
afixedwidth,inpixels.Italsocanbeassignedapercentageoftheavailablewidth,suchas
50percent.Finally,acolumncanbesettoexpandtofilltheavailablespacebysettingthe
valueto*,whichactsasawildcard.
frameborder Thisattributecontrolswhetherornotframebordersshouldbedisplayed.
Netscapesupportsnoandyesvalues.Microsoftuses1and0aswellasnoandyes.
framespacing Thisattributeindicatesthespacebetweenframes,inpixels.
rows Thisattributecontainsacomma-delimitedlistthatspecifiesthenumberandsizeof
rowscontainedwithinasetofframes.Thenumberofentriesinthelistindicatesthenumber
ofrows.Rowsizeisspecifiedwiththesameformatsusedforcolumns.
Examples
<!--Thisexampledefinesaframesetofthreecolumns.Themiddlecolumn
is50pixelswide.Thefirstandlastcolumnsfilltheremainingspace.
-->
<framesetcols="*,50,*">
<framesrc="column1.html">
<framesrc="column2.html">
<framesrc="column3.html">
</frameset>
<!--Thisexampledefinesaframesetoftwocolumns,oneofwhichis20%
ofthescreen,andtheother,80%.-->
Chapter 3: HTML and XHTML Element Reference 257
<framesetcols="20%,80%">
<framesrc="controls.html"name="controls">
<framesrc="display.html"name="body">
<noframes>
PART I
<p>Error:Noframesupport</p>
</noframes>
</frameset>
<!--Thisexampledefinestworows,oneofwhichis10%ofthescreen,
andtheother,whateverspaceisleft.-->
<framesetrows="10%,*">
<framesrc="adbanner.html"name="ad_frame">
<framesrc="contents.html"name="content_frame">
</frameset>
Compatibility
HTML 4 and 4.01 (frameset DTD) Firefox 1+, Internet Explorer 3+,
XHTML 1.0 (frameset DTD) Netscape 2+,
Opera 4+, Safari 1+
Notes
• Thecontentmodelsaysthatthe<frameset>tagcontainsoneormore<frame>
tags,whichareusedtoindicatetheframedcontents.A<frameset>tagalsomight
containa<noframes>tag,whosecontentswillbedisplayedbybrowsersthatdo
notsupportframes.
• HTML5currentlydoesincludesupportforframesbeyondtheinlineframedefined
byan<iframe>tag.
• The<frameset>tagreplacesthe<body>taginaframingdocument,asshown
here:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml"lang="en">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>FrameDemo</title>
</head>
<framesetcols="*,50,*">
<framesrc="column1.html"name="col1"/>
<framesrc="column2.html"name="col2"/>
<framesrc="column3.html"name="col3"/>
<noframes>
<body>
<p>Pleasevisitour<ahref="noframes.html">noframes</a>site.</p>
</body>
</noframes>
</frameset>
</html>
258 Part I: Core Markup
Standard Syntax
<h1
align="center|justify|left|right"
(transitionalonly)
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</h1>
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
PART I
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Examples
<h1align="justify">ThisisaMajorDocumentHeading</h1>
<h2align="center=">Secondheading,alignedtothecenter</h2>
<h3align="right">Thirdheading,alignedtotheright</h3>
<h4>Fourthheading</h4>
<h5style="font-size:20px;">Fifthheadingwithstyleinformation</h5>
<h6>Theleastimportantheading</h6>
<!--HTML5example-->
<section>
<header>
<h1>SectionHeading</h1>
<h2>SectionSub-head</h2>
</header>
<p>Sectionbody</p>
</section>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• Inmostimplementations,headingnumberscorrespondinverselywiththesixfont
sizessupportedbythefontelement.Forexample,<h1>correspondsto<font
size="6">.Thedefaultfontsizeis3.However,thisapproachtolayoutisnot
encouraged,andpagedesignersshouldconsiderusingstylestosetevenrelative
sizes.Interestingly,theHTML5specificationalsoclearlyindicatesthefontsizeof
variousheadingslikeh1(2em),h2(1.5em),andsoon,whichisreallynotany
differentfromtherelativenatureofolder<font>tags.
• HTML3.2supportsonlythealignattribute.HTML2doesnotsupportany
attributesforheadings.
260 Part I: Core Markup
• ThestrictdefinitionsofHTML4andXHTMLdonotincludesupportforthealign
attribute.Stylesheetpropertiesliketext-alignshouldbeusedinstead.
• UnderHTML5,theseheadingelementsareusedtoformanoutlineofthedocument.
Standard Syntax
<head
dir="ltr|rtl"
lang="languagecode"
profile="URL">
title,base,script,style,meta,linkandobjectelements
</head>
PART I
Element-Specific Attribute
profile ThisattributespecifiesaURLforameta-informationdictionary.Thespecified
profileshouldindicatetheformatofallowedmetadataanditsmeaning.
Examples
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN""http://www.w3.org/TR/
html4/strict.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>DemoCompanyHomePage</title>
<basehref="http://www.democompany.com">
<metaname="Keywords"content="DemoCompany,SuperWidget">
</head>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN""http://www.w3.org/TR/
html4/strict.dtd">
<html>
<headprofile="http://www.democompany.com/metadict.xml">
Compatibility
HTML 2, 3.2, 4, 4.01, 5+ Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Notes
• UndertheXHTML1.0specification,theheadelementnolongercanbeimplied,but
rathermustbeusedinalldocumentsandmusthaveaclosetag.Understandard,
olderHTMLspecificationsaswellasHTML5,theelementisactuallyoptional.
• Often,a<meta>tagspecifyingthecharactersetinplayshouldbefoundasthefirst
childoftheheadelement,particularlyifthedocument’stitleelementcontains
specialcharacters.
• Themeaningoftheprofileattributeissomewhatunclear,andnobrowsersappear
tosupportitinanymeaningfulway.
• HTML2and3.2supportnoattributesforthiselement.
<header> (Header)
ThisHTML5elementrepresentstheheadersectionofadocumentorasectionelementitis
containedwithin.Likeatypicaldocumentheaderinprint,itshouldcontaintitleand
headinginformationabouttherelatedcontent.
262 Part I: Core Markup
Examples
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>DocumentHeader</title>
</head>
<body>
<header>
<h1>WelcometotheExample</h1>
<h2>Themoreexcitingsubheading</h2>
</header>
<p>Yesitisyetanotherboringexample.</p>
<footer><p>©2010BoringExamples,Inc.</p></footer>
</body>
</html>
Chapter 3: HTML and XHTML Element Reference 263
<!--Simplesectionheader-->
<section>
<header>
<p>Itwasadarkandstorynight...</p>
PART I
<h1>TheSpookyHeading</h1>
</header>
<p>Afantasticstorythatisspookywouldbefoundhere.
IfIweren'tsobusywritingHTML5examples.</p>
<footer>
<p><cite>HTML:TheCompleteReference</cite>©2010</p>
</footer>
</section>
Compatibility
HTML5 Not currently supported by any browser, but addressed with a custom element.
Notes
• UnderHTML5,thiselementmaybeusedforautomaticdocumentoutlining.
• Whilethiselementisnotyetsupported,itiseasilysimulatedbyusingacustomtag
orusinga<div>tagwithaspecialclass.
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>hgroupExample</title>
</head>
<body>
<header>
<hgroup>
<h1>WelcometotheExample</h1>
<h2>Clearlythebestexampleyou'veseen</h2>
</hgroup>
<nav>
<ul>
<li><ahref="#">Link</a></li>
<li><ahref="#">Link</a></li>
<li><ahref="#">Link</a></li>
<li><ahref="#">Link</a></li>
</ul>
</nav>
</header>
<hgroup>
<h1>Sectionhead</h1>
<h2>Asubhead</h2>
</hgroup>
<p>Okherewegosomecontenthere.</p>
<p>Morecontentgoeshereandhere.</p>
<footer><p>©2010BoringExamples,Inc.</p></footer>
</body>
</html>
Compatibility
HTML5 Not currently supported by any browser, but addressed with a custom element.
Chapter 3: HTML and XHTML Element Reference 265
Notes
• ThehgroupelementisusedtocontroltheHTML5sectioningalgorithm.Itsprimary
purposeistocollapseelementsthatwouldnormallyaddoutlineentriesintoa
PART I
singleentry.Forexample,whenmultipleheadings(h1–h6)areused,theywill
individuallyadditemstotheoutline.Bycontainingheadingstogetherinthe
hgroupelement,theyformonlyasingleentryinanoutline.Asdemonstratedinthe
precedingexample,theneedforthiselementismostlytosupportsubheadings.
• ThiselementwasaddedmuchlaterthanmanyotherHTML5elements,andthereis
somecontroversyoverwhatitshouldbecalled.
• Whilethiselementisnotyetsupported,itiseasilysimulatedbyusingacustomtag
orusinga<div>tagwithaspecialclass.
Standard Syntax
<hr
align="center|left|right"(transitionalonly)
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"id="uniquealphanumericidentifier"
noshade="noshade"(transitionalonly)
size="pixels"(transitionalonly)
style="styleinformation"
title="advisoryinformation"
width="percentage|pixels">(transitionalonly)
hidefocus="true|false"(5.5)
tabindex="number"(5.5)
unselectable="on|off"(5.5)
Element-Specific Attributes
color Thisattributesetstherulecolorusingeitheranamedcolororacolorspecifiedinthe
hexadecimal#RRGGBBformat.ThisattributecurrentlyissupportedonlybyInternet
Explorer.
noshade Thisattributecausestheruletoberenderedasasolidbarwithoutshading.
size Thisattributeindicatestheheight,inpixels,oftherule.
width Thisattributeindicateshowwidetheruleshouldbe,specifiedeitherinpixelsorasa
percentofscreenwidth,suchas80%.
Examples
<!--transitionalrules-->
<hralign="left"noshade="noshade"size="1"width="420">
<hralign="center"width="100%"size="3"color="#000000"/>
<!--simpleXHTMLstyle-->
<hr/>
Chapter 3: HTML and XHTML Element Reference 267
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
PART I
XHTML 1.0, 1.1 Netscape 1+, Opera 4+, Safari 1+
Notes
• TheHTML4.01strictandHTML5specificationsremovesupportforthealign,
noshade,size,andwidthattributesforhorizontalrules.Theseeffectsarepossible
usingstylesheets.
• AsanemptyelementunderXHTMLorwhenusingXML-stylesyntaxforHTML5,a
trailingslashisrequiredforthiselement:<hr/>.
Standard Syntax
<html
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
xmlns="http://www.w3.org/1999/xhtml|someothernamespace">
</html>
Element-Specific Attributes
manifest ThisHTML5attributeissettothedocument’sapplicationcachemanifest,which
isusedtodescribethevariouscomponentsthepagereliesupon.Itisgenerallyusedto
supportofflineaccess.
scroll Thisattributeisusedtosetwhetherornotscrollbarsshouldshowforthe
document.Thedefaultvalueofautoputsinscrollbarsasneeded.Thisattribute,while
documentedbyMicrosoft,doesnotappeartoworkproperlyandshouldbeavoided.
xmlns ThisattributedeclaresanamespaceforXML-basedcustomtagsinthedocument.
ForXHTML,thisvalueisalwayshttp://www.w3.org/1999/xhtml,thoughitcouldbe
someothervalueinthecaseofsomecustomlanguageormixtureoflanguages.
version ThisInternetExplorer6–specificattributewasusedtoindicatetheversionof
HTMLbeingused.Itisnolongerusedbecauseitisredundantofwhatisprovidedbythe
<!DOCTYPE>statement.
Example
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml"lang="en">
<head>
<title>MinimalDocument</title>
<metahttp-equiv="content-type"content="text/html;charset=ISO-8859-1"/>
</head>
<body>
<p>Helloworld!</p>
</body>
</html>
Compatibility
HTML 2, 3.2, 4, 4.01,5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Chapter 3: HTML and XHTML Element Reference 269
Notes
• Thehtmlelementisthefirstelementinadocument.Exceptforcomments,theonly
tagsitdirectlycontainsare<head>followedbyeither<body>or<frameset>.
PART I
• Becauseitistheoutermosttaginadocument,thehtmlelementiscalledtheroot
element.
• The<html>taganditsclosingtag</html>arebothmandatoryunderXHTML.
Underotherspecifications,includingHTML5,theelementisactuallyoptional
becauseitisimpliedunlessacommentisfoundasthefirstitemwithinthe
document.
<i> (Italic)
Thiselementindicatesthattheenclosedtextshouldbedisplayedinanitalictypeface.
Standard Syntax
<i
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</i>
Examples
<p>Hereissome<i>italicized</i>text.
Thisisalso<istyle="color:red;"id="myItalic">italic</i></p>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
longdesc="URLofdescription"
marginheight="pixels"
marginwidth="pixels"
name="string"
PART I
scrolling="auto|no|yes"
src="URLofframecontents"
style="styleinformation"
title="advisorytext"
width="percentage|pixels">
</iframe>
Element-Specific Attributes
allowtransparency ThisInternetExplorer–specificattributedetermineswhetherthecontent
ofan<iframe>istransparentoropaque.Thedefaultvalueisfalse,whichmeansitis
opaque.
application ThisMicrosoft-specificattributeisusedtoindicatewhetherthecontentsofan
<iframe>aretobeconsideredanHTMLapplication(HTA).HTAsareapplicationsthatuse
HTML,JavaScript,andInternetExplorerbutarenotlimitedtothetypicaltypeofsecurity
considerationsofaWebpage.Givenitssecurityimplications,thisattributeshouldonlybe
setifthedeveloperisfamiliarwithHTAs.
border Thisattributespecifiesthethicknessoftheborder,inpixels.
bordercolor Thisattributespecifiesthecoloroftheborder.
frameborder Thisattributedetermineswhethertheiframeissurroundedbyaborder.The
HTML4specificationdefines0tobeoffand1tobeon.Thedefaultvalueis1.Internet
Exploreralsodefinesthevaluesnoandyes.
framespacing Thisattributecreatesadditionalspacebetweentheframes.
longdesc ThisattributespecifiestheURLofadocumentthatcontainsalongdescriptionof
theframe’scontents.
marginheight Thisattributesetstheheight,inpixels,betweenthefloatingframe’scontent
anditstopandbottomborders.
marginwidth Thisattributesetsthewidth,inpixels,betweenthefloatingframe’scontent
anditsleftandrightborders.
name Thisattributeassignsanametothefloatingframesothatitcanbethetarget
destinationofhyperlinks.
Chapter 3: HTML and XHTML Element Reference 273
sandbox ThisHTML5attributeconstrainstheabilitiesofanyiframedcontent.Itmay
containaspace-separatedlistofexceptionsonincludediframecontent.Currentlysupported
valuesincludeallow-same-origin,allow-scripts,andallow-forms.Bydefault,the
PART I
includedcontentwillbehighlyrestricted,buteachallowvaluewillextendthesandboxto
allowtheincludedcontenttotalktoitsorigindomain(allow-same-origin),invoke
scripting(allow-scripts),orpostforms(allow-forms).
scrolling Thisattributedetermineswhethertheframehasscrollbars.Ayesvalueforces
scrollbars;anovalueprohibitsthem.Thedefaultvalueisauto,inwhichcasescrollbars
appearonlyasneeded.
seamless ThisHTML5Booleanattributeissettomaketheiframeberenderedinsucha
waythatitappearstobepartoftheprimarybrowsingcontext.
security Thisattributesetsthevalueindicatingwhetherthesourcefileofaniframehas
securityrestrictionsapplied.Theonlyallowedvalueisrestricted.
src ThisattributecontainstheURLofthecontenttobedisplayedinthefloatingframe.If
absent,theframeisblank.
Examples
<iframesrc="http://www.democompany.com"height="150"width="200"
name="FloatingFrame1">
Sorry,yourbrowserdoesn'tsupportinlineframes.
</iframe>
<!--HTML5examplehighlyrestricted-->
<iframesrc="http://www.fakewebgadets.com/gadget"height="200"width="200"
id="chat"sandbox>
</iframe>
<!--HTML5examplelessrestricted-->
<iframesrc="http://www.fakewebgadets.com/gadget2"height="200"width="200"
id="weather"sandbox="allow-same-originallow-scripts"seamless>
</iframe>
Compatibility
HTML 4 (transitional), 5 Firefox 1+, Internet Explorer 3+,
XHTML 1.0 (transitional or frameset) Netscape 6+, Opera 5+, Safari 1+
Notes
• UndertheHTML4strictspecification,theiframeelementisnotdefined.However,
underXHTMLtransitionalandXHTMLframeset,iframeisallowed.XHTML1.1
doesnotallowiteither.Floatingframescanbeimitatedusingthedivelementand
CSSpositioningfacilities.
• Iframesareusefulfornotonlyincludingcontentfromwithinasiteorbeyond,but
alsoasacommunicationmechanismsimilartoAjax.
274 Part I: Core Markup
• HTML5includestheiframebutdoesnotincludestandardframes.
• Whenabrowserdoesnotunderstandan<iframe>tag,itdisplaysthetextincluded
withinitasanalternaterendering.
Element-Specific Attributes
above Thisattributecontainsthenameofthelayertoberenderedabovethecurrentlayer.
background ThisattributecontainstheURLofabackgroundimageforthelayer.
below Thisattributecontainsthenameofthelayertoberenderedbelowthecurrentlayer.
bgcolor Thisattributespecifiesalayer’sbackgroundcolor.Itsvaluecanbeeitheranamed
colororacolorspecifiedinthehexadecimal#RRGGBBformat.
clip Thisattributespecifiestheclippingregionorviewableareaofthelayer.Alllayer
contentoutsidethatrectanglewillberenderedastransparent.Thecliprectangleisdefined
Chapter 3: HTML and XHTML Element Reference 275
bytwox,ypairs:topx,leftyandbottomx,andrighty.Coordinatesarerelativetothe
layer’soriginpoint,0,0,initstop-leftcorner.
PART I
height Thisattributespecifiestheheightofalayer,inpixelsorasapercentagevalue.
left Thisattributespecifies,inpixels,thehorizontaloffsetofthelayer.Theoffsetisrelative
toitsparentlayer,ifithasone,ortotheleftpagemarginifitdoesnot.
name Thisattributeassignstothelayeranamethatcanbereferencedbyprogramsina
client-sidescriptinglanguage.Theidattributealsocanbeused.
pagex Thisattributespecifiesthehorizontalpositionofthelayerrelativetothebrowser
window.
pagey Thisattributespecifiestheverticalpositionofthelayerrelativetothebrowser
window.
src ThisattributeisusedtosettheURLofafilethatcontainsthecontenttobeloadedinto
thelayer.
top Thisattributespecifies,inpixels,thetopoffsetofthelayer.Theoffsetisrelativetoits
parentlayer,ifithasone,orthetoppagemarginifitdoesnot.
visibility Thisattributespecifieswhetheralayerishidden,shown,orinheritsitsvisibility
fromthelayerthatincludesit.
width Thisattributespecifiesalayer’swidth,inpixels.
z-index Thisattributespecifiesalayer’sstackingorderrelativetootherlayers.Positionis
specifiedwithpositiveintegers,with1indicatingthebottommostlayer.
Example
<p>Contentcomesbefore.</p>
<ilayername="background"bgcolor="green">
<p>Layeredinformationgoeshere.</p>
</ilayer>
<p>Contentcomesafter.</p>
Compatibility
No standards support Netscape 4, 4.5–4.8
Note
• Pagedevelopersarestronglyencouragednottousethiselementbutinsteaduse
<div>tagswithCSSrelativepositioning.Netscapedroppedthiselementfor
browserversions6.0andhigher.Itsinclusioninthisbookisforsupportofexisting
documentsonly.
276 Part I: Core Markup
<img> (Image)
Thiselementindicatesamediaobjecttobeincludedinan(X)HTMLdocument.Usually,the
objectisabitmapgraphicimage,butsomeimplementationssupportmovies,vector
formats,andanimations.
Standard Syntax
<img
align="bottom|left|middle|right|top"(transitionalonly)
alt="alternativetext"
border="pixels"(transitionalonly)
class="classname(s)"
dir="ltr|rtl"
height="pixels"
hspace="pixels"(transitionalonly)
id="uniquealphanumericidentifier"
ismap="ismap"
lang="languagecode"
longdesc="URLofdescriptionfile"
name="uniquealphanumericidentifier"
src="URLofimage"
style="styleinformation"
title="advisorytext"
usemap="URLofmapfile"
vspace="pixels"(transitionalonly)
width="pixels">
dynsrc="URLofmovie"(4)
galleryimg="yes|no|true|false"(6)
hidefocus="true|false"(5.5)
language="javascript|jscript|vbs|vbscript"(4)
PART I
loop="infinite|number"(4)
start="fileopen|mouseover"(5)
unselectable="on|off"(5.5)
Element-Specific Attributes
align Thisattributecontrolsthehorizontalalignmentoftheimagewithrespecttothepage.
Thedefaultvalueisleft.Manybrowsers,suchasNetscapeandInternetExplorer
implementations,supporttheabsbottom,absmiddle,baseline,andtexttopvalues.This
attributeisdeprecatedunderstrictvariantsof(X)HTMLaswellasHTML5.
alt Thisattributecontainsastringtobedisplayedinsteadoftheimageforbrowsersthat
cannotdisplayimages.
border Thisattributeindicatesthewidth,inpixels,ofthebordersurroundingtheimage.
HTML5suggeststheelementshouldnotbeusedotherthantosetavalueof0,asCSS
shouldbeusedinstead.
278 Part I: Core Markup
dynsrc IntheMicrosoftimplementation,thisattributeindicatestheURLofamoviefileand
isusedinsteadofthesrcattribute.Commonformatsusedhereare.avi(Audio-Visual
Interleaved),.mov(QuickTime),and.mpgand.mpeg(MotionPictureExpertsGroup).Be
careful,becausesupportofthisattributebeyondInternetExplorer6issuspectandsecurity
settingsmayrestrictit.
galleryimg ThisMicrosoftattributeisusedtocontrolwhetherthegalleryimagemenushould
appearwhenthemousepointerhoversoveranimage.Thedefaultvalueistrueoryes.Avalue
ofnoorfalsesuppressesthemenu.Ametataglike<metahttp-equiv="imagetoolbar"
content="no">canbeusedtosuppresstheimagetoolbardocument-wide.Thisattributeis
renderedobsoleteinlaterversionsofInternetExplorer(7+).
ismap Thisattributeindicatesthattheimageisaserver-sideimagemap.Usermouse
actionsovertheimagearesenttotheserverforprocessing.
longdesc ThisattributespecifiestheURLofadocumentthatcontainsalongdescriptionof
theimage.Thisattributeisusedasacomplementtothealtattribute.
loop IntheMicrosoftimplementation,thisattributeisusedwiththedynsrcattributeto
causeamovietoloop.Itsvalueiseitheranumericloopcountorthekeywordinfinite.
LaterversionsofInternetExplorersuggestusing–1toindicateinfinite.Sinceitisrelatedto
dynsrc,theuseof<img>toplaymoviesdoesnotworkpastInternetExplorer6unless
securitysettingsaremodified.
lowsrc Thisnonstandardattribute,supportedinmostbrowsers,containstheURLofan
imagetobeinitiallyloaded.Typically,thelowsrcimageisalow-resolutionorblack-and-
whiteimagethatprovidesaquickpreviewoftheimagetofollow.Oncetheprimaryimage
isloaded,itreplacesthelowsrcimage.
name Thiscommonattributeisusedtobindanametotheimage.Olderbrowsers
understandthenamefield,and,inconjunctionwithscriptinglanguages,itispossibleto
manipulateimagesbytheirdefinednamestocreateeffectssuchas“rollover”buttons.
UndermodernversionsofHTMLandXHTML,theidattributeshouldbeusedasan
elementidentifierforscriptingandstyleapplication.Thenameattributecanstillbeusedfor
backwardcompatibility.
src ThisattributeindicatestheURLofanimagefiletobedisplayed.Mostbrowserswill
display.gif,.jpeg,and.pngfilesdirectly.Olderformatslike.bmp,.xpm(XBitmap),and
.xpm(XPixelmap)arealsocommonlysupported,thoughtheiruseisneverrecommended.
Somemodernbrowsersmaysupport.svg(ScalableVectorGraphics)filesaswellwiththe
imgelement.
start IntheMicrosoftimplementation,thisattributeisusedwiththedynsrcattributeto
indicatewhenamovieshouldplay.Thedefaultvalue,ifnovalueisspecified,istoplaythe
videoassoonasithasfinishedloading.Thiscanbeexplicitlysetwithavalueoffileopen.
Alternatively,avalueofmouseovercanbesettoplaythemoveoncetheuserhasmoved
theirmouseoverthevideo.This,likeotherdynsrcfeatures,maynotworkpastInternet
Explorer6browsersbecauseofsecuritychanges.
Chapter 3: HTML and XHTML Element Reference 279
usemap Thisattributemakestheimagesupportclient-sideimagemapping.Itsargumentis
aURLspecifyingthemapfile,whichassociatesimageregionswithhyperlinks.TheURLis
generallyafragmentidentifierthatreferencesalocationinthecurrentdocumentrather
PART I
thanaremoteresource.
Examples
<imgsrc="graham.jpg"alt="GrahamAllan"height="320"width="150">
<imgsrc="olivia.jpg"lowsrc="loading.jpg"border="0"height="50%"
width="50%"alt="PictureofOlivia"longdesc="olivia-bio.html">
<ahref="home.html"><imgsrc="homebutton.png"width="50"height="20"
alt="LinktoHomePage"/></a>
<!--xhtmlstylesyntax-->
<imgsrc="hugeimagemap.gif"usemap="#mainmap"border="0"height="200"
width="200"alt="ImageMapHere"/>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Notes
• Typically,whenyouusetheusemapattribute,theURLisafragment,suchas
#map1,ratherthanafullURL.Somebrowsersdonotsupportexternalclient-side
mapfiles.HTML5makesthisstatementmorestronglythaninotherspecifications.
• UnderthestrictHTMLandXHTMLdefinitions,the<img>tagdoesnotsupport
align,border,height,hspace,vspace,andwidth.Thefunctionalityofthese
attributesshouldbepossibleusingstylesheetrules.
• WhereastheHTML4specificationreservesdata-bindingattributessuchasdatafld
ordatasrcformanyelements,theyarenotspecifiedfor<img>;however,Internet
Explorerprovidessupportfortheseattributes.
• AsanemptyelementunderXHTMLorwhenusingXML-stylesyntaxforHTML5,
atrailingslashisrequiredforthiselement:<img/>.
• UnderfutureversionsofXHTMLsuchas2,<img>maybedroppedinfavorof
<object>.
• ItshouldbenotedthatsomecoreattributesforHTML5,mostnoticably
spellcheck,makelittlesensewithinthemeaningofthiselement.
Standard Syntax
<input
accept="MIMEtypes"
accesskey="character"
align="bottom|left|middle|right|top"(transitionalonly)
alt="text"
checked="checked"
class="classname(s)"
dir="ltr|rtl"
disabled="disabled"
id="uniquealphanumericidentifier"
lang="languagecode"
maxlength="maximumfieldsize"
name="fieldname"
readonly="readonly"
size="fieldsize"
src="URLofimagefile"
style="styleinformation"
tabindex="number"
title="advisorytext"
type="button|checkbox|file|hidden|image|
password|radio|reset|submit|text"
usemap="URLofmapfile"
value="fieldvalue">
spellcheck="true|false"
step="float"
type=oldertypevaluesfromabove|color|date|datetime|
datetime-local|email|list|number|month|range|
PART I
tel|time|url|search|week
width="pixels"
onpropertychange,onreadystatechange,onresize(button,file,image,
password,reset,submit,text),onresizeend,onresizestart,onselectstart
(alltypesexcepthidden),ontimeerror
Element-Specific Attributes
accept ThisattributeisusedtolisttheMIMEtypesacceptedforfileuploadswhenusinga
fileuploadcontrol(<inputtype="file">).
align Withimageformcontrols(type="image"),thisattributealignstheimagewith
respecttosurroundingtext.TheHTML4.01transitionalspecificationdefinesbottom,left,
middle,right,andtopasallowablevalues.NetscapeandMicrosoftbrowsersmightalso
allowtheuseofattributevaluessuchasabsbottomorabsmiddle.Likeotherpresentation-
specificaspectsofHTML,thealignattributeisdroppedunderthestrictHTML4.01
specification.
alt Thisattributeisusedtodisplayanalternativedescriptionofimagebuttonsfortext-
onlybrowsers.Themeaningofaltforformsof<input>beyondtype="input"isnot
defined.
autocomplete ThisMicrosoft-specificattributeisusedtoindicatewhetherornottheform
fieldshouldbeautomaticallyfilledin.Thedefaultvalueisno.HTML5alsosupportsthis
attribute.
autofocus ThisHTML5Booleanattributeisusedtoindicatethattheuseragentshould
immediatelyfocusthisformitemonceitscontainingwindowobject(usuallythedocument)
ismadeactive.ItonlytakesanattributevalueofautofocuswhenusingtheXML-style
syntaxforHTML5.Itisnotdefinedfor<inputtype="hidden">.
checked Thecheckedattributeshouldbeusedonlyforcheckbox(type="checkbox")
andradio(type="radio")formcontrols.Thepresenceofthisattributeindicatesthatthe
controlshouldbedisplayedinitscheckedstate.
disabled Thisattributeisusedtoturnoffaformcontrol.Elementswillnotbesubmitted,
norwilltheyreceiveanyfocusfromthekeyboardormouse.Disabledformcontrolswillnot
bepartofthetabbingorder.Thebrowseralsomightgrayouttheformthatisdisabled,to
indicatetotheuserthattheformcontrolisinactive.Thisattributerequiresnovalue.
dynsrc IntheMicrosoftimplementation,thisattributeindicatestheURLofamoviefileand
isusedinsteadofthesrcattributefor<inputtype="image">.
form ThisHTML5attributeshouldbesettoastringthatcorrespondstotheidoftheform
elementthataninteractivecontrolsuchasabuttonisassociatedwith.Thisallowsform
elementsinoneformtotriggeractionsinothers.
formaction ThisHTML5attributespecifiesaURLtotargetwhenthebuttonisclicked,
similartotheuseoftheactionattributeonaformelement.
formenctype Thisattributeindicateshowformdatashouldbeencodedbeforebeingsentto
theserver.Thedefaultisapplication/x-www-form-urlencoded.Thisencodingreplaces
Chapter 3: HTML and XHTML Element Reference 283
blankcharactersinthedatawithapluscharacter(+)andallothernonprintingcharacters
withapercentsign(%)followedbythecharacter’sASCIIHEXrepresentation.The
multipart/form-dataoptiondoesnotperformcharacterconversionandtransfersthe
PART I
informationasacompoundMIMEdocument.Thismustbeusedwhenusing<input-
type="file">.Italsomightbepossibletouseanotherencoding,suchastext/plain
withamailedform,butingeneralyoushouldbecautiousaboutchangingtheenctype.
formmethod ThisHTML5attributeindicateshowforminformationshouldbetransferred
totheserverusingaparticularHTTPmethod.Agetvalueintheattributeindicatesthat
formdatashouldbeappendedtotheURLspecifiedbytheactionattributethuscreatinga
querystring.Thisapproachisquitesimplebutimposesasizelimitationthatisdifficultto
gauge(maybeaslowas2kilobytesinrealsituations).Avalueofpostforthisattribute
transfersthedataoftheforminthemessagebodyusingtheHTTPPOSTmethod,which
imposesnodatasizelimitation.BrowsersmayallowforotherHTTPmethodslikedelete
orput,assuggestedbytheHTML5specification,butsofarsuchusageisrare.ThePOST
methodmustbeusedwhenfileattachmentsareusedinaform.
formnovalidate ThisHTML5Booleanattributeisusedtoindicateaformshouldnotbe
validatedduringsubmission.Itisfalsebydefaultbutmaybecontrolledeitheronthe
buttondirectlyoronacontainingorrelatedform.Initiallythiswassimplyknownas
novalidate.
formtarget ThisHTML5attributeissettothenameofawindoworframethatthebutton
willtargettheresultofaction;inotherwords,wheretheresultshouldappear.Thisactionis
similartothetargetattributeon<a>and<form>tags.Initially,thisattributewassimply
targetinearlydraftsofHTML5.
height DefinedunderHTML5,thoughcommonlysupportedinolderbrowsers,this
attributeisusedtosizeaninputelementparticularlywhenimagesareusedasin<input
type="image">.CSSpropertiesarepreferred.
hspace ThisInternetExplorer–specificattributeindicatesthehorizontalspace,inpixels,
betweentheimageandsurroundingtextwhenusing<inputtype="image">.
list TheHTML5listattributeisusedtosettheidofadatalistelementusedto
provideapredefinedlistofoptionssuggestedtotheuserforentry.
loop IntheMicrosoftimplementation,thisattributeisusedwith<inputtype="image">
andthedynsrcattributetocauseamovietoloop.Itsvalueiseitheranumericloopcount
orthekeywordinfinite.LaterversionsofInternetExplorersuggestusing–1toindicate
infinite.
lowsrc ThisMicrosoft-supportedattributecontainstheURLofanimagetobeinitially
loadedwhenusing<inputtype="image">.Typically,thelowsrcimageisalow-
resolutionorblack-and-whiteimagethatprovidesaquickpreviewoftheimagetofollow.
Oncetheprimaryimageisloaded,itreplacesthelowsrcimage.
max ThisHTML5attributeshouldbesettoanumericvaluethatisthehighrangeallowed
intheformcontrol.Theminattributesetsthelowrange.
284 Part I: Core Markup
maxlength Thisattributeindicatesthemaximumcontentlengththatcanbeenteredina
textformcontrol(type="text").Themaximumnumberofcharactersalloweddiffersfrom
thevisibledimensionoftheformcontrol,whichissetwiththesizeattribute.
min ThisHTML5attributeshouldbesettoanumericvaluethatisthelowrangeallowed
intheformcontrol.Themaxattributesetsthehighrange.
multiple ThisHTML5Booleanattribute,whensettotrue,indicatesthatmultiplevalues
areallowedforthefield.
name Thisattributeallowsaformcontroltobeassignedanametosetasthename/value
pairvaluesenttotheserver.Traditionally,thisvaluewasalsousedforreferencebya
scriptinglanguage,butusingtheidvalueismoreappropriate.However,giventhat
browserssometimesfavortheoldersyntax,bothmayoftenbeusedandsettothesame
value,withsomelimitations,particularlywithradiobuttons.
pattern ThisHTML5attributespecifiesaregularexpressionagainstwhichthefieldshould
bevalidated.Thetitleattributeshouldbeprovidedwhenthisattributeisused,togivean
indicationofwhatisanacceptablepatternandwhatisn’t.
placeholder ThisHTML5attributespecifiesashortbitoftextthatisusedtohelptheuser
figureoutwhattypeofinformationtofillinforaformcontrol.Likely,thetextwillbe
placedinthefieldandcleareduponfocus.
readonly Thisattributepreventstheformcontrol’svaluefrombeingchanged.Form
controlswiththisattributesetmightreceivefocusfromtheuserbutnotpermittheuserto
modifythevalue.Becauseitreceivesfocus,areadonlyformcontrolwillbepartofthe
form’stabbingorder.Thecontrol’svaluewillbesentonformsubmission.Thisattributecan
beusedonlywith<input>whentypeissettotextorpassword.Theattributealsois
usedwiththetextareaelement.
required ThepresenceofthisHTML5Booleanattributeindicatesthattheformfieldmust
besetinorderforformsubmissiontoproceed.Useragentsthatunderstandthisshouldset
theCSSpseudo-class:invalidwhenthefieldgoesintoerror.
size Thisattributeindicatesthevisibledimension,incharacters,ofatextformcontrol
(type="text").Thisdiffersfromthemaximumlengthofcontent,whichcanbeenteredina
formcontrolsetbythemaxlengthattribute.
src Thisattributeisusedwithimageformcontrols(type="image")tospecifytheURLof
theimagefiletoload.
step ThisHTML5attributedefinesthestepinwhichvaluescantake;forexample,bytwos
(2,4,6…)ortens(10,20,30…).Itisgenerallyusedinrangecontrols.
tabindex Thisattributetakesanumericvaluethatindicatesthepositionoftheformcontrol
inthetabbingindexfortheform.Tabbingproceedsfromthelowestpositivetabindex
valuetothehighest.Negativevaluesfortabindexwillleavetheformcontroloutofthe
tabbingorder.Whentabbingisnotexplicitlyset,thebrowsertabsthroughitemsinthe
Chapter 3: HTML and XHTML Element Reference 285
ordertheyareencountered.Disabledformfieldswillnotbepartofthetabbingindex,
althoughread-onlycontrolswillbe.
PART I
type Thisattributespecifiesthetypeoftheformcontrol.Avalueofbuttonindicatesa
general-purposebuttonwithnowell-definedmeaning.However,anactioncanbe
associatedwiththebuttonbyusinganeventhandlerattribute,suchasonclick.Avalueof
checkboxindicatesacheckboxcontrol.Checkboxformcontrolshaveacheckedand
uncheckedsetting,butevenifthesecontrolsaregroupedtogether,theyallowauserto
selectmultiplecheckboxessimultaneously.Incontrast,avalueofradioindicatesaradio
buttoncontrol.Whengrouped,radiobuttonsallowonlyoneofthemanychoicestobe
selectedatagiventime.
Aformcontroltypeofhiddenindicatesafieldthatisnotvisibletotheviewerbutis
usedtostoreinformation.Ahiddenformcontroloftenisusedtopreservestateinformation
betweenpages.
Avalueoffileforthetypeattributeindicatesacontrolthatallowstheviewerto
uploadafiletoaserver.Thefilenamecanbeenteredinadisplayedfield,orauseragent
mightprovideaspecialbrowsebuttonthatallowstheusertolocatethefile.Avalueof
imageindicatesagraphicimageformcontrolthatausercanclickontoinvokean
associatedaction.(Mostbrowsersallowtheuseofimg-associatedattributessuchasheight,
width,hspace,vspace,andaltwhenthetypevalueissettoimage.)Avalueof
passwordforthetypeattributeindicatesapasswordentryfield.Apasswordfieldwillnot
displaytextenteredasitistyped;itmightinsteadshowaseriesofdots.Notethat
password-entereddataisnottransferredtotheserverinanysecurefashion.Avalueof
resetforthetypeattributeisusedtoinsertabuttonthatresetsallcontrolswithinaform
totheirdefaultvalues.Avalueofsubmitinsertsaspecialsubmissionbuttonthat,when
clicked,sendsthecontentsoftheformtothelocationindicatedbytheactionattributeof
theenclosing<form>tag.Lastly,avalueoftext(thedefault)forthetypeattribute
indicatesasingle-linetextinputfield.
HTML5expandsgreatlyonthisattribute’spossiblevalues,specifyingsearch,url,
email,tel,datetime,date,month,week,time,datetime-local,number,range,and
coloraswell.Likelytherewillbeothers.ManyoftheseideasderivedfromtheWeb
Forms2.0specification,whichOperaimplementspartially.WebKitalsoimplementsaselect
numberoftheseformfieldtypes.Likelyotherbrowserswillquicklyfollowsuit.
usemap ThisHTML4.0attributeisusedtoindicatethemapfiletobeassociatedwithan
imagewhentheformcontrolissetwithtype="image".Thevalueoftheattributeshould
beaURLofamapfilebutgenerallywillbeintheformofaURLfragmentreferencinga
mapfilewithinthecurrentfile.
value Thisattributehastwodifferentuses,dependingonthevalueforthetypeattribute.
Withdata-entrycontrols(type="text"andtype="password"),thisattributeisusedto
setthedefaultvalueforthecontrol.Whenusedwithcheckboxorradiobuttonform
controls,thisattributespecifiesthereturnvalueforthecontrol.Ifitisnotsetforthesefields,
adefaultvalueofonwillbesubmittedwhenthecontrolisactivated.
vspace ThisInternetExplorer–specificattributeindicatestheverticalspace,inpixels,
betweentheimageandsurroundingtextwhenusing<inputtype="image">.
286 Part I: Core Markup
width Thisattribute,initiallysupportedbymanybrowserssuchasInternetExplorerfor
imagebuttonsandnowdefinedunderHTML5,isusedtosetthesizeoftheformcontrol,in
pixels.ThisshouldbecontrolledwithCSSinstead.
Examples
<formaction="#"method="get">
<fieldset>
<legend>Basics</legend>
<p>Enteryourname:<inputtype="text"maxlength="35"size="20"><br>
Enteryourpassword:<inputtype="password"maxlength="35"size="20">
</p>
</fieldset>
<p><label>Whichisyourfavoritefood?</label>
<inputtype="radio"name="favorite"value="Mexican">Mexican
<inputtype="radio"name="favorite"value="Russian">Russian
<inputtype="radio"name="favorite"value="Japanese">Japanese
<inputtype="radio"checkedname="favorite"value="Other">Other
</p>
<p>
<inputtype="submit"value="Submit">
<inputtype="reset"value="Reset">
</p>
</form>
<!--HTML5snippets-->
<p><label>ThreeLetterAcronyms:
<inputpattern="[A-Z]{3}"name="threeletter"
title="Enteranuppercasethreelettercombination."/>
</label></p>
<p><label>Name:<inputtype="text"name="fullname"placeholder="ThomasA.
Powell"></label></p>
<p><inputtype="range"name="slider"></p>
<p><inputtype="date"oninput="year.value=valueAsDate.getYear();">
<p>HTML5finalizedintheyear<outputoutput="year"> </output></p>
<p><label>FavoriteDog:<inputlist="dogs"></label></p>
<datalistid="dogs">
<option>Angus</option>
<option>Tucker</option>
<option>Cisco</option>
<option>Sabrina</option>
</datalist>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Chapter 3: HTML and XHTML Element Reference 287
Notes
• TheHTML2.0and3.2specificationssupportonlythealign,checked,maxlength,
name,size,src,type,andvalueattributesfortheinputelement.
PART I
• TheHTML4.01specificationalsoreservestheuseofthedatafld,dataformatas,
anddatasrcdata-bindingattributes.TheywerenotincludedintheXHTML
specificationbutaresupportedbyInternetExplorer.
• Useofautocompletemayhavesecurityimplications.Usewithcaution.
• UnderthestrictHTMLandXHTMLspecifications,thealignattributeisnot
allowed.
• AsanemptyelementunderXHTMLorwhenusingXML-stylesyntaxforHTML5,
atrailingslashisrequiredforthiselement:<input/>.
• SafarirunningontheiPhoneextendsthiselementwithautocorrectand
autocapitalizeattributes.Giventhedifficultyoffillinginformsonsmall-factor
devices,itislikelytheremaybeotherproprietarychangesthataredevicespecific.
Standard Syntax
<ins
cite="URL"
class="classname(s)"
datetime="date"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</ins>
NOTE MSDNdocumentationforthiselementappearsincorrectforeventhandlers.Notallcore
eventsarelisted,butduringtestingtheyallworked.Otherextendedeventslikeonbeforecopy,
oncopy,oncontextmenu,andmorewerealsoverifiedasfunctionalunderInternetExplorer8.
Element-Specific Attributes
cite ThevalueofthisattributeisaURLthatdesignatesasourcedocumentormessagefor
theinformationinserted.Thisattributeisintendedtopointtoinformationexplainingwhy
thetextwaschanged.
datetime Thisattributeisusedtoindicatethedateandtimetheinsertionwasmade.The
valueoftheattributeisadateinaspecialformatasdefinedbyISO8601.Thebasicdate
formatis
yyyy-mm-ddthh:mm:ssTZD
wherethefollowingistrue:
yyyy=four-digityearsuchas2010
mm=two-digitmonth(01=January,02=February,andsoon)
dd=two-digitdayofthemonth(01through31)
Chapter 3: HTML and XHTML Element Reference 289
hh=two-digithour(00to23)(24-hourclocknotAMorPM)
mm=two-digitminute(00to59)
ss=two-digitsecond(00to59)
tzd=timezonedesignator
PART I
ThetimezonedesignatoriseitherZ,whichindicatesUniversalTimeCoordinateor
coordinateduniversaltimeformat(UTC),or+hh:mm,whichindicatesthatthetimeisalocal
timethatishhhoursandmmminutesaheadofUTC.Alternatively,theformatforthetime
zonedesignatorcouldbe–hh:mm,whichindicatesthatthelocaltimeisbehindUTC.Note
thattheletterTactuallyappearsinthestring,alldigitsmustbeused,and00valuesfor
minutesandsecondsmightberequired.Anexamplevalueforthedatetimeattribute
mightbe2009-10-6T09:15:00-05:00,whichcorrespondstoOctober6,2010,9:15A.M.,
U.S.EasternStandardTime.
Example
<p>Wehavethelowestpricesinthegalaxy!<inscite="http://www
.democompany.com/changes/jan10.html"
date="2010-05-01T09:15:00-05:00">
Newratesareeffectivein2010.
</ins></p>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1 Netscape 6+, Opera 4+, Safari 1+
Note
• Browserscanrenderinserted(<ins>)ordeleted(<del>)textinadifferentstyleto
showthechangesthathavebeenmadetothedocument.Typically,newlyinserted
entriesareunderlinedanddeletionsappearwithstrikethrough.Intheory,abrowser
couldhaveawaytoshowarevisionhistoryonadocument,butgenerallythisisleft
uptoscriptingortheenvironmentthepageisbuiltin.
Element-Specific Attributes
action ThisattributespecifiestheURLofthequeryactiontobeexecutedwhentheviewer
pressestheENTERkey.AlthoughthisattributeisnotdefinedunderanyHTMLspecification,
itiscommontomanybrowsers,particularlyInternetExplorer3,whichdefinedit.
prompt Thisattributeallowsacustomqueryprompttobedefined.Thedefaultpromptis
“Thisisasearchableindex.Entersearchkeywords.”
Examples
<isindexaction="cgi-bin/search.pl"prompt="Entersearchterms">
<!--veryoldHTMLstylesyntaxbelow-->
<basehref="cgi-bin/search">
<isindexprompt="Entersearchterms">
<isindexhref="cgi-bin/search"prompt="Keywords:">
Compatibility
HTML 2, 3.2, 4, 4.01 (transitional) Firefox 1+, Internet Explorer 4+,
XHTML 1.0 (transitional) Netscape 1.1+, Opera 4+, Safari 1+
Notes
• Originally,theW3Cintendedthiselementtobeusedinadocument’sheader.
Browservendorshaverelaxedthisusagetoallowtheelementinadocument’sbody.
Earlyimplementationsdidnotsupporttheactionattributeanduseda<base>tag
oranhrefattributetospecifyasearchfunction’sURL.
• Asanemptyelement,<isindex>requiresnoclosingtagunderHTMLspecifications.
However,undertheXHTMLspecification,atrailingslash<isindex/>isrequired.
• TheHTML3.2specificationonlyallowsthepromptattribute,whereasHTML2
expectedatextdescriptiontoaccompanythesearchfield.
Chapter 3: HTML and XHTML Element Reference 291
• Netscape1.1originatedtheuseofthepromptattribute.
• ThiselementisnotfoundatallinnewerspecificationslikeHTML5.
PART I
<kbd> (Keyboard Input)
Thisinlineelementlogicallyindicatestextaskeyboardinput.Abrowsergenerallyrenders
textenclosedbythiselementinamonospacedfont.
Standard Syntax
<kbd
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</kbd>
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Example
<p>OnaLinuxorUnixbasedsystemyoucanlistfilesbytyping
<kbd>ls</kbd>atacommandprompt.</p>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Note
• TheHTML2and3.2specificationssupportnoattributesforthiselement.
id="uniquealphanumericidentifier"
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
PART I
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
keytype="enumeratedvaluefortypeofkey(generallyrsa)"
lang="languagecode"
name="fieldname"
spellcheck="true|false"
style="styleinformation"
tabindex="number"
title="advisorytext">
</keygen>
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>keygenExample</title>
</head>
<body>
<formmethod="post"action="makecert.php">
<keygenname="RSApublickey"challenge="123456789"keytype="RSA">
<inputtype="submit"name="createcert"value="Generate">
</form>
</body>
</html>
Compatibility
HTML5 Browsers such as Netscape, Firefox, Safari, and Opera may have
partial support for this element.
Notes
• AsanemptyelementwhenusingXML-stylesyntaxforHTML5,atrailingslashis
requiredforthiselement:<keygen/>.
294 Part I: Core Markup
• ThiselementwasinitiallyintroducedbyNetscapeand,althoughithasbeenpoorly
documented,hasbeenformalizedforHTML5.Thereisstrongindicationthatsome
browservendorslikeMicrosoftmaynotsupportthiselementorsupportitonlyasa
dummyelement.
Standard Syntax
<label
accesskey="key"
class="classname(s)"
dir="ltr|rtl"
for="idofformfield"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</label>
PART I
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Element-Specific Attributes
for Thisattributespecifiestheidfortheformcontrolelementthelabelreferences.Thisis
optionalwhenthelabelenclosestheformcontrolitisboundto.Inmanycases,particularly
whenatableisusedtostructuretheform,a<label>tagwillnotbeabletoenclosethe
associatedformcontrol,sotheforattributeshouldbeused.Thisattributeallowsmorethan
onelabeltobeassociatedwiththesamecontrolbycreatingmultiplereferences.
Examples
<formaction="search.php"method="get">
<p>
<labelid="searclabel">Search:
<inputtype="text"name="search"id="search">
</label>
</p>
</form>
<formaction="tracker.php"method="POST">
<table>
<tr>
<td><labelfor="username">Name</label></td>
<td><inputtype="text"id="username"></td>
</tr>
</table>
</form>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1, Basic Netscape 6+, Opera 4+, Safari 1+
296 Part I: Core Markup
Notes
• Each<label>mustnotcontainmorethanoneformfield.
• Thelabelelementshouldnotbenested.
Element-Specific Attributes
above Thisattributecontainsthenameofthelayer(assetwiththenameattribute)tobe
rendereddirectlyabovethecurrentlayer.
background ThisattributecontainstheURLofabackgroundpatternforthelayer.Like
backgroundsforthedocumentasawhole,theimagemighttile.
below Thisattributespecifiesthenameofthelayertoberenderedbelowthecurrentlayer.
bgcolor Thisattributespecifiesalayer’sbackgroundcolor.Theattribute’svaluecanbe
eitheranamedcolor,suchasred,oracolorspecifiedinthehexadecimal#RRGGBBformat,
suchas#FF0000.
Chapter 3: HTML and XHTML Element Reference 297
clip Thisattributeclipsalayer’scontenttoaspecifiedrectangle.Alllayercontentoutside
thatrectanglewillberenderedtransparent.Thecliprectangleisdefinedbytwox,ypairs
thatcorrespondtothetopx,lefty,andbottomx,rightycoordinateoftherectangle.The
PART I
coordinatesarerelativetothelayer’soriginpoint,0,0,initstop-leftcorner,andmighthave
nothingtodowiththepixelcoordinatesofthescreen.
height Thisattributeisusedtosettheheightofthelayer,eitherinpixelsorasapercentage
ofthescreenorregionthelayeriscontainedwithin.
left Thisattributespecifies,inpixels,theleftoffsetofthelayer.Theoffsetisrelativetoits
parentlayer,ifithasone,ortotheleftbrowsermarginifitdoesnot.
name Thisattributeassignstothelayeranamethatcanbereferencedbyprogramsina
client-sidescriptinglanguage.Theidattributealsocanbeused.
overflow Thisattributespecifieswhatshouldhappenwhenthelayer’scontentexceedsits
renderingboxandclippingarea.Avalueofnonedoesnotclipthecontent,whileclipclips
thecontenttoitsdimensionsordefinedclippingarea.
pagex Thisattributeisusedtosetthehorizontalpixelpositionofthelayerrelativetothe
documentwindowratherthananyenclosinglayer.
pagey Thisattributeisusedtosettheverticalpixelpositionofthelayerrelativetothe
documentwindowratherthananyenclosinglayer.
src ThisattributespecifiestheURLthatcontainsthecontenttobeincludedinthelayer.
Usingthisattributewithanemptyelementisagoodwaytopreservelayoutsunderolder
browsers.
top Thisattributespecifies,inpixels,thetopoffsetofthelayer.Theoffsetisrelativetoits
parentlayer,ifithasone,ortothetopbrowsermarginifitisnotenclosedinanotherlayer.
visibility Thisattributespecifieswhetheralayerishidden(hidden),shown(show),or
inherits(inherits)itsvisibilityfromthelayerenclosingit.
width Thisattributespecifiesalayer’swidth,inpixelsorasapercentagevalueofthe
enclosinglayerorbrowserwidth.
z-index Thisattributespecifiesalayer’sstackingorderrelativetootherlayers.Positionis
specifiedwithpositiveintegers,with1indicatingthebottommostlayer.
Examples
<!--90sappropriateexampletoillustratethiselement-->
<layername="scene"bgcolor="#00FFFF">
<layername="Shaq"left="100"top="100">
<imgsrc="shaq.gif">
</layer>
<layername="Rodman"left="200"top="100"
visibility="hidden">
<imgsrc="pinkhair.gif">
</layer>
</layer>
298 Part I: Core Markup
<!--Linkedlayers-->
<layersrc="contents.html"left="20"top="20"
height="80%"width="80%">
</layer>
Compatibility
No standards support Netscape 4, 4.5–4.8
Notes
• Thefunctionalityofthelayerelementiseasilyreplicatedusinga<div>tagand
theCSSpropertyposition:absolute.InolderNetscapebrowsers,usingthis
moreappropriateapproachdidpopulatetheJavaScriptdocument.layers
collection.
• BecausethiselementisspecifictoNetscape4,itshouldneverbeusedandis
discussedonlyforreaderssupportingexisting<layer>-filledpagestheymaycome
across.Thenexteditionofthisbookwillremovethishistoricalfootnote.
• Applets,plug-ins,andotherembeddedmediaforms,genericallycalledobjects,can
beincludedinalayer;however,theywillfloattothetopofallotherlayers,evenif
theircontaininglayerisobscured.
Standard Syntax
<legend
accesskey="character"
align="bottom|left|right|top"(transitionalonly)
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</legend>
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
PART I
Attributes Defined by Internet Explorer
align="center"(4)
contenteditable="false|true|inherit"(5.5)
disabled="false|true"(5.5)
hidefocus="true|false"(5.5)
language="javascript|jscript|vbs|vbscript"(4)
tabindex="number"(5.5)
unselectable="on|off"(5.5)
Element-Specific Attributes
accesskey Thisattributespecifiesakeyboardnavigationacceleratorfortheelement.
PressingALTorasimilarkeyinassociationwiththespecifiedkeyselectstheformsectionor
thelegenditself.Pagedesignersareforewarnedtoavoidkeysequencesalreadyboundto
browsers.
align Thisattributeindicateswherethelegendvalueshouldbepositionedwithinthe
bordercreatedbya<fieldset>tag.Thedefaultpositionforthelegendistheupper-left
corner.Italsoispossibletopositionthelegendtotherightbysettingtheattributetoright.
300 Part I: Core Markup
Thespecificationdefinesbottomandtop,aswell.Microsoftalsodefinestheuseofthe
valuecenter.
Example
<formaction="#"method="get">
<fieldset>
<legendalign="top">UserInformation</legend>
<div>
<label>FirstName:
<inputtype="text"id="firstname"size="20">
</label><br>
<label>LastName:
<inputtype="text"id="lastname"size="20">
</label><br>
</div>
</fieldset>
</form>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1 Netscape 6+, Opera 4+, Safari 1+
Notes
• Traditionally,a<legend>tagshouldoccuronlywithina<fieldset>tag.There
shouldbeonlyonelegendperfieldsetelement.
• UnderearlydraftsoftheHTML5specification,thiselementisalsofoundinthe
figureanddetailselements.Thiswaslaterreplacedbythedtelement.
• SomeversionsofMicrosoftdocumentationshowavalignattributefor<legend>
positioning.However,thevalignattributedoesnotappeartoworkconsistently
andhassincebeendroppedfromtheofficialdocumentation.
Standard Syntax
<li
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext"
type="circle|disc|square|a|A|i|I|1"(transitionalonly)
value="number">(transitionalonly)
</li>
Chapter 3: HTML and XHTML Element Reference 301
PART I
contextmenu="idofmenu"
data-X="user-defineddata"
draggable="true|false|auto"
hidden="hidden"
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
Element-Specific Attributes
type Thisattributeindicatesthebullettypeusedinunorderedlistsorthenumberingtype
usedinorderedlists.Fororderedlists,avalueofaindicateslowercaseletters,Aindicates
uppercaseletters,iindicateslowercaseRomannumerals,IindicatesuppercaseRoman
numerals,and1indicatesnumbers.Forunorderedlists,valuesareusedtospecifybullettypes.
Althoughthebrowserisfreetosetbulletstyles,avalueofdiscgenerallyspecifiesafilled
circle,avalueofcirclespecifiesanemptycircle,andavalueofsquarespecifiesafilled
square.ThisattributeshouldbeavoidedinfavoroftheCSSpropertylist-style-type.
value Thisattributeindicatesthecurrentnumberofitemsinanorderedlistasdefinedby
an<ol>tag.RegardlessofthevalueoftypebeingusedtosetRomannumeralsorletters,
theonlyallowedvalueforthisattributeisanumber.Listitemsthatfollowwillcontinue
numberingfromthevalueset.Thevalueattributehasnomeaningforunorderedlists.
CSS2counterscanprovidemuchmoreflexibilitythanthisattribute.
Examples
<ul>
<litype="circle">Firstlistitemisacircle</li>
<litype="square">Secondlistitemisasquare</li>
<litype="disc">Thirdlistitemisadisc</li>
</ul>
<ol>
<litype="i">RomanNumerals</li>
<litype="a"value="3">SecondlistitemisletterC</li>
<litype="a">Continuelistinlowercaseletters</li>
</ol>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• UnderthestrictHTMLandXHTMLdefinitions,thelielementlosesthetypeand
valueattributes,asthesepresentationstylescanbeemulatedwithCSSproperties
likelist-item-styleandCSScounters.
• HTML5reintroducesthevalueattributetolistitemsbutCSSshouldbeused
instead.
• Whereasbulletstylescanbesetexplicitly,browserstendtochangestylesforbullets
when<ul>listsarenested.However,orderedlistsgenerallydonotchangestyle
automatically,nordotheysupportoutline-stylenumbering(1.1,1.1.1,andsoon).
CSSrules,ofcourse,candothis.
• Theclosingtag</li>isoptionalunderHTMLspecifications,includingHTML5.
However,itisrequiredunderXHTMLandshouldalwaysbeused.
Chapter 3: HTML and XHTML Element Reference 303
PART I
frameworkfornavigationandlinkingthedocumenttoastylesheet.
Standard Syntax
<link
charset="charsetlistfromRFC2045"
class="classname(s)"
dir="ltr|rtl"
href="URL"
hreflang="languagecode"
id="uniquealphanumericidentifier"
lang="languagecode"
media="all|aural|braille|print|projection|
screen|other"
rel="relationshipvalue"
rev="relationshipvalue"
style="styleinformation"
target="framename"(transitionalonly)
title="advisoryinformationorrelationshipspecificduty"
type="MIMEtype">
Element-Specific Attributes
charset Thisattributespecifiesthecharactersetusedbythelinkeddocument.Allowed
valuesforthisattributearecharactersetnames,suchasEUC-JP,asdefinedinRFC2045.
disabled ThisDOMLevel1–definedattributeisusedtodisablealinkrelationship.
Thepresenceoftheattributeisallthatisrequiredtoremovealinkingrelationship.In
conjunctionwithscripting,thisattributecouldbeusedtoturnonandoffvariousstyle
sheetrelationships.
href ThisattributespecifiestheURLofthelinkedresource.AURLmightbeabsoluteor
relative.
hreflang Thisattributeisusedtoindicatethelanguageofthelinkedresource.Seethe
“LanguageAttributesReference”sectionearlierinthischapterforinformationonallowed
values.
media Thisattributespecifiesthedestinationmediumforanylinkedstyleinformation,as
indicatedwhentherelattributeissettostylesheet.Thevalueoftheattributemightbea
singlemediadescriptor,suchasscreen,oracomma-separatedlist.Possiblevaluesforthis
attributeincludeall,aural,braille,print,projection,andscreen.Othervaluesalso
mightbedefined,dependingonthebrowser.
rel Thisattributenamesarelationshipbetweenthelinkeddocumentandthecurrent
document.Multiplevaluescanbespecifiedandshouldbeseparatedbyspaces.Thevalue
oftherelattributeissimplyatextvalue,whichcanbeanythingtheauthordesires.
However,abrowsercaninterpretstandardizedrelationshipsinaparticularway.For
example,abrowsermightprovidespecialiconsornavigationfeatureswhenthemeaning
ofalinkisunderstood.Currently,documentrelationshipvaluesareneitherwidely
understoodnorsupportedbybrowsers,buttheHTML4.01andHTML5specificationslist
someproposedrelationshipvalues,asshowninTable3-22.Notethatthesevaluesarenot
casesensitive.
Chapter 3: HTML and XHTML Element Reference 305
PART I
alternate version of the .html"rel="alternate"
document that the link lang="fr">
is in. For example, this
might be a translated <linkhref="secondstyle
version of the document, .css"rel="alternate
as suggested by the lang stylesheet">
attribute.
appendix The link references a <linkhref="intro HTML 4
document that serves .html"rel="appendix">
as an appendix for a
document or site.
archives A reference to document(s) <linkhref="/archives" HTML5
of historical interest. rel="archives">
author A reference to information <linkhref="/tap.html" HTML5
about the document’s rel="author">
author.
chapter The link references a <linkhref="ch01.html" HTML 4
document that is a chapter rel="chapter">
in a site or collection of
documents.
contents The link references a <linkhref="toc.html" HTML 4
document that serves rel="contents">
as a table of contents,
most likely for the site,
although it might be for the
document.
copyright The link references a page <linkhref="copyright HTML 4
that contains a copyright .html"rel="copyright">
statement for the current
document.
first A reference to the first <linkhref="page1.html" HTML5
document in a collection. rel="first">
glossary The link references a <linkhref="glossary.html" HTML 4
document that provides a rel="glossary">
glossary of terms for the
current document.
PART I
previous document in rel="previous">
a linear collection of
documents.
search Link to a search facility <linkhref="search/" HTML5
used in a site. rel="search">
section The link references a <linkhref="sect07.html" HTML 4
document that is a section rel="section">
in a site or collection of
documents.
sidebar Specifies a URL that should <linkhref="instructions HTML5
be displayed in a browser .html"rel="sidebar">
sidebar.
start The link references the <linkhref="begin.html" HTML 4
first document in a set of rel="start">
documents.
stylesheet The link references an <linkhref="style.css" HTML 4, 5
external style sheet. This rel="stylesheet">
is by far the most common
use of <link> and the
most widely supported in
browsers.
subsection The link references <linkhref="sect07a.html" HTML 4
a document that is a rel="subsection">
subsection in a collection
of documents.
tag Gives a tag that applies to <linkhref="extag.html" HTML5
the document. rel="tag">
up Provides a link to a <linkhref="/main/index HTML5
document or section “up” .html"rel="up">
from the current document,
usually the parent or
index document for the
current URL.
Underafewbrowsers,suchasOpera,theselinkrelationshipvaluesarerecognizedand
placedinaspecialnavigationmenu.Forexample,giventheexamplehere
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>LinkRelationshipExamples</title>
<linkrel="home"href="http://htmlref.com"title="Homepage">
<linkrel="toc"href="http://htmlref.com/chapters/toc.html"
title="Tableofcontents">
<linkrel="help"href="http://htmlref.com/help.html"title="Needhelp?">
<linkrel="copyright"href="http://www.htmlref.com/copyright.html"
title="Copyrightstatement">
<linkrel="author"href="http://htmlref.com/about/author.html"
title="Abouttheauthor">
</head>
<body>
<p>Testinglinkelementrelvalues</p>
</body>
</html>
whenviewedinasupportingbrowserlikeOpera,youmighthavespecialbuttonsto
navigateasite:
Unfortunately,therealityisthatovertimefewerbrowsershavesupportedtheselink
elementfeatures.
ThemostcommonlyusedrelvaluesfromTable3-22aredescribedhereinmoredepth.
Certainly,themostcommonuseofthisattributeistospecifyalinktoanexternalstyle
sheet.Therelattributeissettostylesheet,andthehrefattributeissettotheURLofan
externalstylesheettoformatthepage:
<linkrel="stylesheet"type="application/pdf"href="/css/global.css">
Thealternatestylesheetrelationship,whichwouldallowuserstopickfroma
varietyofstyles,alsoisdefined.Tosetseveralalternativestyles,thetitleattributemustbe
settogroupelementsbelongingtothesamestyle.Allmembersofthesamestylemusthave
exactlythesamevaluefortitle.Forexample,thefollowingfragmentdefinesastandard
Chapter 3: HTML and XHTML Element Reference 309
stylecalledbasestyle.css,andtwoalternativestyles,titled640x480and1024x768,havebeen
added;theserefertostylesheetstoimprovelayoutatvariousscreenresolutions:
PART I
<linkrel="alternatestylesheet"title="640x480"href="small.css"
type="text/css">
<linkrel="alternatestylesheet"title="1024x768"href="big.css"
type="text/css">
<linkrel="stylesheet"href="basestyle.css"type="text/css">
AWebbrowsershouldprovideamethodforuserstoviewandpickfromthelistof
alternativestyles,wherethetitleattributecanbeusedtonameeachchoice.
Arelvalueisalsocommonlyusedtospecifythelocationofablogfeed.Using
markuplike
<linkrel="alternate"type="application/rss+xml"
title="PINTBlogRSSFeed"href="http://blog.pint.com/feed/">
intheheadofadocumentwillcausesupportingbrowserstoputaspecialsubscriptionicon
inthelocationbar:
Giventhattheremaybemultiplefeedformats,theremaybeanumberoflinkalternate
entries:
<linkrel="alternate"type="application/rss+xml"
title="TheBlog"href="/rss/index.xml">
<linkrel="alternate"type="application/atom+xml"
title="Atom0.3"href="/atom/index.xml">
Sofarthissyntaxisthecommonmethod,butthingschangerapidlyinthe“blogosphere,”
socheckingwiththedocumentationofbloggingplatformsisprobablythebestwayto
ensureyouhavetheverylatestfeedsyntaxfor(X)HTML.
Anothercommonuseofthisattributeistosetabrowserlocationbariconcalleda
favicon.Theseiconsaresetwiththerelattributeusingthevalueoficonorshortcut
icon:
<linkrel="icon"href="/favicon.ico"type="image/x-icon">
<linkrel="shortcuticon"href="/favicon.ico"type="image/x-icon">
BrowserscommonlyplacethesesmallimagesintheURLbarlikeso:
310 Part I: Core Markup
Browsersmayalsousefaviconsinabookmarkmenu.Currently,thefaviconimage
shouldbea16×16image,thoughlargerimagesizesmaybesupportedinothersituations.
Forexample,Appledevicessupportarelationshipofapple-touch-icontosetalarger
57×57PNGformaticon
<linkrel="apple-touch-icon"href="/apple-touch-icon.png">
tobeusedonitsmobiledevices.Thisisjustanexampletoillustratethatmanybrowser-or
environment-specificusesof<link>relationshipslikelyexist.
Finally,insomebrowsersiftherelattributeissetwiththevalueofnext(or,inother
cases,prefetch)alongwithanhrefvalueofsomedataobject,thebrowserwill“prefetch”
theiteminquestionduringtheidletimeofthebrowser.Ifthecontentofthenextpageis
storedinthebrowser’scache,thepageloadsmuchfasterthanifthepagehastobe
requestedfromtheserver.
Mozilla-basedbrowserssupportthissyntaxalreadywitharelationtypeofeithernext
orprefetch.Forexample,youmightuse<link>likethis:
<linkrel="prefetch"href="/images/product.jpeg">
ThiswouldbethesameasprovidingaprefetchinghintusinganHTTPLink:header:
Link:</images/product.jpeg>;rel=prefetch
Itispossibletoprefetchavarietyofobjectsinapageduringabrowser’sidletime.
Considerthefollowingexample:
<linkrel="prefetch"href="bigflash.swf">
<linkrel="prefetch"href="ajaxlibrary.js">
<linkrel="next"href="2.html">
Whileprefetchingisonlybuiltintosomebrowsers,itispossibleusingJavaScriptto
preloadobjectsaswell.Regardlessoftheprefetchmethod,becarefulnottodisrupttheload
oruseofacurrentlyviewedpagewithpreloading,andbemindfulthatyoumaybewasting
bandwidthonrequeststhatareneverused.
rev Thevalueoftherevattributeshowstherelationshipofthecurrentdocumenttothe
linkeddocument,asdefinedbythehrefattribute.Theattributethusdefinesthereverse
relationshipcomparedtothevalueoftherelattribute.Multiplevaluescanbespecified
andshouldbeseparatedbyspaces.Valuesfortherevattributearesimilartothepossible
valuesforrel.Theymightincludealternate,bookmark,chapter,contents,
copyright,glossary,help,index,next,prev,section,start,stylesheet,and
subsection.HTML5doesnotdefinethisattribute—likelywithgoodcause,becauseits
usageisquiterareanditsvaluenebulous.
sizes ThisHTML5attributeisusedwhentherelattributehasavalueoficontodefine
thesizeoftherelatediconinaHeight×Widthformat.Theattributetakesaspace-separated
listifmultipleformsarepossibleortakesthekeywordanyifsizedoesn’tmatter.Seethe
examplesthatfollowforademonstration.
Chapter 3: HTML and XHTML Element Reference 311
target Thevalueofthetargetattributedefinestheframeorwindownamethathasthe
definedlinkingrelationshiporthatwillshowtherenderingofanylinkedresource.
PART I
type Thisattributeisusedtodefinethetypeofthecontentlinkedto.Thevalueofthe
attributeshouldbeaMIMEtype,suchastext/html,text/css,andsoon.Thecommon
useofthisattributeistodefinethetypeofstylesheetlinked,andthemostcommoncurrent
valueistext/css,whichindicatesaCSSformat.
Examples
<linkhref="products.html"rel="parent">
<linkhref="corpstyle.css"rel="stylesheet"type="text/css"media="all">
<!--XHTMLsyntax-->
<linkhref="corpstyle.css"rel="stylesheet"type="text/css"media="all"/>
<linkhref="nextpagetoload.html"rel="next>
<!--HTML5iconexamples-->
<linkrel=icon"href="icon.png"sizes="16x16">
<linkrel=icon"href="icon2.png"sizes="16x1632x32">
<linkrel=icon"href="icon3.svg"sizes="any">
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 3+,
XHTML 1.0, 1.1, Basic Netscape 4+, Opera 4+, Safari 1+
Notes
• AsanemptyelementunderXHTML,orwhenusingXML-stylesyntaxforHTML5,
atrailingslashisrequiredforthiselement:<link/>.
• A<link>tagcanoccuronlyintheheadelement;however,therecanbemultiple
occurrencesof<link>.
• HTML3.2definesonlythehref,rel,rev,andtitleattributesforthelink
element.
• HTML2definesthehref,methods,rel,rev,title,andurnattributesforthe
linkelement.Themethodsandurnattributeswerelaterremovedfromthe
specifications.
Example
<listing>
Thisisacodelisting.Thepreformattedtextelement<PRE>
shouldbeusedinsteadofthisdeprecatedelement.
</listing>
Compatibility
HTML 2 Firefox 1+, Internet Explorer 2+,
Netscape 1+, Opera 6+, Safari 1+
Notes
• Asadeprecatedelement,thiselementshouldnotbeused.Thiselementisnot
supportedbyHTML4,XHTML1.0,or1.1.Itisstilldocumentedandsupportedby
manybrowservendors.Thepreelementshouldbeusedinsteadof<listing>.
• Manybrowsersalsomaketextwithin<listing>tagsonesizesmallerthannormal
text,probablybecausetheHTML2specificationsuggestedthat132charactersfiton
atypicallineratherthan80.
imagethroughtheuseoftheusemapattributeintheimgelement,whichissettothename
ofthemap.
Syntax
PART I
<map
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
name="uniquealphanumericidentifier"
style="styleinformation"
title="advisorytext">
</map>
Element-Specific Attribute
name Likeid,thisattributeisusedtodefineanameassociatedwiththeelement.Inthe
caseofthemapelement,thenameattributeisthecommonwaytodefinethenameofthe
imagemaptobereferencedbytheusemapattributewithinan<img>tag.
Example
<mapname="mainmap"id="mainmap">
<areashape="circle"coords="200,250,25"
href="file1.html"/>
<areashape="rectangle"coords="50,50,100,100"
href="file2.html#important"/>
<areashape="default"nohref="nohref"/>
</map>
Compatibility
HTML 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1 Netscape 1+, Opera 4+, Safari 1+
Notes
• HTML3.2supportsonlythenameattributeforthemapelement.
• Whenthenameattributeisused,itshouldbethesameastheidattribute.
• Client-sideimagemapsarenotsupportedunderHTML2.Theywerefirst
suggestedbySpyglassandlaterincorporatedintoNetscapeandotherbrowsers.
• Giventheusabilityconcernswithimagemaps,alternateaccessformssuchas
relatedtextlinksshouldbeprovided.
dir="ltr|rtl"
draggable="true|false|auto"
hidden="hidden"
id="uniquealphanumericidentifier"
PART I
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
lang="languagecode"
spellcheck="true|false"
style="styleinformation"
tabindex="number"
title="advisorytext">
</mark>
Examples
<p>ThenewHTML5specificationisintheworks.While
<markstyle="background-color:red;">manyfeaturesarenotcurrently
implementedorevenwelldefined</mark>yet,
<markstyle="background-color:green;">progressisbeingmade</mark>.
StaytunedtoseemorenewHTMLelementsaddedtoyourWebdocumentsin
theyearstocome.</p>
<p>Thisis<mark>markedtext</mark>wasityellow?</p>
Compatibility
HTML5 Not currently supported by any browser, but addressed with a custom element.
Notes
• HintsintheHTML5specificationsuggesttextwithinthiselementwillbeblackon
ayellowbackgroundunlessotherCSSrulesoverrideit.
• Thiselementisnotyetimplementedinanybrowser.However,giventhatmost
browserscanhandlecustomelements,itwouldbeeasyenoughtosimulatethe
ideaofit.
316 Part I: Core Markup
Element-Specific Attributes
behavior Thisattributecontrolsthemovementofmarqueetextacrossthemarquee.The
alternateoptioncausestexttocompletelycrossthemarqueefieldinonedirectionand
Chapter 3: HTML and XHTML Element Reference 317
thencrossintheoppositedirection.Avalueofscrollfortheattributecausestexttowrap
aroundandstartoveragain.Thisisthedefaultvalueforamarquee.Avalueofslidefor
thisattributecausestexttocrossthemarqueefieldandstopwhenitsleadingcharacter
PART I
reachestheoppositeside.
bgcolor Thisattributespecifiesthemarquee’sbackgroundcolor.Thevaluefortheattribute
caneitherbeacolornameoracolorvaluedefinedinthehexadecimal#RRGGBBformat.
direction Thisattributespecifiesthedirectioninwhichthemarqueeshouldscroll.The
defaultisleft.Otherpossiblevaluesfordirectionincludedown,right,andup.
loop Thisattributeindicatesthenumberoftimesthemarqueecontentshouldloop.By
default,amarqueeloopsinfinitelyunlessthebehaviorattributeissettoslide.Italsois
possibletouseavalueofinfiniteor−1tosetthetexttoloopindefinitely.
scrollamount Thisattributespecifiesthewidth,inpixels,betweensuccessivedisplaysof
thescrollingtextinthemarquee.
scrolldelay Thisattributespecifiesthedelay,inmilliseconds,betweensuccessivedisplays
ofthetextinthemarquee.
truespeed Whenthisattributeispresent,itindicatesthatthescrolldelayvalueshould
behonoredforitsexactvalue.Iftheattributeisnotpresent,anyvaluelessthan60is
roundedupto60milliseconds.
Examples
<marqueebehavior="alternate">
SPECIALVALUE!!!Thisweekonly!!!
</marquee>
<marqueeid="marquee1"bgcolor="red"direction="right"height="30"
width="80%"hspace="10"vspace="10">
Thesuperscrollerscrollsagain!!
Morefunthanabarrelof<BLINK>elements.
</marquee>
Compatibility
No standards support Firefox 1+, Internet Explorer 3+, Netscape 6+, Opera 7+, Safari 1+
Notes
• ThisisprimarilyaMicrosoft-specificelement,althoughmostbrowserssupportitto
somedegree.Donotexpectalleventsandattributesbeyondbasicanimationtobe
supportedconsistentlyorevenatallbeyondInternetExplorer.
• ThereisaplaceholderinthecurrentHTML5specificationthatdiscussesthis
elementwillbefoundinbrowsers,soitsfutureisstillunclear.
318 Part I: Core Markup
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
PART I
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Element-Specific Attributes
compact Thisattributeindicatesthatthelistshouldberenderedinacompactstyle.Few
browsersactuallychangetherenderingofthelist,regardlessofthepresenceofthis
attribute.ThecompactattributerequiresnovalueundertraditionalHTMLbutshouldbe
settoavalueofcompactunderXHTMLtransitional.
label ThisHTML5attributedefinesastringlabelforthemenu.Thiswillbeparticularly
usefulinthecaseofanestedmenu.
type ThisHTML5attributeindicateswhetherthemenushouldbeastandardmenuthat
ausercaninteractwith(toolbar)oracontextualmenu,usuallyactivatedbyaright-click
(contextmenu).
HTML 4 Example
<h2>TacoList</h2>
<menu>
<li>Fish</li>
<li>Pork</li>
<li>Beef</li>
<li>Chicken</li>
</menu>
HTML5 Examples
<menutype="menubar">
<commandlabel="Add"type="Command"icon="plus.png">
<commandlabel="Edit"type="Command"default>
<commandlabel="Delete"type="Command"disabled>
</menu>
<menutype="context"label="Actions">
<menutype="context"label="New">
320 Part I: Core Markup
<commandlabel="Document"type="Command"default>
<commandlabel="Link"type="Command">
<commandlabel="Section"type="Command">
</menu>
<hr>
<commandlabel="SortAscending"type="radio"radiogroup="sort">
<commandlabel="SortDescending"type="radio"radiogroup="sort">
</menu>
Compatibility
HTML 2, 3.2, 4, 4.01 (transitional), 5 (new functionality) Firefox 1+, Internet Explorer 2+,
XHTML 1.0 (transitional) Netscape 1+, Opera 4+, Safari 1+
Notes
• UnderthestrictHTMLandXHTMLspecifications,thiselementisnotdefined.
Becausemostbrowserssimplyrenderthisstyleoflistasanunorderedlist,usingthe
<ul>taginsteadispreferable.
• HTML5keepsthetraditionalsenseofthiselement,butitalsointroducesanew
senseasanactualmenuofcommands.Inthisnewuse,thecontentmodelismuch
differentandtheelementmayincludelistitems,anchors,formfields,command
elements,andhorizontalrules.Atthetimeofthiswriting,nobrowserssupportthis
extendedfunctionality.
• HTML5mayalsoallowmenuelementstobereferencedbyidusingtheglobal
contextmenuattribute.
• TheHTML2.0and3.2specificationssupportonlythecompactattribute,though
mostbrowsersdon’tdoanythingwiththisattributeanyway.
<meta> (Meta-Information)
Thiselementspecifiesgeneralinformationaboutadocumentthatcanbeusedindocument
indexing.ItalsoallowsadocumenttodefinefieldsintheHTTPresponseheaderwhenitis
sentfromtheserver.
Standard Syntax
<meta
content="string"
dir="ltr|rtl"
http-equiv="httpheaderstring"
id="uniquealphanumericstring"
lang="languagecode"
name="nameofmeta-information"
scheme="schemetype">
contextmenu="idofmenu"
data-X="user-defineddata"
draggable="true|false|auto"
hidden="hidden"
PART I
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
Element-Specific Attributes
charset ThisHTML5attributeisusedtosetthecharacterencodingforthedocumentlike
“UTF-8”.Thisapproachisanalternativetousingthehttp-equivmethodcurrently
employed.
content Thisattributecontainstheactualmeta-information.Theformofthemeta-information
variesgreatly,dependingonthevaluesetforname.
http-equiv Thisattributebindsthemeta-informationinthecontentattributetoan
equivalentHTTPresponseheader.Ifthisattributeispresent,thenameattributeshouldnot
beused.
name Thisattributeassociatesanamewiththemeta-informationcontainedinthe
contentattribute.Ifthenameattributeispresent,thehttp-equivattributeshouldnot
beused.
scheme Theschemeattributeisusedtoindicatetheexpectedformatofthevalueofthe
contentattribute.Theparticularschemealsocanbeusedinconjunctionwiththemetadata
profile,asindicatedbytheprofileattributefortheheadelement.Thisattributeisnot
currentlydefinedforinclusioninHTML5.
322 Part I: Core Markup
Examples
<!--Useofthemetaelementtoassistdocumentindexing-->
<metaname="keywords"content="html,metaelement,meta">
<metaname="description"content="Thisisasimpleexampleofthemeta
elementwithafakedescriptionforthepage.">
<!--Useofthemetaelementtoimplementclient-pulltoautomatically
loadapageusingXHTMLsyntax-->
<metahttp-equiv="refresh"
content="3;URL='http://www.pint.com/'"/>
<!--Useofthemetaelementtoaddratinginformation-->
<metahttp-equiv="PICS-Label"content="(PICS-1.1
'http://www.rsac.org/ratingsv01.html'
1gentruecomment'RSACiNorthAmerica
Server'by'webmaster@democompany.com'
for'http://www.democompany.com'on
'1999.05.26T13:05-0500'
r(n0s0v0l1))">
<!--userdefineduseofmetaelement-->
<metaname="SiteContentID"content="123asdasa1324a">
<!--TraditionalCharsetandContent-Typesetting-->
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<!--HTML5charsetexample-->
<metacharset="utf-8">
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1.1+, Opera 4+, Safari 1+
Notes
• Themetaelementcanoccuronlyintheheadelement.Itcanbedefinedmultiple
times.
• AsanemptyelementunderXHTML,orwhenusingXML-stylesyntaxforHTML5,
atrailingslashisrequiredforthiselement:<meta/>.
• Acommonuseofthemetaelementistosetinformationforindexingtools,suchas
searchengines.Commonvaluesforthenameattributewhenperformingthis
functionincludeauthor,description,andkeywords;otherattributesalsomight
bepossible.
• Thehttp-equivattributeisoftenusedtocreateadocumentthatautomatically
loadsanotherdocumentafterasettime.Thisiscalledclient-pull.Anexampleofa
client-pullmetaelementis<metahttp-equiv="refresh"content="10;URL='
nextpage.html'">.Notethatthecontentattributecontainstwovalues:thefirst
isthenumberofsecondstowait,andthesecondistheidentifierURLandtheURL
toloadafterthespecifiedtime.
Chapter 3: HTML and XHTML Element Reference 323
• Thehttp-equivattributeisalsousedforpageratings,cachecontrol,setting
defaultssuchaslanguageorscripting,andavarietyofothertasks.Inmanycases,it
wouldbebettertosetthesevaluesviatheactualHTTPheadersratherthanviaa
PART I
<meta>tag.
• The<meta>tagcanbeusedarbitrarilybysiteowners,searchservices,andbrowser
vendors.Forexample,whendefiningpagesforApple’siPhone,theviewportand
format-detectionvaluesfora<meta>tagcanbesettocontrolpresentationon
thedevice.Googleusesaverify-v1valueforapprovingsitesforsome
Webmaster-relatedfeatures.Manymoreexamplescanbefoundonline;thepointis
thattheelementisquiteflexibleandhasnumeroususes.
• TheHTML2.0and3.2specificationsdefineonlythecontent,http-equiv,and
nameattributes.
• ThemeaningsofsomeHTML5commonattributes(particularlythosethatare
interface-oriented,suchasaccesskey,dragable,andspellcheck)arequite
unclear.Thespecificationcurrentlyputstheseattributeseverywhere,unlikeHTML4,
whichdoesremovecoreattributeswhencontextisinappropriate.Donotbe
surprisediftheyareremovedfromsomeHTML5elementsinfuturerevisionstothe
specification.
• TheHTML5specificationstatesthatthehttp-equivattributeshouldnotset
Content-Languagevalues;thelangattributeshouldbeusedinthedocument
instead.
optimum="float"
spellcheck="true|false"
style="styleinformation"
title="advisorytext"
tabindex="number"
value="float">
</meter>
Element-Specific Attributes
low Thisattributeholdsafloatvaluethatindicatesthelowrangeofthemeasurement.
max Thisattributeholdsafloatvaluethatindicatesthemaximumrangeofthe
measurement.
min Thisattributeholdsafloatvaluethatindicatestheminimumrangeofthe
measurement.
optimum Thisattributeholdsafloatvaluethatindicatestheoptimumrangeofthe
measurement.
value Thisattributeholdsafloatvaluethatindicatesthecurrentvalueofthemeasurement.
Examples
<p>Energylevel:<meter>50%</meter></p>
<p>Energylevel:<meter>1/2</meter></p>
<p>WarpDriveOutput:
<metermin="0"max="10"low="3"optimum="7"high="9"value="9.5"
title="Captainshecan'ttakemuchmoreofthis!">
</meter>
</p>
Compatibility
HTML5 Not currently supported by any browsers, but could be simulated in modern browsers
with a custom element and JavaScript.
Chapter 3: HTML and XHTML Element Reference 325
Notes
• Theassumptionisthatvaluesareusedinthecorrectsense;forexample,aminvalue
cannotbegreaterthanamaxvalue,alowvaluecan’tbegreaterthanahighvalue,
PART I
anoptimumvaluecannotbegreaterthanahighvalue,andsoon.
• Thiselementisnotyetimplementedinanybrowser.However,giventhatmost
browserscanhandlecustomelements,itwouldbeeasyenoughtosimulatetheidea
ofitandevenapplyaCSSdisplaypropertyforit.Usingscripting,youmight
animateorpresentsomevisualrepresentationofthedata.
Element-Specific Attributes
cols Thisattributeindicatesthenumberofcolumnsinwhichtodisplaythetext.The
browserattemptstofillthecolumnsevenly.
gutter Thisattributeindicatesthewidth,inpixels,betweenthecolumns.Thedefaultvalue
forthisattributeistenpixels.
width Thisattributeindicatesthecolumnwidthforallcolumns.Thewidthofeachcolumn
issetinpixelsandisequivalentforallcolumnsinthegroup.Iftheattributeisnotspecified,
thewidthofcolumnswillbedeterminedbytakingtheavailablewindowsize,subtracting
thenumberofpixelsforthegutterbetweenthecolumns(asspecifiedbythegutter
attribute),andevenlydividingtheresultbythenumberofcolumnsinthegroup(assetby
thecolsattribute).
Example
<multicolcols="3"gutter="20">
Putalongpieceoftexthere....
</multicol>
326 Part I: Core Markup
Compatibility
No standards support Netscape 3, 4, 4.5–4.8
Notes
• Pagedevelopersarestronglyencouragednottousethiselement.Netscapedropped
thiselementforitsownbrowsersstartingwithversion6.0.Theinclusioninthis
bookofthiselementisforsupportofexistingdocumentsonly.
• ThefacilitiesofthiselementarebetterhandledusingtheCSSmulticolumn
propertiesdiscussedinChapter6.
<nav> (Navigation)
ThisHTML5elementrepresentsagroupoflinkstootherlocationseitherinsideoroutside
ofadocument.
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Example
PART I
<nav>
<ul>
<li><ahref="about.html">About</a></li>
<li><ahref="services.html">Services</a></li>
<li><ahref="contact.html">Contact</a></li>
<li><ahref="index.html">Home</a></li>
</ul>
</nav>
Compatibility
HTML5 Not currently supported by any browser, but addressed with a custom element.
Notes
• Linksarenotrestrictedtooccursolelywithin<nav>tags.Theintentofthiselement
isthatitcollectsnavigationtogetheroftenasaunit;commonlythiswouldbeprimary
orsecondarysitenavigationorpossiblypage-relatedlinks.
• Whilethiselementisnotyetsupported,itiseasilysimulatedbyusingacustomtag
orusinga<div>tagwithaspecialclass.
Common Syntax
<nobr
class="classname(s)"
id="uniquealphanumericidentifier"
style="styleinformation"
title="advisorytext">
</nobr>
Examples
<nobr>Thisreallylongtext...willnotbebroken.</nobr>
<nobr>Withthiselementitisoftenimportanttohintwherealinemay
bebrokenusing<wbr>.<wbr>Thiselementactsasasoftreturn.</
nobr>
Compatibility
No standards support Firefox 1+, Internet Explorer 4+, Netscape 1.1+, Opera 4+
Notes
• Whilemanybrowserssupportthisattribute,itisnotpartofanyW3Cstandard.
• Seethe“<wbr>(WordBreak)”sectionlaterinthechapterforadiscussionofhowto
implementsoft-breakfunctionalitywithouttheproprietarywbrelement.
Element-Specific Attributes
Netscapedoesnotspecificallydefineattributesforthiselement;however,testingand
documentationsuggeststhatclass,id,style,andtitlemightbesupportedforthis
elementinmanybrowsers.
Example
<embedsrc="trailer.mov"height="300"width="300">
<noembed>
<imgsrc="error.gif"alt="Error">
<p>Thisbrowserisnotconfiguredtodisplayvideo</p>
</noembed>
</embed>
Compatibility
No standards support Netscape 2, 3, 4–4.7
Chapter 3: HTML and XHTML Element Reference 329
Note
• Evenifotherbrowsersdonotsupportthetagandrenderthecontentsofa
<noembed>tag,itworksinthemanneritwasdesigned,givenhowbrowsershandle
PART I
unknownelements.
Standard Syntax
<noframes
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
Alternativecontentforbrowsersthatdonotsupportframes
</noframes>
Example
<framesetrows="100,*">
<framename="nav"src="controls.html">
<framename="body"src="content.html">
<noframes>
<p>Sorry,thisbrowserdoesnotsupportframes.</p>
</noframes>
</frameset>
Compatibility
HTML 4, 4.01 (transitional and frameset) Firefox 1+, Internet Explorer 2+,
XHTML 1.0 (transitional and frameset) Netscape 2+, Opera 4+, Safari 1+
Notes
• Thiselementshouldbeusedwithinthescopeoftheframesetelement.
• ThiselementhasnoinclusionunderHTML5becausestandardframesarenot
includedinthatspecification.
330 Part I: Core Markup
• Thebenefitofeventsandsophisticatedattributes,suchasstyle,isunclearfor
browsersthatwouldusecontentwithin<noframes>,giventhatolderbrowsers
thatdon’tsupportframesprobablywouldnotsupportthesefeatures.
Syntax
<noscript
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
Alternativecontentfornon-script-supportingbrowsers
</noscript>
PART I
Examples
<scripttype="type/javascript">
<!--
window.location="http://www.pint.com";
//-->
</script>
<noscript>
<p>JavaScriptisnotsupported.Followthis
<ahref="http://www.pint.com">link</a>instead.</p>
</noscript>
<!--HTML5refreshtrick-->
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>WebApplication</title>
<!--requirescripton-->
<noscript>
<metahttp-equiv="Refresh"content="0;URL=/errors/noscript.html">
</noscript>
<!--moreheadcontentfollows-->
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 3+,
XHTML 1.0, 1.1 Netscape 2+, Opera 4+, Safari 1+
Note
• Besidesusingthenoscriptelement,itmaybewisetoemployacommentmask
aroundanyscriptcodethatisembeddedratherthanlinked.Oddly,underHTML4
<noscript>isnotallowedintheheadeventhough<script>is.UnderHTML5it
isallowed,thoughwithalimitedsetofcontentwithinitandisnotdefinedwhen
XMLsyntaxisused.
Standard Syntax
<object
align="bottom|left|middle|right|top"(transitionalonly)
archive="URL"
border="percentage|pixels"(transitionalonly)
332 Part I: Core Markup
class="classname(s)"
classid="id"
codebase="URL"
codetype="MIMEType"
data="URLofdata"
declare="declare"
dir="ltr|rtl"
height="percentage|pixels"
hspace="percentage|pixels"(transitionalonly)
id="uniquealphanumericidentifier"
lang="languagecode"
name="uniquealphanumericname"
standby="standbytextstring"
style="styleinformation"
tabindex="number"
title="advisorytext"
type="MIMEType"
usemap="URL"
vspace="percentage|pixels"(transitionalonly)
width="percentage|pixels">
paramelementsandalternativerendering
</object>
PART I
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Element-Specific Attributes
align Thisattributealignstheobjectwithrespecttothesurroundingtext.Thedefaultis
left.TheHTMLspecificationdefinesbottom,middle,right,andtop,aswell.Browsers
mightprovideanevenrichersetofalignmentvalues.Thebehaviorofalignmentforobjects
issimilartoimages.UnderthestrictHTMLandXHTMLspecifications,theobjectelement
doesnotsupportthisattribute.
archive ThisattributecontainsaURLforthelocationofanarchivefile.Anarchivefile
typicallyisusedtocontainmultipleobjectfilestoimprovetheefficiencyofaccess.
border Thisattributespecifiesthewidthoftheobject’sborders,inpixelsorasapercentage.
classid ThisattributecontainsaURLforanobject’simplementation.TheURLsyntax
dependsupontheobject’stype.WithActiveXcontrols,thevalueofthisattributedoesnot
appeartobeaURLbutsomethingoftheformCLSID:object-id;forexample,CLSID:
99B42120-6EC7-11CF-A6C7-00AA00A47DD2.
code UndertheoldMicrosoftimplementation,thisattributecontainstheURLreferencing
aJavaappletclassfile.ThewaytoaccessaJavaappletundertheHTML/XHTML
specificationistouse<objectclassid="java:classname.class">.Thepseudo-URL
java:isusedtoindicateaJavaapplet.MicrosoftInternetExplorer4andbeyondsupport
thisstyle,socodeshouldnotbeused.
codebase ThisattributecontainsaURLtouseasarelativebasetoaccesstheobject
specifiedbytheclassidattribute.
codetype Thisattributespecifiesanobject’sMIMEtype.Donotconfusethisattributewith
type,whichspecifiestheMIMEtypeofthedatatheobjectmayuse,asdefinedbythedata
attribute.
334 Part I: Core Markup
data ThisattributecontainsaURLfordatarequiredbyanobject.
declare Thisattributedeclaresanobjectwithoutinstantiatingit.Thisisusefulwhenthe
objectwillbeaparametertoanotherobject.IntraditionalHTML,thisattributetakesno
value;underXHTML,setitequaltodeclare.
name UndertheolderformsofHTML,thisattributedefinesthenameofthecontrolso
thatscriptingcanaccessit.Theidattributeshouldbeusedifpossible.
standby Thisattributecontainsatextmessagetobedisplayedwhiletheobjectisloading.
type ThisattributespecifiestheMIMEtypefortheobject’sdata.Thisisdifferentfrom
codetype,whichistheMIMEtypeoftheobjectandnotofthedataituses.
usemap ThisattributecontainstheURLoftheimagemaptobeusedwiththeobject.
Typically,theURLwillbeafragmentidentifierreferencingamapelementsomewhereelse
withinthefile.Thepresenceofthisattributeindicatesthatthetypeofobjectbeingincluded
isanimage.
vspace Thisattributeindicatestheverticalspace,inpixelsorasapercentage,betweenthe
objectandsurroundingtext.
Examples
<!--UsingXHTMLsyntaxwithtrailingslasheshere-->
<objectid="IeLabel1"width="325"height="65"
classid="CLSID:99B42120-6EC7-11CF-A6C7-00AA00A47DD2">
<paramname="_ExtentX"value="6879"/>
<paramname="_ExtentY"value="1376"/>
<paramname="Caption"value="HelloWorld"/>
<paramname="Alignment"value="4"/>
<paramname="Mode"value="1"/>
<paramname="ForeColor"value="#FF0000"/>
<paramname="FontName"value="Arial"/>
<paramname="FontSize"value="36"/>
<b>HelloWorldfornon-ActiveXusers!</b>
</object>
<!--StandardHTMLstyle-->
<objectclassid="java:Blink.class"
standby="Hereitcomes"
height="100"width="300">
<paramname="lbl"
value="Javaisfun,exciting,andnew.">
<paramname="speed"value="2">
Thiswilldisplayinnon-Java-awareor-enabled
browsers.
</object>
<!--pullsinremotecontenthere-->
<objectdata="pullinthisfile.html">
Datanotincluded!
</object>
Chapter 3: HTML and XHTML Element Reference 335
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 3+,
PART I
XHTML 1.0, 1.1, Basic Netscape 4+, Opera 4+, Safari 1+
Notes
• UnderthestrictHTMLandXHTMLspecifications,theobjectelementlosesmost
ofitspresentationattributes,includingalign,border,height,hspace,vspace,
andwidth.Theseattributesarereplacedbystylesheetrules.
• TheHTML4.01specificationreservesthedatafld,dataformatas,anddatasrc
attributesforfutureuse.However,theseattributesweredroppedinXHTML,
thoughtheyarewellsupportedbyInternetExplorer4andbeyond.
• Alternativecontentshouldbedefinedwithinan<object>tagafteranyenclosed
<param>tags.
• Theobjectelementisstillmainlyusedtoincludemultimediabinariesinpages.
AlthoughthespecificationdefinesthatitcanloadinHTMLfiles,insertavarietyof
otherobjects,andcreateimagemaps,noteverybrowsersupportsthis,andfew
developersareawareofthesefeatures.Intheory,thisveryversatiletagshouldtake
overdutiesfromthevenerable<img>taginfuturespecifications,thoughgiventhe
media-specificelementtrendsofHTML5,thisseemsunlikelytohappen.
Standard Syntax
<ol
class="classname(s)"
compact="compact"(transitionalonly)
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
start="number"(transitionalversionsandHTML5)
style="styleinformation"
title="advisorytext"
type="a|A|i|I|1">(transitionalonly)>
lielementsonly
</ol>
draggable="true|false|auto"
hidden="hidden"
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
reversed="reversed"
spellcheck="true|false"
tabindex="number"
Element-Specific Attributes
compact Thisattributeindicatesthatthelistshouldberenderedinacompactstyle.Few
browsersactuallychangetherenderingofthelist,regardlessofthepresenceofthis
attribute.ThecompactattributerequiresnovalueundertraditionalHTMLbutunder
XHTMLshouldbesettocompact.
Chapter 3: HTML and XHTML Element Reference 337
reversed ThisHTML5Booleanattributespecifiesthatthecountingofthelistshouldgoin
reverseorder.CSScountersprovidemuchmorefunctionalitythanthisattribute,butitis
usefulintheabsenceofthismorecomplicatedsyntax.
PART I
start Thisattributespecifiesthestartvaluefornumberingtheindividuallistitems.
AlthoughtheorderingtypeoflistelementsmightbeRomannumerals,suchasXXXI,or
letters,thevalueofstartisalwaysrepresentedasanumber.Tostartnumberingelements
fromtheletterC,use<oltype="A"start="3">.
type Thisattributeindicatesthenumberingtype:aindicateslowercaseletters,Aindicates
uppercaseletters,iindicateslowercaseRomannumerals,IindicatesuppercaseRoman
numerals,and1indicatesnumbers.Typesetinanolelementisusedfortheentirelist
unlessatypeattributeisusedwithinanenclosedlielement.
Examples
<oltype="1">
<li>Firststep
<ol>
<li>Watchnestedlists</li>
<li>Oftenclosedwrong</li>
</ol></li>
<li>Secondstep</li>
<li>Thirdstep</li>
</ol>
<olcompact="compact"type="I"start="30">
<li>Clause30</li>
<li>Clause31</li>
<li>Clause32</li>
</ol>
<!--HTML5changes-->
<olstart="3"reversed>
<li>...</li>
<li>...</li>
<li>...</li>
<li>Blastoff!</li>
</ol>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• UnderthestrictHTMLandXHTMLspecifications,theolelementnolonger
supportsthecompact,start,andtypeattributes.Theseaspectsoflistscanbe
controlledwithstylesheetrules.
338 Part I: Core Markup
• HTML5returnsthestartattributetoorderedlistsandaddsthereversed
attribute.
• UndertheXHTML1.0specification,thecompactattributemusthaveaquoted
attributevalue:<olcompact="compact">.
• TheHTML3.2specificationsupportsonlythecompact,start,andtypeattributes.
• TheHTML2.0specificationsupportsonlythecompactattribute.
Standard Syntax
<optgroup
class="classname(s)"
dir="ltr|rtl"
disabled="disabled"
id="uniquealphanumericidentifier"
label="textdescription"
lang="languagecode"
style="styleinformation"
title="advisorytext">
optionelements
</optgroup>
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
PART I
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Element-Specific Attributes
disabled Occurrenceofthisattributeindicatesthattheenclosedsetofoptionsisdisabled.
label Thisattributecontainsashortlabeltousewhentheselectionlistisrenderedasitems
inahierarchy.
Example
<label>
Wherewouldyouliketogoforyourvacation?
<select>
<optionid="choice1"value="HongKong">HongKong</option>
<optgrouplabel="SouthPacific">
<optionid="choice2"label="Australia"value="Australia">
Australia</option>
<optionid="choice3"label="Fiji"value="Fiji">
Wakaya(FijiIslands)</option>
<optionid="choice4"value="NewZealand">
NewZealand</option>
</optgroup>
<optionid="choice5"value="home"selected>Yourbackyard</option>
</select>
</label>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 6+,
XHTML 1.0, 1.1 Netscape 6+, Opera 7+, Safari 1+
Notes
• Thiselementshouldoccuronlywithinthecontextofaselectelement.
• Thevisualpresentationofthiselementmayvaryslightlybetweenbrowsers.
Standard Syntax
<option
class="classname(s)"
dir="ltr|rtl"
disabled="disabled"
id="uniquealphanumericidentifier"
340 Part I: Core Markup
label="textdescription"
lang="languagecode"
selected="selected"
style="styleinformation"
title="advisorytext"
value="optionvalue">
</option>
Element-Specific Attributes
disabled Presenceofthisattributeindicatesthattheparticularitemisnotselectable.
TraditionalHTMLdidnotrequireavalueforthisattribute,butitshouldbesettodisabled
underXHTML.
Chapter 3: HTML and XHTML Element Reference 341
label Thisattributecontainsashortlabelthatmightbemoreappealingtousewhenthe
selectionlistisrenderedasahierarchyduetothepresenceofanoptgroupelement.
PART I
selected Thisattributeindicatesthattheassociateditemisthedefaultselection.Ifthis
attributeisnotincluded,thefirstitemintheselectionlististhedefault.Iftheselect
elementenclosingtheoptionelementshasthemultipleattribute,theselectedattribute
mightoccurinmultipleentries.Otherwise,itshouldoccurinonlyoneentry.Under
XHTML,thevalueoftheselectedattributemustbesettoselected.
value Thisattributeindicatesthevaluetobeincludedwiththeformresultwhentheitem
isselected.
Example
<p>Whichisyourfavoritedog?:
<select>
<optionvalue="Scottie">Angus"</option>
<optionvalue="MiniSchnauzer"selected>Tucker</option>
<optionvalue="AustralianShepard">Sabrina</option>
<optionvalue="GermanShepard">Lucky</option>
</select>
</p>
Compatibility
HTML 2, 3.2. 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Notes
• UnderHTMLspecifications,theclosingtagfor<option>isoptional.However,for
XHTMLcompatibility,theclosingtag</option>isrequired.
• Thiselementshouldoccuronlywithinthecontextofaselectelement.
• TheHTML2.0and3.2specificationsdefineonlytheselectedandvalueattributes
forthiselement.
form="idofrelatedformelement"
hidden="hidden"
id="uniquealphanumericidentifier"
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
lang="languagecode"
name="elementnameforsubmissionpurposes"
spellcheck="true|false"
style="styleinformation"
tabindex="number"
title="advisorytext">
</output>
Element-Specific Attributes
for Thisattributeshouldbesettotheidvalue(s)oftheelementsthattargetthiselement.
form Thisattributeshouldbesettotheidvalueoftheformelementthattheoutput
elementisassociatedwith;otherwise,thenearestparentformisused.
name Thisattributeshouldsetthenametobeusedinaname/valuepairiftheelementis
usedinformsubmission.
Examples
<formaction="#"method="get"id="testform">
<p><inputtype="date"id="year"
oninput="year.value=valueAsDate.getYear()">
<p>HTML5releasedintheyear
<outputfor="year"> </output></p>
</form>
<outputform="testform"for="year"></output>
Compatibility
HTML5 Not currently supported by any browser, but addressed with a custom element.
Chapter 3: HTML and XHTML Element Reference 343
Note
• Thiselementsupportstwousefuleventhandlersthataregloballydefinedby
HTML5,onformchangeandonforminput,iftheelementwillbeusedtomonitor
PART I
formsitisassociatedwithratherthanformstargetingit.
<p> (Paragraph)
Thisblockelementisusedtodefineaparagraphoftext.
Standard Syntax
<p
align="center|justify|left|right"(transitionalonly)
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</p>
Element-Specific Attribute
align Thisattributespecifiesthealignmentoftextwithinaparagraph.Thedefaultvalueis
left.ThetransitionalspecificationofHTML4.01alsodefinescenter,justify,and
right.However,underthestrictHTMLandXHTMLspecifications,textalignmentcanbe
handledthroughtheCSSpropertytext-align.
Examples
<palign="right">Aright-alignedparagraph</p>
<pid="para1"class="defaultParagraph"
title="IntroductionParagraph">
Thisistheintroductoryparagraphforaverylongpaperaboutnothing.
</p>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Notes
• Becausepisablockelement,browserstypicallyinsertablankline,butthis
renderingshouldnotbeassumed,giventheriseofstylesheets,whichcanusethe
displaypropertytooverridethisaction.
• Underthestrict(X)HTMLandHTML5specifications,thealignattributeisnot
supported.AlignmentoftextcaninsteadbeaccomplishedusingCSSpropertieslike
text-align.
Chapter 3: HTML and XHTML Element Reference 345
• Theclosingtagforthe<p>tagisoptionalundertheHTMLspecification;however,
undertheXHTML1.0specification,theclosingtag</p>isrequiredforXHTML
compatibility.
PART I
• Asalogicalelement,emptyparagraphsareignoredbybrowsers,sodonottryto
usemultiple<p>tagsinarow,like<p><p><p><p>,toaddblanklinestoaWeb
page.
• Often,nonbreakingspaceentitiesareusedtoholdopenemptyparagraphs,likeso:
<p> </p>.Thevalueofthismarkupisquestionable.
• TheHTML3.2specificationsupportsonlythealignattributewithvaluesof
center,left,andright.
• TheHTML2.0specificationsupportsnoattributesforthepelement.
Standard Syntax
<param
id="uniquealphanumericidentifier"
name="parametername"
type="mimeType"
value="parametervalue"
valuetype="data|object|ref">
Element-Specific Attributes
name Thisattributecontainstheparameter’sname.Thenameoftheparameterdepends
ontheparticularobjectbeinginsertedintothepage,anditisassumedthattheobjectknows
howtohandlethepasseddata.Donotconfusethenameattributeforthiselementwiththe
nameattributeusedforformelements.Inthelattercase,thenameattributedoesnothavea
similarmeaningtoid,butratherspecifiesthenameofthedatatobepassedtoanenclosing
<object>tag.
type Whenthevaluetypeattributeissettoref,thetypeattributecanbeusedtoindicate
thetypeofinformationtoberetrieved.Legalvaluesforthisattributeareintheformof
MIMEtypes,suchastext/html.
value Thisattributecontainstheparameter’svalue.Theactualcontentofthisattribute
dependsontheobjectandtheparticularparameterbeingpassedin,asdeterminedbythe
nameattribute.
valuetype Thisattributespecifiesthetypeofthevalueattributebeingpassedin.Possible
valuesforthisattributeincludedata,object,andref.Avalueofdataspecifiesthatthe
informationpassedinthroughthevalueparametershouldbetreatedjustasdata.Avalue
ofrefindicatesthattheinformationbeingpassedinisaURLthatindicateswherethedata
tobeusedislocated.Theinformationisnotretrieved,buttheURLispassedtotheobject,
whichthencanretrievetheinformationifnecessary.Thelastvalue,object,indicatesthat
thevaluebeingpassedinisthenameofanobjectassetbyitsidattribute.Inpractice,the
dataattributeisusedbydefault.
Examples
<appletcode="plot.class">
<paramname="min"value="5">
<paramname="max"value="30">
<paramname="ticks"value=".5">
<paramname="line-style"value="dotted">
</applet>
<!--XHTMLstylehere-->
<objectclassid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="swflash.cab#version=2,0,0,0"
height="100"width="100">
Chapter 3: HTML and XHTML Element Reference 347
<paramid="param1"name="Movie"value="SplashLogo.swf"/>
<paramid="param2"name="Play"value="True"/>
</object>
PART I
Compatibility
HTML 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 3+,
XHTML 1.0, 1.1, Basic Netscape 4+, Opera 5+, Safari 1+
Notes
• TheHTML3.2specificationsupportsonlythenameandvalueattributesforthis
element.
• AsanemptyelementunderXHTMLorwhenusingXML-stylesyntaxforHTML5,a
trailingslashisrequiredforthiselement:<param/>.
Example
<!DOCTYPEhtmlPUBLIC"-//IETF//DTDHTML2.0//EN">
<html>
<head><title>PlaintextExample</title></head>
<body>
Therestofthisfileisinplaintext.
<plaintext>
Eventhoughthisissupposedtobe<b>bold</b>,thetagsstillshow.
Thereisnowaytoturnplaintextoffonceitison.</plaintext>
doesnothingtohelp.Even</body>and</html>willshowup.
348 Part I: Core Markup
Compatibility
HTML 2 Firefox 1+, Internet Explorer 2+, Netscape 1+, Opera 4+, Safari 1+
Notes
• Noclosingtagforthiselementisnecessarybecausethebrowserwillignorealltags
afterthestartingtag.
• Thiselementshouldnotbeused.Plaintextinformationcanbeindicatedbyafile
type,andinformationcanbeinsertedinapreformattedfashionusingthepre
element.
• Allmodernbrowsersatthetimeofthiseditioncontinuetosupportthistagdespite
documentationtothecontrary.
Standard Syntax
<pre
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericvalue"
lang="languagecode"
style="styleinformation"
title="advisorytext"
width="number"(transitionalonly)
xml:space="preserve">
</pre>
PART I
disabled="false|true"(5.5)
hidefocus="true|false"(5.5)
language="javascript|jscript|vbs|vbscript"(4)
tabindex="number"(5.5)
wrap="soft|hard|off"(4)
Element-Specific Attributes
width Thisattributeshouldbesettothewidthofthepreformattedregion.Thevalueofthe
attributeshouldbethenumberofcharacterstodisplay.Inpractice,thisattributeisnot
supportedandisdroppedunderthestrictHTML4.01specification.
wrap InsomeversionsofMicrosoftbrowsers,thisattributecontrolswordwrapbehavior
withina<pre>tag.Thedefaultvalueofofffortheattributeforcestheelementnottowrap
text,sotheviewermustmanuallyenterlinebreaks.Avalueofhardorsoftcausesword
wrapandsetsdifferenttypesoflinebreaksinthewrappedtext.Giventhenatureofthepre
element,thevalueofthisattributeislimited.
xml:space ThisattributeisincludedfromXHTML1.0andisusedtosetwhetherspacesneed
tobepreservedwithintheelementorthedefaultwhitespacehandlingshouldbeemployed.
350 Part I: Core Markup
Itiscuriousthatanelementdefinedtooverridetraditionalwhitespaceruleswouldallow
suchanattribute,andinpracticethisattributeisnotusedbydevelopers.
Example
<pre>
WithinPREFORMATTEDtextALLformattingISPRESERVED
NOmatterhowwilditis.Rememberthatsome
<b>HTML</b>markupisallowedwithinthe<PRE>element.
</pre>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• TheHTML4.01andXHTML1.0transitionalspecificationsstatethattheapplet,
basefont,big,font,img,object,small,sub,andsupelementsshouldnotbeused
withina<pre>tag.ThestrictHTMLandXHTMLspecificationsstatethatonlythe
<big>,<img>,<object>,<small>,<sub>,and<sup>tagsshouldnotbeusedwithin
the<pre>tag.Theotherexcludedelementsaremissing,astheyaredeprecatedfrom
thestrictspecification.Althoughtheseelementsshouldnotbeused,itappearsthatthe
morepopularbrowserswillrenderthemanyway.
• ThestrictHTMLandXHTMLspecificationsdropsupportforthewidthattribute,
whichwasnotwellsupportedanyway.
• TheHTML2.0and3.2specificationssupportonlythewidthattributeforthepre
element.
itemtype="microdatatypeinURLformat"
lang="languagecode"
max="positivefloatingpointnumber"
spellcheck="true|false"
PART I
style="styleinformation"
tabindex="number"
title="advisorytext"
value="0orfloatingpointnumber">
</progress>
Element-Specific Attributes
max Thevalueofthisattributeisapositivefloating-pointnumberindicatingthe
maximumvalueforprogress;oftenitwillbe100.
value Thevalueofthisattributeistheamountoftaskcomplete.Thismaybeapercentage,
butthereisnorequirementthatitbesuchameasurement.
Example
<p>Progress:<progressid="prog1"max="100.00"value="33.1">33.1</
progress>%</p>
<!--JavaScriptwouldbeusedtochangethevalueofthiselement
dynamically-->
Compatibility
HTML5 Not currently supported by any browsers, but could be simulated in modern browsers
via a custom element and JavaScript.
Notes
• Therearenounitsimpliedforthiselement.
• Thiselementisnotyetimplementedinanybrowser.However,giventhatmost
browserscanhandlecustomelements,itwouldbeeasyenoughtosimulatetheidea
ofitandevenapplyaCSSdisplaypropertyforit.But,withoutJavaScriptchanging
valueandpresentationdynamically,acustomelementwouldhavelittlevalue.
<q> (Quote)
Thiselementindicatesthattheenclosedtextisashortinlinequotation.
352 Part I: Core Markup
Standard Syntax
<q
cite="URLofsource"
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericstring"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</q>
PART I
oncontrolselect,oncopy,oncut,ondblclick,ondeactivate,ondrag,
ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,
onfocus,onfocusin,onfocusout,onhelp,onkeydown,onkeypress,onkeyup,
onlosecapture,onmousedown,onmouseenter,onmouseleave,onmousemove,
onmouseout,onmouseover,onmouseup,onmousewheel,onmove,onmoveend,
onmovestart,onpaste,onpropertychange,onreadystatechange,onresize,
onresizeend,onresizestart,onselectstart,ontimeerror
Element-Specific Attribute
cite ThevalueofthisattributeisaURLthatdesignatesasourcedocumentormessagefor
theinformationquoted.Thisattributeisintendedtopointtoinformationexplainingthe
contextorthereferenceforthequote.
Example
<p>IfyouwanttomakeagreatWebsitedon'tfollowthis
advice:<qstyle="color:red;"cite="http://democompany.com/ugly.html">
AfewgreenballsandarainbowbarwillgiveyouanexcitingWebpage
ChristmasTree!</q></p>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1, Basic Netscape 6+, Opera 4+, Safari 1+
Notes
• Thiselementisintendedforshortquotationsthatdon’trequireparagraphsorlarger
structures,ascomparedtotextthatwouldbecontainedwithin<blockquote>.
• Somebrowsers,likeInternetExplorer6,maynotmakeanysortofstylechangefor
quotations,butitispossibletoapplyastyleruletoprovidesomeindicationofa
changeinstyle.
• Mostbrowsers,includingIE8+,Opera,Safari,andMozilla-basedbrowserslike
Firefox,willwrapinlinequotationsinquotemarks.Thesecanbecontrolledbystyle
rules.MentionsintheHTML5specificationsuggestthatuseragentswillnotputin
quotationmarksandthiswillbeleftsolelytothedeveloper.Thisseemsahighly
dubiouspossibility.
Example
<!--TheKanjiforJapaneselanguagewiththehiraganaaboveitor
withinparensfornonrubyawarebrowsers-->
<p>
<ruby>
日本語<rp>(</rp><rt>にほんご</rt><rp>)</rp>
</ruby>
</p>
Compatibility
HTML5 XHTML 1.1 Internet Explorer 5+
Chapter 3: HTML and XHTML Element Reference 355
Note
• Otherbrowsersdonotpositiontherubytextelement(rt)butinsteadmovethert
contentabovethetextitisassociatedwith;thus,thesebrowsersarenotlistedas
PART I
supportingrt.Thepurposeoftherpelementistoshowthegroupingparentheses
insuchnonsupportingbrowsers,soinsomesenseallbrowserssupportthis
element.
Ruby No Ruby
contenteditable="false|true|inherit"(5.5)
dir="ltr|rtl"(5)
disabled="false|true"(5.5)
hidefocus="true|false"(5.5)
id="uniquealphanumericidentifier"(5)
lang="languagecode"(5)
language="javascript|jscript|vbs|vbscript"(5)
name="string"(5)
style="styleinformation"(5)
tabindex="number"(5)
title="advisorytext"(5)
unselectable="on|off">(5)
rubytext
</rt>
Example
<!--TheKanjiforJapaneselanguagewiththeromanjiaboveitor
withinparensfornonrubyawarebrowsers-->
<ruby>
日本語<rp>(</rp><rt>nihongo</rt><rp>)</rp>
</ruby>
</p>
Note
• Thertelementmustbeusedwithintherubyelement.
Chapter 3: HTML and XHTML Element Reference 357
Compatibility
HTML5 XHTML 1.1 Internet Explorer 5+
PART I
<ruby> (Ruby Annotation)
ThisinitiallyMicrosoft-specificelement,nowpartofHTML5,isusedwiththertelementto
createannotationsorpronunciationguidesforwordsandphrases.Thebasetextshouldbe
enclosedina<ruby>tag;theannotation,enclosedinan<rt>tag,willappearassmaller
textabovethebasetext.Therpelementcanbeusedtowrapcontenttodelimitrubytext
forbrowsersthatdonotsupportthisformatting.
tabindex="number"(5)
title="advisorytext">(5)
...basetext...
<rt>rubytext</rt>
</ruby>
Element-Specific Attribute
name Thisattributesetsanamefortherubybasetext.
Examples
<p>
<ruby>Thisisthebasetextwithintherubyelement
<rt>Thisistherubytext,whichshouldappearinasmallerfont
abovethebasetextinInternetExplorer5.0orhigher.</rt>
</ruby>
</p>
<p>
<ruby>
日本語<rp>(</rp><rt>にほんご</rt><rp>)</rp>
</ruby>
</p>
<p>
<ruby>
Japanese<rp>(</rp><rt>Don'tspeakit</rt><rp>)</rp>
</ruby>
</p>
Chapter 3: HTML and XHTML Element Reference 359
PART I
Compatibility
HTML5 XHTML 1.1 Internet Explorer 5+
Notes
• ThiselementwasintroducedinInternetExplorer5.0andisnowpartoftheHTML5
specification.
• Therubyelementmustbeusedinconjunctionwiththertelement;otherwise,it
willhavenomeaning.
<s> (Strikethrough)
Thiselementrenderstheenclosedtextwithalinedrawnthroughitandisasynonymfor
thestrikeelement.
Examples
<p>Thislinecontainsa<s>misstake</s>!</p>
<p>strike<s>1</s>...<strike>2</strike>...<s>3</s>...<strong>You'reout!</
strong></p>
Compatibility
HTML 4, 4.01 transitional Firefox 1+, Internet Explorer 2+,
XHTML 1.0 transitional Netscape 3+, Opera 4+, Safari 1+
Notes
• Thiselementshouldactthesameasthestrikeelement.
• ThisHTML3elementeventuallywasadoptedbyNetscapeandMicrosoftandlater
wasincorporatedintotheHTML4.01transitionalspecification.
• ThiselementhasbeendeprecatedbytheW3C.ThestrictHTML4.01specification
doesnotincludetheselementorthestrikeelement,andtheHTML5specification
indicatesitisobsoleteaswell.
• Itispossibletoindicatestrikethroughtextusingastylesheetwiththe
text-decorationpropertysettoline-through.
Standard Syntax
<samp
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericstring"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</samp>
Chapter 3: HTML and XHTML Element Reference 361
PART I
contenteditable="true|false|inherit"
contextmenu="idofmenu"
draggable="true|false|auto"
hidden="hidden"
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
Example
<p>Usethefollowingsalutationinalle-mailmessagestotheboss:
<samp>Pleaseexcusetheinterruption,ohexaltedmanager.</samp></p>
362 Part I: Core Markup
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• Asalogicalelement,sampisusefultobindstylerulesto.
• TheHTML2.0and3.2specificationssupportnoattributesforthiselement.
<script> (Scripting)
Thiselementenclosesstatementsinascriptinglanguageforclient-sideprocessing.Scripting
statementscaneitherbeincludedinlineorloadedfromanexternalfileandmightbe
commentedouttoavoidexecutionbybrowsersthatarenotscripting-aware.
Standard Syntax
<script
charset="characterset"
defer="defer"
id="uniquealphanumericidentifier"
language="scriptinglanguagename"
src="URLofscriptcode"
type="mimetype"
xml:space="preserve">
</script>
PART I
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Element-Specific Attributes
async PresenceofthisHTML5attributeindicatesthatthebrowsermightperformthefetch
orexecutionofthescripttobeasynchronouslyfromotheractivityinthepage.Themeaning
ofthisattributeversusthedeferattributewithremotescriptsinparticularisquiteunclear.
charset Thisattributedefinesthecharacterencodingofthescript.Thevalueisaspace-and/
orcomma-delimitedlistofcharactersetsasdefinedinRFC2045.
defer Presenceofthisattributeindicatesthatthebrowsermightdeferexecutionofthe
scriptenclosedbythe<script>tag.Supportforthisattributeisinconsistent,thoughitis
nowpartoftheHTML5specification.
event ThisMicrosoft-specificattributeisusedtodefineaparticulareventthatthescript
shouldreactto.Itmustbeusedinconjunctionwiththeforattribute.Eventnamesarethe
sameaseventhandlerattributes;forexample,onclick,ondblclick,andsoon.
for TheforattributeisusedinMicrosoftbrowserstodefinethenameoridoftheelement
towhichaneventdefinedbytheeventattributeisrelated.Forexample,<script
event="onclick"for="button1"language="vbscript">definesaVBScriptthatwill
executewhenaclickeventisissuedforanelementnamedbutton1.
language Thiscommonthoughnonstandardattributespecifiesthescriptinglanguagebeing
used.TheNetscapeimplementationsupportsJavaScript.TheMicrosoftimplementation
supportsJScript(aJavaScriptclone)aswellasVBScript,whichcanbeindicatedbyeither
vbsorvbscript.Othervaluesthatincludetheversionofthelanguageused,suchas
JavaScript1.1andJavaScript1.2,alsomightbepossibleandareusefultoexclude
browsersfromexecutingscriptcodethatisnotsupported.TheHTML5specification
indicatesthatwhilethisattributemaybewidelysupporteditshouldnotbeusedbypage
authors.
src ThisattributespecifiestheURLofafilecontainingscriptingcode.Typically,files
containingJavaScriptcodewillhavea.jsextension,andaserverwillattachtheappropriate
MIMEtype;ifnot,thetypeattributemightbeusedtoexplicitlysetthecontenttypeofthe
externalscriptfile.Thelanguageattributealsomightbehelpfulindeterminingthis.
364 Part I: Core Markup
type ThisattributeshouldbesettotheMIMEtypecorrespondingtothescriptinglanguage
used.ForJavaScript,forexample,thiswouldbetext/javascript.Inpractice,the
languageattributeismorecommonlyused,butthetypeattributeisstandard.Whennot
specified,thedefaultvalueistext/javascript.Thereisindicationthatitshouldactually
beapplication/javascript,butgiventhatbrowsersupportforthisvalueisnot
consistentitisdangeroustouse.Also,itispossibletoindicateversioninformationinthe
typeattributeforcertainbrowsers;forexample,toindicateJavaScript1.8youwoulduse
<scripttype="application/javascript;version=1.8">.
xml:space ThisattributeisincludedfromXHTML1.0andisusedtosetwhetherspaces
needtobepreservedwithinthescriptelementorthedefaultwhitespacehandlingshould
beemployed.Inpractice,thisattributeisnotoftenusedbydevelopers.
Examples
<scripttype="text/javascript">
alert("HelloWorld!!!");
</script>
<!--codeinexternalfile-->
<scriptlanguage="JavaScript1.2"src="superlib.js"></script>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 3+,
XHTML 1.0, 1.1 Netscape 2+, Opera 4+, Safari 1+
Notes
• Itiscommonpracticetocommentoutstatementsenclosedbya<script>tag.
Withoutcommenting,scriptcodecanbedisplayedaspagecontentbyuseragents
thatdonotsupportscripting.Theparticularcommentstylemightbedependenton
thelanguagebeingused.Forexample,inJavaScript,use
<scripttype="text/javascript">
<!--
JavaScriptcodehere
//-->
</script>
InVBScript,use
<scripttype="text/vbscript">
<!--
VBScriptcodehere
-->
</script>
XMLescapesusingCDATAsectionsarealsopossible;however,inallcasesitisbetter
toavoidintermixingscriptcodeinamarkupdocumentandinsteadtolinktoit.
• TheHTML3.2specificationdefinedaplaceholderscriptelement.
• TheeventandforattributesaredefinedundertransitionalversionsofHTML4.01
butonlyasreservedvalues.Laterspecificationsappeartohavedroppedpotential
supportforthem,thoughtheycontinuetobesupportedbyInternetExplorer.
Chapter 3: HTML and XHTML Element Reference 365
• MostbrowsersassumeJavaScriptwhenparsingascriptelementwithoutasettype
orlanguageattribute.
• Refertothe<noscript>tagreferenceinthisreferencetoseehowcontentmightbe
PART I
identifiedforbrowsersthatarenotscripting-aware.
• HTML5currentlyspecifiesallcommonattributesfora<script>tag,suchas
accesskey,spellcheck,andsoon,butmostofthesemakelittleifnosenseinthe
contextofthiselement.
<section> (Section)
ThisHTML5elementdefinesagenericsectionofadocumentanditmaycontainaheading
andfooterofitsown.
Element-Specific Attribute
Examples
<sectionid="section1">
<p>Firstparagraph.</p>
<p>Secondparagraph</p>
</section>
<!--sectionexample#2-->
<sectionid="section2">
<header><h1>SectionHeading</h1></header>
<p>Firstparagraph.</p>
<p>Secondparagraph.</p>
<footer><p>©2010FakeExamples,Inc.</p></header>
</section>
<!--nestedsectionexample#3-->
<section>
<h1>SectionHeading</h1>
<section>
<h2>NextSectionHeading</h2>
</section>
</section>
Compatibility
HTML5 Not currently supported by any browser, but can be addressed with a custom element.
Notes
• ThesectionelementisincludedinHTML5’sdocumentoutliningprocess.
• Thiselementisnotyetimplementedinanybrowser.However,giventhatmost
browserscanhandlecustomelements,itwouldbeeasyenoughtosimulatetheidea
ofitandevenapplyaCSSdisplaypropertyforit.
Standard Syntax
<select
class="classname(s)"
dir="ltr|rtl"
disabled="disabled"
id="uniquealphanumericidentifier"
lang="languagecode"
multiple="multiple"
name="uniquealphanumericname"
size="number"
Chapter 3: HTML and XHTML Element Reference 367
style="styleinformation"
tabindex="number"
title="advisorytext">
PART I
optionandoptgroupelementsonly
</select>
Element-Specific Attributes
align ThisMicrosoft-specificattributecontrolsthealignmentoftheimagewithrespectto
thecontentonthepage.Thedefaultvalueisleft,butothervaluessuchasabsbottom,
absmiddle,baseline,bottom,middle,right,texttop,andtopalsomightbe
supported.Themeaningofthesevaluesshouldbesimilartothoseusedforinsertedobjects,
suchasimages.
autofocus ThisHTML5Booleanattributeisusedtoindicatethattheuseragentshould
immediatelyfocusthisformitemonceitscontainingwindowobject(usuallythedocument)
ismadeactive.ItonlytakesanattributevalueofautofocuswhenusingtheXML-style
syntaxforHTML5.
disabled Thisattributeisusedtoturnoffaformcontrol.Elementswillnotbesubmitted,
norcantheyreceiveanyfocusfromthekeyboardormouse.Disabledformcontrolswillnot
bepartofthetabbingorder.Thebrowseralsocangrayouttheformthatisdisabled,to
indicatetotheuserthattheformcontrolisinactive.Thisattributerequiresnovalueunder
traditionalHTML,butunderXHTMLvariantsitshouldbesettodisabled.
form ThisHTML5attributeshouldbesettoastringthatcorrespondstotheidoftheform
elementthatthebuttonisassociatedwith.Thisallowsformelementsinoneformtotrigger
actionsinothers.
multiple Thisattributeallowstheselectionofmultipleitemsintheselectionlist.The
defaultissingle-itemselection.UnderXHTML,thisattributemusthaveitsvaluesetto
multiple.
name Thisattributeallowsaformcontroltobeassignedanamefordefiningthename/
valuepairusedinformsubmission.Traditionally,thesevalueswereusedbyscripting
languagesaswell,thoughthestandardsencouragetheuseoftheidattribute.For
compatibilitypurposes,bothmighthavetobeused.
size Thisattributesetsthenumberofvisibleitemsintheselectionlist.Whenthemultiple
attributeisnotpresent,onlyoneentryshouldshow;however,whenmultipleispresent,
thisattributeisusefulforsettingthesizeofthescrollinglistbox.
tabindex Thisattributetakesanumericvalueindicatingthepositionoftheformcontrol
inthetabbingindexfortheform.Tabbingproceedsfromthelowestpositivetabindex
valuetothehighest.Negativevaluesfortabindexwillleavetheformcontroloutofthe
Chapter 3: HTML and XHTML Element Reference 369
tabbingorder.Whentabbingisnotexplicitlyset,thebrowsermighttabthroughitemsin
theordertheyareencountered.Formcontrolsthataredisabledduetothepresenceofthe
disabledattributewillnotbepartofthetabbingindex.
PART I
Examples
<formaction="#"method="get">
<p><label>Chooseyourfavoritecolors:</label>
<selectname="colors"multiple="multiple"size="2">
<option>Red</option>
<option>Blue</option>
<option>Green</option>
<option>Yellow</option>
</select>
</p>
<label>TacoChoices:</label>
<selectname="tacomenu"id="tacomenu">
<optionvalue="SuperChicken">Chicken</option>
<optionvalue="Baja">Fish</option>
<optionvalue="TastyPig">Carnitas</option>
</select>
</p>
</form>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• TheHTML4.01specificationreservestheattributesdatafldanddatasrcfor
futureuse,buttheseareremovedunderXHTML.
• InternetExplorer’svariantofthedisabledattributeallowsvaluesoftrueand
false,aswellasthestandarddisabledvalue.
• UndertraditionalHTML,theendtag</option>isoftenomitted.
• Becarefulofthenameandidattributeproblemthatmayoccur,particularlywhen
settingthemultipleattribute.Itmaybebettertohaveseparatevalues.
• TheHTML2.0and3.2specificationsdefineonlymultiple,name,andsize
attributes.
Standard Syntax
<small
class="classname(s)"
dir="ltr|rtl"
370 Part I: Core Markup
id="uniquealphanumericstring"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</small>
onfocus,onfocusin,onfocusout,onhelp,onkeydown,onkeypress,onkeyup,
onlosecapture,onmousedown,onmouseenter,onmouseleave,onmousemove,
onmouseout,onmouseover,onmouseup,onmousewheel,onmove,onmoveend,
onmovestart,onpaste,onpropertychange,onreadystatechange,onresize,
PART I
onresizeend,onresizestart,onselectstart,ontimeerror
Examples
<p>Hereissome<small>smalltext</small>.</p>
<p>Thiselementcanbeapplied<small><small><small>multiple
times</small></small></small>tomakethingsevensmaller.</p>
Compatibility
HTML 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1 Netscape 2+, Opera 4+, Safari 1+
Notes
• Thiselementisequivalenttousingfont-size:smaller.
• A<small>tagcanbeusedmultipletimestodecreasethesizeoftexttoagreater
degree.Usingmorethansix<small>tagstogetherdoesn’tmakesensebecause
browserscurrentlyonlysupportrelativefontsizesfrom1to7or,inCSS,from
xx-smalltoxx-large.
• Withstylesheets,itwouldseemthiselementshouldbeinappropriate,similarto
otherobsoleteordeprecatedelements,includingbig,whichismarkedobsolete
underHTML5.However,currentlyitisincludedinthespecificationandisdefined
toindicatesidecommentsorsmallprinttext,asinlegalinformation.
<source> (Source)
ThisemptyHTML5elementisusedtospecifymultiplemediaresourcesformediaelements
likeaudioandvideo.
itemtype="microdatatypeinURLformat"
lang="languagecode"
media="mediatype"
spellcheck="true|false"
src="URLofmediaresource"
style="styleinformation"
tabindex="number"
title="advisorytext"
type="MIMEtypeoflinkedmedia">
Element-Specific Attributes
media Thisattributedefinestheintendedmediatypeofthelinkedmediasource,to
provideahinttoauseragentastowhetherthemediareferencedisappropriateorhowit
mightbeused.Itissimilartotheideaofamediaattributeinastylesheetspecifyingprint,
screen,projection,orothercommonvalues.
src ThisattributeissettotheURLofthemediasourcetolinkto.
type ThisattributeissettotheMIMEtypeofthelinkedmediafilespecifiedbythesrc
attribute.Oftenitalsoincludesacodecsvaluetoindicatehowamediaresourceis
encoded.However,theuseofcodecs,asalludedtoinChapter2,isabitofamessunder
HTML5sopageauthorsareurgedtotestcarefully.
Examples
<!--Multiplesourcestotry-->
<audio>
<sourcesrc="angus.ogg">
<sourcesrc="angus.mp4"type="audio/mp4">
</audio>
<!--XHTMLstyle-->
<video>
<sourcesrc="angus.mp4"type="video/mp4;codecs='avc1.58A01E,mp4a.40.2'"/>
</video>
Compatibility
HTML5 Firefox 3.5+, Safari 3.1+
Chapter 3: HTML and XHTML Element Reference 373
Notes
• Asanemptyelement,sourceshouldbewrittenunderXHTML5withaself-
identifyingclosetaglikeso<source/>.
PART I
• Browsersshouldusemultiplesourceelementsinafall-throughfashionfindingthe
firstappropriateversionforplayback.Pageauthorsshouldconsiderputtinginan
appropriatenumberofmediavariationstoaccountforbrowserdifferences.
Element-Specific Attributes
align Thisattributespecifiesthealignmentofthespacerwithrespecttosurroundingtext.
Itisusedonlywithspacerswithtype="block".Thedefaultvalueforthealignattribute
isbottom.Themeaningsofthealignvaluesaresimilartothoseofthealignvaluesused
withtheimgelement.
height Thisattributespecifiestheheightoftheinvisibleregion,inpixels.Itisusedonly
withspacerswithtype="block".
size Usedwithtype="block"andtype="horizontal"spacers,thisattributesetsthe
spacer’swidth,inpixels.Usedwithatype="vertical"spacer,thisattributeisusedtoset
thespacer’sheight.
type Thisattributeindicatesthetypeofinvisibleregion.Ahorizontalspaceradds
horizontalspacebetweenwordsandobjects.Averticalspaceraddsspacebetweenlines.
Ablockspacerdefinesageneral-purposepositioningrectangle,likeaninvisibleimagethat
textcanflowaround.
width Thisattributeisusedonlywiththetype="block"spacerandisusedtosetthe
widthoftheregion,inpixels.
Example
Alineoftextwithtwo<spacertype="horizontal"size="20">words
separatedby20pixels.Hereisalineoftext.<br>
<spacertype="vertical"size="50">
Hereisanotherlineoftextwithalargespacebetweenthetwo
374 Part I: Core Markup
lines.<spaceralign="left"type="block"height="100"width="100">This
isabunchoftextthatflowsaroundaninvisibleblockregion.You
couldhaveeasilyperformedthislayoutwithatable.
Compatibility
No standards support Netscape 3, 4, 4.5–4.8
Note
• Thiselementshouldnotbeused,becauseevennewerversionsoftheNetscape
browser(6and7)havedroppedsupportforthiselement.Itispresentedfor
historicalreasonsandwillbedroppedfromthereferenceinthenexteditionofthis
book.
Syntax
<span
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericstring"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</span>
datafld="columnname"(4)
dataformatas="html|text"(4)
datasrc="datasourceid"(4)
hidefocus="true|false"(5.5)
PART I
language="javascript|jscript|vbs|vbscript"(4)
tabindex="number"(5.5)
unselectable="on|off"(5.5)
Examples
<p>Hereissome<spanstyle="font-size:14px;color:purple;">very
strange</span>text.</p>
<p><spanid="toggletext"
onclick="this.style.color='red';"
ondblclick="this.style.color='black';">
ClickandDoubleClickMe
</span></p>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 3+,
XHTML 1.0, 1.1, Basic Netscape 4+, Opera 4+, Safari 1+
376 Part I: Core Markup
Notes
• TheHTML4.01specificationreservedthedatafld,dataformatas,anddatasrc
attributesforfutureuse.TheywerelaterdroppedfromXHTML.InternetExplorer4
andlatercontinuetosupporttheseattributesfordatabinding.
• Asagenericelement,span,likediv,isusefulforbindingstyletoarbitrary
content.However,spanisaninlineelementanddoesnotcauseareturnby
defaultasdivdoes.
Examples
<p>Thislinecontainsaspelling<strike>misstake</strike>mistake</p>.
PART I
<p>Price:$<strikestyle="color:red;">5.00</strike>3.00</p>
Compatibility
HTML 3.2, 4, 4.01 (transitional) Firefox 1+, Internet Explorer 2+,
XHTML 1.0 (transitional) Netscape 3+, Opera 4+, Safari 1+
Notes
• Thistagshouldactthesameasthe<s>tag.
• ThiselementhasbeendeprecatedbytheW3C.ThestrictHTMLandXHTML
specificationsincludeneitherthe<strike>tagnorthe<s>tagbecauseitispossible
toindicatestrikethroughtextusingthestylesheetpropertytext-decoration:
line-through.TheHTML5specificationalsoindicatesthiselementasobsolete.
Syntax
<strong
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericstring"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</strong>
Examples
<p>Itisreally<strong>important</strong>topayattention.</p>
<p>Thisisan<strongstyle="font-size:4em;color:red;">emergency!
</strong></p>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Notes
• Thiselementgenerallyrendersasboldtext.Asalogicalelement,however,strong
isusefultobindstylerulesto.
Chapter 3: HTML and XHTML Element Reference 379
• Ascomparedtob,thiselementdoeshavesomelogicalmeaning.Forexample,voice
browsersmayspeak<strong>-enclosedtextinadifferentvoicethanisusedfor
textthatisenclosedby<b>,thoughpracticallysuchdistinctionmaynotholdgiven
PART I
theneedofvoicebrowserstoactreasonablywithpagesnotcodedforthem.
Syntax
<style
dir="ltr|rtl"
id="uniquealphanumericstring"
lang="languagecode"
media="all|print|screen|others"
title="advisorytext"
type="MIMEType"
xml:space="preserve">
CSSrules
</style>
Common Attributes
disabled="disabled"(DOMLevel1)
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Element-Specific Attributes
disabled ThisinitiallyMicrosoft-definedattributeisusedtodisableastylesheet.The
presenceoftheattributeisallthatisrequiredtodisablethestylesheet.Inconjunctionwith
scripting,thisattributecouldbeusedtoturnonandoffvariousstylesheetsinadocument.
WhilenotdocumentedinlaterversionsofInternetExplorer,thisattributeisverymuch
supportedandused,sinceitispartoftheDOMstandard.InternetExplorermayalso
supportvaluesoftrueandfalse.
media Thisattributespecifiesthedestinationmediumforthestyleinformation.Thevalue
oftheattributecanbeasinglemediadescriptor,suchasscreen,oracomma-separatedlist.
Possiblevaluesforthisattributeincludeall,aural,braille,print,projection,
screen,andtv.Othervaluesalsomightbedefined,dependingonthebrowser.Internet
Explorersupportsall,print,andscreenasvaluesforthisattribute.
scoped ThisHTML5Booleanattributeisusedtoindicateifthestylesheetshouldbescoped;
inotherwords,applyonlythetreeitisenclosedwithin.Forexample,hereweseea<style>
tagfoundwithina<noscript>tag.
<noscript>
<styletype="text/css"scoped>
h1{color:red;}
</style>
<h1>Error:scriptingrequired</h1>
</noscript>
Withthescopedattributepresent,thestylingrulesshouldberestrictedsolelytothe
elementswithinthe<noscript>tag;thus,otherh1elementswouldnotbecoloredred.
Giventhelackofimplementationsandsomespecificationunclarity,pageauthorsshould
approachthisattributecautiously.
type Thisattributeisusedtodefinethetypeofstylesheet.Thevalueoftheattribute
shouldbetheMIMEtypeofthestylesheetlanguageused.Themostcommoncurrentvalue
forthisattributeistext/css,whichindicatesaCSSformat.
xml:space ThisattributeisincludedfromXHTML1.0andisusedtospecifywhether
spacesneedtobepreservedwithinthescriptelementorthedefaultwhitespacehandling
shouldbeemployed.
Chapter 3: HTML and XHTML Element Reference 381
Example
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN""http://www.w3.org/TR/
html4/strict.dtd">
PART I
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>SimpleStyleElementExample</title>
<styletype="text/css">
body{background:black;color:white;
font:12pxHelvetica;}
h1{color:red;font:14pxImpact;}
</style>
</head>
<body>
<h1>A14-pixelredImpactheadingonablack
background</h1>
<p>Regularbodytext,whichis12pixelwhiteHelvetica.</p>
</body>
</html>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 3+,
XHTML 1.0, 1.1 Netscape 4+, Opera 4+, Safari 1+
Notes
• Styleinformationalsocanbespecifiedinexternalstylesheetsasdefinedbya
<link>tag.
• Styleinformationcanalsobeassociatedwithaparticularelementusingthestyle
attribute.
• Stylerulesareoftencommentmaskedwithina<style>tagtoavoidinterpretation
bynonconformingbrowsers.
<styletype="text/css">
<!--
body{background-color:red;}
-->
</style>
• InternetExplorer’sconditionalcommentsalsoareusefultoaddressbrowser
concerns.Seethesection“<!--.[]..-->(ConditionalComment)”towardthestartof
thereference.
• ThemeaningofsomeHTML5globalattributeslikeaccesskey,contextmenu,
spellcheck,andstyleinparticulararequiteunclearforthiselementandmaybe
erroneous.
<sub> (Subscript)
Thiselementrendersitscontentassubscriptedtext.
382 Part I: Core Markup
Syntax
<sub
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericstring"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</sub>
PART I
oncontrolselect,oncopy,oncut,ondblclick,ondeactivate,ondrag,
ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,
onfocus,onfocusin,onfocusout,onhelp,onkeydown,onkeypress,onkeyup,
onlosecapture,onmousedown,onmouseenter,onmouseleave,onmousemove,
onmouseout,onmouseover,onmouseup,onmousewheel,onmove,onmoveend,
onmovestart,onpaste,onpropertychange,onreadystatechange,onresize,
onresizeend,onresizestart,onselectstart,ontimeerror
Examples
<p>Hereissome<sub>subscripted</sub>text.</p>
<p>ThesecretvalueoftheformulaisX<sub><small>2</small></sub>.</p>
Compatibility
HTML 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 3+,
XHTML 1.0, 1.1, Basic Netscape 2+, Opera 4+, Safari 1+
Notes
• TheHTML3.2specificationsupportsnoattributeforthesubelement.
• TheCSSpropertyvertical-aligncanbeusedtosimulatethiselement.
• Mostbrowsersmayslightlyshifttextlinesbelowa<sub>tag.
<sup> (Superscript)
Thiselementrendersitscontentassuperscriptedtext.
Syntax
<sup
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericstring"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</sup>
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
Examples
<p>Hereissome<sup>superscripted</sup>text.</p>
<p><var>x</var><sup>2</sup>=4when<var>x</var>=2</p>
Compatibility
HTML 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 2+, Opera 4+, Safari 1+
Chapter 3: HTML and XHTML Element Reference 385
Notes
• TheHTML3.2specificationsupportsnoattributeforthesupelement.
• ThiselementcanbesimulatedusingtheCSSpropertyvertical-align.
PART I
• Mostbrowsersmayslightlyshifttextlinesabovea<sup>tag.
<table> (Table)
Thiselementisusedtodefineatable.Tablesshouldbeusedtoorganizedata.However,
theyareoftenusedtoprovidestructureforlayingoutpagesintheabsenceofCSS.
Standard Syntax
<table
align="center|left|right"(transitionalonly)
bgcolor="colorname|#RRGGBB"(transitionalonly)
border="pixels"
cellpadding="pixels"
cellspacing="pixels"
class="classname(s)"
dir="ltr|rtl"
frame="above|below|border|box|hsides|
lhs|rhs|void|vsides"
id="uniquealphanumericidentifier"
lang="languagecode"
rules="all|cols|groups|none|rows"
style="styleinformation"
summary="summaryinformation"
title="advisorytext"
width="percentage|pixels">
caption,col,colgroup,thead,tbody,tfoot,andtrelementsonly
</table>
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
Element-Specific Attributes
align Thisattributespecifiesthealignmentofthetablewithrespecttosurroundingtext.
TheHTML4.01specificationdefinescenter,left,andright.Somebrowsersalsomight
supportalignmentvalues,suchasabsmiddle,thatarecommontoblockobjects.
Chapter 3: HTML and XHTML Element Reference 387
background Thisnonstandardattribute,whichissupportedbynearlyeverybrowser,
specifiestheURLofabackgroundimageforthetable.Theimageistiledifitissmallerthan
thetabledimensions.NotethatsomeearlyversionsofNetscapedisplaythebackground
PART I
imageineachtablecellratherthanbehindthecompletetable.
bgcolor Thisattributespecifiesabackgroundcolorforatable.Itsvaluecanbeeithera
namedcolor,suchasred,oracolorspecifiedinthehexadecimal#RRGGBBformat,suchas
#FF0000.
border Thisattributespecifies,inpixels,thewidthofatable’sborders.Avalueof0makes
aborderlesstable,whichisusefulforgraphicslayout.
bordercolor Thisattribute,supportedbyInternetExplorerandNetscape,isusedtosetthe
bordercolorforatable.Theattributeshouldbeusedonlywithapositivevalueforthe
borderattribute.Thevalueoftheattributecanbeeitheranamedcolor,suchasgreen,ora
colorspecifiedinthehexadecimal#RRGGBBformat,suchas#00FF00.Thecolor
applicationsmaybeslightlydifferentinbrowsers,sinceNetscapecolorsonlytheouter
borderofthetable.CSSshouldbeusedforborderstylinginsteadofthisattribute.
bordercolordark ThisInternetExplorer–specificattributespecifiesthedarkeroftwoborder
colorsusedtocreateathree-dimensionaleffectforcellborders.Itmustbeusedwiththe
borderattributesettoapositivevalue.Theattributevaluecanbeeitheranamedcolor,
suchasblue,oracolorspecifiedinthehexadecimal#RRGGBBformat,suchas#0000FF.
CSSshouldbeusedforborderstylinginsteadofthisattribute.
bordercolorlight ThisInternetExplorer–specificattributespecifiesthelighteroftwoborder
colorsusedtocreateathree-dimensionaleffectforcellborders.Itmustbeusedwiththe
borderattributesettoapositivevalue.Theattributevaluecanbeeitheranamedcolor,
suchasred,oracolorspecifiedinthehexadecimal#RRGGBBformat,suchas#FF0000.
CSSshouldbeusedforborderstylinginsteadofthisattribute.
cellpadding Thisattributesetsthewidth,inpixels,betweentheedgeofacellandits
content.
cellspacing Thisattributesetsthewidth,inpixels,betweenindividualcells.
cols Thisattributespecifiesthenumberofcolumnsinthetableandisusedtohelpquickly
calculatethesizeofthetable.Thisattributewaspartofthepreliminaryspecificationof
HTML4.0,butwaslaterdropped.Afewbrowsers,notablyNetscapeandInternetExplorer,
supportit.
datapagesize ThevalueofthisMicrosoft-specificattributeisthenumberofrecordsthatcan
bedisplayedinthetablewhendatabindingisused.
frame Thisattributespecifieswhichedgesofatablearetodisplayaborderframe.Avalue
ofaboveindicatesonlythetopedge;belowindicatesonlythebottomedge;andborder
andboxindicatealledges,whichisthedefaultwhentheborderattributeisapositive
integer.Avalueofhsidesindicatesonlythetopandbottomedgesshouldbedisplayed;
lhsindicatestheleftedgeshouldbedisplayed;rhsindicatestherightedgeshouldbe
388 Part I: Core Markup
displayed;vsidesindicatestheleftandrightedgesbothshouldbedisplayed;andvoid
indicatesnobordershouldbedisplayed.
height Thisattributespecifiestheheightofthetable,inpixelsorasapercentageofthe
browserwindow.Becareful,becausesomebrowserversionsmaynotsupportpercentage
valuesforheightormayhavevariationsinthiscalculationwhentheydosupportit.
hspace ThisNetscape-specificattributeindicatesthehorizontalspace,inpixels,between
thetableandsurroundingcontent,similartothesameattributeon<img>.
rules Thisattributecontrolsthedisplayofdividingruleswithinatable.Avalueofall
specifiesdividingrulesforrowsandcolumns.Avalueofcolsspecifiesdividingrulesfor
columnsonly.Avalueofgroupsspecifieshorizontaldividingrulesbetweengroupsoftable
cellsdefinedbythethead,tbody,tfoot,orcolgroupelements.Avalueofrowsspecifies
dividingrulesforrowsonly.Avalueofnoneindicatesnodividingrulesandisthedefault.
summary Thisattributeisusedtoprovideatextsummaryofthetable’spurposeand
structure.Thiselementisusedforaccessibility,anditspresenceisimportantfornonvisual
useragents.
vspace ThisNetscapeattributeindicatestheverticalspace,inpixels,betweenthetableand
surroundingcontent,similartothesameattributeon<img>.
width Thisattributespecifiesthewidthofthetable,eitherinpixelsorasapercentageof
theenclosingwindow.
Examples
<tablebgcolor="white"border="2">
<tr>
<td>Cell1</td>
<td>Cell2</td>
<td>Cell3</td>
<td>Cell4</td>
</tr>
<tr>
<td>Cell5</td>
<td>Cell6</td>
</tr>
</table>
<tablerules="all"bgcolor="yellow">
<caption>WidgetsbyArea</caption>
<theadalign="center"bgcolor="green"valign="middle">
<tr>
<td>Region</td>
<th>RegularWidget</th>
<th>SuperWidget</th>
</tr>
</thead>
Chapter 3: HTML and XHTML Element Reference 389
<tfootalign="right"bgcolor="red"valign="bottom">
<tr>
<td>Thisispartofthefooter.</td>
<td>Thisisalsopartofthefooter.</td>
PART I
</tr>
</tfoot>
<tbody>
<tr>
<th>WestCoast</th>
<td>10</td>
<td>12</td>
</tr>
<tr>
<th>EastCoast</th>
<td>1</td>
<td>20</td>
</tr>
</tbody>
</table>
Compatibility
HTML 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1.1+, Opera 4+, Safari 1+
Notes
• Inadditiontodisplayingtabulardata,tableshavebeenusedtosupportgraphics
layoutanddesign.CSSiscurrentlythesuggestedmethodforlayout,butcurrent
inspectionofsitessuggeststhatin2009table-basedlayoutisaliveandwell.
• TheHTML4specificationreservedtheattributesdatasrc,datafld,
dataformatas,anddatapagesizeforfutureversions.However,XHTMLdropped
theseattributes.TheyaresupportedinInternetExplorer4andlater.Earlydraftsof
theHTML5specificationintroducedadatagrid,whichseemtorevisittheseideas,
butitwaslaterdroppedwithindicationsitmayreturninfutureversionsofHTML.
• Atthetimeofthiswriting,mostbrowsershaveproblemswithcharandcharoff
attributesinalltable-relatedtags.
• TheHTML3.2specificationdefinesonlythealign,border,cellpadding,
cellspacing,andwidthattributesforthetableelement.
• Thecolsattributemightprovideanundesirableresultundersomeversionsof
Netscape,whichassumesthesizeofeachcolumninthetableisexactlythesame.
Standard Syntax
<tbodyalign="center|char|justify|left|right"
char="character"
charoff="offset"
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext"
valign="baseline|bottom|middle|top">
trelementsonly
</tbody>
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
PART I
Events Defined by Internet Explorer
onactivate,onbeforeactivate,onbeforecopy,onbeforecut,onbeforedeactivate,
onbeforeeditfocus,onbeforepaste,onblur,onclick,oncontextmenu,
oncontrolselect,oncopy,oncut,ondblclick,ondeactivate,ondrag,
ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,
onfocus,onfocusin,onfocusout,onhelp,onkeydown,onkeypress,onkeyup,
onlosecapture,onmousedown,onmouseenter,onmouseleave,onmousemove,
onmouseout,onmouseover,onmouseup,onmousewheel,onmove,onmoveend,
onmovestart,onpaste,onpropertychange,onreadystatechange,onresize,
onresizeend,onresizestart,onselectstart,ontimeerror
Element-Specific Attributes
align Thisattributeisusedtoalignthecontentsofthecellswithina<tbody>tag.
Commonvaluesarecenter,justify,left,andright.Thespecificationalsodefinesa
valueofchar.Whenalignissettochar,theattributecharmustbepresentandsettothe
charactertowhichcellsshouldbealigned.Acommonuseofthisapproachwouldbetoset
cellstoalignonadecimalpoint.Unfortunately,browsersdonotsupportthecharvaluefor
alignwell.
bgcolor Thisattributespecifiesabackgroundcolorforthecellswithina<tbody>tag.Its
valuecanbeeitheranamedcolor,suchasred,oracolorspecifiedinthehexadecimal
#RRGGBBformat,suchas#FF0000.
char Thisattributeisusedtodefinethecharactertowhichelementcontentsarealigned
whenthealignattributeissettothecharvalue.
charoff Thisattributecontainsanoffsetasapositiveornegativeintegertoaligncharacters
asrelatedtothecharvalue.Avalueof2wouldaligncharactersinacelltwocharactersto
therightofthecharacterdefinedbythecharattribute.
valign Thisattributeisusedtosettheverticalalignmentforthetablecellswithina
<tbody>tag.TheHTMLspecificationdefinesbaseline,bottom,middle,andtop.
InternetExploreralsosupportscenter,whichshouldactlikemiddle.
Example
<tablerule="all">
<thead>
<tr>
<td>Region</td>
<th>RegularWidget</th>
<th>SuperWidget</th>
</tr>
</thead>
<tbody>
<tr>
<th>WestCoast</th>
392 Part I: Core Markup
<td>10</td>
<td>12</td>
</tr>
<tr>
<th>EastCoast</th>
<td>1</td>
<td>20</td>
</tr>
</tbody>
</table>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1 Netscape 6+, Opera 5+, Safari 1+
Notes
• Thiselementisfoundonlyina<table>tagandcontainsoneormoretablerows,as
indicatedby<tr>tags.
• ForXHTMLcompatibility,theclosing</tbody>tagmustbeusedwiththis
element;however,itisoptionalundertraditionalHTMLaswellasHTML5.
Standard Syntax
<td
abbr="abbreviation"
align="center|justify|left|right"
axis="groupname"
bgcolor="colorname|#RRGGBB"(transitionalonly)
char="character"
charoff="offset"
class="classname"
colspan="numberofcolumnstospan"
dir="ltr|rtl"
headers="space-separatedlistofassociatedheader
cells'idvalues"
height="pixelsorpercentage"(transitionalonly)
id="uniquealphanumericidentifier"
lang="languagecode"
nowrap="nowrap"(transitionalonly)
rowspan="numberorrowstospan"
scope="col|colgroup|row|rowgroup"
style="styleinformation"
title="advisorytext"
valign="baseline|bottom|middle|top"
width="pixelsorpercentage">(transitionalonly)
</td>
Chapter 3: HTML and XHTML Element Reference 393
PART I
Attributes Introduced by HTML5
accesskey="spacedlistofacceleratorkey(s)"
contenteditable="true|false|inherit"
contextmenu="idofmenu"
data-X="user-defineddata"
draggable="true|false|auto"
hidden="hidden"
itemid="microdataidinURLformat"
itemprop="microdatavalue"
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
onfocus,onfocusin,onfocusout,onhelp,onkeydown,onkeypress,onkeyup,
onlosecapture,onmousedown,onmouseenter,onmouseleave,onmousemove,
onmouseout,onmouseover,onmouseup,onmousewheel,onmove,onmoveend,
onmovestart,onpaste,onpropertychange,onreadystatechange,onresize,
onresizeend,onresizestart,onselectstart,ontimeerror
Element-Specific Attributes
abbr Thevalueofthisattributeisanabbreviatednameforaheadercell.Thismightbe
usefulwhenattemptingtodisplaylargetablesonsmallscreens.Useragentsrarely
implementthisfeature.
align Thisattributeisusedtoalignthecontentsofthecells.Supportedvaluesarecenter,
justify,left,andright.
axis Thisattributeisusedtoprovideanameforagroupofrelatedheaders.
background Thisnonstandardattribute,whichissupportedbymajorbrowsers,specifies
theURLofabackgroundimageforthetablecell.Theimageistiledifitissmallerthanthe
cell’sdimensions.
bgcolor Thisattributespecifiesabackgroundcolorforatablecell.Itsvaluecanbeeithera
namedcolor,suchasred,oracolorspecifiedinthehexadecimal#RRGGBBformat,suchas
#FF0000.NotethatsomeolderversionsofNetscapeNavigatormaynotrenderanempty
cellwithacoloredbackgroundunlesssomecontentservingasplaceholder,suchasa
nonbreakingspaceortransparentpixel-gif,isinsertedinthecell.
bordercolor Thisattribute,supportedbyInternetExplorerandNetscape,isusedtosetthe
bordercolorforatablecell.Theattributeshouldbeusedonlywithapositivevalueforthe
borderattribute.Thevalueoftheattributecanbeeitheranamedcolor,suchasgreen,ora
colorspecifiedinthehexadecimal#RRGGBBformat,suchas#00FF00.
bordercolordark ThisInternetExplorer–specificattributespecifiesthedarkeroftwoborder
colorsusedtocreateathree-dimensionaleffectforacell’sborders.Itmustbeusedwiththe
borderattributesettoapositivevalue.Theattributevaluecanbeeitheranamedcolor,
suchasblue,oracolorspecifiedinthehexadecimal#RRGGBBformat,suchas#0000FF.
bordercolorlight ThisInternetExplorer–specificattributespecifiesthelighteroftwoborder
colorsusedtocreateathree-dimensionaleffectforacell’sborders.Itmustbeusedwiththe
borderattributesettoapositivevalue.Theattributevaluecanbeeitheranamedcolor,
suchasred,oracolorspecifiedinthehexadecimal#RRGGBBformat,suchas#FF0000.
char Thisattributeisusedtodefinethecharactertowhichelementcontentsarealigned
whenthealignattributeissettothecharvalue.
charoff Thisattributecontainsanoffset,specifiedasapositiveornegativeinteger,toalign
charactersasrelatedtothecharvalue.Avalueof2,forexample,wouldaligncharactersin
acelltwocharacterstotherightofthecharacterdefinedbythecharattribute.
Chapter 3: HTML and XHTML Element Reference 395
colspan Thisattributetakesanumericvaluethatindicateshowmanycolumnswideacell
shouldbe.Thisisusefulforcreatingtableswithcellsofdifferentwidths.
PART I
headers Thisattributetakesaspace-separatedlistofidvaluesthatcorrespondtothe
headercellsrelatedtothiscell.
height Thisattributeindicatestheheightofthecell,inpixelsorasapercentage.Some
browsersmayhaverenderingproblemswithpercentagevalues.
nowrap Thisattributekeepsthecontentwithinatablecellfromautomaticallywrapping.
ThenowrapattributetakesnovalueunderHTMLbutshouldbesettothevaluenowrap
underXHTML.
rowspan Thisattributetakesanumericvaluethatindicateshowmanyrowshighatable
cellshouldspan.Thisattributeisusefulindefiningtableswithcellsofdifferentheights.
scope Thisattributespecifiesthetablecellsforwhichthecurrentcellprovidesheader
information.Avalueofcolindicatesthatthecellisaheaderfortherestofthecolumn
belowit.Avalueofcolgroupindicatesthatthecellisaheaderforitscurrentcolumn
group.Avalueofrowindicatesthatthecellcontainsheaderinformationfortherestofthe
rowitisin.Avalueofrowgroupindicatesthatthecellisaheaderforitsrowgroup.This
attributemightbeusedinplaceoftheheaderattributeandisusefulforrendering
assistancebynonvisualbrowsers.ThisattributewasaddedverylatetotheHTML4
specification,andsupportforthisattributeisstillminimal.
valign Thisattributeisusedtosettheverticalalignmentforthetablecell.Thespecification
definesbaseline,bottom,middle,andtop.InternetExploreralsosupportscenter,
whichshouldbethesameasmiddle.
width Thisattributespecifiesthewidthofacell,inpixelsorasapercentagevalue.
Examples
<table>
<tr>
<tdalign="left"valign="top"width="100">
Putmeinthetopleftcorner.
</td>
<tdalign="right"bgcolor="red"valign="bottom"width="100">
Putmeinthebottomrightcorner.
</td>
</tr>
</table>
<tableborder="1"width="80%">
<tr>
<tdcolspan="3">
Aprettywidecell
</td>
<tr>
<td>Item2</td>
396 Part I: Core Markup
<td>Item3</td>
<td>Item4</td>
</tr>
</table>
Compatibility
HTML 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1.1+, Opera 4+, Safari 1+
Notes
• UndertheXHTML1.0specification,theclosing</td>tagceasestobeoptional.
• TheHTML3.2specificationdefinesonlyalign,colspan,height,nowrap,
rowspan,valign,andwidthattributes.
• Thiselementshouldalwaysbewithinthetrelement.
Standard Syntax
<textarea
accesskey="character"
class="classname"
cols="number"
dir="ltr|rtl"
disabled="disabled"
id="uniquealphanumericidentifier"
lang="languagecode"
name="uniquealphanumericidentifier"
readonly="readonly"
rows="number"
style="styleinformation"
tabindex="number"
title="advisorytext">
</textarea>
maxlength="positivenumber"
pattern="validationpattern"
placeholder="placeholdertext"
required="required"
PART I
spellcheck="true|false"
tabindex="number"
wrap="hard|soft"
Element-Specific Attributes
autofocus ThisHTML5Booleanattributeisusedtoindicatethattheuseragentshould
immediatelyfocusthisformitemonceitscontainingwindowobject(usuallythedocument)
398 Part I: Core Markup
ismadeactive.ItonlytakesanattributevalueofautofocuswhenusingtheXML-style
syntaxforHTML5.
cols Thisattributesetsthewidth,incharacters,ofthetextarea.Thetypicaldefaultvalue
forthesizeofa<textarea>tagwhenthisattributeisnotsetis20characters.
disabled Thisattributeisusedtoturnoffaformcontrol.Elementswillnotbesubmitted,
norcantheyreceiveanyfocusfromthekeyboardormouse.Disabledformcontrolswillnot
bepartofthetabbingorder.Thebrowseralsocangrayouttheformthatisdisabled,to
indicatetotheuserthattheformcontrolisinactive.Thisattributerequiresnovalue.
form ThisHTML5attributeshouldbesettoastringthatcorrespondstotheidoftheform
elementthataninteractivecontrolsuchasabuttonisassociatedwith.Thisallowsform
elementsinoneformtotriggeractionsinothers.
name Thisattributeallowsaformcontroltobeassignedanameforsubmittingtothe
servertheappropriatename/valuepair.Previouslyitwasalsousedsothatthefieldcould
bereferencedbyascriptinglanguage.However,itismoreappropriatetousetheid
attribute.Forcompatibilitypurposes,bothattributesmightbeusedandsettothesame
value.
pattern ThisHTML5attributespecifiesaregularexpressionagainstwhichthefieldshould
bevalidated.Thetitleattributeshouldbeprovidedwhenthisattributeisused,togivean
indicationofwhatisanacceptablepatternandwhatisn’t.
placeholder ThisHTML5attributespecifiesashortbitoftextthatisusedtohelptheuser
figureoutwhattypeofinformationtofillinforaformcontrol.Likely,thetextwillbe
placedinthefieldandcleareduponfocus.
readonly Thisattributepreventstheformcontrol’svaluefrombeingchanged.Form
controlswiththisattributesetmightreceivefocusfromtheuserbutshouldnotpermitthe
usertomodifythevalue.Becauseitreceivesfocus,areadonlyformcontrolwillbepartof
theform’stabbingorder.Finally,thecontrol’svaluewillbesentonformsubmission.Under
XHTML,thevalueofthereadonlyattributeshouldbesettoreadonly.
required ThepresenceofthisHTML5Booleanattributeindicatesthattheuserisrequired
toprovideavalueforthe<textarea>tagfortheformtobesubmitted.Useragentsthat
understandthisshouldsettheCSSpseudo-class:invalidwhenthefieldgoesintoerror.
rows Thisattributesetsthenumberofrowsinthetextarea.Thevalueoftheattribute
shouldbeapositiveinteger.
wrap InsomeversionsofNetscape(laterFirefox)andMicrosoftbrowsers,thisattribute
controlsword-wrapbehavior.Avalueofofffortheattributeforcesthe<textarea>tag
nottowraptext,sotheviewermustmanuallyenterlinebreaks.Avalueofhardcauses
wordwrapandincludeslinebreaksintextsubmittedtotheserver.Avalueofsoftcauses
wordwrapbutremoveslinebreaksfromtextsubmittedtotheserver.InternetExplorer
supportsavalueofphysical,whichisequivalenttoNetscape’shardvalue,andavalueof
virtual,whichisequivalenttoNetscape’ssoftvalue.Ifthewrapattributeisnot
Chapter 3: HTML and XHTML Element Reference 399
included,textwillstillwrapunderInternetExplorer,butolderversionsofNetscape,
notablyNetscape4,willscrollhorizontallyinthetextbox.Giventhisproblem,eventhough
itisnonstandard,itmaybeagoodideatoincludethewrapattribute.HTML5reintroduces
PART I
thisattributewiththevaluesofhardandsoft.Useofthisattributeassumesthatthecols
attributehasbeensetproperly.
Examples
<textareaid="CommentBox"cols="40"rows="8">
Defaulttextinfield
</textarea>
<textareaname="comment"id="comment"rows="10"cols="40"wrap="hard"
align="center">
</textarea>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• Anytextbetweenthe<textarea>and</textarea>tagsisrenderedasthedefault
entryfortheformcontrol.Contentwithinatextareaelementisnotinterpreted,so
whitespaceispreservedandtagsthemselvesareignored.
• Thetextareaelementtraditionallylacksamaxlengthattribute,whichcausesa
moreobvioussecurityrisk.TheHTML5specificationdoesintroduceamaxlength
valuetorestrictthenumberofcharactersthatmaybeentered.However,itshould
benotedthatallclient-sideformvalidationsshouldbeassumedasuser
conveniencesonlyandnotsecurity,astheymaybeeasilyremovedbymalicious
users.
• A<textarea>tagcannotbeadescendentofana(anchor)orbuttonelement.
• TheHTML4.01specificationreservesthedatafldanddatasrcattributesfor
futureusewiththetextareaelement.
• TheHTML2.0and3.2specificationsdefineonlythecols,name,androws
attributesforthiselement.
Standard Syntax
<tfoot
align="center|char|justify|left|right"
char="character"
charoff="offset"
400 Part I: Core Markup
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext"
valign="baseline|bottom|middle|top">
trelementsonly
</tfoot>
PART I
oncontrolselect,oncopy,oncut,ondblclick,ondeactivate,ondrag,
ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,
onfocus,onfocusin,onfocusout,onhelp,onkeydown,onkeypress,onkeyup,
onlosecapture,onmousedown,onmouseenter,onmouseleave,onmousemove,
onmouseout,onmouseover,onmouseup,onmousewheel,onmove,onmoveend,
onmovestart,onpaste,onpropertychange,onreadystatechange,onresize,
onresizeend,onresizestart,onselectstart,ontimeerror
Element-Specific Attributes
align Thisattributeisusedtoalignthecontentsofthecellswithina<tfoot>tag.
Commonvaluesarecenter,justify,left,andright.TheHTMLandXHTML
specificationsalsodefineavalueofchar.Whenalignissettochar,theattributechar
mustbepresentandsettothecharactertowhichcellsshouldbealigned.Acommonuseof
thisapproachwouldbetosetcellstoalignonadecimalpoint.
char Thisattributeisusedtodefinethecharactertowhichelementcontentsarealigned
whenthealignattributeissettothecharvalue.
charoff Thisattributecontainsanoffset,asapositiveornegativeinteger,foraligning
charactersasrelatedtothecharvalue.Avalueof2,forexample,wouldaligncharactersin
acelltwocharacterstotherightofthecharacterdefinedbythecharattribute.
valign Thisattributeisusedtosettheverticalalignmentforthetablecellswithina
<tfoot>tag.Thespecificationdefinesbaseline,bottom,middle,andtop.Internet
Exploreralsosupportscenter,whichshouldbethesameasmiddle.
Example
<tableborder="1"width="80%">
<tfootalign="center"class="tablefooter"
valign="bottom">
<td>Thisispartofthefooter.</td>
<td>Thisisalsopartofthefooter.</td>
</tfoot>
<tbodyclass="tablebody">
<tr>
<td>Thecontentsofthetable!</td>
</tr>
</tbody>
</table>
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1 Netscape 6+, Opera 5+, Safari 1+
402 Part I: Core Markup
Notes
• Thiselementiscontainedonlybythetableelementandcontainstablerowsas
delimitedbytrelements.
• Whileitwouldseemthatthiselementshouldcomeaftera<tbody>tag,itactually
shouldcomebeforeit,withina<table>tag.
• UndertheXHTML1.0specification,theclosing</tfoot>tagceasestobeoptional.
Standard Syntax
<th
abbr="abbreviation"
align="center|justify|left|right"
axis="groupname"
bgcolor="colorname|#RRGGBB"(transitionalonly)
char="character"
charoff="offset"
class="classname"
colspan="number"
dir="ltr|rtl"
headers="space-separatedlistofassociatedheader
cells'idvalues"
height="pixels"(transitionalonly)
id="uniquealphanumericidentifier"
lang="languagecode"
nowrap="nowrap"(transitionalonly)
rowspan="number"
scope="col|colgroup|row|rowgroup"
style="styleinformation"
title="advisorytext"
valign="baseline|bottom|middle|top"
width="pixels">(transitionalonly)
</th>
draggable="true|false|auto"
hidden="hidden"
itemid="microdataidinURLformat"
itemprop="microdatavalue"
PART I
itemref="space-separatedlistofIDsthatmaycontainmicrodata"
itemscope="itemscope"
itemtype="microdatatypeinURLformat"
spellcheck="true|false"
tabindex="number"
Element-Specific Attributes
abbr Thevalueofthisattributeisanabbreviatednameforaheadercell.Thismightbe
usefulwhenattemptingtodisplaylargetablesonsmallscreens.Useragentsrarelysupport
thisattribute.
404 Part I: Core Markup
align Thisattributeisusedtoalignthecontentsofthecellswithina<th>tag.Common
valuesarecenter,justify,left,andright.
axis Thisattributeisusedtoprovideanameforagroupofrelatedheaders.
background Thisnonstandardattribute,whichissupportedbymostbrowsers,specifiesthe
URLofabackgroundimageforthetablecell.Theimageistiledifitissmallerthanthecell’s
dimensions.
bgcolor Thisattributespecifiesabackgroundcolorforatablecell.Itsvaluecanbeeithera
namedcolor,suchasred,oracolorspecifiedinthehexadecimal#RRGGBBformat,suchas
#FF0000.
bordercolor Thisattribute,supportedbyInternetExplorerandNetscape,isusedtosetthe
bordercolorforatablecell.Theattributeshouldbeusedonlywithapositivevalueforthe
borderattribute.Thevalueoftheattributecanbeeitheranamedcolor,suchasgreen,ora
colorspecifiedinthehexadecimal#RRGGBBformat,suchas#00FF00.
bordercolordark ThisInternetExplorer–specificattributespecifiesthedarkeroftwoborder
colorsusedtocreateathree-dimensionaleffectforacell’sborders.Itmustbeusedwiththe
borderattributesettoapositivevalue.Theattributevaluecanbeeitheranamedcolor,
suchasblue,oracolorspecifiedinthehexadecimal#RRGGBBformat,suchas#0000FF.
bordercolorlight ThisInternetExplorer–specificattributespecifiesthelighteroftwoborder
colorsusedtocreateathree-dimensionaleffectforacell’sborders.Itmustbeusedwiththe
borderattributesettoapositivevalue.Theattributevaluecanbeeitheranamedcolor,
suchasred,oracolorspecifiedinthehexadecimal#RRGGBBformat,suchas#FF0000.
char Thisattributeisusedtodefinethecharactertowhichelementcontentsarealigned
whenthealignattributeissettothecharvalue.
charoff Thisattributecontainsanoffset,specifiedasapositiveornegativeinteger,for
aligningcharactersasrelatedtothecharvalue.Avalueof2,forexample,wouldalign
charactersinacelltwocharacterstotherightofthecharacterdefinedbythecharattribute.
colspan Thisattributetakesanumericvaluethatindicateshowmanycolumnswideacell
shouldbe.Thisisusefulforcreatingtableswithcellsofdifferentwidths.
headers Thisattributetakesaspace-separatedlistofidvaluesthatcorrespondtothe
headercellsrelatedtothiscell.
height Thisattributeindicatestheheightofthecell,inpixelsorasapercentage.Some
browsersmayhaverenderingproblemswithpercentagevalues.
nowrap Thisattributekeepsthecontentwithinatablecellfromautomaticallywrapping.
ThenowrapattributetakesnovalueunderHTMLbutshouldbesettothevaluenowrap
underXHTML.
rowspan Thisattributetakesanumericvaluethatindicateshowmanyrowshighatable
cellshouldspan.Thisattributeisusefulindefiningtableswithcellsofdifferentheights.
Chapter 3: HTML and XHTML Element Reference 405
scope Thisattributespecifiesthetablecellsforwhichthecurrentcellprovidesheader
information.Avalueofcolindicatesthatthecellisaheaderfortherestofthecolumn
belowit.Avalueofcolgroupindicatesthatthecellisaheaderforitscurrentcolumn
PART I
group.Avalueofrowindicatesthatthecellcontainsheaderinformationfortherestofthe
rowitisin.Avalueofrowgroupindicatesthatthecellisaheaderforitsrowgroup.This
attributecanbeusedinplaceoftheheaderattributeandisusefulforrenderingassistance
bynonvisualbrowsers.ThisattributewasaddedverylatetotheHTML4.0specification,
andsupportforthisattributeisstillminimalinbrowsers.
valign Thisattributeisusedtosettheverticalalignmentforthetablecell.Thespecification
definesbaseline,bottom,middle,andtop.InternetExploreralsosupportscenter,
whichshouldbethesameasmiddle.
width Thisattributespecifiesthewidthofacell,inpixelsorasapercentagevalue.
Example
<tableborder="1">
<tr>
<th>Names</th>
<th>Apples</th>
<th>Oranges</th>
</tr>
<tr>
<td>Rusty</td>
<td>10</td>
<td>5</td>
</tr>
<tr>
<td>RubySue</td>
<td>20</td>
<td>3</td>
</tr>
</table>
Compatibility
HTML 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1.1+, Opera 4+, Safari 1+
Notes
• TheHTML3.2specificationdefinesonlyalign,colspan,height,nowrap,
rowspan,valign,andwidthattributes.
• Thiselementshouldalwaysbewithinthetrelement.
• UndertheXHTML1.0specification,theclosing</th>tagceasestobeoptional.
Standard Syntax
<thead
align="center|char|justify|left|right"
char="character"
charoff="offset"
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext"
valign="baseline|bottom|middle|top">
trelementsonly
</thead>
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
PART I
Events Defined by Internet Explorer
onactivate,onbeforeactivate,onbeforecopy,onbeforecut,onbeforedeactivate,
onbeforeeditfocus,onbeforepaste,onblur,onclick,oncontextmenu,
oncontrolselect,oncopy,oncut,ondblclick,ondeactivate,ondrag,
ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,
onfocus,onfocusin,onfocusout,onhelp,onkeydown,onkeypress,onkeyup,
onlosecapture,onmousedown,onmouseenter,onmouseleave,onmousemove,
onmouseout,onmouseover,onmouseup,onmousewheel,onmove,onmoveend,
onmovestart,onpaste,onpropertychange,onreadystatechange,onresize,
onresizeend,onresizestart,onselectstart,ontimeerror
Element-Specific Attributes
align Thisattributeisusedtoalignthecontentsofthecellswithina<thead>tag.Common
valuesarecenter,justify,left,andright.Thespecificationalsodefinesavalueof
char.Whenalignissettochar,theattributecharmustbepresentandsettothecharacter
towhichcellsshouldbealigned.Acommonuseofthisapproachwouldbetosetcellsto
alignonadecimalpoint.
char Thisattributeisusedtodefinethecharactertowhichelementcontentsarealigned
whenthealignattributeissettothecharvalue.
charoff Thisattributecontainsanoffset,specifiedasapositiveornegativeinteger,for
aligningcharactersasrelatedtothecharvalue.Avalueof2,forexample,wouldalign
charactersinacelltwocharacterstotherightofthecharacterdefinedbythecharattribute.
valign Thisattributeisusedtosettheverticalalignmentforthetablecellswitha<thead>
tag.Thespecificationdefinesbaseline,bottom,middle,andtop.InternetExploreralso
supportscenter,whichshouldbethesameasmiddle.
Example
<tableborder="1"width="80%">
<theadalign="center"class="footer"
valign="bottom">
<td>ThisistheImportantTableHeadline</td>
</thead>
<tbodyclass="tablebody">
<tr>
<td>Thecontentsofthetable!</td>
</tr>
</tbody>
</table>
408 Part I: Core Markup
Compatibility
HTML 4, 4.01, 5 Firefox 1+, Internet Explorer 4+,
XHTML 1.0, 1.1 Netscape 6+, Opera 5+, Safari 1+
Notes
• Thiselementiscontainedonlybya<table>tagandcontainstablerowsas
delimitedby<tr>tags.
• UndertheXHTML1.0specification,theclosing</thead>tagceasestobeoptional.
<time> (Time)
ThisinlineHTML5elementenclosescontentthatrepresentsadateand/ortime.
Element-Specific Attributes
datetime Thisattributeisusedtoindicatethedateandtimeoftheenclosedcontent.The
PART I
valueoftheattributeisadateinaspecialformatasdefinedbyISO8601.Thebasicdate
formatis
YYYY-MM-DDThh:mm:ssTZD
wherethefollowingistrue:
YYYY=four-digityearsuchas1999
MM=two-digitmonth(01=January,02=February,andsoon.)
DD=two-digitdayofthemonth(01through31)
hh=two-digithour(00to23)(24-hourclock,notAMorPM)
mm=two-digitminute(00through59)
ss=two-digitsecond(00through59)
TZD=timezonedesignator
ThetimezonedesignatoriseitherZ,whichindicatesUniversalTimeCoordinateor
coordinateduniversaltimeformat(UTC),or+hh:mm,whichindicatesthatthetimeisalocal
timethatishhhoursandmmminutesaheadofUTC.Alternatively,theformatforthetime
zonedesignatorcouldbe-hh:mm,whichindicatesthatthelocaltimeisbehindUTC.Note
thattheletterTactuallyappearsinthestring,alldigitsmustbeused,and00valuesfor
minutesandsecondsmightberequired.Anexamplevalueforthedatetimeattribute
mightbe1999-10-6T09:15:00-05:00,whichcorrespondstoOctober6,1999,9:15A.M.,
U.S.EasternStandardTime.
pubdate ThisBooleanattribute,whenspecified,indicatesthatthedateandtimegiven
bythiselementshouldbeappliedasthepublicationdateofanenclosingarticleelement.
Ifthereisnoenclosingarticleelement,thepublicationdatewouldapplytotheentire
document.UnderXHTML5,thevalueoftheattributeshouldbepubdateforXMLsyntax
conformance.
Examples
<p>Mysonwasbornon<timedatetime="2006-01-13">Fridaythe13th</time>so
itismynewluckyday.</p>
<p>Todayitis<time>2010-07-08</time>whichisaninterestingdate.</p>
<p>WhendidtheMoonrunaway?<time>1999-09-13T09:15:00-05:00</time></p>
<!--exampleshowsthepubdateapplicationtotheenclosingarticle-->
<articleid="article1">
<header>
<h1>HTML5isComingSoon!</h1>
<p><timepubdatedatetime="2009-10-31T12:30-11:00"></time></p>
</header>
<p>ThenewHTML5specificationisintheworks.Whilemanyfeaturesare
notcurrentlyimplementedorevenwelldefinedyet,progressisbeingmade.
StaytunedtoseemorenewHTMLelementsaddedtoyourWebdocumentsinthe
yearstocome.</p>
</article>
410 Part I: Core Markup
Compatibility
HTML5 Not currently supported by any browser, but addressed via a custom element.
Notes
• Thiselementshouldcontaincontentthatisinthecorrectformatunlessthe
datetimeattributeisused.Ofcourse,browsersaren’tgoingtoenforcethis,butitis
importantifyouwantcorrectHTML5conformance.
• Thiselementisnotyetimplementedinanybrowser.However,giventhatmost
browserscanhandlecustomelements,itwouldbeeasyenoughtosimulatetheidea
ofitdirectlyorusea<span>tagwithacustomclass.
Standard Syntax
<title
dir="ltr|rtl"
lang="languagecode">
</title>
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
PART I
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Example
<head><title>BigCompany:Products:SuperWidget</title></head>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 2.1+, Safari 1+
Notes
• Often,thetitleissetasthefirstelementfoundinthehead,thoughitshouldcome
afteracharactersetindicationifthatisnottakencareofbyappropriateHTTP
headers.
• Meaningfulnamesshouldprovideinformationaboutthedocument.Apoortitle
wouldbesomethinglike“MyHomePage,”whereasabettertitlewouldbe“Joe
SmithHome.”
• Browserscanbeextremelysensitivetothe<title>tag.Ifthetitleelementis
malformedornotclosed,thepagemightnotevenrenderinthebrowser.
• TheHTML2.0and3.2specificationsdefinenoattributesforthetitleelement.
• Undermostbrowsers,coreHTML4attributevalueslikeidandclasswillwork
forDOMaccessandmakesomesenseformanipulationviaJavaScript,butother
attributesforeventsorstyle-relatedfeaturesdonot.
• Thetitleelementmaycontaincharacterentitiestosetaccentsorintroduceother
specialcharacters,thoughyoushouldusecautiontomakesuretheappropriate
charactersethasbeendefined.Markupmaynotbeincludedinthetitleelement.
• Currently,theHTML5specificationdefinesallthecommonattributesforthetitle
element,likeaccesskey,class,contextmenu,andsoon.Theircontext,however,
seemsinappropriategivenhowbrowserswork.Forexample,whileitispossibleto
imagineatabbingorderorcontextmenuforabrowsertitle,sofarsuchthingsare
unclearandsuggestanovergeneralizationoftheHTML5specificationwhenit
comestoglobalattributes.
Syntax
<tr
align="center|justify|left|right|char"
bgcolor="colorname|#RRGGBB"(transitionalonly)
char="character"
charoff="offset"
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext"
valign="baseline|bottom|middle|top">
tdorthelementsonly
</tr>
ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,
onerror,onfocus,onformchange,onforminput,oninput,oninvalid,onkeydown,
onkeypress,onkeyup,onload,onloadeddata,onloadedmetadata,onloadstart,
onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,
PART I
onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,
onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,
onsuspend,ontimeupdate,onvolumechange,onwaiting
Element-Specific Attributes
align Thisattributeisusedtoalignthecontentsofthecellswithintheelement.Common
valuesarecenter,justify,left,andright.Ifavalueissettochar,alignmentissetto
alignoffthecharacterdefinedbythecharattribute,withoffsetappliedbycharoffset.
bgcolor Thisattributespecifiesabackgroundcolorforallthecellsinarow.Itsvaluecanbe
eitheranamedcolor,suchasred,oracolorspecifiedinthehexadecimal#RRGGBBformat,
suchas#FF0000.
bordercolor Thisattribute,supportedbyanumberofbrowsers,includingInternetExplorer,
isusedtosetthebordercolorfortablecellsintherow.Theattributeshouldbeusedonly
withapositivevaluefortheborderattribute.Thevalueoftheattributecanbeeithera
namedcolor,suchasgreen,oracolorspecifiedinthehexadecimal#RRGGBBformat,such
as#00FF00.CSSshouldbeusedinstead.
bordercolordark ThisInternetExplorer–specificattributespecifiesthedarkeroftwoborder
colorsusedtocreateathree-dimensionaleffectforthecell’sborders.Itmustbeusedwith
theborderattributesettoapositivevalue.Theattributevaluecanbeeitheranamedcolor,
suchasblue,oracolorspecifiedinthehexadecimal#RRGGBBformat,suchas#0000FF.
CSSshouldbeusedinstead.
bordercolorlight ThisInternetExplorer–specificattributespecifiesthelighteroftwoborder
colorsusedtocreateathree-dimensionaleffectforacell’sborders.Itmustbeusedwiththe
borderattributesettoapositivevalue.Theattributevaluecanbeeitheranamedcolor,
suchasred,oracolorspecifiedinthehexadecimal#RRGGBBformat,suchas#FF0000.
CSSshouldbeusedinstead.
char Thisattributeisusedtodefinethecharactertowhichelementcontentsarealigned
whenthealignattributeissettothecharvalue.
414 Part I: Core Markup
charoff Thisattributecontainsanoffset,specifiedasapositiveornegativeinteger,for
aligningcharactersasrelatedtothecharvalue.Avalueof2,forexample,wouldalign
charactersinacelltwocharacterstotherightofthecharacterdefinedbythecharattribute.
valign Thisattributeisusedtosettheverticalalignmentforthetablecellswitha<tr>tag.
Thespecificationdefinesbaseline,bottom,middle,andtop.InternetExploreralso
allowscenter,whichshouldbethesameasmiddle.
Example
<tablewidth="300"border="1">
<tralign="center"valign="middle">
<td>3</td>
<td>5.6</td>
<td>7.9</td>
</tr>
</table>
Compatibility
HTML 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1.1+, Opera 4+, Safari 1+
Notes
• Thistagiscontainedonlyinthe<table>,<thead>,<tbody>,and<tfoot>tags.It
containsthe<th>and<td>tags.
• TheHTML3.2specificationdefinesonlythealignandvalignattributesforthis
element.
• InternetExplorer6introducedchandchoffattributesperadraftstandardatthe
time,buttheydonotdoanythingandlateraresetascharandcharoff.
• CSSvisualchangestotablesaresuggested,butmanysitesclaimthatunderstrict
variantsthevariousattributeslikebgcolornolongerwork.Testinginmodern
browsers(IE8,Firefox3)atthetimethiseditionwaswrittendoesnotsupportthese
claims.
• UndertheXHTML1.0specification,theclosing</tr>tagisrequired,butunder
olderHTMLandHTML5,theclosingtagisoptional.
• ThereareextendedDOMmethodsfortable-relatedtagslike<tr>,including
insertRow()anddeleteRow().
Standard Syntax
<tt
class="classname(s)"
dir="ltr|rtl"
Chapter 3: HTML and XHTML Element Reference 415
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext">
PART I
</tt>
Examples
<p>Hereissome<tt>monospacedtext</tt></p>.
<p>Sourcecodeinthistag:<tt>main(){printf("helloworld");}</tt></p>
Compatibility
HTML 2, 3.2, 4, 4.01 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1 Netscape 1+, Opera 2.1+, Safari 1+
Note
• ThiselementhasbeendeprecatedbytheW3CunderXHTML1.1andmarkedas
obsoleteHTML5.However,likeotherHTML5obsoleteitemsthiselementcontinuesto
workinbrowsers.Thelookofthetagcanbereplicatedwiththefontorfont-family
CSSpropertysettoavalueofmonospaceoracommonfixed-widthfontname.
<u> (Underline)
Thiselementindicatesthattheenclosedtextshouldbedisplayedunderlined.Itisdeprecatedor
obsoleteinmostspecificationsinfavoroftheCSSpropertytext-decoration:underline.
416 Part I: Core Markup
Examples
<p>Hereissome<u>underlinedtext</u>.</p>
<p>Becarefulwith<u>underlined</u>text;itlookslike
<ahref="http://www.pint.com/">alink</a>.</p>
<p>Ifyoumust<spanstyle="text-decoration:underline;">underlineuse
CSS</span>please.</p>
Compatibility
HTML 3.2, 4, 4.01 (transitional) Firefox 1+, Internet Explorer 2+,
XHTML 1.0 (transitional) Netscape 3+, Opera 4+, Safari 1+
Chapter 3: HTML and XHTML Element Reference 417
Notes
• ThiselementhasbeendeprecatedbytheW3C.Underthestrict(X)HTML
specifications,theelementisnotsupported,andunderHTML5itismarked
PART I
obsolete.ThelookprovidedbythiselementissupportedbytheCSSproperty
text-decoration:underline.
• Underliningtextcanbeproblematicbecauseitlookssimilartoalink,especiallyin
ablack-and-whiteenvironment.
Standard Syntax
<ul
class="classname(s)"
compact="compact"(transitionalonly)
dir="ltr|rtl"
id="uniquealphanumericidentifier"
lang="languagecode"
style="styleinformation"
title="advisorytext"
type="circle|disc|square">(transitionalonly)
Listitemsspecifiedby<li>tags
</ul>
Element-Specific Attributes
compact Thisattributeindicatesthatthelistshouldberenderedinacompactstyle.Few
browsersactuallychangetherenderingofthelist,regardlessofthepresenceofthis
attribute.ThecompactattributerequiresnovalueunlessitisusedwithXML-stylesyntax,
whereittakesthevalueofcompact.
type Thetypeattributeisusedtosetthebulletstyleforthelist.Thevaluesdefinedunder
HTML3.2andthetransitionalversionofHTMLandXHTMLarecircle,disc,and
square.Auseragentmightdecidetouseadifferentbulletdependingonthenestinglevel
ofthelist,unlessthetypeattributeisused.Thetypeattributeisdroppedunderthestrict
versionsofHTML4andXHTMLbecausestylesheetscanprovidericherbulletcontrol
usingthelist-style-typeandlist-style-imageproperties.
Examples
<ulcompact="compact"title="SushiShortList"type="circle">
<li>Maguro</li>
<li>Ebi</li>
<li>Hamachi</li>
</ul>
<!--Correctlistnesting-->
Chapter 3: HTML and XHTML Element Reference 419
<ulcompacttitle="SushiShortList"type="circle">
<li>Item1
<ul>
<li>ItemA</li>
PART I
<li>ItemB</li>
</ul></li>
<li>Item2</li>
</ul>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• HTML2.0supportsonlythecompactattribute.
• TheHTML3.2specificationsupportscompactandtype.
• Underthestrict(X)HTMLspecificationsaswellasHTML5,theulelementdoesnot
supportthecompactattributeorthetypeattribute.Bothoftheseattributescanbe
easilyreplacedwithCSSproperties.
• DuetoXHTML’sdeprecationofattributeminimization,thecompactattributemust
haveaquotedattributewhenusedinthetransitionalvariant:
<ulcompact="compact"></ul>
• ManyWebpagedesignersandpagedevelopmenttoolsusethe<ul>tagtoindent
text.Theonlyelementthatshouldoccurwithinaulelementisli,sosuchmarkup
doesnotconformtostandards.However,thiscommonpracticeislikelytocontinue.
• Sincethecontentmodelofulsayslistitemsshouldbetheonlyitemwithin<ul>
tags,nestedlistsshouldoccurwithin<li>tagsratherthanoutsidethemastheyare
commonlyfound.
<var> (Variable)
Thislogicalinlineelementisusedtoindicateavariable(anidentifierthatoccursina
programminglanguageoramathematicalexpression),withanyenclosedtextgenerally
renderedinitalics.
Standard Syntax
<var
class="classname(s)"
dir="ltr|rtl"
id="uniquealphanumericvalue"
lang="languagecode"
style="styleinformation"
title="advisorytext">
</var>
420 Part I: Core Markup
Example
<p>InMaththevariable<var>x</var>holdstheanswertomany
oflife'smostimportantquestions.Itcontainsthetimeittakes
PART I
twospeedingtrainstomeetwhentheyhavelefttwodifferent
stationstravellingatdifferentspeeds,thenumberoflemonsyou
haveleftoveraftertradingwithpeople,andallsortsofother
interestingvalues.</p>
Compatibility
HTML 2, 3.2, 4, 4.01, 5 Firefox 1+, Internet Explorer 2+,
XHTML 1.0, 1.1, Basic Netscape 1+, Opera 4+, Safari 1+
Notes
• Asalogicalelement,varisaperfectcandidateforstylesheetbinding.
• TheHTML2.0and3.2specificationssupportnoattributesforthiselement.
<video> (Video)
ThisHTML5elementembedsavideointoadocument.
ondragstart,ondrop,onerror,onfocus,onhashchange,onkeydown,onkeypress,
onkeyup,onload,onmessage,onmousedown,onmousemove,onmouseout,
onmouseover,onmouseup,onmousewheel,onresize,onscroll,onselect,
onstorage,onsubmit,onunload
Element-Specific Attributes
autobuffer ThisBooleanattributeindicatesthebrowsershouldbeginbufferingavideo
rightaway.Thisattributeshouldbeusedifitisassumedtheuserwillplaythevideo.This
attributeismeaningfulonlyifautoplayisnotset,asinthatcasethebrowserwillplay
videoassoonasitcan,allowingnotimeforfurtherbuffering.
autoplay ThisBooleanattributeindicatesthebrowsershouldbeginplayingavideoafter
pageloadonceenoughcontenthasbeenreceivedanditisreasonabletoplaywithout
interruptions.
controls ThisBooleanattributeissettoindicatewhetherornotthebrowsershouldpresent
controlsforvideo,suchasplayback,pause,volume,andseek.Ifnotpresent,nocontrols
willbeshownanditwillbeuptothedevelopertoscriptthecontrolofthevideoelement.
loop ThisBooleanattribute,ifpresent,indicatesthatthevideoshouldloop.
poster ThisattributeissettotheURLofanimagethatthebrowserwilluseinplaceofthe
videobeforeitisloadedandplaying.
src ThisattributeissettotheURLofthevideotoshow.
Examples
<videosrc="movies/movie1.ogg"autoplay>
<p>NosupportforHTML5<code>video</code>element.</p>
</video>
<videosrc="movies/movie1.ogg"poster="coming.png"loop
playcount="3"start="45">
<p>NosupportforHTML5<code>video</code>element.</p>
</video>
<video>
<sourcesrc="movie2.ogg"type="video/ogg">
<sourcesrc="movie2.mov">
<p>NosupportforHTML5<code>video</code>element.</p>
</video>
Compatibility
HTML5 Firefox 3.5+, Opera 10+, Safari 3.1+
Notes
• Alternatecontentshouldbeplacedinsideofthevideoelementforbrowsersthatdo
notsupportit.
Chapter 3: HTML and XHTML Element Reference 423
• Browsersarequitevariableinwhatcodecstheysupport.Forexample,Firefox3.5
supportsTheoraforvideoinOggcontainers,whileSafaribrowsersfavor
QuickTimemovies.
PART I
• Flashvideowilloftenbeusedtoavoidcross-browserrenderingconcerns.Untilthis
elementiswidelysupported,developersareadvisedtocontinueusingFlashvideo.
Proprietary Syntax
<wbr
id="uniquealphanumericvalue">
Examples
<nobr>Alinebreakcanoccurhere<wbr>butnotelsewhere,evenif
thelineisreallylong.</nobr>
<nobr>Forcomparisonalinebreakcannotoccurhereevenifthe
lineisreallylonglikethisoneis.</nobr>
Compatibility
No standards support Internet Explorer 2–7, Netscape 1.1, 2, 3, 4, 4.5–4.8
Notes
• Earlyversionsofstandards-basedbrowsers,suchasMozillaandOpera,donot
supportthistagbut,oddly,seemtosupport<nobr>.However,laterversions,
includingIE8,correctlyignorethisfeature.
• Tosimulatethiselement’sfunctionalityforsettingasoftbreakinmodernbrowsers
thatapplywhite-space:nowraptoanelement,usethetagasacustomtagand
setitsstylelikeso:<wbrstyle="display:inline-block;>.Otherschemes
usingthe­and​entitiesmayprovideusefulfunctionalityaswellin
somecases.
• DocumentationforolderversionsofInternetExplorerdefinedclass,language,
style,andtitleforthistag.However,theyhavelittlemeaning,giventhistag’s
purpose,andhavesincebeeneliminatedfromthedocumentation,thoughtheymay
effectivelyberecognizedinsomemannerbythebrowserparser.
• Thoughthisisanemptyelementandshouldbewrittenas<wbr/>underXHTML,
itdoesnotneedtobe.Itisnotstandardandwillnotvalidateanyway.
424 Part I: Core Markup
Element-Specific Attribute
src ThisattributereferencesanexternalXMLdatafile.
Examples
<!--ThiscodeembedsXMLdatadirectlyintoadocument.
Allcodebetweenthe<xml>tagsisnotHTML,buta
hypotheticalexampleofXML.-->
<xmlid="tasty">
<combomeal>
<burger>
<name>TastyBurger</name>
<bunbread="white">
<meat/>
<cheese/>
<meat/>
</bun>
</burger>
<friessize="large"/>
<drinksize="large"flavor="Cola"/>
</combomeal>
</xml>
<!--Thiscodefragmentusesthesrcattributetoreferencean
externalfilecontainingXMLdata.-->
<xmlsrc="combomeal.xml"></xml>
Chapter 3: HTML and XHTML Element Reference 425
Compatibility
No standards support Internet Explorer 5+
PART I
Note
• Nativebrowsersupportforthe<xml>tagislimitedtoInternetExplorer5orlater,
thoughgivennativesupportforXMLinmodernbrowsers,itispossibletosimulate
theideabydefiningacustomtagandhidingitusingCSSdisplayorvisibility
properties.Seehttps://developer.mozilla.org/en/Using_XML_Data_Islands_in_
Mozillaforanexample.
<xmp> (Example)
Thisdeprecatedbutstillwidelysupportedelementindicatesthattheenclosedtextisan
example.Exampletextgenerallyisrenderedinamonospacedfont,andthespaces,tabs,
andreturnsarepreserved,aswiththepreelement.
Example
<xmp>Thisisalargeblockoftextusedasanexample.
426 Part I: Core Markup
Notethatreturns
aswellasSPACESarepreserved.</xmp>
Compatibility
HTML 2 Firefox 1+, Internet Explorer 2+, Netscape 1+, Opera 2.1+, Safari 1+
Notes
• ThiselementwasfirstdeprecatedunderHTML3.2,yetallmajorbrowserscontinue
tosupportit,anditiswelldocumentedandevenextendedforInternetExplorer.
The<pre>tagorstylesheetsshouldbeusedinsteadofthistag.
• NotethattheMSDNdocumentationdoesnotshowoncopyandonbeforecopy
eventsforthiselementbuttestingshowstheydoworkupuntilIE8.
II
PART
Core Style CHAPTER 4
IntroductiontoCSS
CHAPTER 5
CSSSyntaxand
PropertyReference
CHAPTER 6
CSS3Proprietaryand
EmergingFeaturesReference
This page intentionally left blank
CHAPTER
4
Introduction to CSS
I
nthepast,muchofthevisualformattingofWebpageswassuppliedbymarkup
elements,squarelymixingtheconceptsoflogicalandphysicalmarkupintothemess
thatisclassicHTML.Strictvariantsof(X)HTMLdeprecatedtheelementsandattributes
thatfocusedonpresentation,providingacleardistinctionbetweenthestructureprovided
bymarkupandthelookdictatedbyastylesheetwritteninCascadingStyleSheets(CSS)
syntax.Thedistinctdivisionofdutiesbetweenmarkupandstylecanprovidenumerous
production,maintenance,andevenperformancebenefits,makingitafarsuperior
presentationsolutiontomarkupalone.
Presentational HTML
Traditionally,forrightorwrong,markuphasbeenusedforformatting.Forexample,many
HTMLelementssupportthealignattribute,whichprovidessimplesupportfortext
alignment.Combinetheseaspectsofmarkupwiththeassumptionofvisualrendering,such
asthebeliefthath1elementsalwaysshouldmaketextbig,anditwouldactuallyseemclear
tosomethatHTMLismeantforformatting,asdemonstratedhere:
<h1align="center">BigCenteredText!</h1>
Nowanargumentcanbemadeaboutthesemanticvalueoftheh1specifyinga
headline,butforthosesolelycomingatHTMLfromapointofviewofknowingwhatatag
does,theideathatan<h1>tagmakessomethingbigwinsout.Yet,beyondsuch
misunderstandingsbaseduponobservationratherthantheintentofthespecification,there
areelementsthatarestrictlypresentational,likefont,whichispartofHTML3.2,4.01
transitional,andXHTML1.0transitionalspecifications:
<fontsize="7"color="red">Iambigandred!</font>
Further,whenlookingatbrowser-specificelements,plentyofpresentationalmarkup
canbefound.Forexample,thefollowingmarkup
<blink>ProprietaryHTMLTagSale:50%OffforFirefoxUsers!</blink>
429
430 Part II: Core Style
createsblinkingtextinFirefox,whilethismarkup
<marquee>Sale!Sale!Sale!AllPresentationTagsMustGo!!!</marquee>
animatestextinnearlyanybrowser.Historyhasalreadybeenwritten.Likeitornot,
markuphasbeenusedtovisuallypresentWebpagesforwelloveradecade.
TheproblemwithusingHTMLforformattingisthatitjustisn’treallyverygoodatit,
norwasitgenerallydesignedforit.Forexample,justtomakesomecenteredredtextwitha
yellowbackground,you’dlikelyresorttousingmarkuplikeso:
<tablealign="center"width="100%">
<tr>
<tdbgcolor="yellow"align="center">
<fontsize="7"
color="red"
face="Arial,Helvetica,sans-serif">
BigRedHTMLText
</font>
</td>
</tr>
</table>
WhenusingHTMLforWebpagepresentation,weseeatremendousamountofmarkup
beingusedtostylethepage,oftenfilledwithcomplexstackedorevennestedtables.Layout
workaroundsusinginvisiblepixelimages,proprietaryelementsandattributes,textinimages,
andotherarcaneideaswere,andoftenstillare,requiredtodeliverquality,high-fidelity
designinHTML.Fortunately,fornowandthefuture,thereisabetterway—stylesheets.
NOTE Asthiseditiongoestoprint,manybrowserspassAcid3aswell.Thepointhereistoshow
thatinthepastfewyearsCSShasbecomeviableandappropriate,andthatittookawhiletoget
there,ratherthantodeclareanybrowserawinnerorloserinastandardsrace.
Chapter 4: Introduction to CSS 431
PART II
FIGURE 4-1 Older browsers failing Acid2
Newerversionsofbrowsersarefarbetterthantheirpredecessors,andnowhavegood
supportforCSS1andCSS2.1aswellasmanyfeaturesfromCSS3.YetevenasCSSsupport
hasbecomemorecommonplace,significantissuesremain.Browserbugsstillexist,portions
oftheCSSspecificationremainunsupported,developereducationanduptakeislagging,
andproprietaryextensionstostylesheetsarerapidlybeingintroducedbybrowservendors.
Itseemsthemorethingschangethemoretheystaythesameregardlessofthetechnologyin
use.HTMLwonkswhohavespenttimeaddressingquirksandworkaroundswillfindplenty
ofnewonestoaddressintheworldofCSS.We’llreturntothissadfactattheendofthe
chapterwhenwediscussthepragmaticuseofCSS,butnowlet’stakeourfirstlookatCSS.
432 Part II: Core Style
property-name1:value1;...property-nameN:valueN;
Chapter 4: Introduction to CSS 433
CSSrulescanbeplaceddirectlywithinmost(X)HTMLtagsbysettingthecoreattribute
styletotherule.Forexample,tosetthecolorandalignmentofanh1heading,wemightuse
<h1style="color:red;text-align:center;">BigRedCSSText!</h1>
SuchdirectuseofCSSiscalledinlinestyleandistheleastfavorableformofCSSbecauseof
itstightcouplingtotheactual(X)HTMLtags.
Insteadofplacingrulesdirectlywithinmarkupelements,wemightmoreappropriately
createarulethatbindstoaparticularelementorsetofelements,whichwilllenditselffor
futurereuse.CSSrulesnotfoundwithinaparticulartagconsistofaselectorfollowedbyits
associatedstyledeclarationswithincurlybraces.Similartobeingusedinline,astyleruleis
composedofpropertynamesandpropertyvaluesseparatedbycolons,witheachstyle
PART II
declaration(property/valuepair)inturnbeingseparatedbyasemicolon.Ingeneral,the
syntaxis
selector{property1:value1;...propertyN:valueN;}
AnexampleruleconformingtocorrectCSSsyntaxbrokenoutintoitsindividual
componentsisshownhere:
NOTE Thefinaldeclarationinastyleruleblockdoesnotrequirethesemicolon.However,forgood
measureandeasyinsertionoffutureproperties,pageauthorsshouldalwaysusesemicolonsafter
allstyleproperties.
CSSpropertynamesareseparatedbydasheswhentheyaremultiplewords—for
example,font-face,font-size,line-height,andsoon.Allowedvaluescomeinmany
forms;fromsimplekeywordslikexx-small,stringslike"Arial",plainnumberslike0,
numberswithunitslike100pxor2cm,andspecialdelimitedvaluessuchasURLs,url(../
styles/fancy.css).
GiventhisbriefCSSsyntaxoverview,tocreateastyledictatingthatallh1elementsare
redandcentered,usethefollowingrule:
h1{color:red;text-align:center;}
Asrulesareadded,youmaytakeadvantageofthefactthatCSSisnotterribly
whitespacesensitive,so
h1{font-size:xx-large;color:red;font-family:Arial;}
434 Part II: Core Style
willrenderthesameas
h1{font-size:xx-large;
color:red;
font-family:Arial;}
GiventhenatureofwhitespaceinCSS,youmayfindformattingleadstobetter
readabilityforfuturedevelopment.Alsoliketraditionalcoding,weshouldaddcomments
usingthecommonprogramminglanguagesyntax/**/likeso:
/*firstCSSrulebelow*/
h1{font-size:28px;color:red;font-family:Arial;}
Ofcourse,whenpublishingCSSandHTMLonpublic-facingWebsites,removing
commentsandreducingwhitespacetoimprovedeliveryandslightlyobfuscateexecution
maybeappropriate.
Lastly,caseshouldbewellconsidered.InCSS,propertynamesandmanyvaluesare
caseinsensitive,so
h1{FONT-SIZE:28px;color:RED;FONT-WEIGHT:bold;}
and
h1{font-size:28px;color:red;font-weight:bold;}
arethesame.However,insomeimportantcases,suchaswithURLvalues,fontnames,and
certainselectorssuchasidandclassvalues,casewillbeenforced.Forexample,
#foo{background-imageurl(tile.gif);font-family:Arial;}
and
#FOO{background-imageurl(TILE.GIF);font-family:ARIaL;}
willnotnecessarilybethesame,withtheURLsometimesworkingdependingontheWeb
serverinvolved,thefontspotentiallynotmatching,andthedifferingidselectorspossibly
notworkingunlessanextremelypermissivebrowserisinplay.Giventhepotentialfor
confusion,itismuchsafertoassumethatCSSiscasesensitive.
Whennotplaceddirectlyinline,styleruleswouldbeplacedeitherwithina<style>tag
foundinthedocumenthead
<styletype="text/css">
/*asamplestylesheet*/
h1{color:red;text-align:center;}
p{line-height:150%;}
</style>
orwillbeexternalizedandreferencedviaa<link>tagfoundintheheadofthedocument,
likeso:
<linkhref="mystyle.css"rel="stylesheet"type="text/css">
Chapter 4: Introduction to CSS 435
GiventhatlinkwouldbeanemptyelementifwewereusingXHTMLasourbase
document,the<link>tagrequiresthetrailingslash:
<linkhref="mystyle.css"rel="stylesheet"type="text/css"/>
TheexternalstylesheetwouldsolelycontainCSSrules,andnoHTMLmarkupwouldbe
found.Asmallexamplehereillustratesthis:
/*mystyle.css-asamplestylesheet*/
h1{color:red;text-align:center;}
p{line-height:150%;}
PART II
Tobuildastylesheet,weneedtodefinetherulesthatselectelementsandapplyvarious
stylepropertiestothem.Besideselementselectors,previouslyintroduced,thetwomost
commonformsofCSSrulesareidselectors,whichareusedtospecifyaruletobindtoa
particularuniqueelement,andclassselectors,whichareusedtospecifyagroupof
elements.
Elementsarenamedin(X)HTMLusingtheidattribute,whichisfoundonnearlyany
element.Asanexample,hereweidentifyaparticular<h1>tagastheprimaryheadlineof
thedocument:
<h1id="primaryHeadline">CSSWorksFine!</h1>
Nowthatthetagisnamed,wecanbindastylerulejustforitbyusinga#id-value
selectorlikeso:
#primaryHeadline{color:black;font-size:xx-large;font-weight:bold;}
Thevaluesforidmustbeunique,soinordertoaffectaselectgroupoftags,werelate
thembysettingtheirclassattributetothesamevalue:
<pclass="fancy">I’mfancy!</p>
<p>PoormeIamaplainparagraph.</p>
<p>Iamnotcompletelyfancy,but<spanclass="fancy">partofme
is</span>!</p>
Noticethatweutilizeda<span>tagaroundaportionofcontentwedesiredtostyle.
We’llseegenericelementslikespananddivcommonlyemployedwithCSS.Nowtobinda
ruletotheelementsintheclassfancy,weuseaselectoroftheform.class-namelikeso:
.fancy{background-color:orange;color:black;font-style:italic;}
Thereisnothingthatkeepsanelementfrombeingidentifiedwithbothanidanda
classattribute.Further,itisnotrequiredthatatagbefoundinonlyoneclass,asshown
here:
<pid="p1"class="fancymodernLook2">Thisuniqueparagraphcalledp1
willsportafancyandmodernlook.</p>
436 Part II: Core Style
Giventhatmanyrulesmaybeappliedatonce,thefinalstyleappliedtoaparticular
elementmaynotbeimmediatelyobvious.Infact,inquiteanumberofcases,theproperties
affectinganelement’slookmaybeinheritedfromanenclosingparentelement.Asavery
simpleexample,considerthefollowingrules:
<styletype="text/css">
body{background-color:white;color:black;}
p{font-family:Arial,Helvetica,Sans-Serif;
line-height:150%;}
.intro{font-style:italic;}
#firstPara{background-color:yellow;}
</style>
Whentheprecedingisappliedtoaparagraphlike
<pid="firstPara"class="intro">Paragraphtextgoeshere.</p>
itproducesaparagraphwithayellowbackgroundandblack,Arial,italicizedtextthatis
spacedwitha150percentlineheight.Whathashappenedisthatthevariousrulesare
appliedbyselectors,andsomepropertyvaluesareinheritedfromtheirenclosingparent
elements.Usingasmallparsetree,Figure4-3showsjusthowtherulescascadedownward
totheenclosedelements,whichexplainsthemotivationbehindthenameCascadingStyle
Sheets.
Insomecases,rulesareevenoverriddenbylater-definedormore-preciserulesthatmay
evenbewithininlinestyles.
Clearly,determiningwhatrulesapplytoaparticulartagcanbeabittricky,butasaruleof
thumb,themorespecifictherule,themorerecentlydefinedtherule,andtheclosertothetag
theruleis,themorepowerfulitis.Forexample,aninlinestylepropertywouldbeatavaluein
adocument-widestylerule,whileadocument-widestylerulewouldbeatapreviously
definedlinkedstylerule.Further,rulesusinganidwouldbeatrulesusingaclass,which
wouldbeatrulesbaseduponelements.Ofcourse,allthiscanbeoverriddenusingan
!importantindicatorattheendofaparticulardeclaration,sohere
<styletype="text/css">
#hulk{color:green!important;font-size:xx-large!important;}
</style>
theelementwithanidvalueof'hulk'shouldbebigandgreen.Thoughthattoocanbe
overriddenwithsubsequentrulessettingthesepropertieswith!important.Giventhe
potentialconfusionofwhatrulesarebeingappliedatwhattimes,CSSdevelopersshould
utilizeatoolthatcanshowtherenderedstyleofanelementuponinspection,asshownin
Figure4-4.
Thereisplentymoretocomewithunderstandingthecascade,inheritance,andallthe
variousselectors.Fornow,withourbriefintroductionoutoftheway,itistimetoseeour
firststylesheetinaction.
Chapter 4: Introduction to CSS 437
PART II
Class rule
Element rule
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HelloCSSWorld</title>
<styletype="text/css">
/*samplestylesheet*/
body{background-color:black;color:white;}
h1{color:red;font-size:xx-large;text-align:center;}
#heart{color:red;font-size:xx-large;}
.fancy{background-color:orange;color:black;font-weight:bold;}
</style>
</head>
<body>
<h1>WelcometotheWorldofCSS</h1>
Chapter 4: Introduction to CSS 439
<hr>
<p>CSS<emclass="fancy">really</em>isn'tsohardeither!</p>
<p>Soonyouwillalso<spanid="heart">♥</span>usingCSS.</p>
<p>Youcanputlotsoftexthereifyouwant.
Wecouldgoonandonwith<spanclass="fancy">fake</span>textforyou
toread,butlet'sgetbacktothebook.</p>
</body>
</html>
O NLINE http://htmlref.com/ch4/hellocssworld.html
TheprecedingexampleusessomeofthecommonCSSpropertiesusedin(X)HTML
PART II
documentsandtherearesomeslightchangestothedocumentstructurebecauseofit,including:
• Settingcolorswithbackground-colorandcolor
• Sizingtextwithfont-size
• Settingboldnesswithfont-weight
• Settingbasictextalignmentwithtext-align
• Usingidandclassattributestospecifyelementstobindstylerulesto
• Usinglogicalmarkuplike<em>asopposedtomorephysicalmarkuplike<i>
• Relyingongenerictagcontainerslike<span>tostylearbitraryportionsoftext
TherearenumerousotherCSSpropertieswemightemploybesidesthefewweseehere,
andwewillexplorethosethroughoutthebook,butfornowthissamplingisenoughtoget
ourfirstexampleupandrunning.InFigure4-5,weseetheCSSversionofthepageas
comparedtotheHTML-onlyversion.
Plain HTML
HTML styled
by CSS
Whiletwotechnologiesarerequiredtomaketheexample,notethatCSSwhenwell
executedisbothdistinctfromanHTMLdocumentanddependentonit.CSSisnota
replacementformarkup;itinfactreliesonit.Asanexample,ifanHTMLdocumentis
malformed—thetagsarenotclosedproperlyorothermistakesweremade—theCSSmay
notattachproperlyandthelookwouldbedistorted.However,mistakescanalsobemade
intheCSSrules,whichtendtobeabitmorestrictlyinterpretedbybrowsersandthusmay
similarlyresultinavisualrenderingproblem.Clearly,asymbioticrelationshipexists
betweenCSSandHTML,butthatrelationshiphaschangedovertime,sothatevolutionis
describednext.
CSS Versions
CascadingStyleSheetsisafairlyoldtechnologyasfarastheWebisconcerned.Thefirst
ideasaboutCSSwerepresentedasearlyas1994,andbyDecemberof1996theCSS1
specification(www.w3.org/TR/REC-CSS1/)wasratified.ThisearlyversionofCSSwas
partiallysupportedinbrowserslikeInternetExplorer3andNetscape4tovaryingdegrees.
WhilethefeaturesofCSS1werefarsuperiortowhatpresentationHTMLhadwithits
<font>tagsandworkarounds,uptakewasslow.
CSS1providedmanyfeaturestochangeborders,margins,backgrounds,colors,anda
varietyoftextcharacteristics,butthemuchdemandedabilitytodirectlypositionobjectswas
absent.AninterimspecificationonpositioningHTMLelementscommonlycalledCSS-Pfor
short(www.w3.org/TR/WD-positioning-19970819)wasimplementedinNetscape4and
InternetExplorer4andlaterrolledintoCSS2(www.w3.org/TR/1998/REC-CSS2-19980512/),
whichwasreleasedinMay1998.WhileCSS2introducedmanyvaluablefeatures,including
positioning,mediatypesforstylesheets,auralstylesheets,andmuchmore,noteverythinghas
beenimplementedeveninthemostmodernbrowsers.Arevisionofthisspecification,CSS2.1
(www.w3.org/TR/CSS21/),releasedin2007,removedanumberofunimplementedfeatures
andnormalizedthespecificationtoamorerealisticvisionofwhatbrowsersactuallydo.
WhilethefutureisclearlyCSS3(www.w3.org/Style/CSS/current-work#CSS3)withits
multitudeofmodulesforaddressingcolor,deviceconstraints,foreignlanguagerendering,
improvedprinting,andmore,itisfarfromclearwhenthatfuturewillarrive.Atthetimeofthis
edition’swriting,selectfeaturesofvariousCSS3moduleshavebeenimplementedinsome
browsers,but,saveforafewhigh-valuefeaturesliketheopacityproperty,fullcross-
browsersupportisstillspotty.Table4-1summarizestheversionhistoryofCSS.
Proprietary CSS
ForsomeWebdevelopers,CSSisassociatedwithstandardsandspecification,butthereality
isthat,likemarkup,ittoohasproprietaryfeatures.Allbrowservendorshaveintroduced
somefeatureoranothertoimprovewhattheirbrowsercoulddo.Manyofthesefeaturesare
previewsofwhatislikelytobeimplementedintheeventualCSS3specification,butfor
nowtheyareproprietary.
Unlike(X)HTML,CSSmakesiteasyforbrowservendorstoextendthespecification,as
newlyintroducedkeywordsandpropertynamesthatstartwithahyphen“-”orunderscore
“_”areconsideredvendor-specificextensions.Thesyntaxis-vendoridentifier-newpropertyor
_vendoridentifier-newproperty,thoughinpracticethehyphenatednamesappeartobethe
onlyextensionsinuse.Asanexample,-mozisusedtoprefixMozillafeatureslike-moz-
border-radius.AlistofprefixesthatarecommonlyseenisshowninTable4-2.
Chapter 4: Introduction to CSS 441
PART II
CSS 2.1 A revision of the CSS2 specification that makes some corrections and is normalized
to more clearly represent what most browser vendors have implemented. Note that
many CSS2 features removed from this specification are found in CSS3 modules.
This is currently the recommended CSS specification for study and use.
CSS3 Modularized specification of CSS. Various modules extend and improve aspects
of previous CSS versions; for example, the CSS3 Color module addresses color
correction, transparency, and more, while the CSS3 Fonts module addresses
features to add effects to fonts, adjust their display, and even download custom
fonts. Some modules are all new, like the Transitions and Animations modules,
and others are quite old looking with activity levels suggesting they are abandoned
or near abandon. Whatever the situation, when it comes to CSS3, readers are
encouraged to check the CSS3 Web site and test support carefully.
ThereareotherproprietyCSSprefixesthatmaybeencountered,whichmayormaynot
followtheappropriateprefixingscheme.Forexample,wirelessphonesthatsupportWAP
(WirelessApplicationProtocol)mayuse-wap-prefixbasedpropertiessuchas–wap-
accesskey.SomeimplementationsofMicrosoftOfficemayuseCSSruleslikemso-,such
asmso-header-data.Donotethatthissyntaxlackstheappropriateextensioncharacter
indicator.Ingeneral,itwouldseemthatextensionsshouldbeavoidedifpossibleunless
theirpresentationdegradesgracefully,particularlysincetheircompatibilityandfuture
supportbybrowsersorstandardsbodiesisfarfromclear.Interestingly,manyextension
propertiesappeartobeCSS3propertieswithstemsjustwaitingforthespecificationsto
catchup.Chapter6willshowthistobethecaseinnumerousinstances.
<h1align="center">HeadlineCentered</h1>
Inthecaseofstrictmarkup,however,thealignattributeisdeprecatedandthusCSS
shouldbeemployed.Thiscouldbeaccomplishedeitherusinganinlinestylelikeso
<h1style="text-align:center;">HeadlineCentered</h1>
or,moreappropriately,withsomeCSSruleappliedviaclass,id,orelementselector.Here
weuseaclassrule
h1.centered{text-align:center;}
whichwouldapplytotagswithclassvaluescontaining“centered”likethefollowing:
<h1class="centered">CenteredHeadline</h1>
<h1class="fancycentered">AnotherCenteredHeadline</h1>
Insomecases,wefindthatvariousHTMLelementssimplyarenolongernecessaryin
thepresenceofCSS.Forexample,insteadoftagslike<u>,<sub>,<sup>,<font>,and
others,CSSrulesareusedoftenwithgenericelementslikedivorspan.Table4-3details
mostofthe(X)HTMLmarkupelementsorattributesdeprecatedinstrictvariantsand
presentstheirCSSalternatives.
Thereareothercases,like<sub>,<sup>,<big>,<small>,andmanymore,wherewe
couldavoidusingmarkupandapplystyle.Thevariousmarkupspecificationshavenot
deprecatedeverypresentational-likeelement,andevenifCSSalleviatestheneedforsome
presentationalelements,theirusagestubbornlyliveson.Forthatsimplefact,theseelements
andtheirequivalentsarepresentedinthisbook.Infact,thecontinuedinclusionofpresentation
ideasintheemergingHTML5specificationtendstosuggestthatdespiteadesiretomoveto
apurelysemanticmarkupworld,whilecertainlyworthwhile,thisisunlikelytocometopass
ontheWebatlarge,atleastnotrapidly.
Chapter 4: Introduction to CSS 443
PART II
text-align.
Color attributes for <body> color, To set some of the body
background-color attributes like link, vlink,
alink, pseudo-classes :link,
:visited, :active should be
used for <a> tags.
Background image attributes background-image
for <body>, <table>, and
<td>
The type and start attributes list-style-type, Single CSS properties can’t
on lists and list items CSS counters directly substitute some features.
The clear attribute for <br> clear
<s>, <strike> text-decoration:
line-through
<u> text-decoration:
underline;
<blink> text-decoration: Not supported in all browsers.
blink
ruleset
:selector[COMMAS*selector]*
LBRACES*declaration[';'S*declaration]*'}'S*
444 Part II: Core Style
Roughly,thissaysthatarulesetcontainsaselectorofsomesort,acurlyleftbrace(LBRACE),
adeclarationorasetofdeclarationsfollowedbyasemicolon,andthenaclosingrightbrace.
Thisbasicallydefinestherulesyntaxwehaveseenearlier,repeatedagainhere:
selector{property1:value1;...propertyN:valueN;}
Nowifyoucontinuetoreadthespecification,youcanseethatselectorsarethendefinedby
selector
:simple_selector[combinatorsimple_selector]*
;
whichinturnreferencesasimple_selector,whichwouldincludesomeofthetypesof
selectorslikeelementnames,class,andidvalueswehaveseenearlier.Theproduction
ruleofCSSgrammarhereshowsjustthat:
simple_selector
:element_name[HASH|class|attrib|pseudo]*
|[HASH|class|attrib|pseudo]+
;
Yetasyouexpandthegrammar,youshouldseewhatappearstobeambiguity.For
example,whenyouexpandtoanelement_name,itwillindicatethatawildcardvalueof
“*”canbeusedtomatchanelementandthensimplyavalueofIDENT,shownhere:
element_name
:IDENT|'*'
;
IDENTwillresolvetoanotherpartofthespecificationthatdefinesavalidtokenthatisa
fairlylargerangeofstrings.Simplyput,theelement_nameselectorcanbejustabout
anything,whichmakesperfectsensebecauseCSScanbeusedfornotjustHTMLbutalso
forarbitraryXMLlanguages,whichcouldhaveavarietyofpossibletags.Giventhewide
possibilityofusageforCSS,thisambiguityissomewhattobeexpected,buteventhe
variouspropertynamesandvaluesarenotdirectlyspelledoutinthegrammarandareleft
totheproseofthespecification.Infact,theforward-lookingnatureoftheCSSspecification
givessomelatitudehereintermsofsuchvaluesinsteadofspecifyingtherulesforwhata
browsershoulddowhenfacedwithpropertiesorvaluesitdoesn’tunderstand,asdiscussed
inthenextsection.
ThevariousaspectsoftheCSSgrammarthatareabitambiguousaresonotbecauseof
someoversightbutduetotheintersectionbetweenCSSandothertechnologies.Forexample,
considerthesituationofcasesensitivity,aspreviouslydiscussedinthechapter.CSSproperty
namesandmanyvalueswillbecaseinsensitive,sofont-sizeandFONT-SIZEareboth
okayasaredeclarationslikefont-size:REDandfont-size:red.Evenselectorsmay
notbecasesensitive;forexample,
H1{color:red;}
shouldbethesameas
h1{color:red;}
Chapter 4: Introduction to CSS 445
becauseHTMLelementscanvaryincase.However,inthecaseofXMLelementslike
MYTAG{color:red;}
and
mytag{color:red;}
thesewouldn’tnecessarilybethesame.Similarly,giventheintersectionofJavaScript,which
iscasesensitive,idandclassnamesshouldbeconsideredtobecasesensitive.Depending
ontheserverbeingused,portionsofURLvalues,includingthepathandfilename,mayalso
becasesensitive.So,therulesofCSScancausemuchconfusionbecausetheyarehighly
PART II
influencedbyitscontextofuse.Thereareclearcases,however,thatsyntaxisincorrectorat
leastnotunderstoodbytheparsinguser-agent;fortunately,theCSSspecificationspellsout
whatoughttobedoneinsuchsituations,thoughthisassumesbrowservendorsfollowthe
specification!
Unknown Properties
Ifanunknownpropertyisencountered,aCSS-conforminguseragentshouldignorethe
declaration.Given
h1{color:red;trouble:right-here;}
thepropertytroublewouldsimplybeignoredandtherulewouldsimplysetthecolor.It
doesnotmatterwhatthepositionoftheboguspropertydeclarationis,theresultshouldbe
thesameaslongasthedeclarationisotherwisewellformed.
h1{trouble:right-here;color:red;}
Thecaseisobviouslydifferentifthevariousseparatorsaremissing.
Malformed Rules
Inthecasewheresemicolons(;),colons(:),quotes('or"),orcurlybraces({})aremisused,
abrowsershouldtrytohandleanyunexpectedcharactersandreadthepropertiesuntil
amatchingvaluecanbefound.Asanexample,considerthesimplecaseofforgettinga
semicolon:
h1{color:redtext-decoration:underline;font-style:italic;}
Inthiscase,weshouldseethebrowsercontinuetoparsethevalueofcoloras“redtext-
decoration:underline”beforeitseesaclosingsemicolon.Thefont-stylepropertythat
446 Part II: Core Style
followswouldthenbeused.Becausethecolorpropertyhasanillegalvalue,itshouldbe
ignored.
Othercasesareabitmoreobvious.Forexample,hereweseethecolonmissinginastyle
ruledeclaration:
h1{colorred;text-decoration:underline;font-style:italic;}
Inthiscase,thecolorpropertyissimplyignoredandthetextisunderlinedanditalic.
Thesituationforquotesandbracesisthesame,withcompliantbrowsersworkingto
findamatchingclosingcharacterforanyopenconstruct,potentiallydestroyinganythingin
between.Considerthissetofrules,wherequitealargeamountofstylemaybelost:
h1{color:green;font-family:"SuperFont;}
h2{color:orange;}
h3{color:blue;font-family:"DuperFont";}
Becareful,though,becauseinthiscaseyoumightassumethattheruleclosesoffwitha
quote,butthatmayintroducemoreopenconstructerrorslateroninthestylesheet.
<styletype="text/css">
h1{color:green
</style>
shouldrenderproperly,astheopenrulewouldbeclosedautomaticallybytheendofthe
stylesheet.Openquoteswouldalsobeclosedinasimilarmannerwhentheendofthestyle
sheetisreached.Testingrevealsthisactionisactuallythecaseinbrowsers,butcreatinga
syntacticallycorrectstylesheetisobviouslyfarsuperiorthanunderstandingtheexpected
failuresofaconformantbrowser.
h1{font-size:microscopic;color:red;}
wouldsimplynotsetthefont-sizevaluebuth1elementswouldbered.Usageofillegal
characterscanturnwhatwouldappeartobeacorrectvalueintoanincorrectone.For
example,
h1{color:"green";}
isincorrectnotbecausegreenisanillegalcolor,butbecauseitisnotthesameasthe
keywordgreenwhenitisquoted.
DonotassumethataCSS-compliantbrowserwillfixsuchsmalloversights.For
example,abrowsergiven
h1{color:greenforest;}
Chapter 4: Introduction to CSS 447
shouldnotusegreenbutinsteadignorethewholerule.Ofcourse,whatbrowservendors
actuallydointhefaceofmalformedWebdocumentsvaries.
PART II
Whenstylesheetsarelinkedratherthanplacedwithinthepage,thebrowsermustapplyall
typesitisabletofetchandsimplyignorethoseitcan’t.Soifyouhad
<linkrel="stylesheet"href="global.css"type="text/css">
<linkrel="stylesheet"href="pagelevel.css"type="text/css">
andthefirstwasfetchedbythebrowser,butthesecondfailed,itwouldsimplyapplythe
rulesithad.Obviously,suchtransitoryerrorsarehardtoaccountfor,butother
considerationspresentedinthissectionshouldhavebeencaughtinthevalidationof
markupandstyle,discussednext.
Validating CSS
Like(X)HTML,itisquitepossibletocheckyourstyleusageagainstthespecification.
Thisisalsocalled“validation,”thoughtheterm“conformancechecking”maybemore
appropriate,buttheintentisstillclear.TheW3CprovidesavalidationserviceforCSSat
http://jigsaw.w3.org/css-validator/.Asanexample,validatingthepagefoundatwww
.htmlref.com/ch4/hellomalformedcssworld.htmlshowsthatitcontainsanumberofsimple
errors,asshownhere:
Theprevioussectionidentifieswhataconformantbrowsershoulddowithsucherrors
and,interestingly,theresultisthatthemalformedpageshouldappearthesameasthe
“well-formedpage.”LikeHTML,weoftenwon’tpayapriceforourmistakesuntillater.
Thegoodnewsisthatwecaneasilyuncoverthesetypesoferrors,asshowninFigure4-6.
Noticethattheserviceshowswhatisconsideredtheresultingstylesheetinlightofthe
encounterederrors.
448 Part II: Core Style
AchallengewithCSSvalidationisthatwhatisvalidCSSinthesimplesenseofrule
definitionmaynotbevalidwhencombinedwithmarkuporJavaScript.Forexample,isthe
followingruleinerror?
<styletype="text/css">
#unique{color:red;font-size:xx-large;}
</style>
Chapter 4: Introduction to CSS 449
Atfirstblushthereisnothingwrong,butitturnsouttheidvalueisusedtwice,as
demonstratedhere:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>CSSValidationChallenges</title>
<styletype="text/css">
#unique{color:red;font-size:xx-large;}
</style>
</head>
PART II
<body>
<pid="unique">Iamtheparagraphwithidunique.</p>
<p>Iamnottheuniqueparagraph.</p>
<pid="unique">Yetanotheruniqueparagraph?</p>
</body>
</html>
IfthisdocumentisCSSvalidated,everythingisapparentlyokay:
However,withHTMLvalidationweseethatisactuallynotthecase:
450 Part II: Core Style
Again,visuallywemaygetthedesiredeffectoftwolargeredparagraphs,butitisn’t
executedcorrectlyandwewillpotentiallypayapricelaterwithJavaScript,whichtypically
doesnotallowthesamelatitudethatpresentationaltechnologiesdo.Considersimplythat
eachlayeroftechnologyweaddonwithsmallmistakesmakestheoverallexecution
shakierandshakier.Giventhisfoundationalapproach,weshouldfirstvalidatemarkupand
then,onceitissolid,validatetheCSSthatislayeredontop.
#boxexample{border:20pxsolid;
padding:30px;
width:300px;}
somebrowserswouldcorrectlyinterpretthetotalwidthoftheboxdefinedasincludingthe
borderandpaddingvaluesaddedtothewidthofthedefinedbox,asfollows:
20 30 30 20
300 px
px px px px
400 px
1
TheBoxModelHackwasinitiallyintroducedbyawell-knownCSSexpert,TantekÇelik(http://tantek
.com/CSS/Examples/boxmodelhack.html),whocertainlyisquiteawareofwhattodoandnottodowith
CSS.Thechoiceofthishackisonlyillustrativeofthebreaktherulespurposefullyapproach.
Chapter 4: Introduction to CSS 451
However,abrowserthatmisinterpretstheCSSboxmodel,suchasInternetExplorer5,
wouldincludetheborderandpaddinginthemeasurement,soitwouldsubtractthese
valuestoproducetherenderedregion:
20 30 30 20
200 px
PART II
px px px px
300 px
Withsuchavastdifferenceinmeasurement,layoutvariationsarequitenoticeable:
IE 5.5 needs fix IE 6+ no fix needed
Ifyouhaveaveryoldbrowser,tryityourselfathttp://htmlref.com/ch4/boxmodelhack.html.
452 Part II: Core Style
Togetaroundthisdifference,ingeniousWebdevelopersdevelopedatechniquetoforce
thebrowserparserinsomecasestoexplodepredictably.Forexample,given
#boxexample{border:20pxsolid;
padding:30px;
width:300px;}
wefirstmodifyit,asshownnext,tosettheboxwidthtoitscorrectmeasurementof400px
forbrowsersthatmisinterpretthecalculation.Next,weaddrulesthattheseolderbrowsers
willhaveproblemswith,thuskillingtherestoftheline.Finally,weaddaruleforthose
browsersthatdon’thaveissuestoresetthewidthpropertybacktothecorrectlyinterpreted
valueof300px.
#boxexample{width:400px;
voice-family:"\"}\"";
voice-family:inherit;
width:300px;}
Whatthishackdoesistoactasasimpleifstatement,choosingonewidthvalueinone
caseandadifferentoneinanother.Ifthesolutionseemsmessyandinappropriatetoyou,
knowyouaren’talone.However,recognizethatwhenfacedwithbrowseradversity,Web
developers,whoareawilygroup,willsolvealmostanyproblemusingonlythetoolsthey
know,whetherthemethodisappropriateornot.
You’llcertainlyseemorehacksandinelegantsolutionsasyouexploretheuseofCSS.
ThepointhereisnotonlytoshowthatunderstandingtherulesofCSSandbrowseractivity
canbeusedpurposefully,butalsotoillustratetheWebdevelopmenttruismthat,while
wealwaysaimforstandardscompliance,theneedforhackingandaddressingbrowser
incompatibility,justlikeintheolddaysofpresentationalmarkup,stubbornlyliveson.
Regardlessofthisnecessity,let’smoveontoexploreallthedetailsofhowstyleisapplied
tomarkup.
1. Useanexternalstylesheet,eitherbyimportingitorbylinkingtoit.
2. Directlyembedadocument-widestyleintheheadelementofthedocument.
3. Setaninlinestyleruleusingthestyleattributedirectlyonanelement.
Eachofthesestylesheetapproacheshasitsownprosandcons,aslistedinTable4-4.
PART II
round-trip for the style information for other style information
sheet, which might documents, bulking throughout the
delay page rendering, up the document document and
particularly when and making it more outside documents.
multiple files are difficult to apply • Bound too closely to
Cons in use. updates. markup, making it
• In some cases when even more difficult
@import is used, the to update than other
browser may cause a approaches.
rendering “flash” under
slow loading conditions.
<link <styletype="text/ <h1style="color:
rel="stylesheet" css"media="all"> red;">
href="main.css" h1{color:red;} Iamred!
type="text/css" </style> </h1>
Example media="screen">
NOTE Atrailingslashis
neededforXHTML.
example,thefollowingCSSrulescanbefoundinafilecalledsitestyle.css,whichdefinesa
stylesheetusedsite-wide:
/*sitestyle.css*/
body{font-size:medium;
font-family:Serif;
background-color:black;
color:white;}
#page{background-color:white;
color:black;
padding:1em;}
454 Part II: Core Style
h1{font-size:xx-large;
font-family:Sans-Serif;
color:black;
text-align:center;
border-bottom:solid4pxorange;}
p{text-indent:1em;
text-align:justify;
line-height:150%;}
a:link{color:blue;text-decoration:none;}
a:visited{color:red;text-decoration:none;}
a:hover{color:red;text-decoration:underline;}
a:active{color:red;text-decoration:none;}
Don’tworry,wehaven’tcoveredallthesepropertiesyet,butwewillcertainlydosoasthe
bookprogresses.Fortunately,mostoftheselectorsaresimpleelementandidselectorsthat
havealreadybeenintroduced,savethepseudo-classes,a:link,a:visited,a:hover,and
a:active,whichareselectorsthatareassociatedwiththevariousstatesofalink.
An(X)HTMLfilecouldusethestylesheetbyreferencingitbyusinga<link>tag
withintheheadelementofthedocument.Toindicatetherelationshipbetweenthe
documents,settherelattributetoavalueof"stylesheet."Thehrefattributeisused
tospecifytheURLofthestylesheettofetch.TheURLmayberelativeorevenremote,
pointingtoastylesheetonsomeotherserver,thoughyoushouldbecautiousabout
linkingtoremotefiles,givendownloaddelaysandthepossibilitythatthefilecouldbe
changedwithoutyourknowledge.Thetypeattributeissettoindicatethetypeofstyle
sheettechnologyinuse,asdefinedbytheMIMEtypetext/css.Themediaattributecan
beusedtosethowthestylesheetshouldbeapplied.Whenomitted,thedefaultis"all".
Laterinthechapter,wewilldiscusshowitispossibletodefinedifferentstylesforscreen,
print,andotherpotentialoutputenvironments.Thegeneralsyntaxforassociatingastyle
usinga<link>tagisshownhere:
<linkrel="stylesheet"
href="stylesheetURL"
type="MIMEtypeofstylesheet"
media="media-type">
Thissyntaxisillustratedherewithafewexamples:
<linkrel="stylesheet"href="global.css"type="text/css">
<linkrel="stylesheet"href="../styles/mainscreen.css"
type="text/css"media="screen">
<linkrel="stylesheet"href="http://htmlref.com/ch4/print.css"
type="text/css"media="print">
TIP Likeotherdependentfiles,itisadvisabletoputallyourstylesheetsinaspecialstylesdirectory,
usuallynamed“styles”or“css,”availableatasiteroot.
Chapter 4: Introduction to CSS 455
Ofcourse,unlessthestyleisboundintoadocumentrelatedtothedefinedrules,nothing
willbeseen,soafullexampleispresentedhere,witharenderingshowninFigure4-7:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>LinkedStyles</title>
<linkrel="stylesheet"href="sitestyle.css"type="text/css">
</head>
<body>
<divid="page">
PART II
<h1>HTMLwithLinkedStyle</h1>
<p>CascadingStyleSheets2.1asdefinedbythe
<ahref="http://www.w3.org">W3C</a>provides
powerfulpagelayoutfacilities.Thetechnology
dependsoncorrectmarkupsomakesure
yougetthatrighttoo!</p>
</div>
</body>
</html>
O NLINE http://htmlref.com/ch4/linkedstyle.html
CSSis,atleasttheoretically,nottheonlystyletechnologywecoulduse,thoughasit
stands,bydefault,mostbrowsersassumethatCSSisbeingused.Wesettypetobespecific
butthatmaygetabitredundant.TheHTMLspecificationsuggestsyoucansetadefault
stylesheetlanguageintheheadelementofthedocumentbyusingthe<meta>tag,as
shownhere,
<metahttp-equiv="Content-Style-Type"content="text/css">
orbyoutputtingthisvalueintheHTTPheadersdeliveredtoasite.Interestingly,manysites
setthe<meta>tagandusethetypeattribute,whichisparticularlyappropriateasofthis
edition’spublicationasthespecificationdictatesthatthetypeattributemustbesetand
thustheW3Cvalidatorwillcomplainiftheattributeisnotsetregardlessoftheappearance
ofthe<meta>tag.Checkthecurrentsituationbyvalidatingthefilehttp://htmlref.com/
ch4/metacsscheck.htmlusingtheW3validatorservice.Dependingontheresult,youmay
noticethatspecificationsorthetoolsthatcheckthemaren’talwaysperfect.
<styletype="text/css"media="all|print|screen">
*styleruleshere*
</style>
Here,thetypeattributeisagainusedtoindicatetheMIMEtypeoftheenclosedstyle
sheet.However,thisisquiteoftenomittedbecausebrowsersgenerallyinferCSS.Themedia
attributeindicatesthemediaforwhichthestylesheetapplies.Bydefault,thestylesheetis
appliedtoallmedia,somostdevelopersomitthisattributeaswell.However,asmentioned
before,itispossibletodefinestylesheetsthatareappliedonlytoaparticularoutput
medium.Themostcommonvaluesare"print"and"screen,"whichindicatesthatrules
areappliedtothepageonlywhenitisprintedorcorrespondinglyshownonscreen.Other
valuesarepossibleforthemediaattributebutgenerallynotsupported.Withinthestyle
block,stylesheetrulesareincluded.Itisimportanttonotethatoncewithinthe<style>
tag,therulesof(X)HTMLdonotnecessarilyapply.The<style>tagdefinesanislandof
CSSwithinanoceanofmarkup.Thetwotechnologiesareintertwined,buthavetheir
owndistinctcharacteristics.
Oneconcernwhenincludingstylesheetswithinamarkupdocumentisthatnotalluser
agents,particularlyolderonesorcertainindexingsystemslikesimplisticbots,may
understandstylesheets.Giventhepossibilitythatthecontentofastylesheetistreatedas
regulartext,itisdesirabletomasktherules.Toavoidsuchaproblem,commentoutthe
styleinformationbyusingan(X)HTMLcomment,suchas<!---->:
<styletype="text/css"media="all">
<!--
h1{color:red;font-size:48px;}
-->
</style>
Chapter 4: Introduction to CSS 457
Whilethistechniqueiscommonpracticeandusedforscriptmaskingaswell,there
aresomesubtleissues,particularlywhenincludingnon-comment-friendlycontentlike
multipledashesortryingtoaddressXMLstrictness.Fornow,here’sacompleteexampleof
adocument-wideembeddedstylesheetincludingascriptmask:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>EmbeddedStyles</title>
<styletype="text/css"media="all">
<!--
PART II
body{font-size:medium;
font-family:Serif;
background-color:black;
color:white;}
#page{background-color:white;
color:black;
padding:1em;}
h1{font-size:xx-large;
font-family:Sans-Serif;
color:black;
text-align:center;
border-bottom:solid4pxorange;}
p{text-indent:1em;
text-align:justify;
line-height:150%;}
a:link{color:blue;text-decoration:none;}
a:visited{color:red;text-decoration:none;}
a:hover{color:red;text-decoration:underline;}
a:active{color:red;text-decoration:none;}
-->
</style>
</head>
<body>
<divid="page">
<h1>HTMLwithEmbeddedStyle</h1>
<p>CascadingStyleSheets2.1asdefinedbythe
<ahref="http://www.w3.org">W3C</a>provides
powerfulpagelayoutfacilities.Thetechnology
dependsoncorrectmarkupsomakesure
yougetthatrighttoo!</p>
</div>
</body>
</html>
O NLINE http://htmlref.com/ch4/embeddedstyle.html
458 Part II: Core Style
Youcanhavemultipleoccurrencesofthestyleelementwithintheheadofthe
document,andyoucanevenimportsomestyleswiththeseelements,asdiscussednext.
@importurl(corerules.css);
Thoughnotadvisablestylisticallyorforensuredbrowsercompatibility,thespecification
alsoallowsustosetastringafter@importoftheURL,likeso:
@import"corerules.css";
The@importdirectivemustbeincludedwithina<style>taganditmustprecedeall
othertypesofrulesinastylesheet.Inpractice,wemightseeanintermixtureofimported
andembeddedstyleswithinasingle<style>tag,asshowninthisexample:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>ImportedStyles</title>
<styletype="text/css"media="all">
<!--
@importurl(corerules.css);
@importurl(linkrules.css);
h1{font-size:xx-large;
font-family:Sans-Serif;
color:black;
text-align:center;
border-bottom:solid4pxorange;}
p{text-indent:1em;
text-align:justify;
line-height:150%;}
-->
</style>
</head>
<body>
<divid="page">
<h1>HTMLwithImportedStyle</h1>
<p>CascadingStyleSheets2.1asdefinedbythe
<ahref="http://www.w3.org">W3C</a>provides
powerfulpagelayoutfacilities.Thetechnology
Chapter 4: Introduction to CSS 459
dependsoncorrectmarkupsomakesure
yougetthatrighttoo!</p>
</div>
</body>
</html>
O NLINE http://htmlref.com/ch4/importedstyle.html
Intheprecedingexample,wecouldincluderulesforbodyanddivinthefilecorestyles.
css,whereastherulesaffectingthelinksareincludedviathedocumentlinkstyles.css.We
mightimaginethattheserulesareusedinotherstylesheets,andthusbreakingthemoutfor
PART II
reuseviaembeddingorlinkingmakessense.Rulesforh1andpelementsareplacedwithin
thestyleblockbecausetheymaybespecifictothisparticularpage.
<styletype="text/css"media="all">
<!--
/*ruleshiddenfromnon-importsupportingbrowsers*/
@importurl(hackingrules.css);
/*otherruleshere*/
-->
</style>
Similartothebox-modelhackdiscussedearlierinthechapter,thiskindofrudimentary
selectionstatementapproach,developedbyunderstandingthelikelybehaviorofabrowser,
isreallysomewhatofahack.Evenworse,weseethattheeffectofusing@importisan
annoyingflashingofunstyledcontentinsomeolderInternetExplorerversions.Becauseof
thepotentialproblemswith@import,Webpagedesignersshouldconsiderwellwhythey
needanoutsideinclusionschemebesideslinkedstyles,untilsuchquirksareancienthistory.
Inline Styles
Insteadofusingastylesheetforawholepage,youcanaddstyleinformationdirectlywithin
asingleelement.Supposeyouwanttosetoneparticular<h1>tagtorenderinextra-large,
green,Arialfont.Youcouldquicklyapplythestyletoonlythetaginquestionusingits
styleattribute,whichisacoreattributecommontonearlyanyHTMLelement.Asan
example,thefollowingmarkupshowsaninlinestyleappliedtoaheading:
<h1style="font-size:xx-large;font-family:Arial;color:green;">Inline
Style!</h1>
Thissortofstyleinformationdoesn’tneedtobehiddenfromabrowserthatisn’tstyle
sheet−aware,becausebrowsersignoreanyattributesthattheydon’tunderstand.
460 Part II: Core Style
AlthoughusinginlinestylesseemstobeaneasyroutetousingCSS,itdoeshavea
numberofdrawbacks.Thelargestproblemisthatinlinerulesareboundverycloselytoatag.
Ifyouwanttoaffectmorethanone<h1>tag,youhavetocopyandpastethestyleattribute
intoeveryotherheadingofinterest.TheseparationofmarkupfromCSSpresentationisnot
optimalwithaninlinestyle.However,forquickanddirtyapplicationofCSSrules,thismight
beappropriate,particularlyfortestingthingsout.
Thesecondandlesser-knownconcernwithinlineCSSrulesisthatyousimplycannot
performeverytaskwiththem.Forexample,ifyouwanttochangethelookofvariouslink
states,thisiseasilyaccomplishedinadocument-wideorlinkedstylesheetwithpseudo-class
ruleslike
a:link{color:blue;text-decoration:none;}
a:visited{color:red;text-decoration:none;}
a:hover{color:red;text-decoration:underline;}
a:active{color:red;text-decoration:none;}
However,ifyouattempttoputsuchrulesinan<a>tag,howareotherstatesindicated?The
simpleexampleherewouldappeartosetthecolortoblueforanystate:
<ahref="http://www.w3.org"style="color:blue;">InlineLinkStyles?</a>
Similarly,inordertochangethefirstletterofaparagraphtolarge,redtext,youmight
useapseudo-elementrulelike
p:first-letter{color:red;font-size:xx-large;}
However,whenyouattempttodothisinline,youareforcedtointroduceanelementto
holdthefirstletter:
<p><spanstyle="color:red;font-size:xx-large;">T</span>hisisatest.</p>
Whiletheseexamplesindicatewhytheseselectorsweregiventhenamespseudo-class
andpseudo-element,theydon’treallyshowushowtousesuchinlinestyles.
Itturnsoutthataworkingdraftspecificationforaddressingthisissuewasexploredin
20022.Theideawastoincludestyleblockswithoutaselectorforthedefaultstyleandfor
thevariousotherselectorsfortheelement,staterulesdirectlywithinthestyleattribute.
Forexample,tosetthelinkstates,wewoulduse:
<ahref="http://www.w3.org/"
style="{text-decoration:none;}
:link{color:blue;}
:visited{color:red;}
:hover{color:red;text-decoration:underline;}
:active{color:red;}">InlineLinkStyles?</a>
Tosetthefirstletteronparagraphs,wewoulduse:
<pstyle="{text-indent:1em;
text-align:justify;
line-height:150%;}
2
www.w3.org/TR/css-style-attr
Chapter 4: Introduction to CSS 461
:first-letter{color:red;font-size:xx-large;}">
Thisisatest.</p>
Theemergingspecificationevensuggestedtheimportationofstylesheetsdirectlyinline:
<divid="navbar"
style="@importurl(navigationstyles.css);">justanexample</div>
Whilealltheseideasarequiteinteresting,morethansevenyearsaftertheworkingdraft
wasauthored,notasinglebrowsersupportsthissyntaxatthetimethiseditionisbeing
completed.So,besidesbeingtoocloselyboundtotags,understandthatunlessthissituation
haschangedbythetimeyoureadthisedition,onlyusinginlinestylesisgoingtolimityour
applicationofsomeofthemoreusefulCSSselectors.
PART II
NOTE Innumerousplacesinthisbook,inlinestyleswillbeusedtodemonstratetheapplicationof
look.Whileitisclearthischoicedoesnotdemonstratetheidealapproachtobindstyletomarkup,
thedecouplednatureofotherapproachessimplydoesnotlenditselftoexplanationsinprose.
Frequentreminderswillbegiventoencourageyoutomorelooselycouplestyleandmarkuponce
youunderstandthepropertyortaginquestion.
Media Types
AsignificantgoalofCSS2wastoaddsupportforotheroutputmediaformsbeyondthe
computerscreen.TheCSS2.1specificationdefinesnumerousmediatypes,listedinTable4-5.
Today,primarilythevaluesall,screen,andprintareused,sountilbrowservendorsor
developersofotheruseragentsbegintosupportadditionalmediatypes,thesedefinitions
havenomeaningoutsideofthespecification.
TIP Ifyouarecurioustoexperimentwithothermediatypevaluesbeyondscreenandprint,the
Operabrowser(www.opera.com)supportsanumberoftypesbeyondwhatmorepopularbrowsers
support.
CSSprovidestwomainwaystodefinemediatypesforstylesheets.Thefirstmethod
simplyusesthemediaattributeforthe<link>tagtodefinethemediatype.Thisattribute
enablesthepagedesignertodefineonestyleforcomputerscreens,oneforprint,and
perhapsoneforhandhelddevicesorothersupportedmediatypes.Forexample,herewe
associatethreedifferentstylesheetsthatvarybymedia:
<linkrel="stylesheet"href="screen.css"media="screen"
type="text/css">
<linkrel="stylesheet"href="smallscreen.css"media="handheld"
type="text/css">
<linkrel="stylesheet"href="print.css"media="print"
type="text/css">
Multiplevaluesalsocanbesetfortheattribute.Theseshouldbeseparatedbycommas,
toshowthatthestylecanapplytomanymediaforms;forexample:
<linkrel="stylesheet"href="screen.css"media="screen,projection,tv"
type="text/css">
Thedefaultvalueformediaisallandisappliediftheattributeisnotused.
Whenusinganembeddedstylesheet,themediaattributeisusedinasimilarway:
<styletype="text/css"media="screen,projection,tv">
/*screenrules*/
</style>
<styletype="text/css"media="print">
/*printrules*/
</style>
Whenstylesareimported,the@importrulecanalsobeusedwithamediatypeby
addingtheappropriatemediatypeafterdefiningtheURL,asshowninthiscode
fragment:
@importurl("screen.css")screen;
@importurl("print.css")print;
A@mediaruleisusedtodefinestylerulesformultiplemediatypesinasingle
embeddedstylesheet:
<styletype="text/css">
@mediascreen{/*screenrules*/}
@mediaprint{/*printrules*/}
@mediascreen,print{/*screenandprintrules*/}
</style>
Chapter 4: Introduction to CSS 463
Thesyntaxmaylookalittleoddbecauseyouhavetowrapstyleblockswithmorecurly
braces,likeso:
<styletype="text/css">
@mediascreen{body
{font-family:sans-serif;
font-size:14px;}
}
@mediaprint{body
{font-family:serif;
font-size:10px;}
PART II
}
</style>
Similartolimitationsofinlinestylesforsupportingpseudo-classesandpseudo-elements,
itisnotpossibleatthetimeofthisedition’swritingtobuildequivalentmedia-specificsyntax
intoavaluepresentinanelement’scorestyleattribute.However,giventheprevious
discussionofpossiblechangestoinlinestyles,itseemslikelythatsyntaxlike
<pstyle="@mediaprint{line-height:100%;font-size:10px;}
@mediascreen{line-height:150%;}">
Thisisatest.</p>
mightsomedaybesupportedinabrowser.However,thisispurelyspeculationonthe
author’spart,andtheexampleanddiscussionhereshouldbeyetmoreindicationthat
inlinestyleshavetheirlimitations.
NOTE Oneexcitingemerginguseofmediaattributesand@mediadirectivesistheuseofqueries
toapplydifferentlooksdependingondevicecharacteristics.SeetheChapter6section“Media
Queries”formoreinformation.
Printer-Specific CSS
Currently,themainuseofmedia-specificstylesheetsistospecifyonestylesheetfor
printingandoneforviewingonscreen,asdemonstratedhere:
464 Part II: Core Style
Allmodernbrowserssupportprinterstyles,whichwouldseemtosuggestthatthe
practiceofinsertingaspecial“printformat”buttonisobsolete.However,thesenseof
“whatyouseeiswhatyouget”isimportanttousers,soitisagoodideausability-wiseto
allowtheusertoeasilypreviewtheprintedpage.
Aprinterstylesheetmaybeusedtoformatcontentquitedifferently.Commonly,certain
browser-specificfeatureslikenavigationelementsmayberemoved,usuallyaccomplished
usingthedisplayproperty.URLsmaybewrittenoutnexttoembeddedlinks.Forprinter
styles,fontsizesandlayoutmaybechangedtomoreappropriatelyfitpaperconsumption
whichmayincluderesortingtocompletelydifferentmeasurementunitsthanwhatisused
onscreen.
Alternative Styles
Theopportunitytohavedifferentlooksfordifferentsituationsisanaspectoftenmentioned
aboutCSSbutrarelyseen.Theeasiestwaytoillustratethisisthroughalternativestyle
sheets.Inanumberofbrowsers,itispossibletothenchangethelookofapagebyselecting
analternativestyle.Toinsertdifferentstyles,usea<link>tagandsettherelattribute
equalto“alternatestylesheet.”Youwillalsoneedtosetthetitleattributeforthetagso
thatthebrowsercanpresentachoicefortheuser.Threeexamplesareshownhere:
<linkrel="stylesheet"href="standard.css"title="standard">
<linkrel="alternatestylesheet"href="orange.css"title="HappyHalloween">
<linkrel="alternatestylesheet"href="greenandred.css"title="Merry
Christmas">
Abrowserthatsupportstheselectionofalternativestylesheetswouldthenpresentthe
possibilityofchoosingadifferentlooktotheuser,asshownunderthemenuselectionhere:
Chapter 4: Introduction to CSS 465
PART II
FIGURE 4-8 Drastic look changes per style sheet
Thelookscreatedwithalternativestylesheetsmightberadicallydifferent,asshownin
Figure4-8.
O NLINE http://htmlref.com/ch4/alternatestyles.html
Probablythemostsignificantchallengewithalternativestylesheetsissimplymaking
usersawarethatsuchchoicesexist.Inpractice,sitesthatallowforsuchcustomization
usuallyemploysomeJavaScript-basedstylepickersystemtomakeitclearcustomizations
canbeemployed:
466 Part II: Core Style
User Styles
UsersmayopttousetheirownstylesheetswhenviewingaWebpage.Mostoften,thisis
donetocreatealookthatiseasierfortheusertoread.UnderInternetExplorer,usersset
theirownstyleusingtheAccessibilityfeaturesunderInternetOptions:
Insomecases,settinguserstylesmightrequireabrowseradd-onoreditingofsome
preferencefile.However,inthecaseofveryaccessibility-orientedbrowserslikeOpera,
rapidlyswitchingbetweenuserstylesiseasilyperformed.
Chapter 4: Introduction to CSS 467
Userstylescanbeappliedtoarbitrarysitestoimproveormodifytheviewingexperience.
Userstylesheetsdirectlyexposethetensionbetweenwhatthesitedesignerwantstodeliver
andwhattheenduseractuallyendsupviewing.
PART II
ManyWebdesigners,however,arenotcomfortablewiththissharedcontrolandmay
attempttousefixedsizesandfixedpositions,resortto!important,orevenimplement
othertechnologicaloverridesusingFlashorimages.Forcingappearanceisnotinthebest
interestofusability.Forexample,ifyoucanforceaparticularlayoutorfontsize,what
happenstotheuserwithpooreyesightwhoreallyneedstoadjustthingsinordertoreadthe
content?TheWebisnotprint,andforcinginflexibledesignsonenduserswillnotalwaysbe
metwithsuccess.
468 Part II: Core Style
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>TestFile</title>
</head>
<body>
<h1>Test</h1>
<p>Thisisa<strong>Test</strong>!</p>
</body>
</html>
Intheexampleparsetree,notehowthe<strong>tagisachildofthe<p>tag,whichis
inthe<body>,whichisinthe<html>tag.Whathappensifyousetastyleruletop
elements,asfollows?
p{color:red;}
doctype
html
head
meta
title
body
h1
strong
Wouldthecontentsofthe<strong>tagenclosedinthe<p>tagalsobered?Theansweris
yes,becausethecolorisinheritedfromtheparentelement:
p {color:red;}
body
h1
p Red
PART II
strong Red
Whereasmostelementscaninheritthestylefeaturesoftheirparents,somestyleproperties
donotinherit.Forexample,considersettingtheborderpropertyoftheparagraphlikeso:
p{border:solid;}
Iftheenclosed<strong>tagfromthepreviousexampleinheritedtheborder,youwould
expecttoseesomethinglikethis:
This is a test
However,thisdoesnothappen;theborderislimitedjusttotheparagraphitselfbecausethe
bordervalueisnotinherited.ThereferenceinChapter5willpointoutimportantnon-
inheritingproperties.
Assumingthatapropertydoesinherit,itisstillpossibletooverridetheinheritanceof
aproperty.Forexample,considerthefollowingtworules:
p{color:red;font-size:xx-large;}
strong{color:yellow;}
Inthiscase,thecolorofthetextwithinthe<strong>tagwouldbeyellowandhaveanxx-
largesize.Bothofthepropertieswereinherited,butthecolorpropertywasoverridden
bythecolorruleforthe<strong>tag,whichismorespecific:
body
p Red, xx-large
Override Inherit
strong Yellow, xx-large
470 Part II: Core Style
Thecombinationofmultiplerules,withelementsinheritingsomepropertiesand
overridingothers,istheideaofthecascadethatCSSisnamedfor.Thegeneralideaofthe
cascade,ineffect,isthatitprovidesasystemtosortoutwhichrulesapplytoadocument
thathasmanystylesheets.Forexample,aruleforaspecific<p>tagmarkedwithanid
attributeismorepowerfulthanaclassruleappliedto<p>,whichinturnismorepowerful
thanaruleforthepelementitself.Inlinestylessetwithastyleattributearemoreimportant
thanadocument-widestyleorlinkedstyle.Aneasywaytothinkaboutwhichrulewinsisto
followthesehelpfulrulesofthumb:
• Themorespecifictherulethemorepowerful.
• Theclosertheruleistothetagthemorepowerful.
Sowiththeserules,weseethatidrulesaremorespecificthanclassrulesandthus
willoverridethem.Inlinestylesareclosertotagsthandocument-wideorexternalstyle
rulesandthustakeprecedence,andsoon.
TIP Thereisanactualprocesstodeterminethespecificityofaparticularruleversusanotherby
assigningnumericvaluestoeachrule,butifadesignerrequiressuchacarefulanalysisofthe
stylerulestodetermineanendresult,thestylesheetissimplytoocomplex.
!important Override
Ifaparticularruleshouldneverbeoverriddenbyanotherrule,the!importantindication
shouldbeused.Forarulenevertobeignored,inserttheindication!importantjustbefore
thesemicolonoftherule.Forexample,toalwayssetallparagraphstoredtext,youmight
usethefollowing:
p{color:red!important;font-size:12px;}
Lateron,youmighthaveaparagraphwithaninlinestylesuchasthis:
<pstyle="color:green;font-size:24px;">Thisisatest</p>
Inthisparagraph,thetextwouldstillberedduetotheinclusionofthe!important
indicator,althoughitwouldbelargerbecausethatrulewasoverriddenasexpected.When
usingthe!importantindicator,alwaysmakesuretoputitattheendofarule;otherwise,
itwillbeignored.Usingthe!importantoverrideisnotencouragedbutitisaneasywayto
forceastyleandcanbeusefuliffindingtheoriginatingsourceofavalueisdifficult.
Nowthatwehavediscussedthegeneralsenseofrulesbeingappliedtoadocument
tree,let’sdiscusstheselectorsthatbindparticularCSSrulestosectionsofadocument.
Selectors
TounderstandCSSrules,youmustfirstmasterselectors.Wehavebrieflyintroducedbasic
selectorssuchaselementvaluesandwillreviewthosefirst,butdon’tmoveontooquickly,
becausetherearemanymoreselectorstodiscuss.
Chapter 4: Introduction to CSS 471
Element Selectors
Asshownintheprevioussections,thesimplestrulescanbeappliedtoalloccurrencesofa
particulartag,suchas<p>.Theseselectorsarecalledelementselectorsandaresimplyused
asfollows:
element-name{/*properties*/}
Asanexample,tosetthelinespacingforallparagraphs,usearulesuchasthefollowing:
p{line-height:150%;}
Tosetavalueforallelements,thewildcardselector*(asterisk)canbeused.Forexample,
PART II
toremovethemarginsonallelements,use
*{margin:0;}
Tosetavalueformorethanonebutfewerthanallelements,wecangroupelementsby
separatingthemwithacomma.Forexample,ifyouwantthetags<h1>,<h2>,and<h3>to
havethesamebasicbackgroundandcolor,youcouldapplythefollowingrule:
h1,h2,h3{background-color:yellow;color:black;}
Ifitturnsoutthateachparticularheadingshouldhaveadifferentcustomsize,youcan
thenaddthatcharacteristicbyaddingotherrules:
h1{font-size:200%;}
h2{font-size:150%;}
h3{font-size:125%;}
Theresult,aswe’llseelater,istocombinealltherulestoformthefinalrenderedstyle.
Althoughassociatingallelementswithacertainlookisuseful,veryoftendesignerswant
tocreateveryspecificrulesthatareappliedonlytocertainelementsinadocumentorthat
canbecombinedtoformmorecomplexrules.
id Selectors
Byapplyinganidrule,astylecanbeappliedtojustasingletag.Forexample,ifwenamea
tagwithauniqueidattributeasfollows
<tagid="id-value">AffectedText</tag>
wecanthenreferenceitwithaCSSselector#id-value.Forexample,
<h1id="FirstHeading">ThisistheFirstHeading!</h1>
canbestyledwith
#FirstHeading{background-color:green;}
andthiswouldapplyagreenbackgroundtotheelementthathasitsidattributesetto
FirstHeading.
472 Part II: Core Style
Thefollowingmarkupshowshowagreenbackgroundisappliedtothe<p>tagwith
theidvalueof"p2",whereasnostyleisappliedtotheotherparagraphs:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>IdSelectorExample</title>
<styletype="text/css"media="all">
#p2{background-color:green;}
</style>
</head>
<body>
<p>Thisisthefirstparagraph.</p>
<pid="p2">Thisisthesecondparagraph.</p>
<p>Thisisthethirdparagraph.</p>
</body>
</html>
O NLINE http://htmlref.com/ch4/idselector.html
Asacore(orglobal)attribute,theidattributeiscommontonearlyall(X)HTML
elements.However,givenwidespreaduseofidattributes,pageauthorsneedtobevery
carefultoensurethatelementsarenameduniquely.Developersmustnotnametwo
elementsthesamenameusingtheidattribute.Iftwooftheparagraphshaveid="p2",
whatwillhappen?Inthecaseofmostbrowsers,bothparagraphswillshowupgreen.
However,thisissuchsloppystylethatitgenerallywillresultinsignificanterrorsonce
scriptingisaddedtothedocument.Furthermore,thedocumentwillnotvalidatewithsuch
mistakes.Ifmultipleelementsshouldbeaffectedinasimilarway,useaclassruleinstead.
Element-Specific id Rules
Onenonintuitivevariationofanidselectorisanelement-specificselectorlike
p#p2{background-color:green;}
Thiswouldselectonlyparagraphelementswiththeiridattributesetto"p2."Comparethis
toarulelike
#p2{background-color:green;}
Chapter 4: Introduction to CSS 473
whichwouldmatchanyelementwithanidof"p2."Immediately,youshouldthinkthat
thisimpliesthatmorethanoneelementcanshareidvalues—whyelsewouldweneedto
bemorespecificthanasimpleidrule?Well,withinasingledocument,thatiscorrect,andit
isnotappropriatetohavemarkuplike
<pid="p2">Iamacorrectlyidentifiedparagraph</p>
<divid="p2">Waityoualreadyusedthatidvalue!</div>
<p>Not<spanid="p2">again!!!!</span>Youalreadyusedthevaluep2!</p>
andthenusestyleruleslike
p#p2{color:red;}
PART II
div#p2{background-color:blue;color:white;}
span#p2{color:blue;}
However,suchruleswouldmakesenseifthiswerealinkedstylesheetusedsite-wide
andwehaddifferentelementsindifferentdocumentsallnamed"p2."Theauthorconsiders
suchusagebadstyleasitassumesthatpagecontentisalwaysfoundwithinthesame
documentandwillnevermove,whichisnotalwaysthecase.Asite-wideuniqueid
approachwouldsolvesuchfutureproblemsandwouldalleviatetheneedforthistypeof
selector.
class Rules
Theclassattributeisusedtodefinethename(s)oftheclass(es)towhichaparticulartag
belongs.Unlikeidvalues,classvaluesdon’thavetobeuniquebecausemanyelements
canbemembersofthesameclass.Infact,elementsdon’tevenhavetobeofthesametype
tobeinacommonclass.Writingrulesforclassesiseasy:simplyspecifytheclassnameof
yourownchoosing,suchas“nature,”withaperiodbeforeitastheselector:
.nature{color:green;}
Theuseofclassisillustratedhere:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>ClassSelectorExample</title>
<styletype="text/css"media="all">
.veryimportant{background-color:yellow;}
</style>
</head>
<body>
<h1class="veryimportant">Example</h1>
<pclass="veryimportant">Thisisthefirstparagraph.</p>
<p>Thisisthesecondparagraph.</p>
<pclass="veryimportant">Thisisthethirdparagraph.</p>
</body>
</html>
474 Part II: Core Style
O NLINE http://htmlref.com/ch4/classselector.html
Thepreviousexamplehasthreeelements,eachofwhichhasitsclassattributesetto
“veryimportant.”Accordingtothestylesheetinformation,allmembersofthe“veryimportant”
classhaveayellowbackgroundcolor:
Othervariationsonclassrulesarepossible.Forexample,settingallh1elementsofthe
class“veryimportant”tohaveabackgroundcoloroforangecouldbewrittenlikethis:
h1.veryimportant{background-color:orange;}
Insomeways,youcanthinkofaclassrulewithawildcardselectorlike
*.veryimportant{background-color:orange;}
asbeingthesameasthecommonlyusedclassselector
.veryimportant{background-color:orange;}
Whilethisissyntacticallycorrect,itdoesn’taddmuchunderstanding.Moreinterestingand
quiteunderusedisthepossibilityinselectorstocombineclassestogetherdirectly.For
example,considerthefollowingrule:
h1.veryimportant.stuff{background-color:green;}
Thiswouldmatchonly<h1>tagswithclassattributevaluesincluding“veryimportant”
and“stuff.”Giventheserules,thefollowingtagswithclassattributeswouldbeaffectedin
thevariouswaysindicated:
<h1class="veryimportant">Hasanorangebackground</h1>
<h1class="veryimportantdummy">Hasanorangebackground</h1>
<h1class="veryimportantstuff">Hasagreenbackground</h1>
<h1class="veryimportantdummystuff">Hasagreenbackground</h1>
<h1class="dummy">Defaultbackgroundunlessclassrulefordummyset</h1>
Chapter 4: Introduction to CSS 475
Noticethattheruleforgreenbackgroundmatchesany<h1>tagthatincludestheclass
values“veryimportant”and“stuff”butnotnecessarilyuniquelyorinorder.Ifyouare
lookingtowritearulethatmatchesanysingleoccurrenceofaparticulargroupofclass
values,thenthecommaoperatorisinorder.Forexample,separatingthefollowingthree
classnamesbycommas
.larry,.curly,.moe{color:red;}
wouldmeanthatanyelementwithasingleoccurrenceormoreoftheseclassvalueswould
besetasred.
Thefollowingisacompleteexampleshowingmultipleclassrulesworkingtogether:
PART II
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>MultipleClassSelectorExample</title>
<styletype="text/css"media="all">
.heading{font-family:Impact,Sans-Serif;}
.veryimportant{background-color:yellow;}
.stuff{color:red;}
.veryimportant.stuff{font-style:italic;}
.veryimportant.example.stuff{text-decoration:underline;}
</style>
</head>
<body>
<h1class="veryimportantheadingstuff">Heading(yellowbackground,red
text,italic,andImpact)</h1>
<pclass="veryimportant">Thisisthefirstparagraph.(yellowbackground,
blacktext)</p>
<pclass="stuff">Thisisthesecondparagraph.(redtext,default
background)</p>
<pclass="veryimportantstuff">Thisisthethirdparagraph.
(yellowbackground,redtext,italic)</p>
<pclass="stuffveryimportantexampledummy">Thisisthefourthparagraph.
(yellowbackground,redtext,italic,underlined)</p>
</body>
</html>
O NLINE http://htmlref.com/ch4/multiclassselector.html
476 Part II: Core Style
Astheseexampleshaveshown,classescanbeusedtosignificantlyreducethenumber
ofstylerulesnecessaryinadocument.
Contextual Selection
Althoughtheclassandidattributesprovideagreatdealofflexibilityforcreatingstyle
rules,manyothertypesofrulesofequalvalueexist.Forexample,itmightbeusefultospecify
thatall<strong>tagsthatoccurwithina<p>taggettreatedinacertainway,ascomparedto
thesameelementsoccurringelsewherewithinthedocument.Tocreatesucharule,youmust
usecontextualselection.Contextualselectorsarecreatedbyshowingtheorderinwhichthe
tagsmustbenestedfortheruletobeapplied.Thenestingorderisindicatedbyaspace
betweeneachselector.Forexample,giventherule
pstrong{background-color:yellow;}
alloccurrencesofthestrongelementwithinapelementhaveayellowbackground.Other
occurrencesofstrongwithoutapancestorelementmightnotnecessarilyhavetheyellow
background.
TIP BecarefulabouttheuseofthespaceandcommainCSSselectors;itiseasytoturngrouping
intocontextualselectionorviceversawithasimpletypo.
Contextualselectiondoesnotrequireadirectparent-childrelationshipwithelements.
Forexample,withtheruleintheprecedingexample,youwouldfindthatgiven
<p>This<span>isnot<strong>directly</strong>within</span>
theparagraph.</p>
Chapter 4: Introduction to CSS 477
thenested<strong>tagwillstillhaveayellowbackgroundeventhoughitisnotdirectly
withinthe<p>tag.Whatyouareseeinghereisthattherulereallysaysthatall<strong>
tagsthatare“descendents”ofa<p>tagaregivenayellowbackground:
strong
PART II
body Yellow
Direct Descendent
p
strong
body Yellow
Indirect descendent
p
span
strong
Descendentselectionisnotlimitedtoasinglelevel,nordoesitrequirejustgeneric
elementselection;forexample,herewesaythatlinksinsideofunorderedlistsfoundinside
ofthedivelementwiththeidof“nav”shouldhavenounderlines:
div#navula{text-decoration:none;}
Itisalsopossiblethatusingawildcardselectormaybeusefulwithcontextualselection.
Therule
body*a{text-decoration:none;}
wouldselectonly<a>tagsthataredescendentsofsometagfoundunderthebodyelement.
Whileusingmultipleelementstogethercanbequitepowerful,morespecificselections
requireotherCSSselectorsyntax.
478 Part II: Core Style
body>p{background-color:yellow;}
Herewefindthatonlyparagraphsthatarethedirectchildrenofthebodyelementhavea
yellowbackground:
<body>
<p>Ihaveayellowbackground</p>
<div><p>Idonothaveayellowbackground.</p></div>
</body>
body
div
h1+p{color:red;}
Thisstatesthatallparagraphelementsthataredirectlyafteran<h1>arered,asindicated
bythismarkup:
<h1>Iamaheading</h1>
<p>IamanadjacentparagraphsoIamred!</p>
<p>IamnotadjacentsoIamnotred.</p>
h1 + p {color: red;}
body
h1
p Red - Adjacent to h1
h1~p{color:red;}
wouldmeanthat<p>tagsthateventuallyfollowatthesametagnestinglevelas<h1>tags
wouldbered:
<p>Iamnotred.</p>
<h1>Heading1</h1>
<p>Thisisred.</p>
PART II
<h2>Heading2</h2>
<p>Iamredtoo.</p>
<div><p>NotmeasIamnotasiblinggiventhatIamoneleveldown.</p></div>
h1 ~ p {color: red;}
body
p Not Red
h1
p Red
h2
p Red
div
p Not Red
NOTE Advancedcontextualselectorslikedirectchildselectorsarenotsupportedundersome
relativelyrecentInternetExplorerversions,notablyIE6andearlier.
AsummaryofallthecoreelementselectorsdiscussedsofarcanbefoundinTable4-6.
Attribute Selectors
Attributeselectors,firstintroducedinCSS2,allowrulestomatchelementswithparticular
attributesorattributevalues.Forexample,arulesuchas
a[href]{background-color:yellow;}
wouldmatchall<a>tagsthatsimplyhavethehrefattribute,whereasarulesuchas
a[href="http://www.htmlref.com"]{font-weight:bold;}
wouldmatchonlythose<a>tagsthathaveanhrefvaluesettothebook’ssupportsiteURL.
480 Part II: Core Style
Itispossibletomatchmultipleattributevaluesorevenpiecesoftheattributevalues.
Forexample,tomatchavalueinaspace-separatedlist,youmightusearulelikethis:
p[title~="Larry"]{font-style:italic;}
Thisrulewouldmatch
<ptitle="LarryCurlyandMoe">Thisisitalic.</p>
<ptitle="Larry">Thisisitalic.</p>
<ptitle="Larry-The-Stooge">Thisisnotitalic.</p>
Tomatchanattributevalueseparatedbydashes,whichiscommoninlanguagevalues
PART II
(forexample,en-uk,en-us,andsoon),usearulelikethis:
p[lang|="en"]{color:red;}/*Englishtextinred*/
ThisrulewouldthenaffectEnglishparagraphsbutnotparagraphsthathavenolanguage
specifiedoradifferentvaluethananEnglishvariation:
<plang="en">ThisisEnglishandred.</p>
<plang="en-uk">ThisisBritishEnglishandred.</p>
<p>Notrednolangspecified.</p>
<plang="fr">C'estFrancais.(Notred)</p>
LaterwewillseeanalternateformoflanguageselectionusingaCSS3pseudo-class
called:lang().We’llsavethatforlaterwhenwediscussotherpseudo-classes,butwhile
we’reonthetopicofCSS3,let’sseewhatattributeselectionpossibilitiesthisemerging
specificationintroduces.
p[title^="Startmatch"]{background-color:red;}
andapplythemtothefollowingmarkup:
<ptitle="Startmatch">Thisshouldbered.</p>
<ptitle="NoStartMatch">Thisshouldnotbered.</p>
Using[attr$=value],wecanmatchtheendofanattributevalue.Forexample,here
wematchparagraphswithtitleattributesthatendwith“matchend”
p.group4[title$="matchend"]{background-color:red;}
whichisdemonstratedwiththismarkup:
<pclass="group4"title="Thisshouldmatchend">Thisshouldbered.</p>
<pclass="group4"title="Thiswon'tmatchend!">Thisshouldn'tbered.</p>
482 Part II: Core Style
Finally,wecanlookoveranattributevalueandfindmatcheswithinitusing
[attr*=value].Herewematchparagraphelementswiththeword“found”presentinthe
titleattribute:
p[title*="found"]{background-color:red;}
Thiswillmatch
<ptitle="Thematchisfoundinhere">Thisshouldbered.</p>
butnotmatchthisparagraph
<ptitle="Nomatchcanbeseenhere">Thisshouldn'tbered.</p>
asitismissingthewordwematchon.However,notethatthisisn’treallyawordmatchbut
moreasubstringmatchasitwillmatchthefollowingmarkup:
<pclass="group4"title="*foundinside*">Thisshouldbered.</p>
However,asapatternmatch,itissusceptibletocasing,sothismarkup
<pclass="group4"title="*Foundinside*">Thisshouldn'tbered.</p>
wouldn’tmatch.Ifyouarefamiliarwithregularexpressionsandstarttoimagineacomplex
CSSselectorsystemwithcase-sensitivitywildcardsandmore.Ifyouhavebaddreams
aboutregularexpressions,youmightguesswherethistrendmayendupsomeday.
p.group1[title]{background-color:red;}
wouldmatchany<p>tagwiththeclass“group1”andwiththetitleattributeset.
Contextualselectionalsocouldbeapplied,where
#nava[href="http://"]{font-weight:bold;}
wouldmatchany<a>tagswhicharedescendentsofsomeelementwithanidvalueof
“nav”thathavehrefvaluesthatstartwith“http://”andmakethembold.
Wecanalsomatchmultipleattributecharacteristicsatonce.Considerthefollowing:
p[title="TestSelector"][lang|="en"]{border:2pxsolidblack;}
Thisrulewouldmatcha<p>tagwithatitlesetto“TestSelector”andalangvalueinthe
Englishfamily.Toexperimentwithattributeselectors,seetheexampleonlineathttp://
htmlref.com/ch4/attributeselectors.html.Table4-7presentsalltheattributeselectors
together.
Chapter 4: Introduction to CSS 483
PART II
the given value boldonallatagsthathave
theirhrefattributesetto
http://www.htmlref.com*/
E[attr|=value] Selects all elements of p[lang|="en"]{color:red;} CSS2
E that have an attribute /*Englishtextinred*/
that contains a value
that starts with a
value that is a list of
hyphen-separated values
E[attr~=value] Selects all elements p[title~="Test"] CSS2
of E that have a space- {font-style:italic;}
separated list of values /*setsthefontstyleto
for attr where one of italiconallptagsthat
those values is equal to haveonewordintheirtitle
the given value equaltoTest*/
E[attr^=value] Selects all elements of p[title^="HTML"]{color: CSS3
E that have the attribute green;}
attr that begins with the /*setsthecolortogreen
given value ifthetitlestartswith
HTML*/
E[attr$=value] Selects all elements of p[title$="!"]{color:red;} CSS3
E that have the attribute /*setsthecolortored
attr that ends with the ifthetitleendswithan
given value exclamationmark*/
E[attr*=value] Selects all elements of p[title*="CSS"]{font-style: CSS3
E that have the attribute italic;}
attr that contains the /*setsthefontstyleto
given value italicinanyptagthathas
CSSinitstitle*/
Pseudo-Element Selectors
YoumayencountersituationsinwhichyouwanttoselectaparticularportionofanHTML
documentbutthereisnotadefinedelementassociatedwithit.CSSprovidestheabilityto
styleportionsofadocumenttreewithoutauniqueelementassociatedwiththecontent.
Becauseinsomewaysthiscreatesanelementtoeffectthischange,suchselectorsare
dubbedpseudo-elementselectors.
p:first-letter{font-size:xx-large;background-color:red;}
wouldmakeeveryfirstletterofaparagraphlargeandred.Wecanalsomaketheinitialline
ofparagraphsadifferentstyleusingthe:first-linepseudo-element:
p:first-line{font-size:xx-large;text-decoration:underline;}
Thesepseudo-classesaren’tlimitedsolelyto<p>tagsbuttheyaregenerallylimitedtoblock
elements.Asimpleexampleofapplyingthesepseudo-elementsisshownhere:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>FirstLetterandFirstLinePseudo-Elements</title>
<styletype="text/css"media="all">
p#intro:first-letter{font-size:5em;font-weight:bold;
float:left;margin-right:.1em;
color:#999;}
p#intro:first-line{font-size:1.5em;font-weight:bold;}
</style>
</head>
<body>
<pid="intro">Itwasthebestoftimes,itwastheworstoftimes,itwas
theageofwisdom,itwastheageoffoolishness,itwastheepochof
belief,itwastheepochofincredulity,itwastheseasonofLight,itwas
theseasonofDarkness,itwasthespringofhope,itwasthewinterof
despair,wehadeverythingbeforeus,wehadnothingbeforeus,wewereall
goingdirecttoheaven,wewereallgoingdirecttheotherway-inshort,
theperiodwassofarlikethepresentperiod,thatsomeofitsnoisiest
authoritiesinsistedonitsbeingreceived,forgoodorforevil,inthe
superlativedegreeofcomparisononly.</p>
</body>
</html>
Chapter 4: Introduction to CSS 485
Thiswouldstylethefirstlineofsomeclassicprosewithaninitialdropcapandvariedfirst
line,asshowninthefollowingillustration.
O NLINE http://htmlref.com/ch4/firstletterandline.html
PART II
NOTE UnderCSS3,thesyntaxofpseudo-elementshasbeenchangedtohavetwocolons,so
:first-linebecomes::first-line.Thischangemakesthedifferencebetweena
pseudo-elementandapseudo-classexplicit,butsincethissyntaxisnotaswidelysupported
yet,theexampleswillfocusonthetraditionalCSS2syntax,whichwilllikelycontinuetobe
supportedforquitesometime.
div.section:before{content:url(sectionstart.gif);}
div.section:after{content:url(sectionend.gif);}
Thecontentpropertycanbeusedtospecifyobjectslikeimages,asindicatedbythe
precedingexample,butitalsocanspecifyregulartextcontent;forexample,
p.warn:before{content:"Warning!";}
willprinttheword“Warning!”beforeeveryparagraphinclass“warn.”Thefollowing
exampleuses:beforeand:afterpseudo-elements,arenderingofwhichappearsin
Figure4-10:
<!DOCTYPEhtml>
<html>
<head>
486 Part II: Core Style
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>:beforeand:afterPseudo-elements</title>
<styletype="text/css">
.external:after{content:url('offsite.gif');margin-left:.2em;}
.warning:before{content:"Warning!";
background-color:yellow;
border-style:dashed;border-width:1px;
margin-right:1em;}
.warning:after{content:"**";
background-color:yellow;
border-style:dashed;border-width:1px;
margin-left:1em;}
</style>
</head>
<body>
<p>
<ahref="#">Locallink</a><br>
<ahref="http://www.htmlref.com"class="external">externallink</a>
</p>
<pclass="warning">Thisisdangerousexampletext.
Becareful,youmaysufferboredomtypinginabunchoffake
textjusttomakethisexamplework.Don’tworry,almostdone.
Finally!</p>
</body>
</html>
O NLINE http://htmlref.com/ch4/beforeandafter.html
Chapter 4: Introduction to CSS 487
::selection Pseudo-Element
CSS3introducesapseudo-element::selectionthatisusedtostylepartsofanelement
thatiscurrentlyselectedor,asmorecommonlythoughtof,highlighted.Thefollowing
simpleexampledemonstratesthispseudo-element:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>::selectionPseudo-elements</title>
<styletype="text/css">
#select1::selection{background-color:red;}
PART II
#select1::-moz-selection{background-color:red;}
#select2::selection{color:green;}
#select2::-moz-selection{color:green;}
</style>
</head>
<body>
<p>Select<spanid="select1">thistext</span>.Nowselect<span
id="select2">thistext</span>.</p>
</body>
</html>
O NLINE http://htmlref.com/ch4/selection.html
NOTE Becauseofbrowsersupportwithmoreemergingfeatures,youmayseeCSSstemsyntax;in
thiscase,–moz-selectionisemployedtoimprovethelikelihoodofrendering.
Table4-8summarizesallthepseudo-elementsavailableinCSS1throughCSS3.
Pseudo-Class Selectors
Likepseudo-elements,pseudo-classesallowCSSselectorstospecifystylesformultiple
sectionsofadocumenttreethatmaynothavestylegroupsclearlyassociatedwiththem.
Traditionally,pseudo-classesweredominantlyusedwithlinkstatesandsimpleinterface
states,butunderCSS2andCSS3,thenumberofpseudo-classeshasexplodedtoincludea
widevarietyofdocumentpositionandtreelogicselectors.Nodoubtbythetimeyouread
thistherewillbeevenmore!
488 Part II: Core Style
Link-Related Pseudo-Classes
EvenifyouhavejustapassingfamiliaritywithusingaWebsite,you’llnotethatthereare
threeprimarystatestotypicaltextlinks—unvisited,visited,andactive(mid-press)—in
whichthelinktextcolorisblue,purple,andred,respectively.InCSS,thepresentationoflink
statesiscontrolledthroughthepseudo-classselectorsa:link,a:visited,anda:active.
CSS2alsoaddsa:hoverforthemousehoveringoveralink,thoughthispseudo-classin
theoryisn’tlimitedtolinks.Similarly,thepseudo-class:focuswouldbeselectedwhenthe
linkgainsfocus—generallythroughkeyboardnavigation.Anexampledemonstratinghow
theselink-relatedpseudo-classselectorsareusedisshownhere:
<!DOCTYPEhtml>
PART II
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>LinkPseudo-ClassExample</title>
<styletype="text/css"media="all">
a:link{color:blue;text-decoration:none;}
a:active{color:red;background-color:#FFC;}
a:visited{color:purple;text-decoration:none;}
a:hover{color:red;text-decoration:underline;}
a:focus{border-style:dashed;border-width:1px;
background-color:#FFA500;}
</style>
</head>
<body>
<ahref="http://www.htmlref.com">HTML:TheCompleteReference</a>
</body>
</html>
O NLINE http://htmlref.com/ch4/linkstates.html
AlthoughtheCSSrulesassociatedwiththestatesofalinkcanbeusedtochangethelink’s
appearanceindramaticways,designersareencouragedtolimitchangestoimproveusability.
Alsonotethatsizechangesandothersignificantdifferencesinlinkpresentationcanresultin
undesirablescreenrefreshesasthedocumentreloads.Forexample,witharulesuchas
a:hover{font-size:larger;}
youmaynoticetextlinesshiftingupanddownasyourolloverlinks.
Anewerlink-relatedpseudo-classis:target,whichisusedtostyleanelementwhenit
isalinktargetandthecurrentURLofthedocumenthasthatfragmentidentifierinitsURL.
Forexample,giventherule
#top:target{background-color:green;}
ataglike
<spanid="top">Iamthetopofthedocument.</span>
490 Part II: Core Style
wouldgetagreenbackgroundcoloronlywhenthecurrentURLincludesthefragment
identifier#top.
Trytheexampleonlineifyouarestillunsureofhowtheelementworks.
O NLINE http://htmlref.com/ch4/target.html
input[type=text]:focus{background-color:yellow;}
The:hoverpseudo-class,asdiscussedintheprevioussection,isusedprimarilytochange
theappearanceoflinkswhentheuser’spointerishoveringoverthem:
a{text-decoration:none;}
a:hover{text-decoration:underline;}
However,itispossibletoapplythispseudo-classtojustaboutanyelement,soarulesuchas
p:hover{background-color:yellow;}
isperfectlyvalid,althoughitproducesapotentiallyannoyingeffectandnoteverybody’s
browserhassupportforthisselectoronallelements.
Thefollowingisasimpleexampledemonstratingthesepseudo-classselectors:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>HoverandFocusPseudo-ClassExample</title>
<styletype="text/css"media="screen">
.annoy:hover{border-style:dashed;background-color:yellow;}
input[type=text]:hover{background-color:yellow;}
input[type=text]:focus{background-color:#FFA500;}
</style>
</head>
Chapter 4: Introduction to CSS 491
<body>
<pclass="annoy">Rolloverme.</p>
<p>Now<spanclass="annoy">rollover</span>thatbitoftext.</p>
<formaction="#">
<div><inputtype="text"size="40"value="Hoverandthenclickintothis
field"></div>
</form>
</body>
</html>
O NLINE http://htmlref.com/ch4/hoverfocus.html
PART II
Interface State Pseudo-Classes
Userinterfaceelementssuchasformshavevariousstatesdependingonuseractivity.CSS3
introducespseudo-classestostyleformelementsdependingonstate.Forexample,
:enabledand:disabledareusedtospecifythestyleforelementsthathavebeenenabled
ordisabled,respectively,generallybywhetherthe(X)HTMLattributedisabledhasbeen
set.Forexample,therule
input[type=text]:enabled{background-color:yellow;}
wouldapplyayellowbackgroundtothetextfieldhere
<inputtype="text"size="40"value="Thisfieldisenabled"><br>
whilethisrule
input[type=text]:disabled{background-color:red;}
wouldapplytoaredbackgroundtoadisabledfieldlike
<inputtype="text"disabledsize="40"value="Thisfieldisdisabled">
Itshouldbenotedthatveryoftenthedisablingorenablingoffieldswillnotbedirectly
presentinmarkup,butmaybesetbyJavaScript.
Thestyleofcheckboxesandradiobuttonscanbecontrolledusingthe:checked
pseudo-property.Forexample,
input[type=checkbox]:checked{border:2pxsolidred;}
wouldputaspecialborderonthecheckboxonceitwasset.
Otheruser-interfaceselectorsarealsodefinedunderanemergingCSS3UIspecification,3
like:default,:valid,:invalid,:in-range,:out-of-range,:required,:optional,
:read-only,and:read-write.Themeaningofsomeoftheseshouldbeclear;forexample,
input[type=text]:readonly{border:2pxdashedred;}
3
www.w3.org/TR/css3-ui/#pseudo-classes
492 Part II: Core Style
wouldsetanytextfieldthathasareadonlyattributesettohaveadashedredborder.Ifwe
wantedtoselectfieldsthatwerebothreadableandwritable,wewouldusearulelike
input[type=text]:read-write{border:2pxdashedred;}
whichwouldpickalltextfieldsthatarenotread-only.
Ifwehaveasetofvariousinputelementswhereoneisthedefault,wecouldusethe
:defaultpseudo-classruletostyleit.Forexample,
input[type=submit]:default{background-color:red;}
wouldsetthedefaultsubmitbuttoninaformtohavearedbackground.
Lookingfurther,themeaningoftheemergingpseudo-classesbecomeslessclear.While
itseemsobviousreadingthespecificationthat:validand:invalidcouldbeusedtostyle
interfaceelementswhicharenotinavalidstate,apseudo-classof:requiredwouldpick
fieldswhicharerequiredstateandsoon.However,eveniftheselectorsareclear,thebig
questionishowdoyouactuallyindicatesuchstatesformarkupelements?Thespecification
definesthatthisisrelatedtoWebForms,whichisnotawell-implementedtechnology.
However,manyoftheusefulideasofthatspecificationhavemadetheirwayintoHTML5,
soitisquitepossibletheseselectorswillsomedaybeimplemented.Certainlysupportfor
theseselectorsshouldnotbeassumed,sopleasetesttheexampleonline.
O NLINE http://htmlref.com/ch4/elementstate.html
wouldmakethefirst<li>tagfoundwithinanunorderedlisttag(<ul>)bold.Donotethat
withoutusingdescendentselectors,youarespecifyingauniversalselector.Forexample,a
rulelike
p:first-child{color:red;}
reallyis
*p:first-child{color:red;}
becauseitsaysthatanytimea<p>tagisafirstchildofsomeelementincludingthebody
elementitwouldbered.Tryforyourself,usingthissimpleexample:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>FirstChildPseudo-Class</title>
<styletype="text/css"media="screen">
p:first-child{color:red;}
</style>
</head>
Chapter 4: Introduction to CSS 493
<body>
<p>IshouldberedbecauseIamthefirstchildinthebody.</p>
<p>IshouldnotberedbecauseIamthesecondchildinthebody.</p>
<div>
<p>IshouldberedbecauseIamthefirstchildofdiv.</p>
<p>Secondchildofdiv,thusnotred.</p>
</div>
</body>
</html>
O NLINE http://htmlref.com/ch4/firstchild.html
PART II
CSS3introducesamultitudeofdocumenttree–relatedpseudo-classes.Tocomplement
:first-child(),wenowhave:last-child(),so
ulli:last-child{background-color:black;color:white;}
wouldmakethelastlistiteminanunorderedlisthavewhitetextonablackbackground.
Youarenotlimitedtolookingjustatthefirstorlastchildofanelement.Youcanalso
lookatthe:nth-child().Forexample,
ulli:nth-child(5){font-size:xx-large;}
wouldmakethefifthlistitemverylargeifthelisthadafifthitem.Ofcourse,suchsyntax
meansthat:nth-child(1)isthesameas:first-child,whichisofcoursemuchmore
readable.
The:nth-child()selectorisquitepowerfulbecauseyoucanusesimplekeywordslike
oddandeventoalternateeveryotherchild.Forexample,
ulli:nth-child(odd){color:red;}
ulli:nth-child(even){color:blue;}
wouldmakealloddchildreninalistredandallevenonesblue.
Nowsupposeyouwanttomakeeverythirdelementinthisunorderedlistitalic;you
couldusearulelike
ulli:nth-child(3n){font-style:italic;}
Wecanalsoperformtheseactionsfromtheendofatreetolookforthelastchildofa
particularelement.Forexample,
ulli:nth-last-child(2){text-decoration:underline;}
wouldmakethesecond-to-lastiteminthelistunderlined.Giventhissyntax,:nth-last-
child(1)isthesameas:last-child,whichisobviouslypreferable.Wecanuseallthe
samekeywordsandcountingvaluesinthe:nth-last-child()pseudo-classaswedidin
:nth-child().
Wecanalsolookforelementsofparticulartypeswithinasubtree.Forexample,
pspan:first-of-type{color:red;}
pspan:last-of-type{color:green;}
494 Part II: Core Style
wouldsetthefirst<span>tagfoundintheparagraphtoredandthelast<span>tagfound
togreen.Ofcourse,thosemightbeoneandthesame,whichwouldthenmaketheitem
greensincethatwasthefinalruledefinedandapplied.
Itisalsopossibletofindparticularitemsofatype.Forexample,thismakesthethird
<span>tagencounteredinaparagraphlarger,
pspan:nth-of-type(3){font-size:larger;}
whilethismakesthesecond-to-last<span>tagunderlined:
pspan:nth-last-of-type(2){text-decoration:underline;}
Thevalueoftheserulesasopposedtochildrenisclearwhenthereareotherelements
foundinasubtreeorwhenyoustartcombiningrules.Forexample,
p#intro.fancy:nth-of-type(4n){color:red;}
wouldmakeeveryfourthelementinclass“fancy”foundwithintheparagraphcalled
“intro”red.Asyousee,wecangetquitespecificwithCSS3treepseudo-classselectors.
Ifwearelookingforuniqueness,wehavetwopseudo-classesofinterest,:only-child
and:only-of-type.Forexample,thisrulewouldmakeaspangreenwhenitistheonly
childfoundinaparagraph:
pspan:only-child{color:green;}
so
<p>Iamthe<span>onlychildsoIamgreen</span>.</p>
<p>Ihave<span>two</span><em>children</em>sonogreenhere.</p>
Ifwecaretolookforsubtreesthatcontainelements,onlyacertaintypeuse
:only-of-type.Forexample,
pem:only-of-type{background-color:red;}
wouldsetthe<em>tagtohavearedbackgroundifitwastheonlyonefoundina
paragraph,asdemonstratedbythismarkup:
<p>Ihaveasingle<em>emsoIamred</em>.</p>
<p>Ihave<em>two</em><em>em</em>tagssoneitherisred.</p>
Ifallthesedifferenttreeselectorsaremakingyourheadhurt,wewillfinishoffwith
someeasyones.Firstisthe:rootpseudo-class,whichinthecaseof(X)HTMLisalways
goingtobethehtmlelement,so
:root{color:red;}
makesalltagsred.ThevalueofthisselectorisclearlyforXMLwherethedefinitionofthe
rootelementinalanguageisvariableasopposedto(X)HTMLwhereitisalways<html>.
Secondisthe:emptyselector,whichcanbeusedtoselectelementsthatareempty(inother
words,havenochildren).Sothisrulewouldfindallthe<p>tagsthatareemptyandshow
themwithasolidredborder:
p:empty{border:2pxsolidred;}
Chapter 4: Introduction to CSS 495
Anexampleshowingallthetreeselectorsinactionisshownbelow,witharendering
providedinFigure4-11.
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>TreePseudo-classSelectors</title>
<styletype="text/css"media="screen">
:root{font-family:Verdana,Geneva,sans-serif;}/*sameassetting
HTMLelement*/
ulli:nth-child(odd){color:red;}/*odditemsred*/
PART II
ulli:nth-child(even){color:blue;}/*evenitemsblue*/
ulli:nth-child(5){font-size:xx-large;}/*5thitembigger*/
ulli:nth-child(3n){font-style:italic;}/*everythirditemitalic*/
ulli:nth-last-child(2){text-decoration:underline;}/*second
fromthelastchildunderlined*/
ulli:last-child{background-color:black;color:white;}/*same
as:nth-last-child(1)*/
p#test1span:first-of-type{color:green;}
p#test1span:last-of-type{color:red;}
p#test1span:nth-of-type(3){font-size:larger;}
p#test1span:nth-last-of-type(2){text-decoration:underline;}
p.test2span:only-child{color:green;}
p.test3em:only-of-type{background-color:red;}
p:empty{border:2pxsolidred;}
</style>
</head>
<body>
<ul>
<li>Odd(Red)</li>
<li>Even(Blue)</li>
<li>Oddandbythreesoitalic</li>
<li>Even</li>
<li>Oddandbiggerbecauseitis5thchild</li>
<li>Evenandbythreesoitalic</li>
<li>Odd</li>
<li>Even</li>
<li>Oddand2ndtothelastitemshouldbeunderlined,alsobythree
soitalic</li>
<li>Lastitemiswhiteonblack</li>
</ul>
<pid="test1">Thisis<em>notaspan</em>.Iamthe<span>firstspansoI
amgreen</span>.Iamthe<span>secondspan</span>sonothing.Iamthe
<span>thirdspansoIambig</span>.<span>Fourthspanalsonothing.</span>
<span>Fifthspanandsecondtolastsounderlined.</span>Iamthe<span>last
spansoIamred</span>.Thisis<em>notaspan</em>.</p>
496 Part II: Core Style
<pclass="test2">Iam<span>onlychildsoIamgreen</span>.</p>
<pclass="test2">Ihave<span>two</span><b>children</b>sonogreen
here.</p>
<pclass="test3">Ihaveasingle<em>emsoIamred</em>.</p>
<pclass="test3">Ihave<em>two</em><em>em</em>tagssoneitherisred.</p>
<p>Emptyelementbelow.</p>
<p></p>
<p>Emptyelementabove.</p>
</body>
</html>
O NLINE http://htmlref.com/ch4/treeselectors.html
p[lang|="en"]{color:red;}/*Englishtextinred*/
wecanwriteusingapseudo-classselector:
p:lang(en){color:red;}/*Englishtextinred*/
PART II
ThiswouldstyleEnglishparagraphsbutnotparagraphsthathavenolanguagespecifiedor
adifferentvaluethananEnglishvariation:
<plang="en">ThisisEnglishandred.</p>
<plang="en-uk">ThisisBritishEnglishandred.</p>
<p>Notrednolangspecified.</p>
<plang="fr">C'estFrancais.(Notred)</p>
Specification-wise,thepseudo-classapproachispreferred,butforbestsupport,you
mightfindthattheoldersyntaxismorewidelyimplemented.
p:not(.plain){color:red;}
saysthatallparagraphtagsnotinclass“plain”shouldbecoloredred.The:not()selector
takessimpleparameterssuchaselementtypeselectors,thewildcardselector,attribute
selectors,idselectors,classselectors,andmostpseudo-classesbesidesitself.Asamore
complexexample,arulelike
#nav>a:not(:hover){color:green;}
wouldselectalllinkswithanelementcalled“nav”thatarenotbeinghoveredoverandset
themtobegreen.Youcantestthesesimpleexamplestoseeifyourbrowserconformstothis
newerselectorwiththeexampleathttp://htmlref.com/ch4/not.html.
TIP Negativelogiccanbequiteconfusing.Bewareofaddingmorecomplexitythanyouneedto
usingthe:not()pseudo-class.
Nowwearefinishedwithselectors,butmoreselectorsareexpectedanydaynowas
CSS3continuestogrow.WesummarizethelastgroupofselectorsinTable4-9.Allofthe
selectorsaregroupedtogetherinonelargetableinChapter5forreferencepurposes.
498 Part II: Core Style
PART II
parent*/
:last-child Selects the element p:last-child{font-size: CSS3
that is the last child small;}
of its parent /*setsthefontsizetosmall
ontheptagsthatarethe
lastchildoftheirparent*/
:first-of-type Selects the element strong:first-of-type CSS3
that is the first child {font-size:bigger;}
of its parent that is /*setsthefontsizebigger
of its type onthefirststrongtagofits
parent*/
:last-of-type Selects the element strong:last-of-type CSS3
that is the last child {font-size:smaller;}
of its parent that is of /*setsthefontsizesmaller
its type onthelaststrongtagofits
parent*/
:only-child Selects an element if h1:only-child{color:blue;} CSS3
it’s the only child of its /*setstheh1colortoblue
parent iftheh1istheonlychildof
itsparent*/
:only-of-type Selects an element if p:only-of-type{font-weight: CSS3
it’s the only child of its bold;}
parent with its type /*setsthepelementtobe
boldifitistheonlyptag
childofitsparent*/
:nth-child(n) Selects the element div:nth-child(2) CSS3
that is the nth child of {background-color:red;}
its parent /*setsthebackgroundcolor
toredifthedivisits
parent’ssecondchild*/
PART II
padding,padding-top,padding-right,padding-bottom,padding-
left,left,right,top,bottom,width,min-width,max-width,
height,position,float,clear,overflow,clip,z-index
Borders border,border-top,border-right,border-bottom,border-
left,border-color,border-top-color,border-right-color,
border-bottom-color,border-left-color,border-style,
border-top-style,border-right-style,border-bottom-style,
border-left-style,border-width,border-top-width,border-
right-width,border-bottom-width,border-left-width
Lists list-style,list-style-type,list-style-image,list-style-
position
Tables border-collapse,border-spacing,caption-side,empty-cells,
table-layout
Layout and display,visibility,position,float,clear
Display
Outlines outline,outline-color,outline-style,outline-width
Generated content,counter-reset,counter-increment,include-source,
Content quotes
International unicode-bidi,direction
Printing page-break-before,page-break-after,page-break-inside,
page,size,marks,windows,orphans
Aural volume,stress,richness,azimuth,elevation,voice-family,
speak,punctuation,speak-numeral,pitch,pitch-range,
speech-rate,play-during,pause,pause-before,pause-after,
cue,cue-before,cue-after
CSS3,whichisn’tcompleted,definesevenmoreproperties.Ofcourse,thebrowser
vendorsarebusyinventingnewonesallthetimeaswell,whichaddstothechallengeof
documentingwhichemergingpropertiesworks.ThattaskistakenupinChapter6.
502 Part II: Core Style
GiventhemultitudeofCSSproperties,thereisalsoamultitudeofvaluestowhichthey
canbeset.Wenextintroducemeasurementsandwillseetheirusethroughouttheexamples
inthisandthefollowingchapters.
maroon(#800000) red(#ff0000)
orange(#ffA500) yellow(#ffff00)
olive(#808000)
purple(#800080)
fuchsia(#ff00ff) white(#ffffff)
lime(#00ff00) green(#008000)
navy(#000080)
blue(#0000ff)
aqua(#00ffff) teal(#008080)
black(#000000) silver(#c0c0c0)
gray(#808080)
PART II
(00–FF) for red, g in the same range for color:#f3ffff;}
green, and b for blue. For example, #ff0000
would specify pure red, while #ffffff would
specify white. More expressive than the
3-digit hex form, this can represent values
like #ffA500 (orange).
HSL Color CSS3 introduces Hue Saturation #red{
Lightness (HSL), where color values are color:hsl(0,100%,50%);}
specified as hsl(hue,saturation,
lightness). Hue is set as the degree #green{
on the color wheel, where 0 or 360 if you color:hsl(120,100%,50%);}
wrap around is red, 120 is green, and 240
is blue, with the various other colors found #blue{
between. Saturation is a percentage value, color:hsl(240,100%,50%);}
with 100% being the fully saturated color.
Lightness is a percentage, with 0% being
dark and 100% light with the average 50%
being the norm.
HSLa Color This is the CSS3 HSL value with a fourth #bluetrans{color:
value to set the alpha channel value for the hsla(240,100%,50%,0.5);}
color to define the opacity of the element.
An HSLa is specified via a function style
hsla(hue,saturation,lightness,
alpha), where hue, saturation, and
lightness are the same as standard hsl()
values, and the alpha channel value for
defining opacity is a number between 0
(fully transparent) and 1 (fully opaque).
RGB Color A decimal or percentage RGB color can be strong{
specified via a function style rgb(r,g,b) color:rgb(255,0,0);}
value, where r, g, and b are specified
as a decimal value from 0 to 255 or a .super{
percentage from 0 to 100%. Values outside color:rgb(99%,1%,0%;}
this range will be rounded up or down to fit
the closest value.
PART II
the height of font as defined by the size
of its lowercase x character. A ch value
introduced by CSS3 is another font-related
length, which is equivalent to the width
of the character 0 (zero) in the current
font and has started to be supported in
some browsers. Surprising to some Web
developers, a pixel (px) is also a relative
unit, as there may be different pixel
densities on different screens.
Strings Strings are defined with either single p{
quotes (‘example’) or double quotes font-family:"FancyFont";}
(“example”). Quotes may be found within
the opposite quote (“I say this is an a[title="Next\
‘example’!”). Newlines may be specified Linehere"]{color:red;}
with a “\00000a” value. In situations
where a newline is typed, a \ character can
be used as line continuation.
URL Uniform Resource Identifiers generally body{
limited to the commonly known Uniform background:url(stars
Resource Location (URL) are designated .png);}
using the function style url(address),
where address is an absolute or relative URL.
NOTE ThereareothervaluesfoundinCSS3suchasviewportsizes(vh,vw,vm),rootrelative
sizing(rem),andgridmeasurements(gd).AuralCSSsuchasangles[degrees(deg),grads
(grad),andradians(rad)],times[milliseconds(ms)andseconds(s)],frequencies[Hertz(Hz)
andkiloHertz(kHz)]arealsodefined.Thesearediscussedmoreinthereferencethatfollowsin
thenexttwochapters.
However,withoutthecontextofthepropertiesinwhichtheyareused,someofthe
valuesmaynotmakemuchsense;thus,whenusingtheminexamplesandpresenting
variouspropertiesinthefollowingchapters,wewillstrivetousethemincontext.
506 Part II: Core Style
<strongstyle="color:red;">Iamstrong!</strong>
Whilethiswillputthetextcontentsinredasexpected,itwillalsoprobablybebold
becausethatisthetypicalrenderingofthis(X)HTMLelement.Designershavetoconsider
thesedefaultrenderingsasrulesareadded;acarelessdocumentauthorcancreateapotentially
confusinguseofmarkupusingstylesheets.Herewechangetwotagstoacttheoppositeof
howyoumightexpectthemtoact:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>ImproperOverrides</title>
<styletype="text/css"media="all">
b{font-style:italic;font-weight:normal;}
i{font-style:normal;font-weight:bold;}
</style>
</head>
<body>
<p>Iama<b>boldtag</b>andIaman<i>italictag</i>.</p>
</body>
</html>
O NLINE http://htmlref.com/ch4/improperoverride.html
Chapter 4: Introduction to CSS 507
Giventhephysicalnatureofsome(X)HTMLtags,itshouldbeobviousnowwhysome
havebeendeprecatedandlogicalelementshavebecomemoreusefulwiththeriseofstyle
sheets.Whenusingan<em>tag,itmeanssimplythatsomethingisemphasized,notthatit
isgenerallyitalic:
<styletype="text/css"media="all">
em{font-style:normal;font-weight:bold;}
</style>
</head>
<body>
<p>Iam<b>emphasized</b>doesitmatterhow?</p>
PART II
Intheory,settinglogicaltagstorenderanywaythedeveloperwantswillnotcauseas
muchconfusionforlaterviewersofthemarkup.Ofcourse,thisassumesthatreadersdon’t
applypredefinedphysicalthinkingtologicalmarkup,so
<styletype="text/css"media="all">
h1{font-size:xx-small;}
h6{font-size:xx-large;}
</style>
shouldn’tbebad.Unfortunately,itisprobablymorecommonthattheperceivedmeaningof
eachtagimpliesalookwhichtheserulesseemtoviolate.Sowhileitisclearthatlogical
elementsratherthanphysicalelementswouldprovidemoreflexibilitywithCSS,this
choiceassumesthatlogicalelementrenderingsarenotdefinedorassumedtoocommonly
bydevelopers.Itturnsoutthat,givensuchneeds,thenexttwoelementspresentedare
quiteuseful.
<divstyle="background-color:yellow;font-weight:bold;color:black;">
<p>Stylesheetsseparatethestructureofadocumentfromits
presentation.Dividinglayoutandpresentationhasmany
theoreticalbenefitsandcanprovideforflexibledocuments
thatdisplayequallywellonlargegraphicallyrichsystems
andpalmtopcomputers.</p>
<p>Thisisanotherparagraphdescribingthewonderfulbenefitsof
stylesheets</p>
</div>
508 Part II: Core Style
However,asablockelement,divshouldinduceareturn,soifyouwanttoprovide
styleinformationsolelyforafewwords,orevenafewletters,thebestapproachistouse
thespanelement,whichasaninlineelementdoesnotinduceareturn.Forexample,notice
howa<span>tagisusedtocallattentiontoaparticularsectionoftext:
<p>Callingout<spanstyle="background-color:yellow;font-weight:bold;
color:black;">specialsectionsoftext</span>isn'thardwitha
spanandCSS.</p>
Theadvantageofthesegenericelementsisclear,buttheyareeasilyabused.For
example,insteadofusingelementsinameaningfulway,weseeexcessive<div>and
<span>tagsbeingemployed.Forexample,hereweuseaheadingwithaclass
<styletype="text/css"media="all">
h1.heading{font-size:xx-large;color:red;font-style:italic;}
</style>
</head>
<body>
<h1class="heading">Iamaheading?</h1>
butadesignermightresorttousinga<div>taginstead,
<styletype="text/css"media="all">
.heading{font-size:xx-large;color:red;font-style:italic;}
</style>
</head>
<body>
<divclass="heading">Iamaheading?</div>
whichremovesanymeaningthatmayhavebeengainedfromthe<h1>tag.Regardlessof
thespecificlikelihoodoftheexample,whatweseeisthatdevelopersoftenemploywaytoo
many<div>and<span>tagsandthenapplyclassvaluestoassociatemeaningandstyle
withthem.WenotethatthisisreachingepidemicproportionswithsomeCSSdesigners,
leadingsometodubthisaWeb“malady”called“div-itis”or“class-itis.”Thebasicproblem
isthatdevelopersforgoolderHTML-focusedmethodsliketablesandtrumpettablelessand
CSS-focuseddesign,onlytointroducetremendousproblemsoftheirown.Atechnology
willencouragegoodpractices,butitiseasytomisstheintentandgooffthedeepend.
Awell-doneCSSdocumentlookslikeasimple(X)HTMLmarkupdocumentandhasa
diversityoftagsinit.While<div>and<span>tagswithclassandidvalueswillbe
common,iftheyarethemajorityofthedocument,you’relikelydoingthingswrong.
settingvisibility,tobediscussedlater,whichalsopreventsanelementfromdisplaying,but
doestypicallyreservecanvasspace.Toturnoffaparagraph,tryarulesuchasthefollowing,
p.remove{display:none;}
whichmightbeappliedtothefollowingmarkup:
<p>Firstparagraph(nextisdisplay:none).</p>
<pclass="remove">Removedsecondparagraph.</p>
<p>Thirdparagraph(previousisdisplay:none).</p>
Thiswillcompletelyremovethesecondparagraphfromthedocumenttree,asshownhere,
whereweapplyabordertoseetheparagraphs:
PART II
Nowvisibilityisdifferent.Ifweaddedarulelikethis
p.invisible{visibility:hidden;}
andappliedittoasimilarsetofparagraphs
<p>Fourthparagraph(nextisvisibility:hidden).</p>
<pclass="invisible">Invisiblefifthparagraph.</p>
<p>Sixthparagraph(previousisvisibility:hidden).</p>
weseeadifferentresult,astheobjectisstilltakingupcanvasspaceandissimplyinvisible:
Thepointwearemakingwithdisplayisthatyouhavequiteabitofpowertoaffect
howelementsaretreatedinthedocumenttree.Asidefromsimplyturningoffelements,you
canmakeelementsfundamentallyactdifferently.Forexample,wecanturnablockelement
(suchasaparagraph)intoaninlineelement,thuskeepingitfromaddinganewline.For
example,thefollowingwouldchangetheformofallparagraphsinthedocument,
overridingtheknownaction:
p.setasinline{display:inline;}
Whenappliedto
<pclass="setasinline">Inlineparagraph.</p>
<pclass="setasinline">Inlineparagraph.</p>
<pclass="setasinline">Inlineparagraph.</p>
510 Part II: Core Style
itrendersquitedifferentlythanwithoutthedisplaymodified:
Also,wecandothereverseandmakeelementsthatarenotnormallyblockactassuch:
p.setasblockem{display:block;}
Whenthisisappliedto
<pclass="setasblock">Thisparagraph<em>hassome</em><em>emphasistags
</em>thatactasblocks.</p>
<p>Thisparagraph<em>hassome</em><em>emphasistags</em>thatactnormal-
ly.</p>
itproduces:
Youalsocancoerceanelementtoactsomewhatlikealistbycastingitwiththedisplay
property,asshownhere:
p.setaslistem{display:list-item;list-style-position:inside;}
Whenappliedto
<pclass="setaslist">Listmadefromemtags:<em>Item</em><em>Item</em>
<em>Item</em></p>
itrenderslikeso:
Wemightalsomakealistnotactassuchbyusingarulelike
ulli{display:inline;}
Chapter 4: Introduction to CSS 511
andthenapplyingittomarkuplikethis:
<p>Listbelownotdisplayingassuch</p>
<ul>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
PART II
Acompleteexampleshowingallthesedisplayexamplesisprovidedhere:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>DisplayProperty</title>
<styletype="text/css"media="all">
p{border:2pxsolidred;}
p.remove{display:none;}
p.invisible{visibility:hidden;}
p.setasinline{display:inline;}
p.setasblockem{display:block;}
p.setaslistem{display:list-item;list-style-position:inside;}
ulli{display:inline;}
</style>
</head>
<body>
<p>Firstparagraph(nextisdisplay:none).</p>
<pclass="remove">Removedsecondparagraph.</p>
<p>Thirdparagraph(previousisdisplay:none).</p>
<p>Fourthparagraph(nextisvisibility:hidden).</p>
<pclass="invisible">Invisiblefifthparagraph.</p>
<p>Sixthparagraph(previousisvisibility:hidden).</p>
<pclass="setasinline">Inlineparagraph.</p>
<pclass="setasinline">Inlineparagraph.</p>
<pclass="setasinline">Inlineparagraph.</p>
<pclass="setasblock">Thisparagraph<em>hassome</em><em>emphasis
tags</em>thatactasblocks.</p>
<p>Thisparagraph<em>hassome</em><em>emphasistags</em>thatact
normally.</p>
<pclass="setaslist">Listmadefromemtags:<em>Item</em><em>Item</em>
<em>Item</em></p>
512 Part II: Core Style
<p>Listbelownotdisplayingassuch</p>
<ul>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
</body>
</html>
O NLINE http://htmlref.com/ch4/display.html
ThedisplaypropertyshowsusjusthowfarCSScangoinaffectingmarkup.This
powerfulpropertycanproducequiteelegantresults,suchasnavigationmenus,asweshall
seeinnumerousexamplesinthebook.ItisalsomandatorywhenattemptingtostyleXML
elementswithnopredefinedrendering.However,thispowercancomewithapriceof
confusionwhenmisapplied.
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>White-spaceProperty</title>
<styletype="text/css"media="all">
p.pre{white-space:pre;}
p.nowrap{white-space:nowrap;}
</style>
</head>
<body>
<p>Thisisastandardparagraph
PART II
notice
thatwhite
space
isnotpreserved.</p>
<pclass="pre">Thisparagraph
had
it'swhite-space
rulesadjustedto
act
likea
preelement.</p>
<pclass="nowrap">Thisverylongparagraphreallyoughttowrapbut
itdoesn'tbecausethenowrapvaluehasbeensetforthewhite-space
property.</p>
</body>
</html>
O NLINE http://htmlref.com/ch4/whitespace.html
Aswehaveseenthroughoutthissection,CSSaffordsusgreatpowertochangethe
defaultcharacteristicsofmarkuplanguageslike(X)HTML.Wepresentedthesepropertiesin
amoreexpandedformbecauseoftheirpotentialforabuse,butbynomeansshouldthis
advicebeconstruedtosuggestthatyoushouldavoidsuchproperties,astheyareessential
toolsinyourCSStoolbox.We’llcoverthewiderangeofotherpropertiesavailabletousin
thefollowingtwochapters.
HTML
file.html
CSS CSS
original-style.css new-style.css
XYZCORP XYZCORP
Chapter 4: Introduction to CSS 515
Theideaalsosuggestspullingindifferentstylesheetsfordifferentmediaanddevice
types:
HTML
file.html
PART II
CSS CSS
HTML
screen.css phone.css
print.html
XYZCORP
XYZCORP
XYZCORP
OurmainpointhereistoremindyouthattheCSSreliesonthemarkuptodoitsjob.It
isnotpossibletodecouplethelookfromthestructureofthedocument.However,wecan
looselycoupleit.Donottakethistomeanthatwesuggestmarkuphassomefundamental
presentationadvantageoverstyle;itdoesn’t.
516 Part II: Core Style
YoumightbeabletomaketheprecedingpresentationusingHTMLwithimagestogetthe
shadowsandroundedcorners,butitcertainlywon’treflowanditwillnothavesimple
markupthatlookslikethis:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>CSSPower!</title>
<linkrel="stylesheet"href="power.css"media="screen">
</head>
<body>
<divclass="boxedrounded">
<h1>CSSisPowerful!</h1>
<divclass="three-columns">
<p>Itwasthebestoftimes,itwastheworstoftimes,itwastheageof
wisdom,itwastheageoffoolishness,itwastheepochofbelief,itwas
theepochofincredulity,itwastheseasonofLight,itwastheseasonof
Darkness,itwasthespringofhope,itwasthewinterofdespair,wehad
Chapter 4: Introduction to CSS 517
everythingbeforeus,wehadnothingbeforeus,wewereallgoingdirectto
Heaven,wewereallgoingdirecttheotherway--inshort,theperiodwasso
farlikethepresentperiod,thatsomeofitsnoisiestauthoritiesinsisted
onitsbeingreceived,forgoodorforevil,inthesuperlativedegreeof
comparisononly.</p>
</div>
</div>
</body>
</html>
CSSissimplyamuchmorepowerfulpresentationtechnologythanmarkup.
PART II
O NLINE http://htmlref.com/ch4/csspower.html
ormaybepullinastylesheetforallInternetExplorerversionsprevioustothenearly
standards-compliantInternetExplorer8:
<linkrel="stylesheet"href="standard.css"media="screen">
<!--pullolderIEstylesheet-->
<!--[ifltIE8]>
<linkrel="stylesheet"href="oldie.css"media="screen">
<![endif]-->
ConditionalcommentsareuniquetoInternetExplorer,whichreallyisn’taproblemsince
itisusuallythebrowserwedesireto“fix”CSSwise.However,ifconditionalcomments
aren’ttoyourliking,youcouldalsoemploysimpleJavaScripttoreadthetypeofbrowserin
playandincludeastylesheetaswell.We’lldiscussthesetechniquesandothersthroughout
thebook.OuronlypointhereistostressthattheheadacheswithmakingCSSworksimilarly
acrossbrowsersaresignificantandongoing.
claimsmadearepresentedherewithabitofdiscussionaboutwhyreadersshouldavoida
snapjudgmentaboutthepowerofCSS.However,likemanythingsintheworld,thereis
morethanoneinterpretation,soifthissectionprovokesyoutothinkaboutbothsides,the
pointhasbeensuccessfullymaderegardlessofwhatyourultimatepointofviewis.
particularlywithoutshorthandCSSproperties,andCSSdesignsmayactuallybemuch
largerthansimilarHTML-focuseddesigns.Whenthesestylesareusedinlineorina
<style>block,thespeedgainofCSSoverHTMLisprettymucheliminated.Inthecaseof
anexternalstylesheet,assumingcachingisproperlyused,downloadgainsmaycomeon
subsequentpageviewsastheydonotneedtorefetchthestyleinformationwhichcachedin
theexternalstylesheet.Ofcourseassumingthatcachingiscorrectlyimplementedisnota
givenandablanketassertionthatCSSresultsinmoredownload-friendlypagesisfalseand
doesnotacknowledgethecomplexityofpage-deliveryoptimization.Ofcourse,infairness
itshouldbenotedthatevenifCSSwasalwayslarger,whichisnotthecase,thetechnology
providesaricherandmoreappropriatefeaturesetthanpresentationalmarkup.
PART II
Misconception: Redesigns Are Fundamentally Easier with CSS
AcommonthoughtpromotedintheWebdevelopmentcommunityisthatredesigninga
Websiteisjustamatterofchangingstyles.However,nothingcouldbefartherfromthe
truthintheauthor’sexperience.Significantredesignoftenmeanschangingnavigation,
changingcontent,andevenchangingthefocusofasite.Astylesheetisnotgoingtoapply
necessarilytopagesthatarefundamentallydifferentinstructureandcontent.This
observationdoesn’tsuggeststylesheetsaren’tusefulbutitshouldservetocorrectlylower
expectationsinregardtothesimplicityofchangingalookduringasiteredesign.If,
however,thepointissimplyanewskinforanexistingsite,CSSclearlycandeliverthe
promiseofaquicknewlook.
Summary
CSSprovidesbettercontroloverthelookandfeelofWebpages.Stylesheetsaren’tjustuseful
formakingattractivepages.Bydividingstructureandstyle,theycanmakedocumentssimpler
tocreateandeasiertomanipulate.CSSprovidesmanyvaluablelayoutpropertiesthatprovide
aricherpalettefordesignthanpresentationmarkupevercould.CSSshouldnotbeconsidered
areplacementformarkup,however,asitreliesgreatlyoncorrect(X)HTMLmarkupas
wellaspropernamingoftags.WhiledevelopershavefoundthepromiseofCSSalluring,the
executionofcorrectstylesheetsinbrowserscanbequitechallenging.Cross-browserrendering
headachesreemergewithavengeanceunderCSS,andwefindthattheincorrectsolutionsof
hackingaroundforfilteringandselectionshowsthenecessityofclient-sidescripting.
This page intentionally left blank
CHAPTER
5
CSS Syntax and
Property Reference
T
hischapterprovidesacompletereferenceforthepropertiesintheCSS1andCSS2.1
specification.AspectsoftheCSS2specificationthatwerenotimplementedwidely,
liketheauralproperties,areonlybrieflysummarizedgiventheirlackofuse.The
bulkofthematerialonCSS3andemergingandproprietaryCSSfeaturescanbefoundin
Chapter6.However,whereappropriate,CSS3changesthataremodificationsoftraditional
CSSarepresentedtogetherwiththeoldersyntax.
CSS Versions
CascadingStyleSheetsisafairlyoldtechnologyasfarastheWebisconcerned.Thefirst
ideasaboutCSSwerepresentedasearlyas1994,andthreemajorversionsofthetechnology
havebeendevelopedsincethen.Table5-1summarizestheversionhistoryofCSS.
CSS Basics
CSSrulesaredefinedasapropertynamefollowedbyacolonandthenapropertyvalue.
Individualrulesareterminatedbysemicolons,withthefinalrulehavinganoptional
semicolon.Thefollowingisthebasicsyntax:
property-name1:value1;...property-nameN:valueN;
521
522 Part II: Core Style
Individually,wevisuallypickoutthecomponentsofaCSSrule:
NOTE Thefinaldeclarationinastyleruleblockdoesnotrequirethesemicolon.However,forgood
measureandeasyinsertionoffutureproperties,pageauthorsshouldalwaysusesemicolonsafter
PART II
allstyleproperties.
CSSpropertynamesareseparatedbydasheswhentheyaremultiplewords—forexample,
font-face,font-size,line-height,andsoon.Allowedvaluescomeinmanyforms;from
simplekeywordslikexx-small,stringslike“Arial”,plainnumberslike0,numberswithunits
like100pxor2cm,andspecialdelimitedvaluessuchasURLs—url(../styles/fancy.css).
Allallowedvalueswillbecoveredinupcomingsectionsinthischapter.
Propertynamesandmanyvaluesarenotcasesensitivebutsomevaluesmaybe,asmay
selectors,dependingonthelanguageCSSisappliedto.Webdevelopersshouldassumethat
allcomponentsofCSSrulesarecasesensitive,justtobesafe.
CSSrulesareappliedtomarkup,andthevariousstylevaluesappliedtoaparticular
elementmaybeinheritedfromitsparentorevenamoredistantenclosingelement.For
example,arulelike:
p{color:red;}
appliesthecolorredtoparagraphelements.Whenappliedto
<body>
<h1>Test</h1>
<p>Thisisa<strong>Test</strong>!</p>
notonlyistheparagraphelementsetasredbutsotooisthe<strong>tagenclosedin
the<p>tagbecausethecolorpropertyvalueisinheritedfromtheparentelement,as
shownhere:
p {color:red;}
body
h1
p Red
strong Red
Whereasmostelementscaninheritthestylefeaturesoftheirparents,somestyleproperties,
suchasborders,donot.
524 Part II: Core Style
Assumingthatapropertydoesinherit,itisstillpossibletooverridetheinheritanceof
aproperty.Forexample,giventhefollowingtworules:
p{color:red;font-size:xx-large;}
strong{color:yellow;}
thecolorofthetextwithinthe<strong>tagwouldbeyellowandhaveanxx-largesize.
Bothofthepropertieswereinherited,butthecolorpropertywasoverriddenbythecolor
ruleforthe<strong>tag,whichismorespecific:
p {color:red; font-size: xx-large}
strong {color: yellow;}
body
p Red, xx-large
Override Inherit
strong Yellow, xx-large
Inanycase,itispossibletooverridetherenderingofstylebysettingthe!important
directiveattheendoftheruledeclaration,asfollows.
div{font-size:14pt;line-height:150%;font-family:Arial!important;}
Astylespecifiedas!importantshouldoverrideanyotherappliedstyleandthus
shouldbeusedsparingly.
Whilethe!importantindicatormakesthingsclear,thepotentiallyconfusing
combinationofapplyingmultiplerules,withelementsinheritingsomepropertiesand
overridingothers,istheideaofthecascadethatCSSisnamedfor.Thegeneralideaofthe
cascade,ineffect,isthatitprovidesasystemtosortoutwhichrulesapplytoadocument
thathasmanystylesheets.Aneasywaytothinkaboutwhichrulewinsistofollowthese
helpfulrulesofthumb:
• Themorespecifictherule,themorepowerful.
• Theclosertothetagtherule,themorepowerful.
Thespecificnatureoftherulegenerallyisdeterminedbytheselectorused,andthe
inclusionofthestyleruledefinestheclosenesstothemarkup;botharediscussednext.
Linked Styles
Stylescanbecontainedinanexternalstylesheetlinkedtoadocumentorasetof
documents,asshowninthefollowingexample.Linkedinformationshouldbeplacedinside
the<head>tag.
<linkrel="stylesheet"type="text/css"href="/styles/newstyle.css">
Chapter 5: CSS Syntax and Property Reference 525
GiventhatthelinkelementisanemptyelementwhenusingXML-stylesyntax,
aself-identifyingcloseusingatrailingslash(/)mustbeincludedinthetag:
<!--XHTMLstyle-->
<linkrel="stylesheet"type="text/css"href="/styles/newstyle.css"/>
Therelattributeisgenerallysettothevaluestylesheetbutmayalsohaveavalueof
alternatestylesheetwithanassociatedtitlevaluetoprovidedifferentlooksforthe
samepage:
<linkrel="stylesheet"type="text/css"href="standard.css"title="standard">
PART II
<linkrel="alternatestylesheet"type="text/css"href="red.css"title="Red
Sheet">
<linkrel="alternatestylesheet"type="text/css"href="green.css"
title="GreenSheet">
Themediaattributemayalsobeusedtodefinethemediatowhichastylesheetis
applied.Thekeywordvaluesscreenandprintarecommonly.Thedefaultvalueofallis
appliedwhenmediaisnotspecified.
<linkrel="stylesheet"type="text/css"href="screenstyle.css"media="screen">
<linkrel="stylesheet"type="text/css"href="printstyle.css"media="print">
CSS2and2.1dodefinearichsetofmediavalues,asshowninTable5-2,butinpractice
fewaresupported.
LinkedstylesarethepreferredmethodofspecifyingCSSrulesbecausetheycleanly
separatethestylefromthemarkup.However,donotethatusinglinkedstylesdoescome
withthesmallpenaltyofanextraHTTPrequest.
Embedded Styles
Document-widestylescanbeembeddedinadocument’sheadelementusingthe<style>
tag.Notethatstylesshouldbecommentedouttoavoidinterpretationbynon-style-aware
browsers.
<styletype="text/css">
<!--
p{font-size:1.5em;font-family:Georgia,"TimesNewRoman",Times,serif;
color:blue;background-color:yellow;}
em{font-size:2em;color:green;}
-->
</style>
However,beawarethatcommentmaskingisfrowneduponinXHTML,andinstead
youshoulduselinkedstylesoruseaCDATAsectionlikeso:
<styletype="text/css">
<![CDATA[
p{font-size:1.5em;font-family:Georgia,"TimesNewRoman",Times,serif;
color:blue;background-color:yellow;}
em{font-size:2em;color:green;}
]]>
</style>
Giventhesupportofthisstructure,particularlywiththeconfusionofXHTMLservingand
handling,itisbesttoavoidthiscommentingschemeor,betteryet,simplysticktolinkedstyles.
Itispossibletosetamediaattributeona<style>tagtodefinedifferenttypesofrules
peroutputmedium:
<styletype="text/css"media="print">
/*Printruleshere*/
</style>
<styletype="text/css"media="screen">
/*Screenruleshere*/
</style>
Imported Styles—@import
Withinembedded<style>blocks,propertiescanbeimportedfromanexternalfileand
expandedinplace,similartoamacro.Importingcanbeusedtoincludemultiplestyle
sheets.Animportedstyleisdefinedwithina<style>tagusing@importfollowed
optionallybyatypevalueandaURLforthestylesheet:
<styletype="text/css">
@importurl(newstyle.css);
@importprinturl(printstyle.css);
</style>
Chapter 5: CSS Syntax and Property Reference 527
The@importdirectiveallowsstylesheetstobegroupedandjoinedtogether,though
somemightwonderwhatthevalueofthisfunctionisgivenwhatlinkedstylesprovide.
NOTE SomeCSSdevelopersusethe@importdirectivetoperformaweakformofbrowser
selection,becausemanyolderCSSimplementationsdonotsupportthedirective.Thebasicidea
ofthetrickistoputsophisticatedstylerulesinan@importstylesheetandleavebasicstylesin
thestyleblock.Thistrickshouldbeavoided,particularlygiventhatsomebrowsers,notably
versionsofInternetExplorer,willcauseadisturbingflasheffectwhenloadingimportedstyles.
Inline Styles
PART II
Youcanapplystylesdirectlytoelementsinadocumentusingthecoreattributestyle,as
shownnext.Asthecloseststyle-inclusionmethodtoatag,inlinestylestakeprecedence
overdocument-wideorlinkedstyles.
<h1style="font-size:48px;font-family:Arial,Helvetica,sans-serif;
color:green;">CSSTest</h1>
Giventhetightintermixtureofstyleintomarkup,thisschemeshouldbeusedsparingly.
NotethatsomefeaturesofCSS,particularlypseudo-class–relatedvaluessuchaslinkstates,
maynotbesettableusingthismethod.Furthernotethatthereisnowaytosetmedia-
specificstylerulesinlineonindividualelements.
CSS Measurements
CSSsupportsanumberofmeasurements.Inmostcases,theyinvolveanumber,andCSS
supportsbothpositiveandnegativeintegervalues,like3and–14,aswellasrealnumbers
like3.75.Veryoftenthenumbersarefoundwithunits;forexample,
p{margin:5px;}/*allmarginssetto5pixels*/
Butinafewcasestheymaynothaveunits,asthemeasurementmaybecontextualfrom
themeaningoftheproperty:
p{line-height:2;}/*doublespaced*/
Whenameasurementiszero,thereisnoneedforaunit,
*{margin:0;}
butitwon’thurttoincludeone:
*{margin:0px;}
Commonly,absolutelengthunitslikeinches(in),centimeters(cm),millimeters(mm),
points(pt),andpicas(pc)areused.Theseabsolutemeasuresshouldbeusedwhenthe
physicalcharacteristicsofthedisplaymediumarewellunderstood,suchasinprinting.We
alsomightuserelativemeasuresthatcanscale,suchasemunits,exvalues,percentage,or
pixels.Table5-3summarizestheseunitsofmeasure.
528 Part II: Core Style
NOTE TherearemanyothervaluesfoundinCSS3,suchasviewportsizes(vh,vw,vm),root
relativesizing(rem),angles[degrees(deg),grads(grad),andradians(rad)],times
[milliseconds(ms)andseconds(s)],frequencies[Hertz(Hz)andkiloHertz(kHz)],andsoon.
SeeChapter6forinformationontheseandothervalues.
Chapter 5: CSS Syntax and Property Reference 529
p{font-family:"FancyFont";}
Wealsofindthatstringsmaybeusedwithselectors:
a[title="Matchmematchme"]{color:red;}
PART II
Thereisanoccasionalneedforspecialcharactersinstrings;inparticular,newlinesmay
bespecifiedwitha"\00000a"value.Insituationswhereanewlineistyped,a\character
canbeusedaslinecontinuation:
a[title="Next\
Linehere"]{color:red;}
MorecommonthanquotedstringsarethenumerouskeywordvaluesfoundinCSS.The
numberofkeywordsisvastandisusedforspecifyingsizes,
.big{font-size:xx-large;}
.small{font-size:small;}
.downsize{font-size:smaller;}
borderstyles,
.double{border:5pxsolidblack;}
.dashed{border-style:dashed;}
textformattingandstyle,
.style1{text-decoration:underline;}
.style2{font-variant:small-caps;}
.style3{font-weight:bold;}
elementmeaning,
#nav{display:block;}
#gone{display:none;}
#test{display:inline;}
layout,
#region1{position:absolute;top:10px;left:10px;}
#region2{position:relative;top:-60px;left:100px;}
#region3{position:fixed;top:0px;left:0px;}
andmore.
530 Part II: Core Style
Insomesituations,thekeywordmaybepartofafunctionalstylenotation.Forexample,
inCSSthespecificationofaURLasavalueismarkedbyurl(address),whereaddressis
theactualvalueoftheresourcetobelinkedto:
body{background:url(stars.png);}
#div1{background:url(http://democompany.com/images/tile.gif);}
Newercolorformatslikergb(),rgba(),hsl(),andhsla()aresetwithsimilar
notation,andotherfunctionalnotationstylevaluesmayemergeovertimesuchascalc()
(seeChapter6forabriefdiscussion).Forexample,thereisdiscussionofCSSpotentially
includingvariableswhichallowsvaluestobesetinoneplaceandusedinvariousrules.For
example,
@variables{
primaryBackground:#F8D;
primaryColor:#000;
defaultMargin:2em;
}
p{color:var(primaryColor);background-color:var(primaryBackground);
margin:var(defaultMargin);}
Sofarsuchideasarestilluncommon,soifavalueisnotfoundwithinquotesorfollowedby
ameasurement,itislikelyakeywordorcounter.Ifitisn’torissimplynotanunderstood
value,itwillbeignoredbyCSS-conforminguseragentsanyway.
Counters
Countersdemonstratethepossibilityofvariable-likevaluesinCSS.Theyaredefinedas
alphanumericnamesthatcorrespondtosomecurrentcountervalueinadocument.Insome
cases,thecounter()functionalnotationisusedandinsomecasesitisnot,asshownby
theserules:
ol.cT{
counter-reset:counter1;
list-style-type:none;}
ol.cTli:before{
counter-increment:counter1;
content:
counter(counter1)"-";}
Interestingly,theambiguityofallowingthecounter1valuetoappearinakeyword-like
fashionissomewhattroubling.Itislikelythatthecounter()stylesyntaxwilleventually
beappliedeverywhere.
PART II
aqua (#00ffff) teal (#008080)
black (#000000) silver (#c0c0c0)
gray (#808080)
Other color keywords may be commonly
used but are ad hoc in their definition.
See Appendix C for more information.
Commonly defined Most browsers support a number of #gap{color:khaki;}
named colors common colors based upon the X11
windowing system palette, such as
mintcream. Appendix C provides a
complete list of these extended colors
and a discussion of the potential pitfalls
of using them.
System Color CSS2 introduced named color keywords .formLabels{color:
Names which allows Web page colors to be CaptionText;}
matched to an operating system’s color
input[type="button"]
use. A complete list of the allowed values
{background-color:
and their meaning is found in Appendix C.
ButtonFace;}
While these names are commonly
supported, there is some concern that
they will not be supported in CSS3.
6-Hex Color CSS’s six-digit hexadecimal format is div{font-family:
the same as color defined in (X)HTML. Courier;font-size:
The format specifies color as #rrggbb, 10pt;color:#00CCFF;}
where rr is the amount of red, gg the
amount of green, and bb the amount of
blue, all specified in a hexadecimal value
ranging from 00 to FF.
3-Hex Color This is an RGB hexadecimal format of span{font-family:
#rgb, where r corresponds to a hex Helvetica;font-size:
value (0–F) for red, gfor green, and b for 14pt;color:#0CF;}
blue. For example, #f00 would specify
pure red, while #fff would specify white.
Given its data limits, the format is less
expressive than 6-Hex Color.
CSS Selectors
CSSsupportsarichsetofselectorsforspecifyingtowhichparticularelement(s)aCSSrule
applies.CSS1initiallysupportedbasicselectorstoindicateaparticulartag,groupoftags,or
positioninthedocumenttree.CSS2expandedthistoaddressselectingonattributesand
morepositionsinthetree.WeshowherepiecesofCSS3,whichhasgonesomewhat
overboardbymakingselectorsyntaxattimespotentiallyquiteconfusing,particularlywhen
chainedexcessively.Giventhatmanybrowserssupportthisemergingselectorsyntax,itis
importanttoshowittogetherwiththeotherselectorsasacompletereference.Table5-5
summarizestheselectorsyntaxfromCSS1,CSS2,andthecommonlysupportedpartsofthe
CSS3specifications.AsummaryandexpansionofCSS3selectorstoincludethosethatare
PART II
lesssupportedisprovidedinChapter6.
PART II
a:link Specifies the unvisited a:link{font-weight:bold;} CSS1
link /*makesunvisitedlinksbold*/
a:active Specifies the link as it a:active{color:red;} CSS1
is being pressed /*makeslinksredastheyare
pressed*/
a:visited Specifies the link after a:visited{text-decoration:line- CSS1
being pressed through;}
/*putsalinethroughvisited
links*/
:after Sets a style to be used div:after{content: CSS2
immediately following url(sectionend.gif);}
the element /*insertsthesectionend.gif
imageimmediatelyfollowingall
divtags*/
::after Same as :after; div::after{content: CSS3
changed under CSS3 url(sectionend.gif);}
to make pseudo- /*insertsthesectionend.gif
elements obvious imageimmediatelyfollowingall
divtags*/
:before Sets a style to be used div:before{content: CSS2
immediately before the url(sectionstart.gif);}
element /*insertsthesectionstart.gif
imagebeforealldivtags*/
::before Same as :before; div::before{content: CSS3
changed under CSS3 url(sectionstart.gif);}
to make pseudo- /*insertsthesectionstart.gif
elements obvious imagebeforealldivtags*/
:checked Selects the elements :checked{color:blue;} CSS3
that are checked /*setsthecolortoblueifan
elementischecked*/
PART II
:lang(value) Selects all elements *:lang(fr){color:blue;} CSS2
that have the lang /*setsthefontcolortoblue
attribute set to the foreveryelementthathasthe
given value attributelangsetto'fr'*/
:last-child Selects the element p:last-child{font-size:small;} CSS3
that is the last child of /*setsthefontsizetosmallon
its parent theptagsthatarethelastchild
oftheirparent*/
:last-of-type Selects the element strong:last-of-type{font-size: CSS3
that is the last child smaller;}
of its parent that is of /*setsthefontsizesmaller
its type onthelaststrongtagofits
parent*/
:not(s) Selects elements *:not(h1){color:black;} CSS3
that do not match the /*setsthecolortoblackonevery
selector s elementthatisnotanh1tag*/
:nth-child(n) Selects the element div:nth-child(2){background- CSS3
that is the nth child of color:red;}
its parent /*setsthebackgroundcolorto
redifthedivisitsparent's
secondchild*/
:nth-last- Selects the element p:nth-last-child(3){color: CSS3
child(n) that is the nth from yellow;}
last child of its parent /*setsthecolortoyellowifthe
pelementisitsparent'sthirdto
lastchild*/
:nth-last-of- Selects the element p:nth-last-of-type(2){color: CSS3
type(n) that is the nth-from-last purple;}
child of its parent that /*setsthecolortopurpleonthe
is its type secondtolastpelementofits
parent*/
NOTE MostoftheCSS3selectorsarenotsupportedinInternetExplorerbrowsers,including
version8.0,thoughtheyarewidelysupportedbyotherbrowservendors.
NOTE CSSpropertieslikeorphans,page-break-after,page-break-before,
page-break-inside,andwidowsareoftenusedinconjunctionwiththeseselectors.
Seethecorrespondingsectioninthischapterfortheparticularpropertyformoreinformation.
Chapter 5: CSS Syntax and Property Reference 539
Selector or
Construct Description Example Defined In
@media Groups style rules for multiple @mediascreen{body CSS2
media types in a single style {font-family:sans-serif;
sheet font-size:18pt;}
}
@page Used to define rules for page @page{size:8.5in11in;} CSS2
sizing and orientation rules for
printing
:first Sets page layout rules for the @page:first{margin-top: CSS2
PART II
first page in a document when 1.5in;}
printing
:left Sets page layout rules for a @page:left{margin-left: CSS2
left-hand page when printing 4cm;margin-right:2cm;}
:right Sets page layout rules for a @page:right{margin-left: CSS2
right-hand page when printing 6cm;margin-right:3cm;}
/* comments */
Commentscanbeplacedwithinstylesheets.StylesheetsusethecommentsyntaxusedinC
programming(/*comment*/):
<styletype="text/css">
p{font-face:Courier;font-size:14px;font-weight:bold;
background-color:yellow;}
/*ThisstylesheetwascreatedatDemoCompany,Inc.fortheexpresspurpose
ofbeinganexampleinHTML&CSS:TheCompleteReference,5thEdition*/
/*Ohbythewaypeoplecanseeyourcommentssothinktwiceaboutwhatyou
putinthem*/
</style>
HTMLcommentsyntax(<!--comment-->)doesnotapplyinCSS.However,as
discussedpreviouslyinthe“StyleInclusionMethods”section,HTMLcommentsareoften
usedtomaskstyleblocks:
<styletype="text/css">
<!--
p{font-size:1.5em;font-family:Georgia,"TimesNewRoman",Times,serif;
540 Part II: Core Style
color:blue;background-color:yellow;}
em{font-size:2em;color:green;}
-->
</style>
InternetExplorer’sconditionalcommentsarealsofoundinCSSformaskinglinkedstyle
sheetsforonebrowseroranother.SeeentryoncommentsinthereferencefoundinChapter3
formoredetails.
@charset
Asingle@charsetrulecanbeusedinanexternalsheettodefinecharactersetencodingof
thestylerulesandvalues.
Example
@charset"ISO-8859-1"
/*externalstylesheetrulesfollowbelow*/
Note
• Thisruleshouldneverbeusedinanembeddedstylesheet,astherearemanyother
waystoindicatecharactersetswitha<meta>tagoranHTTPheader.
@font-face
This“at”ruleisusedtoassociateafontnametobeusedinastylesheetwithsome
downloadablefont.Afont-familypropertyisusedwithintheruletonamethefont
andasrcpropertyisassociatedwithanexternalfontname:
@font-face{font-family:fontname;
src:url(fontfile);}
Later,thefontcanbeusedasanamewithinpropertieslikefont-familyandfont,
thoughyoushouldspecifyotherfontnamesasafallbackincasedownloadablefont
technologyisnotsupportedorthefontfailstoloadforsomereason.
Examples
@font-face{font-family:"Mufferaw";
src:url(MUFFERAW.ttf);}
body{font-family:"Mufferaw",serif;font-size:5em;}
Itisalsopossibletosetselectionofaparticulardownloadablefontwhenaparticularfont
characteristiclikeboldoritalicisset,byaddingthecorrespondingruletothe@font-facerule:
@font-face{font-family:"Mufferaw";
src:url(MUFFERAW.ttf);}
@font-face{font-family:"Mufferaw";
src:url(MUFFERAWBOLD.ttf);
font-weight:bold;}
p{font-family:"Mufferaw",serif;font-size:5em;}
em{font-weight:bold;}/*wouldspecifytheMufferawboldfont*/
Chapter 5: CSS Syntax and Property Reference 541
Note
• Theparticularfonttechnologiesfordownloadablefontsvarysignificantlybetween
browsers.InternetExplorerhassupportedEOTfilessinceIE4.Netscapesupported
TrueDocdownloadablefontsbutthesewerephasedout.Firefox3.5,Safari3,and
Opera10havereintroduceddownloadablefontsusingTrueTypefiles.SeeAppendixB
forexamplesofmixingthevarioustechnologies.
@media
An@mediarulecanbeusedtodefinestylerulesformultiplemediatypesinasingle
embeddedstylesheet.
PART II
Examples
<styletype="text/css">
@mediascreen{/*screenrules*/}
@mediaprint{/*printrules*/}
@mediascreen,print{/*screenandprintrules*/}
</style>
Thesyntaxmaylookalittleoddbecauseyouhavetowrapstyleblockswithmorecurly
braces,likeso:
<styletype="text/css">
@mediascreen{body
{font-family:sans-serif;
font-size:14px;}
}
@mediaprint{body
{font-family:serif;
font-size:10px;}
}
</style>
Avariationofthissyntaxwithdeviceconstraints,dubbeda“MediaQuery,”issupportedin
manybrowsersandisdiscussedinChapter6.
@page
An@pageruleisusedtodefineapageblockforprintedstyles.Generally,withinthis
constructweseevariousCSSpropertieslikesize,page,andmargintocontrolthe
dimensionsofthepage.
Examples
/*setstablestobeonlandscapepages*/
@page{size:8.5in11in;margin:.5in;}
@page{marks:crop;}
/*wecannameparticularpage'srulesaswellwithanidentifier*/
@pagereport{size:landscape;}
542 Part II: Core Style
/*pseudo-classescanbeusedtoselectalternatingpagesaswell
asthefirstpage*/
@page:left{margin:.5in;}
@page:right{margin:1.5in;}
@page:first{margin:5in;}
Note
• Thisconstructisnotwellsupported,eveninmodernbrowsers.
!important
Thisconstructspecifiesthatastyletakesprecedenceoveranydifferent,conflictingstyles.
Thisconstructshouldbeusedsparingly.
Examples
body{font-family:Times;}
div{font-size:14pt;line-height:150%;font-family:Arial!important;}
#div1{font-family:Sans-Serif;}
/*alldivs,nomatterhowused,willbeinArial,see!important*/
• Briefsummary Briefsummaryoftheproperty’spurpose.
• Syntax Syntaxfortheelement,includingallowedvaluesdefinedbytheW3C
specification.
• Example(s) Oneormoreexamplesdemonstratinguseoftheproperty.
• Compatibility Theproperty’sgeneralcompatibilitywithCSSspecificationsand
browserversions.
• Note(s) Additionalinformationaboutthepropertyoritsusage.Thismayinclude
someCSS3detailsforpropertiesthatareonlyslightlymodifiedintheemerging
specification.ThebulkoftheCSS3informationispresentedinChapter6.
Allthevaluesallowedwithapropertyaredefinedintheearliersection“CSS
Measurements.”Similarly,theexamplesassumethatyouunderstandselectors,which
aresummarizedintheearliersection“CSSSelectors.”
Chapter 5: CSS Syntax and Property Reference 543
TIP Thesupportsitehttp://htmlref.comhasthisreferenceonlineandmayhaveupdatesorfixesto
thisinformation.
background
Thispropertysetsinashorthandformanyorallbackgroundproperties.
Syntax
background:background-colorbackground-imagebackground-repeat
background-attachmentbackground-position;
Propertyordershouldnotmatter,andanypropertiesnotspecifiedusetheirdefaultvalues.
PART II
Examples
body{background:whiteurl(picture.gif)repeat-ycenter;}
.red{background:#ff0000;}
#div1{background:whiteurl(logo.gif)no-repeatfixed10px10px;}
Compatability
CSS 1, 2, 3 IE 4+ Netscape 4 (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Notes
• Aswithallshorthandforms,documentauthorsshouldexperimentwithindividual
background-relatedpropertyvaluesbeforeadoptingashortform.
• UndertheemergingCSS3specification,itispossibletospecifymultiplefilesfora
backgroundandseparateeachwithacomma.Forexample,
body{background:whiteurl(donkey.gif)topleftno-repeat,
url(elephant.gif)bottomrightno-repeat;}
wouldputabackgroundimageinthetop-leftandbottom-rightareasofthebody,
respectively.Supportislimited,thoughSafari1.3+browserssupportmostCSS3
backgroundfeatures.
background-attachment
Thispropertysetsthebackgroundimagetoscrollornottoscrollwithitsassociatedelement’s
content.Thedefaultvalueisscroll,whichsetsthebackgroundtoscrollwiththeassociated
content,typicallytext.Thealternatevalue,fixed,isintendedtomakethebackgroundstatic
whileassociatedcontentsuchastextscrollsoverthebackground.Avalueofinheritapplies
thevalueofthispropertyfromacontainingparentelement.
Syntax
background-attachment:scroll|fixed|inherit
Examples
body{background-image:url(tile.gif);background-attachment:scroll;}
#logo{background-image:url(logo.gif);background-attachment:fixed;}
544 Part II: Core Style
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Thispropertyisoftenusedtocreateawatermarkeffectsimilartotheproprietary
attributeofthe<body>tag,bgproperties,introducedbyMicrosoft.
background-color
Thispropertysetsanelement’sbackgroundcolor.Awidevarietyofcolorvalues,asdetailed
earlierinTable5-4,canbeused,whilethedefaultvalue,transparent,allowsany
underlyingcontenttoshowthrough.
Syntax
background-color:color|transparent|inherit
Examples
.red{background-color:#FF0000;}
.red2{background-color:#F00;}
.red3{background-color:red;}
.red4{background-color:rgb(255,0,0);}
.red5{background-color:hsl(0,100%,50%);}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4 (buggy; may not fit Opera 4+, Safari 1+
entire region), 6+, Firefox 1+
Notes
• Thispropertyisoftenusedinconjunctionwiththecolorproperty.Ifboth
propertiesarenotset,itispossibletohaverenderingproblemsintheunlikelyevent
thatthebrowserdefaultcolorshidecontentbecausecolorsaretoosimilar.TheW3C
CSSvalidatorwillwarnofthepossibilityofthisrarebuttroublingissue.
• Usedwithblockelements,thispropertycolorscontentandpaddingbutnot
margins.
background-image
Thispropertyassociatesabackgroundimagewithanelement.Underlyingcontentmay
showthroughtransparentregionsinthesourceimage.Thebackgroundimagerequiresa
URL(completeorrelative)tolinkittothesourceimagespecifiedwiththeurl()syntax.
Thedefaultvalueisnoneandsetsthebackgroundsothatitdoesn’tdisplayanimage.
Syntax
background-image:url(image-file)|none|inherit
Chapter 5: CSS Syntax and Property Reference 545
Examples
body{background-image:url(plaidpattern.gif);}
p{background-image:none;}
#robot{background-image:url(http://www.democompany.com/images/robot.gif);}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4 (buggy; may not fit Opera 4+, Safari 1+
entire region), 6+, Firefox 1+
Notes
PART II
• UndertheemergingCSS3specification,itispossibletospecifybackgroundimages
andseparateeachwithacomma.Forexample,
body{background-image:url(donkey.gif),url(elephant.gif);}
However,withoutpositioningofthebackgroundsortransparency,youmay
obscureimages.Supportislimited,thoughSafari1.3+browserssupportmostCSS3
background-imagefeatures.
background-position
Thispropertydetermineshowabackgroundimageispositionedwithinthecanvasspace
usedbyitsassociatedelement.Thepositionofthebackgroundimage’supper-leftcorner
canbespecifiedasanabsolutedistance,typicallyinpixels,fromthesurroundingelement’s
origin.Itcanalsobespecifiedasarelativeunit,nearlyalwaysapercentage,alongthe
horizontalandverticaldimensions.Finally,thepositioncanbespecifiedasnamedvalues
thatdescribethehorizontalandverticaldimensions.Thenamedvaluesforthehorizontal
axisarecenter,left,andright;thosefortheverticalaxisaretop,center,andbottom.
Thedefaultvalueforanunspecifieddimensionwhenonlyasinglevalueisgivenis
assumedtobecenter.
Syntax
background-position:horizontalvertical
wherehorizontalis
percentage|length|left|center|right
andverticalis
percentage|length|top|center|bottom
Examples
body{background-image:url(plaidpattern.gif);
background-position:50px100px;}
#div1{background-image:url(bricks.png);background-position:10%45%;}
body{background-image:url(logo.gif);background-position:topcenter;}
546 Part II: Core Style
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
Notes
• AccordingtotheCSS2.1specification,thetilingandpositioningofbackground
imagesoninlineelementsisundefined.Inpractice,browserstendtosupportit.
• Whenkeywordsaresolelyused,theorderingofvaluesisnotimportant.
• UnderCSS3youmayspecifymultiplebackground-positionvaluesandseparate
themwithcommas.Eachvaluewillthenbeappliedtothecorrespondingbackground
inthelistofbackgrounds.Forexample,background-position:50px100px,
200px200px;wouldpositionthefirstbackgroundat50px,100pxandthesecond
backgroundat200px,200px.Supportislimited,thoughSafari1.3+browserssupport
mostCSS3background-positionfeatures.
background-repeat
Thispropertydetermineshowbackgroundimagesspecifiedbythepropertybackground
orbackground-imagetilewhentheyaresmallerthanthecanvasspaceusedbytheir
associatedelements.Possiblevaluesarerepeat(repeatsinbothdirection),repeat-x
(repeatsonlyhorizontally),repeat-y(repeatsvertically),andno-repeat.Thedefault
valueisrepeat.
Syntax
background-repeat:repeat|repeat-x|repeat-y|no-repeat|inherit
Examples
body{background-image:url(yellowpattern.gif)background-repeat:repeat;}
#div1{background-image:url(tile.gif);background-repeat:repeat-x;}
p{background-image:url(tile2.jpg);background-repeat:repeat-y;}
.mark{background-image:url(logo.png);background-repeat:no-repeat;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4 (buggy; may not fit Opera 4+, Safari 1+
entire region), 6+, Firefox 1+
Notes
• AccordingtotheCSS2.1specification,thetilingandpositioningofbackground
imagesoninlineelementsisundefined.Inpractice,browserstendtosupportit.
• UnderCSS3youmayspecifymultiplebackground-repeatvaluesandseparate
themwithcommas.Eachvaluewillthenbeappliedtothecorrespondingbackground
inthelistofbackgrounds.Forexample,background-repeat:no-repeat,
repeat-x;wouldapplyno-repeattothefirstbackgroundandrepeat-xtothe
second.Supportislimited,thoughSafari1.3+browserssupportmostCSS3
background-relatedfeatures.
Chapter 5: CSS Syntax and Property Reference 547
border
Thispropertydefinesinashorthandformthewidth,style,andcolorforallfoursidesofan
element’sborder.
Syntax
border:border-widthborder-styleborder-color
whereborder-widthsetsallbordersinnumericmeasurementsorwithanamedvalueof
thin,medium,orthick.Thesecondvalue,border-style,isusedtosetthestyleofthe
borderandissettoavalueofdashed,dotted,double,groove,hidden,inset,none,
outset,ridge,orsolid.Finally,border-colorisusedtosetthecoloroftheborder
PART II
usingaCSScolorvalue.
Examples
div{border:2pxdoublered;}
.dashed{border:.5emdashed#f00;}
Compatibility
CSS 1, 2, 3 IE 4, 5 (buggy), 5.5+ Netscape 4 (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Tosettheindividualsidesofanelement’sborder,usethevariousrulesthatpertain
toindividualborders,likeborder-bottom,border-bottom-color,border-
bottom-style,border-bottom-width.
border-bottom
Thispropertydefinesinashorthandformthewidth,style,andcolorforthebottomborder
ofanelement.
Syntax
border-bottom:border-widthborder-styleborder-color;
Example
#redbottom{border-bottom:thinsolidred;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• GiventhatCSS1didnotsupportborder-bottom-colorandborder-bottom-
style,thispropertyisusefulforsettingthecharacteristicsofthebottomofboxes
forolderbrowsers.
548 Part II: Core Style
border-bottom-color
Thispropertydefinesthecolorofanelement’sbottomborder.
Syntax
border-bottom-color:color|transparent|inherit
wherecolorisavalidCSScolorvalue.
Example
p{border-style:solid;border-width:thin;border-bottom-color:orange;}
Compatibility
CSS 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
border-bottom-style
Thispropertydefinesthestyleforthebottomborderofanelement.
Syntax
border-bottom-style:dashed|dotted|double|groove|hidden|
inset|inherit|none|outset|ridge|solid
Example
#box{border-width:10px;border-style:solid;border-bottom-style:double;}
Compatibility
CSS 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
border-bottom-width
Thispropertysetsthewidthofanelement’sbottomborder.
Syntax
border-bottom-width:non-negativelength|medium|thick|thin|inherit
Examples
.low{border-bottom-width:thick;}
p{border-bottom-width:15px;}
Compatibility
CSS 1, 2, 3 IE 4, 5 (buggy), 5.5+ Netscape 4 (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Chapter 5: CSS Syntax and Property Reference 549
border-collapse
Thispropertydefineswhethertablecellbordersareconnectedorseparate.
Syntax
border-collapse:collapse|separate|inherit
Thedefaultvalueisseparate,witheachcellhavingaborderwithpossiblespacing.With
avalueofcollapse,thebordersappeartocollapseoneachothersothatthere’snomore
spacingbetweentheborders.Therenderinghereshouldillustratetheideaoftheproperty
clearly:
PART II
Example
<tableborder="1"style="border-collapse:collapse;">
<tr>
<td>Cell1</td><td>Cell2</td><td>Cell3</td>
</tr>
<tr>
<td>Cell4</td><td></td><td>Cell5</td>
</tr>
</table>
Compatibility
CSS 2, 3 IE 5–7 (partial), 8+ Netscape 6+, Firefox 1+ Opera 5+, Safari 1+
border-color
Thispropertydefinesthecolorofanelement’sborder.
Syntax
border-color:color[colorcolorcolor]
wherecolorisavalidCSScolor,transparent,orinherit.
550 Part II: Core Style
Theborder-colorpropertycanbeusedtospecifythecolorofallfourborders
individuallyinthestandardtop,right,bottom,leftstyle:
margin
1 border-top-color
padding
2
4
border-right-color
border-left-color
Content
3 border-bottom-color
Asinglevaluecopiesthecolortoallbordersides.Withtwovalues,thefirstsetsthe
bordercolorofthetopandbottom,andthesecondsetsthebordercoloroftherightandleft.
Withthreevalues,thefirstsetsthebordercolorofthetop,thesecondsetsthecolorofthe
rightandleft,andthethirdsetsthecolorofthebottom.Withfourvalues,eachcolorisset
individuallyintheordertop,right,bottom,andleft.
Examples
p{border-style:solid;border-width:thin;border-color:blue;}
#d1{border-style:double;border-color:#0000EE;}
#rainbow{border-color:redgreenblueorange;}
Compatibility
CSS 1, 2, 3 IE 4, 5 (buggy) 5.5+ Netscape 4 (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Allbordersaresetatonce,butindividualcolorvaluescanbesetwiththeshorthand
border-top,border-right,border-bottom,andborder-leftaswellaswith
thespecificpropertiesborder-top-color,border-right-color,andsoon.
border-left
Thispropertydefinesinashorthandformthewidth,style,andcolorfortheleftborderof
anelement.
Syntax
border-left:border-widthborder-styleborder-color;
Chapter 5: CSS Syntax and Property Reference 551
whereborder-widthsetsthewidthoftheborderasapositivenumericmeasurementor
usinganamedvalueofthin,medium,orthick.Thesecondvalue,border-style,isused
tosetthestyleoftheleftborderandissettoavalueofdashed,dotted,double,groove,
hidden,inset,none,outset,ridge,orsolid.Finally,border-colorisusedtosetthe
coloroftheleftborderusingaCSScolorvalue.
Example
#leftout{border-left:thindashedred;}
Compatibility
PART II
CSS 1, 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• GiventhatCSS1didnotsupportborder-left-colorandborder-left-style,
thispropertyisusefulforsettingthecharacteristicsoftheleftborderofboxesfor
olderbrowsers.
border-left-color
ThisCSS2+propertydefinesthecolorofanelement’sleftborder.
Syntax
border-left-color:color|transparent|inherit
wherecolorisavalidCSScolorvalue.
Example
p{border-style:solid;border-width:thin;border-left-color:#f00;}
Compatibility
CSS 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
border-left-style
Thispropertydefinesthestylefortheleftborderofanelement.
Syntax
border-left-style:dashed|dotted|double|groove|hidden|
inset|inherit|none|outset|ridge|solid
Example
#box{border-width:10px;border-style:solid;border-left-style:dotted;}
552 Part II: Core Style
Compatibility
CSS 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
border-left-width
Thispropertysetsthewidthofanelement’sleftborder.
Syntax
border-left-width:non-negativelength|medium|thick|thin|inherit
Examples
.fat{border-left-width:thick;}
p.left{border-left-width:15px;}
Compatibility
CSS 1, 2, 3 IE 4, 5 (buggy), 5.5+ Netscape 4 (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
border-right
Thispropertydefinesinashorthandformthewidth,style,andcolorfortherightborderof
anelement.
Syntax
border-right:border-widthborder-styleborder-color;
whereborder-widthsetsthewidthoftherightborderasapositivenumericmeasurement
orusinganamedvalueofthin,medium,orthick.Thesecondvalue,border-style,is
usedtosetthestyleoftherightborderandissettoavalueofdashed,dotted,double,
groove,hidden,inset,none,outset,ridge,orsolid.Finally,border-colorisused
tosetthecoloroftherightborderusingaCSScolorvalue.
Example
#greenzone{border-right:thickdashedgreen;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• GiventhatCSS1didnotsupportborder-right-colorandborder-right-style,
thispropertyisusefulforsettingthecharacteristicsoftherightborderofboxesfor
olderbrowsers.
border-right-color
ThisCSS2+propertydefinesthecolorofanelement’srightborder.
Chapter 5: CSS Syntax and Property Reference 553
Syntax
border-right-color:color|transparent|inherit
wherecolorisavalidCSScolorvalue.
Example
p{border-style:solid;border-width:thin;border-right-color:#0f0;}
Compatibility
CSS 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
PART II
border-right-style
Thispropertydefinesthestylefortherightborderofanelement.
Syntax
border-right-style:dashed|dotted|double|groove|hidden|inset|
inherit|none|outset|ridge|solid
Example
#box{border-width:10px;border-style:solid;border-right-style:ridge;}
Compatibility
CSS 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
border-right-width
Thispropertysetsthewidthofanelement’srightborder.
Syntax
border-right-width:non-negativelength|medium|thick|thin|inherit
Examples
div{border-right-width:medium;}
.superfat{border-right-width:40px;}
Compatibility
CSS 1, 2, 3 IE 4, 5 (buggy), 5.5+ Netscape 4 (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
border-spacing
Thispropertydefinesthespacebetweencellsinatable.
Syntax
border-spacing:non-negativelength(s)|inherit
554 Part II: Core Style
Itsvaluecanbeanarbitrarylength,butnotnegative.Ifonelengthisspecified,itgivesboth
thehorizontalandverticalspacing.Iftwolengthsarespecified,thefirstgivesthehorizontal
spacingandthesecondtheverticalspacingbetweencells.
Examples
#table1{border-spacing:10px;}
#table2{border-spacing:10px5px;}
Compatibility
CSS 2, 3 IE 8+ Netscape 6+, Firefox 1+ Opera 5+, Safari 1+
Note
• Thispropertyissimilartothecellspacingattributeofthetableelementin
(X)HTML.
border-style
Thispropertydefinesthevisualstyleofuptofourdifferentsidesofaborder.
Syntax
border-style:style[stylestylestyle]
Eachindividualstylevaluecanbesettoavalueofnone,dotted,dashed,solid,double,
groove,hidden,ridge,inset,oroutset.Visualexamplesofthesestylesareshownhere:
Chapter 5: CSS Syntax and Property Reference 555
Theshorthandstyleallowsindividualborderstobesetinthestandardtop,right,bottom,
leftstyle:
margin
1 border-top-style
padding
2
4
border-right-style
border-left-style
PART II
Content
3 border-bottom-style
Asinglevaluecopiesthestyletoallbordersides.Withtwovalues,thefirstsetstheborder
styleofthetopandbottom,andthesecondsetstheborderstyleoftherightandleft.With
threevalues,thefirstsetsthestyleofthetopborder,thesecondsetsthestyleoftherightand
leftborders,andthethirdsetsthestyleofthebottomborder.Withfourvalues,thestyleof
eachborderissetindividuallyintheordertop,right,bottom,andleft.Ingeneral,missing
valuesareinferredfromthevaluedefinedfortheoppositeside.
Examples
p{border-style:solid;}
.twosides{border-style:dashedsolid;}
.allsides{border-style:soliddashedgrooveinset;}
Compatibility
CSS 1, 2, 3 IE 4, 5 (no dotted/dashed), 5.5+ Netscape 4+ (buggy), Opera 5+, Safari 1+
6+, Firefox 1+
Note
• Allbordersaresetatonce,butindividualstylevaluescanbesetwiththeshorthand
border-top,border-right,border-bottom,andborder-left,aswellaswith
thespecificpropertiesborder-top-style,border-right-style,andsoon.
556 Part II: Core Style
border-top
Thispropertydefinesinashorthandformthewidth,style,andcolorforthetopborderof
anelement.
Syntax
border-top:border-widthborder-styleborder-color;
whereborder-widthsetsthewidthofthetopborderasapositivenumericmeasurement
orusinganamedvalueofthin,medium,orthick.Thesecondvalue,border-style,is
usedtosetthestyleofthetopborderandissettoavalueofdashed,dotted,double,
groove,hidden,inset,none,outset,ridge,orsolid.Finally,border-colorisused
tosetthecolorofthetopborderusingaCSScolorvalue.
Example
#boxtop{border-top:thinsolidblue;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• GiventhatCSS1didnotsupportborder-top-colorandborder-top-style,this
propertyisusefulforsettingthecharacteristicsoftherightborderofboxesforolder
browsers.
border-top-color
ThisCSS2+propertydefinesthecolorofanelement’stopborder.
Syntax
border-top-color:color|transparent|inherit
wherecolorisavalidCSScolorvalue.
Example
p{border-style:solid;border-width:thin;border-top-color:#f00;}
Compatibility
CSS 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
Chapter 5: CSS Syntax and Property Reference 557
border-top-style
Thispropertydefinesthestyleforthetopborderofanelement.
Syntax
border-top-style:dashed|dotted|double|groove|hidden|inset|
inherit|none|outset|ridge|solid
Example
#box{border-width:10px;border-style:solid;border-top-style:dashed;}
Compatibility
PART II
CSS 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
border-top-width
Thispropertysetsthewidthofanelement’stopborder.
Syntax
border-top-width:non-negativelength|medium|thick|thin|inherit
Examples
p{border-top-width:thin;}
#thicktop{border-top-width:25px;}
Compatibility
CSS 1, 2, 3 IE 4, 5 (buggy), 5.5+ Netscape 4 (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
border-width
Thispropertysetsthewidthofanelement’scompleteborder.
Syntax
border-width:width[widthwidthwidth]
wherewidthis
non-negativelength|medium|thick|thin|inherit
558 Part II: Core Style
Theborder-widthpropertycanalsobeusedtospecifyallfourbordersindividuallyinthe
standardtop,right,bottom,leftstyle:
margin
1 border-top-width
padding
2
4
border-right-width
border-left-width
Content
3 border-bottom-width
Asinglevaluecopiesthewidthtoallbordersides.Withtwovalues,thefirstsetsthe
borderwidthofthetopandbottomborders,andthesecondsetsthewidthoftherightand
leftborders.Withthreevalues,thefirstsetsthewidthofthetopborder,thesecondsetsthe
widthoftherightandleftborders,andthethirdsetsthewidthofthebottomborder.With
fourvalues,eachborderissetindividuallyintheordertop,right,bottom,andleft.
Examples
div{border-width:medium;}
/*allsidessetmedium*/
#d1{border-width:10px5px;}
/*10pxtop-bottom,5pxrightandleft*/
#fun{border-width:10px1px4px50px;}
/*sidessetindividually*/
Compatibility
CSS 1, 2, 3 IE 4, 5 (buggy), 5.5+ Netscape 4 (buggy), 6+, Firefox 1+ Opera 5+, Safari 1+
Note
• Allbordersaresetatonce,butindividualwidthvaluescanbesetwiththe
shorthandborder-top,border-right,border-bottom,andborder-left,as
wellaswiththespecificpropertiesborder-top-width,border-right-width,
andsoon.
Chapter 5: CSS Syntax and Property Reference 559
bottom
Thispropertydefinesthey(vertical)coordinateforapositionedelement,relativetothe
bottomoftheenclosingobjectorbrowserwindow.
Syntax
bottom:length|percentage|auto|inherit
wherelengthcanbespecifiedinthestandardunitsoflength,suchasinches(in)andsoon,
butisnearlyalwayssetinpixels(px),andpercentagecorrespondstoapercentageofthe
containingobject’sdimensions.Thedefaultvalue,auto,placestheobjectwhereitnormally
wouldbeinthedocumentorder.Forrelativeposition,thiswilllikelybetreatedas0.For
PART II
absoluteandfixedpositioning,itwillcalculateavaluebaseduponothersetproperties,
particularlytop.
Examples
#div1{position:absolute;left:100px;bottom:150px;}
#div2{position:absolute;left:50%;bottom:30%;}
#div3{position:absolute;left:10px;bottom:auto;top:500px;}
/*bottomwillevaluatetoapositioncalculatedoffthetopposition*/
#footer{position:fixed;left:0;bottom:0;}
Compatibility
CSS 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 6+, Safari 1+
Note
• Browserstendtoassumepixelmeasurementsifalengthunitisnotset.
caption-side
Thispropertydefinesthepositionofacaptionelementwithina<table>tag.
Syntax
caption-side:top|bottom|inherit
Examples
caption{caption-side:bottom;}
.right{caption-side:right;}
Compatibility
CSS 2, 3 IE 8+ Netscape 6+, Firefox 1+ Opera 6+, Safari 1+
Notes
• Manybrowserssupportvaluesofleftandrightaswell,whichweredefinedby
CSS2anddroppedinCSS2.1.
• Avalueoftoptypicallyisthedefaultinabrowserwhichcorrespondstothe
commonpositionofthecaptionelementwitha<table>tag.
560 Part II: Core Style
clear
Thispropertyspecifiestheplacementofanelementinrelationtofloatingobjects.
Syntax
clear:both|left|none|right|inherit
Thepropertyactsmuchliketheclearattributeforthe<br>tagandcontinuestopush
elementsuntiltheleft,right,orbothcolumnsareclear.Thedefaultvalueisnone.
Examples
br.clearright{clear:right;}
#clearboth{clear:both;}
Compatibility
CSS 1, 2, 3 IE 4 (buggy), 5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 5+, Safari 1+
clip
Thispropertysetsthecoordinatesoftheclippingshapethatexposesorhidesthecontentof
absolutelypositionedelements.
Syntax
clip:rect(coordinates)|auto|inherit
wheretheallowedclippingshapeisarectangledefinedrect(toprightbottomleft)
inwhichthevaluesspecifyoffsetsfromtherespectivesidesofthecontainingbox.
Example
<styletype="text/css"media="screen">
#div1{position:absolute;width:200px;height:200px;clip:rect(10px90px
90px10px);border:1pxsolid;background-color:orange;}
#div2{position:absolute;left:220px;width:200px;height:200px;
border:1pxsolid;background-color:orange;}
</style>
</head>
<body>
<divid="div1">Clipped</div>
<divid="div2">NotClipped</div>
Chapter 5: CSS Syntax and Property Reference 561
PART II
Compatibility
CSS 2, 3 IE 4 (buggy), 5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 5+, Safari 1+
Note
• InfutureCSSspecifications,otherclippingshapesmaybesupported.
color
Thispropertysetstheforegroundcolorofanelement’stextcontent.
Syntax
color:color|inherit
wherecolorisavalidCSScolorvalue.
Examples
.sunflower{color:yellow;}
#sunburn{color:#FF0000;}
p{color:#FF0;}
#sunburn2{color:rgb(255,0,0);}
body{color:rgb(100%,100%,100%);}
562 Part II: Core Style
Compatibility
CSS 1, 2, 3 IE 3+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
Notes
• Thispropertyisoftenusedinconjunctionwiththebackground-colorproperty.If
bothpropertiesarenotset,itispossibletohaverenderingproblemswhendefault
colorvalueshidecontent.TheW3CCSSvalidatorwillwarnofthisdangerous
thoughunlikelyissue.
• Aconcernwiththispropertyisnotwhetheritissupported,butwhatCSScolor
valuesaresupported.Developersshouldassumethathsl()andotheremerging
CSS3valuesaremoredangeroustousethanstandardkeywordsorhexvalues.
content
Thispropertygeneratescontentinadocumentandisusedwiththe:beforeand:after
pseudo-elements.
Syntax
content:normal|none|string|url()|counter|attr(X)|open-quote|
close-quote|no-open-quote|no-close-quote|inherit
Themostcommonlyusedstringvaluesimplyinsertsthedefinedquote-delimitedstring
eitherbeforeoraftertheselectedelementdependingontheruleinuse:
div.section:before{content:"SectionName:";}
Theurlvalueisusedtoinsertanexternalresource,typicallyanimage:
div.section:before{content:url(warning.png);}
Itispossibletocombinevalues,
div.section:before{content:"Dangerdanger!"url(warning.png)"Generated
ContentAhead";}
andthegeneratedcontentcanbestyledbyfurtherappliedproperties:
div.section:before{content:"Dangerdanger!";
font-size:xx-large;background-color:black;
color:yellow;}
Countervaluescanbespecifiedandusedtoautomaticallyaddasequentialindicator.It
isgenerallydefinedintheformofcounter(name),wherenameisthenameofthecounter,
orcounter(name,style),wherestyleindicatesthelist-style-typetouse:
ol.countTestli:before{content:counter(counter1)"-";}
Chapter 5: CSS Syntax and Property Reference 563
Multiplecounterscanbeemployedtoallowfornestingofcountervaluesifthe
counters()functionisemployed.Thisiscommonlyusedwithoutlinestylelists:
/*counternestingexamplewithcounters()functionshowinga
value.valuestyleoutline*/
ol.nest{counter-reset:counter1;list-style-type:none;}
ol.nestol{list-style-type:none;counter-reset:counter1;}
ol.nestli:before{counter-increment:counter1;
content:counters(counter1,".")":";}
Thevaluesopen-quoteandclose-quoteinsertquotationsymbolsspecifiedbythe
quotesproperty,orifundefined,defaulttotheuseragent’sdefaultquotestyle:
PART II
q{quotes:'<<''>>'"("")";}
/*Insertquotesbeforeandafterqelementcontent*/
q:before{content:open-quote;}
q:after{content:close-quote;}
Theno-open-quoteandno-close-quotevaluesdonotinsertquotationsymbolsbut
doincrementordecrementthenestinglevelforquotes.
Finally,theattr(X)syntaxreturnsastringvaluefortheattributeXfortheelementthe
ruleisassociatedwith.Forexample,
#p1:before{content:attr(title);}
whenappliedto
<pid="p1"title="Textfromthetitlehere!">Iamtheparagraph</p>
wouldinsertthetitleattribute’scontent“Textfromthetitlehere!”beforetheparagraph.
ThoughiftherelatedelementdoesnothaveanattributenamedX,anemptystringisused.
Examples
div.section:before{content:"Section";font-size:xx-large;}
#div1:before{content:url(sectionstart.gif);}
#div1:after{content:url(sectionend.gif);}
blockquote:before{content:open-quote;}
blockquote:after{content:close-quote;}
p:before{content:counter(par-num,upper-roman)"."}
p:before{content:attr(title);}
Compatibility
CSS 2, 3 IE 8+ Firefox 1.5+ Opera 9+, Safari 3+
Note
• Whenusingattributematches(attr(X))forcontent,notethatbrowsersmayread
attributesofanynameregardlessofvalidity,butdonotassumethatthisisthe
action,becauseitdependsgreatlyonthemarkuptechnologyemployedandhow
itissupportedinabrowser.
564 Part II: Core Style
counter-increment
ThispropertycontrolsCSScountervalues.
Syntax
counter-increment:counter-name1[integer]...counter-nameN[integer]|
none|inherit
Thesyntaxshowsthepropertyacceptsoneormorecounternames(counter-nameX),each
oneoptionallyfollowedbyaninteger.Theintegerindicatesbyhowmuchthecounteris
incrementedordecrementedforeveryoccurrenceoftheelement.Thedefaultincrementis1.
Zeroandnegativeintegersareallowed.
Examples
div.section:before{content:"Section:"counter(section)".";
counter-increment:section;}
/*Add1tosection*/
h1.chapter:before{content:counter(chapterno,upper-latin)".";
counter-increment:chapterno;}
.topten:before{content:counter(countdown)".";
counter-increment:countdown-1;}
Compatibility
CSS 2, 3 IE 8+ Firefox 1.5+ Opera 7+, Safari 3+
counter-reset
Thispropertycontainsalistofoneormorecounternamestobeclearedorsettoaparticular
value.
Syntax
counter-reset:counter-name1[integer]...counter-nameN[integer]|none|
inherit
Thesyntaxshowsthepropertyacceptsoneormorenamesofcounters,eachoneoptionally
followedbyaninteger.Theintegerindicateswhatthecountervalueshouldbesetto;when
avalueisnotspecified,thecounterissetto0.
Examples
div.chapter{counter-reset:section;}
/*Setsectionto0*/
ol{counter-reset:sectioncountlistcountxy;}
/*Setsfourcountersto0*/
#foo{counter-reset:globalCount5;}
/*setto5forsomereason*/
Chapter 5: CSS Syntax and Property Reference 565
Compatibility
CSS 2, 3 IE 8+ Firefox 1.5+ Opera 7+, Safari 3+
cursor
Thispropertydetermineshowthecursordisplayswhenpassedovertheaffectedelement.
Syntax
cursor:url(addressofcursorfile)|auto|crosshair|default|pointer|
move|e-resize|ne-resize|nw-resize|n-resize|se-resize|
sw-resize|s-resize|w-resize|text|wait|help|progress|
PART II
inherit
Thedefaultvalue,auto,leavesthecursordisplaytobedeterminedbytheuseragent,sothe
cursorwilldisplayaccordingtoeitherthebrowserdefaultsortheusersystemsettings.The
commonrenderingsofthevalueslistedinCSS2.1areshowninTable5-7.
Thevalueurl()canbeusedtoreferenceacursorsource;multiplecursorsources
shouldbelisted.Aswithfonts,theuseragentshouldattempttorenderthefirstcursor
listed,trythesecondoneifnecessary,andultimatelydefaulttothegenericcursorvalue
listedlast,whichshouldbelistedthoughitislikelytodefaulttoautoappropriatelyin
conformantbrowsers:
<pstyle="cursor:url(greenarrow.cur),url(greenarrow.png),auto">Custom</p>
Notethatthefiletypeofthecursorlinkedtowilldependonwhatthebrowsermaysupport,
andsomebrowsers,suchasInternetExplorer,mayallowforanimatedcursors.
CSS3addsanumberofnewcursorvalues,includingtheabilitytoturnthecursoroff
completely.WhileitisuncleartheextentofnewcursorsthatCSS3willintroduce,givenits
rawstate,manyhavebeenimplementedalreadyinmodernbrowsers.Table5-8overviews
theseandprovidesrenderingswherepossible.
FormoreinformationonemergingCSS3cursors,seewww.w3.org/TR/css3-ui/#cursor.
Examples
.help{cursor:help;}
p.clickable{cursor:hand;}/*non-standard*/
a:longload{cursor:wait;}
p{cursor:url("mything.cur"),url("second.cur"),text;}
Compatibility
CSS 2, 3 IE 5+, (IE 6+ for custom) Firefox 1+ (1.5 for custom) Opera 7+, Safari 1+
Note
• Whilecustomcursorsmaynotbesupportedinallbrowsers,particularlywhenthey
areanimated,variousJavaScripttricksareoftenemployedtoimitatethisproperty.
566 Part II: Core Style
CSS cursor
Property Values Description Typical Rendering
alias Indicates the element may be a link or reference to
another element or location.
all-resize Shows that the object can be resized in all directions. None currently
cell Presents an icon to indicate a cell is active, similar to
what is performed in a spreadsheet application.
col-resize Displays a resize indicator for a column.
PART II
context-menu Indicates a context menu is available. None currently
copy Indicates the copy action is allowed or triggered by the
element.
move Displays standard four-arrow move cursor.
direction
Thispropertyisusedtocontrolthetextdirection,muchlikethedirattributefor
(X)HTMLtags.
Syntax
direction:ltr|rtl|inherit
Theallowedvaluesrtl(righttoleft)andltr(lefttoright)areoftenimpliedbythelanguage
inuse,thoughthedefaultisspecifiedtobeltr.
568 Part II: Core Style
Examples
<divstyle="direction:rtl">righttoleft</div>
<divstyle="direction:ltr">lefttoright</div>
<div>Warningtestahead...<spanstyle="unicode-bidi:embed;direction:rtl;
background-color:yellow;">heredoingIamWhat!</span>
Thisisjustatest</div>
Compatibility
CSS 2, 3 IE 5+ Netscape 6+, Firefox 1+ Opera 9+, Safari 1+
Note
• Whilethedirectionpropertycaneasilyaffectblockelements,forittoaffect
inline-levelelements,theunicode-bidipropertyvaluemustbeembedor
override.
display
Thispropertyspecifiesanelement’sdisplaytypeandcanoverrideanelement’sdefined
presentation.
Syntax
display:inline|block|list-item|run-in|inline-block|table|
inline-table|table-row-group|table-header-group|
table-footer-group|table-row|table-column-group|table-column|
table-cell|table-caption|none|inherit
Thevalueinlinecausesanelementtoactitwereaninlineelementwithnoreturnsadded,
asshownhere:
Avalueofblockcausestheelementtogenerateablockbox:
Chapter 5: CSS Syntax and Property Reference 569
Alist-itemvaluecreatesablockforthelistboxandaninlineboxforitems:
Thevalueofrun-inissomewhatcontextbasedandwillmaketheiteminlineorblock
dependingonthecontext.Basically,ifablockboxthatisnotfloatedorpositionedfollows
PART II
therun-inboxitbecomesthefirstinlineboxoftheblock,otherwise,itbecomesablock:
Browserstypicallydon’timplementthisvalue,andthereissomequestionofitsvalue.
CSS2supportsnumeroustable-relatedvalues,suchasdefininganelementtoactasa
table:
ortoactasacell:
570 Part II: Core Style
Baseduponthevalueslisted,itisalsopossibletodefinetheelementtoactasagroupof
cellsorotheraspectsofatable,thoughthepracticalapplicationandsupportforsuchvalues
isfuzzyatbest.
Probablythemostimportantvalueforthedisplaypropertyisnone,whichcompletely
removesanelementfromthedocumenttreeand,unlikethehiddenvalueofthe
visibilityproperty,doesnotpreserveanelement’scanvasspace,asdemonstratedhere:
Examples
#p1{display:inline;}/*runthiselementasaninline*/
b{display:block;}
.navigation{display:none;}
/*considerturningoffitemsinaprintstyle*/
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 5+, Safari 1+
Notes
• Thepropertyitselfiscommonlysupportedbutthevaluesarenot.
• CSS1onlydefinesinline,block,list-item,andnone.Designersareencouraged
toutilizethesecommonvaluesfirst.
• Becarefulaboutchangingtheaprioridisplayaspectsofdefinedelements.Making
all<b>tagsactasblockslike<p>tagsormaking<p>tagsrenderinlinedecreases
theunderstandabilityofmarkup.
empty-cells
Thispropertyisusedtocontrolwhetherornotbordersshowonemptytablecells.
Syntax
empty-cells:hide|show|inherit
Chapter 5: CSS Syntax and Property Reference 571
Thisillustrationshowsthesubtledifferencebetweenhideandshow:
Examples
<tableborder="1"style="empty-cells:show;width:80px;">
<caption>ShowCells</caption>
<tr>
PART II
<tdcolspan="2">Cell1</td>
</tr>
<tr>
<td>Cell2</td>
<td></td>
</tr>
</table>
<tableborder="1"style="empty-cells:hide;width:80px;">
<caption>HideCells</caption>
<tr>
<tdcolspan="2">Cell1</td>
</tr>
<tr>
<td>Cell2</td>
<td></td>
</tr>
</table>
Compatibility
CSS 2, 3 IE 7 (partial), IE 8+ Netscape 6+, Firefox 1+ Opera 5+, Safari 1+
Note
• Thedefaultvalueforthispropertyisshow.
float
Thispropertyinfluencesthehorizontalalignmentofanelement,makingit“float”toward
theleftorrightmarginofitscontainingelement.
Syntax
float:left|right|none|inherit;
Examples
#myimage{float:left;}
#pullquote{border-style:double;border-width:5px;
background-color:yellow;float:right;}
572 Part II: Core Style
Compatibility
CSS 1, 2, 3 IE 4–5 (buggy), IE 5.5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 6+, Safari 1+
Notes
• Thedefaultvalueforthispropertyisnone.
• Floatedregionsactmuchlike<img>tagsthathavebeenalignedleftorrightwith
respecttotext.
font
Thispropertyprovidesashorthandwaytospecifyallfontpropertieswithonerule.
Syntax
font:font-stylefont-variantfont-weightfont-size/line-heightfont-family;
Itisnotnecessarytoincludeallproperties,andthelistsofvariantfontsshouldbeseparated
bycommas,withthosefontnamesconsistingofmorethanonewordplacedinquotes.The
allowedvaluesarefoundineachindividualpropertyentry.
Examples
p{font:normalsmall-capsbold12pt/18pt"TimesNewRoman",Courier,serif;}
.super{font:italic18ptsans-serif;}
Compatibility
CSS 1, 2, 3 IE 3 (incomplete), IE 4+ Netscape 4+, Firefox 1+ Opera 6+, Safari 1+
Note
• ThisemergingCSS3specificationspecifiesmorefont-relatedproperties,suchas
font-effect,butinterestinglynoneisreplicatedintheshortformasofyet.
• Aswithallshorthandforms,documentauthorsshouldexperimentwithindividual
background-relatedpropertyvaluesbeforeadoptingashortform.
font-family
Thispropertysetsthefontfacetobeusedfortext.
Syntax
font-family:font1[,font2,...fontN]
Fontsmaybenamedspecificallyoragenericfontfamilynamemaybeused.Whenmultiple
fontnamesarespecifiedandseparatedbycommas,theyarereadindescendingorder
lookingforthefirstmatch.Generally,agenericfontnamewillbelistedattheendofafont
list.Therearefivegenericfontnamescurrentlyavailable:serif,sans-serif,cursive,
Chapter 5: CSS Syntax and Property Reference 573
fantasy,andmonospace.Theirrenderingsundermodernbrowsersareshownherebut
bewarethattheymaynotrenderthesameinallbrowsers:
PART II
Examples
.modern{font-family:'TrebuchetMS',Arial,Helvetica,sans-serif;}
p{font-family:Serif;}
body{font-family:"TimesNewRoman,Courier";}
#special{font-family:fantasy;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
Notes
• Thispropertyisequivalenttothefaceattributeofa<font>tag.
• Undermanybrowsers,downloadablefontsaresupported.Seetheentryfor
@font-faceearlierinthereference.
• Fontsarelistedincomma-separatedform,generallyendingwithaknownavailable
built-inCSSfont.
font-size
Thispropertysetsthefontsizeoftext.
Syntax
font-size:length|percentage|larger|smaller|xx-small|x-small|
small|medium|large|x-large|xx-larger|inherit
574 Part II: Core Style
Lengthsaresetofteninpoints(pt),pixels(px),picas(pc),inches(in),millimeters(mm),or
centimeters(cm).Standardrelativesizingunitsinem(em)andx-height(ex)mayalso
beused,aswellaspercentagevalueslike90%.Percentagevaluessetthefontsizetoa
percentageofthecurrentinheritedfont-size.Thepropertyalsosupportssizekeywords
(xx-small,x-small,small,medium,large,x-large,xx-large).Thesizekeywordsare
roughlyequivalenttothe1–7sizevaluesfora<font>tagandalsoshouldbeequivalentto
particularstockHTMLheadingsizes.Table5-9summarizesthetypicalrelationshipbetween
CSSandHTML,thoughimplementationsmayvary.
Therelativesizekeywordslargerandsmallershouldadjustacurrentsizeupor
downonevalue.
Examples
body{font-size:18pt;}
#heading1{font-size:36px;}
p{font-size:2em;}
h6{font-size:xx-small;}
.special{font-size:75%;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
font-style
Thispropertysetsthestyleofafont.
Syntax
font-style:italic|normal|oblique|inherit
Thenormalvaluewouldbeusedtooverrideanyinheritedfont-variantvalue.
Examples
.backToNormal{font-style:normal;}
#special{font-style:oblique;}
p.emphasis{font-style:italic;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
Note
• Visuallyobliqueanditalicsettingsmaylookthesamebutobliqueisoftensimplya
slantedversionofafont,whereasanitalicizedvariantmaybeacustomfontmade
topurposefullyandcarefullyitalicizeeachletterform.
font-variant
Thispropertysetsavariationofthespecifiedordefaultfontfamily.
PART II
Syntax
font-variant:normal|small-caps|inherit
Thesmall-capsvaluesetstextinsmaller-sizeallcapitals.Thenormalvaluewouldbe
usedtooverrideanyinheritedfont-variantvalue.
Examples
.legalese{font-variant:small-caps;}
.notlegal{font-variant:normal;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
Note
• Thesmall-capsstyleisoftenusedinlicenseandlegalagreements—putinallcapitals
tosuggestimportancebutmadesmalltodiscouragereadingandtofitmorecontent.
font-weight
Thispropertysetstheweight,orrelativeboldness,oftext.
Syntax
font-weight:normal|bold|bolder|lighter|100|200|300|400|500|
600|700|800|900|inherit
Valuescanbesetwithnamedvalues(normalorbold)orwithnumberedvalues(100–900).
Inpractice,undermostbrowsersthevalues100–500displayasnormaltext;600–900display
asbold.Relativevaluesoflighterorbolderwillincreaseordecreasethefont-weight
valuerelativetoitssurroundingweight.
Examples
.bold{font-weight:bold;}
#light{font-weight:300;}
.superbold{font-weight:900;}
strong{font-weight:normal;color:red;}
/*noteoverrideofdefaulttagpresentation*/
576 Part II: Core Style
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
Notes
• Supportforvaryingdegreesoflightorboldbeyondsimpleboldornotboldis
generallynotimplementedbybrowsersthoughtheoreticallyprintingmaysupport
suchdistinctions.
• Theoretically,applicationofboldtoafontmayallowamappingfromonefontlike
HelveticatoarelatedfontlikeHelveticaBoldorHelveticaBlack.Inpractice,such
mappingsdon’thappen.
height
Thispropertysetstheheightofanelement’scontentregion.
Syntax
height:length|percentage|auto|inherit
Standardpositivelengthunitscanbeused,andpixels(px)isoftentheassumedmeasurement
inbrowsers.Percentagevalues,basedontheheightofthecontainingelement,canalsobe
used.Thedefaultvalueofautoautomaticallycalculatesthewidthofanelement,basedon
theheightofthecontainingelementandthesizeofthecontent.
Examples
p{height:400px;width:200px;padding:10px;border:solid5px;}
#div1{height:50%;width:50%;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
Notes
• Theactualsizeofanobjectonabrowsercanvasisnotsolelydefinedbytheheight
property,asvaluesforbordersandpaddingaffectthespacetaken.Forexample,
giventheCSShere
#div1{height:200px;padding:30px;border:solid20px;}
Chapter 5: CSS Syntax and Property Reference 577
theheightofthecontentitselfmaybe200pxbuttheoverallcanvasspaceconsumed
is300pxtoaccountforthebordersandpadding:
20 30 30 20
200 px
px px px px
PART II
300 px
left
Thispropertydefinesthex(horizontal)coordinateforapositionedelement,relativetothe
leftsideofthecontainingelementorbrowserwindow.
Syntax
left:length|percentage|auto|inherit
wherelengthcanbespecifiedinthestandardunitsoflength,suchasinches(in)andsoon,
butisnearlyalwayssetinpixels(px),andpercentagecorrespondstoapercentageofthe
containingobject’sdimensions.Thedefaultvalue,auto,letsthispropertyfunctionasplacing
theobjectwhereitnormallywouldfallinthedocumentflow.Forrelativeposition,thiswill
likelybetreatedas0.Forabsoluteandfixedpositioning,itwillcalculateavaluebasedupon
othersetproperties,particularlyright.
Examples
#div1{position:absolute;left:100px;top:150px;}
#div2{position:absolute;left:50%;top:30%;}
#div3{position:absolute;left:auto;right:500px;bottom:5px;top:auto;}
/*leftwillevaluatetoapositioncalculatedofftherightposition*/
#navBar{position:fixed;left:0;top:0;}
Compatibility
CSS 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 6+, Safari 1+
578 Part II: Core Style
Note
• Browserstendtoassumepixelmeasurementsifalengthunitisnotset.
letter-spacing
Thispropertysetstheamountofspacingbetweenletters.
Syntax
letter-spacing:length|normal|inherit
Lengthvaluescanbesetinvariousunits(negativevaluesarepermitted)ortothedefault
valuenormal.
Examples
.tight{font-family:Arial;font-size:14pt;letter-spacing:2pt;}
p{letter-spacing:1em;}
p.norm{letter-spacing:normal;}
.superTight{letter-spacing:-5px;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Thispropertydoesnotenablefullkerningoftextasitwillnotbepossibletoadjust
thespacebetweentwoadjacentkerningpairsofletterswithoutcrossingtags.In
shortbecauseofthewaymarkupandstyleintersect,itsimplyisnotpossibleto
perfectlyadjustspacingdifferentlyoneithersideofaletter.However,giventhe
fluidnatureofscreendisplays,whatisprovidedforislikelymorethanadequate.
line-height
Thispropertysetstheheight(leading)betweenlinesoftextinablock-levelelementsuchas
aparagraph.
Syntax
line-height:number|length|percentage|normal|inherit
Valuescanbespecifiedasanumberoflines,anumberofunits(pixels,points,inches,
centimeters,andsoon),orapercentageofthefontsize.Negativevaluesarenotallowed.
Thedefaultvalueofnormalistypicallyequivalentto1.0to1.2dependingonthe
implementation.
Examples
.double{line-height:2;}
.double2{line-height:200%;}
p{font-size:14px;line-height:16px;}
p.norm{line-height:normal;}
body{line-height:4ex;}
div{line-height:125%;}
Chapter 5: CSS Syntax and Property Reference 579
Compatibility
CSS 1, 2, 3 IE 3+ Netscape 4+ (bugs), 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Alternatively,line-heightcanbesetthroughtheshorthandfontproperty.
list-style
Thisshorthandpropertysetslist-style-type,list-style-position,andlist-
style-image.
PART II
Syntax
line-style:list-style-type|list-style-position|list-style-image
Eachoftheindividualpropertiesisdetailedinthefollowingentries.Whilethedefinedorder
issuggestedinpractice,thepropertiescanappearinanyorder.
Examples
ul{list-style:insideurl("bullet.gif");}
#square{list-style:outsidesquare;}
ol{list-style:lower-romaninside;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
list-style-image
Thispropertyassignsagraphicimagetoalistitem.
Syntax
list-style-image:url(urlofimage)|none
Examples
ul{list-style-image:url(ball.gif);}
ul.remote{list-style-image:url(http://htmlref.com/book.png);}
Compatibility
CSS 1, 2, 3 IE 3+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
list-style-position
Thispropertyspecifieswhetherthelabelsforanelement’slistitemsarepositionedinsideor
outsidethe“box”definedbythelisteditem.
Syntax
list-style-position:inside|outside|inherit
580 Part II: Core Style
Thedifferencebetweenthedefaultvalueoutsideandsettingthepropertytoinsideis
illustratedclearlyhere:
Examples
ol{list-style-type:upper-roman;list-style-position:outside;
background:yellow;}
ul{list-style-type:square;list-style-position:inside;
background:yellow;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 4+, Safari 1+
list-style-type
Thispropertydefineslabelsforalistofitems.
Syntax
list-style-type:disc|circle|square|decimal|decimal-leading-zero|
lower-roman|upper-roman|lower-greek|lower-latin|
upper-latin|armenian|georgian|lower-alpha|
upper-alpha|none|inherit
Thevaluenonepreventsalistlabelfromdisplaying.CSS1definesdisc,circle,and
square,whicharetypicallyusedonunorderedlists(<ul>).Thevaluesdecimal,lower-
roman,upper-roman,lower-alpha,andupper-alphaaretypicallyusedonorderedlists
(<ol>).Thesepropertytypescorrespondtothe(X)HTMLtypeattributesforlists.CSS2
addsmorevalues,primarilyfororderedlistsinforeignlanguages.
Examples
ol{list-style-type:upper-roman;}
ol.none{list-style-type:none;}
.ichi-ni{list-style-type:hiragana;}
Compatibility
CSS 1, 2, 3 IE 4+ (partial), IE 8+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
Chapter 5: CSS Syntax and Property Reference 581
Notes
• Thegeneralcharacteristicsofthispropertyaresupportedbythetypeattributefor
the<ol>,<ul>,and<li>(X)HTMLtags.
• CSS2alsoincludedvalues,suchashebrew,cjk-ideographic,hiragana,
katakana,hiragana-iroha,andkatakana-iroha.Thesevalueswerelater
removedfromtheCSS2.1specification.
• CSS3includesmanymorelist-style-typevalues,suchasarabic,binary,
lowerhexadecimal,mongolian,thai,ethiopic,hangul,norwegian,and
somali.
• SomeCSS2andmostCSS3valuesforthispropertyarenotsupportedinbrowsers.
PART II
margin
Thispropertysetsaconsistentmarginonallfoursidesoftheaffectedelement.
Syntax
margin:margin1...margin4|inherit
whereeachmarginvalueiseitheralength,percentage,auto,orinheritvalue.Asa
shorthandform,itispossibletosetthefourmarginvalues(margin-top,margin-right,
margin-bottom,andmargin-left)independentlywiththisproperty:
1 margin-top
Border
Padding
4 2
margin-right
margin-left
Content
3 margin-bottom
Asinglevaluewillbecopiedtoallfourmargins.Withtwovalues,thefirstvaluewill
specifythetopandbottommargins,andthesecondvaluewillspecifytherightandleft
margins.Ifthreevaluesarespecified,thefirstdefinesthetopmargin,theseconddefinesthe
leftandrightmargins,andthethirddefinesthebottommargin.Notethattheunspecified
marginisinferredfromthevaluedefinedforitsoppositeside.Lastly,allfourvaluescan
alsobesetinorderoftop,right,bottom,left.
582 Part II: Core Style
Examples
p{margin:15pt;}/*allsides15pt*/
#div1{margin:20px10px;}/*20pxtop-bottom,10pxleft-right*/
#div2{margin:10px10px5px10px;}
/*10pxtop,10pxright5pxbottom,10pxleft*/
Compatibility
CSS 1, 2, 3 IE 4+ (buggy), 5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Elementsmayhavedefaultmarginsonthem,andthesevaluesmayvarybyuser
agent.Becauseofthisinconsistency,manydevelopersprefertoclearallmargins
withawildcardrulelike*{margin:0;}andbuildupindividualvalues.
margin-bottom
Thispropertysetsanelement’sbottommargin.
Syntax
margin-bottom:length|percentage|auto|inherit
wherethelengthismeasuredinanyfixedmeasurement,suchasinches(in)orpixels(px),
andmaytakeanegativevalue.Apercentagevalueisdeterminedasapercentageofthe
heightofthecontainingblock.Thedefaultvalueforthepropertyis0.
Examples
p{margin-bottom:10pt;}
.tight{margin-bottom:0;}
#spec{margin-bottom:10%;}
Compatibility
CSS 1, 2, 3 IE 4+ (buggy), 5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Elementsmayhavedefaultmarginsonthem,andthesevaluesmayvarybyuser
agent.Becauseofthisinconsistency,manydevelopersprefertoclearallmargins
withawildcardrulelike*{margin:0;}andbuildupindividualvalues.
margin-left
Thispropertysetsanelement’sleftmargin.
Syntax
margin-left:length|percentage|auto|inherit
wherethelengthismeasuredinanyfixedmeasurement,suchasinches(in)orpixels(px),
andmaytakeanegativevalue.Apercentagevalueisdeterminedasapercentageofthe
widthofthecontainingblock.Thedefaultvalueforthepropertyis0.
Chapter 5: CSS Syntax and Property Reference 583
Examples
p{margin-left:3em;}
.tight{margin-left:0;}
#spec{margin-left:15px;}
Compatibility
CSS 1, 2, 3 IE 4+ (buggy), 5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Elementsmayhavedefaultmarginsonthem,andthesevaluesmayvarybyuser
PART II
agent.Becauseofthisinconsistency,manydevelopersprefertoclearallmargins
withawildcardrulelike*{margin:0;}andbuildupindividualvalues.
margin-right
Thispropertysetsanelement’srightmargin.
Syntax
margin-right:length|percentage|auto|inherit
wherethelengthismeasuredinanyfixedmeasurement,suchasinches(in)orpixels(px),
andmaytakeanegativevalue.Apercentagevalueisdeterminedasapercentageofthewidth
ofthecontainingblock.Thedefaultvalueforthepropertyis0.
Examples
p{margin-right:1em;}
.tight{margin-right:0;}
#spec{margin-right:25px;}
Compatibility
CSS 1, 2, 3 IE 4+ (buggy), 5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Elementsmayhavedefaultmarginsonthem,andthesevaluesmayvarybyuser
agent.Becauseofthisinconsistency,manydevelopersprefertoclearallmargins
withawildcardrulelike*{margin:0;}andbuildupindividualvalues.
margin-top
Thispropertysetsanelement’stopmargin.
Syntax
margin-top:length|percentage|auto|inherit
wherethelengthismeasuredinanyfixedmeasurement,suchasinches(in)orpixels(px),
andmaytakeanegativevalue.Apercentagevalueisdeterminedasapercentageofthe
heightofthecontainingblock.Thedefaultvalueforthepropertyis0.
584 Part II: Core Style
Example
p{margin-height:3em;}
.tight{margin-height:0;}
#spec{margin-height:15px;}
Compatibility
CSS 1, 2, 3 IE 4+ (buggy), 5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Elementsmayhavedefaultmarginsonthem,andthesevaluesmayvarybyuser
agent.Becauseofthisinconsistency,manydevelopersprefertoclearallmargins
withawildcardrulelike*{margin:0;}andbuildupindividualvalues.
max-height
Thispropertydefinesthemaximumheightaregionmayexpandtoifitisrelativelysized.
Syntax
max-height:length|percentage|inherit
wherethevalueoflengthisgenerallyameasurementusingafixedvalue(forexample,100px).
Percentagesalsomaybeusedforrelativelayouts.Avalueofinheritindicatesthatthe
valueshouldbederivedfromanenclosingparent’svalue.
Examples
#div1{width:50%;max-width:800px;min-width:400px;
height:50%;max-height:1000px;}
#div2{height:100%;max-height:1200px;}
Compatibility
CSS 2, 3 IE 7+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
max-width
Thispropertydefinesthemaximumwidtharegionmayexpandtoifitisrelativelysized.
Syntax
max-width:length|percentage|inherit
wherethevalueoflengthisgenerallyameasurementusingafixedvalue(forexample,
100px).Percentagesalsomaybeusedforrelativelayouts.Avalueofinheritindicates
thatthevalueshouldbederivedfromanenclosingparent’svalue.
Examples
#div1{width:50%;max-width:800px;min-width:400px;}
#div2{width:80%;max-width:500px;}
Chapter 5: CSS Syntax and Property Reference 585
Compatibility
CSS 2, 3 IE 7+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
Note
• Whileinmanycasesmax-widthhasnotbeendeemedasimportantasmin-width,
itisquiteusefultoconstrainlargeregionsoftextfromhavingoverlylonglines,
whichcanresultinreadabilityproblems.
min-height
Thispropertydefinestheminimumheightaregionmayreducetoifitisrelativelysized
PART II
andthebrowserwindowisadjusted.
Syntax
min-height:length|percentage|inherit
wherethevalueoflengthisgenerallyameasurementusingafixedvalue(forexample,
100px).Percentagesalsomaybeusedforrelativelayouts.Avalueofinheritindicates
thatthevalueshouldbederivedfromanenclosingparent’svalue.
Examples
#div1{height:50%;max-height:400px;min-height:200px;}
#div2{height:80%;min-height:200px;}
Compatibility
CSS 2, 3 IE 7+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
Note
• InInternetExplorer6andothernonconformingolderbrowsers,JavaScriptand
variousCSStrickswereoftenemployedtoemulatethisproperty.
min-width
Thispropertydefinestheminimumwidtharegionmayreducetoifitisrelativelysizedand
thebrowserwindowisadjusted.
Syntax
min-width:length|percentage|inherit
wherethevalueoflengthisgenerallyameasurementusingafixedvalue(forexample,
100px).Percentagesalsomaybeusedforrelativelayouts.Avalueofinheritindicates
thatthevalueshouldbederivedfromanenclosingparent’svalue.
Examples
#div1{width:50%;max-width:800px;min-width:400px;}
#div2{width:80%;min-width:200px;}
586 Part II: Core Style
Compatibility
CSS 2, 3 IE 7+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
Note
• InInternetExplorer6andothernonconformingolderbrowsers,JavaScriptor
variousCSStrickswereoftenemployedtoemulatethisproperty.
orphans
Thispropertydefinestheminimumnumberoflinesofaparagraphthatmustbeleftatthe
bottomofapage.
Syntax
orphans:integer|inherit
Examples
#hateorphans{orphans:5;}
.orphaned{orphans:1;}
Compatibility
CSS 2, 3 IE 8+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
Notes
• Thispropertyisreallyonlymeaningfulinapagedenvironmentsuchasprint
output.
• Thedefaultvalueshouldbe2ifunspecified.
• Negativevaluesmaynotbeused.
outline
Thispropertyisashorthandformthatsetsalloutlinepropertiesatonce.
Syntax
outline:outline-coloroutline-styleoutline-width;
Theallowedvaluesaresimilartoborder.Themeaningofeachisdetailedineachindividual
propertythatfollows.Whileoutlinesaresimilartoborders,theirindividualsidescannotbe
set.Nomatterhowoutlinepropertiesaresettheyapplytothewholeoutlineandnot
individualsides.
Chapter 5: CSS Syntax and Property Reference 587
Whileoutlinesmayresembleborders,theytakeupnoadditionalspaceandmayoverlay
othercontentoutsideofablockifneedbe,asshownhere:
PART II
Becauseoutlinesaredrawnoveranitem,ratherthanaroundit,theycausenoreflow
whenapplieddynamically:
Alsonotethatoutlinescanappearasnonrectangulardependingonhowtheyaredrawn
arounditems:
588 Part II: Core Style
Examples
p:hover{outline:dashed1px;}
.test{outline:greensolid10px;}
Compatibility
CSS 2, 3 IE 8+ Firefox 1.5+ Opera 7+, Safari 1.2+
Notes
• OlderFirefox-andMozilla-basedbrowserslikeNetscape6+couldsetthisvalue
usingaproprietaryproperty–moz-outline.
• Theoutlineisthesameonallsides.Unlikeborders,thereisnosenseofoutline-
toporoutline-left.Thisapparentomissionshouldmakeperfectsensewhen
consideringnonrectangularoutlines.
• Thereisunclarityinthespecificationandimplementationonwhattodowith
overlappingoutlines,outlinesaroundemptyitems,andoutlinesthatmaysurround
partiallyobscuredelements.Beawareinsuchcasesofunclaritythatvisual
differencesmayoccur.Forexample,noticeherethatonebrowsercreatedtwo
separatedoutlineboxes,givenitsurroundsemptyelements,whereasinthe
previousillustrationtheemptyelementswereoutlined:
outline-color
Thispropertysetsthecolorofanelement’soutline.
Syntax
outline-color:color|invert|inherit
wherecolorisasupportedCSScolorvalue,asdiscussedearlierinthechapter.Thekeyword
invertisalsosupportedandshouldperformacolorinversiononthepixelsonthe
screen.Inotherwords,anybackgroundwouldbeinvertedfortheoutline:
Chapter 5: CSS Syntax and Property Reference 589
Inthecasewheretherearetwocolors,thiscanchangetheoutlineinvariouslocations.
Thefollowingexamplechangestheoutlineinonecasetoblackgivenawhitebackground
andchangesittobluegivenanorangebackground:
Examples
p:hover{outline-style:dashed;outline-color:green;outline-width:1px;}
PART II
.test{outline-width:10px;outline-style:solid;outline-color:#f00;}
.xray{outline-color:invert;}
Compatibility
CSS 2, 3 IE 8+ Firefox 1.5+ Opera 7+, Safari 1.2+
Notes
• Manybrowsersdonotsupporttheinvertvaluethesameandmayinvertbased
upononecolorinthecaseofmultiplecolorsfoundindifferentareasofanelement’s
background.
• OlderFirefox-andMozilla-basedbrowserslikeNetscape6+couldsetthisvalue
usingaproprietaryproperty–moz-outline-color.
outline-style
Thispropertydefinesastyleforanelement’soutline.
Syntax
outline-style:dashed|dotted|double|groove|inset|none|outset|
ridge|solid|inherit
Thevaluessupportedshouldbethesameaswhatisdefinedforborder-styleexceptthe
valuehiddenwhichisnotdefinedforthisproperty.
Examples
p:hover{outline-style:dashed;}
.test{outline-width:10px;outline-style:solid;outline-color:black;}
Compatibility
CSS 2, 3 IE 8+ Firefox 1.5+ Opera 7+, Safari 1.2+
Notes
• OlderFirefox-andMozilla-basedbrowserslikeNetscape6+couldsetthisvalue
usingaproprietaryproperty–moz-outline-style.
590 Part II: Core Style
• Seetheentryfortheborder-stylepropertyforavisualexampleofeachoutline
style.
• Outlinesmaynotpresentthemselvesasboxes,asborderstendtodo,becausethey
maywrapirregularlyshapedelements;seetheentryforoutlineforavisual
exampleofthis.
outline-width
Thispropertydefinesawidthforanelement’soutline.
Syntax
outline-width:length|medium|thick|thin|inherit
Likeborder-width,thisproperty’svaluescanbekeywords(thin,medium,orthick)and
numericallengthssuchaspixels(px),inches(in),andsoon.
Examples
p{outline-style:dashed;outline-width:thick;}
.test{outline-width:10px;outline-style:solid;outline-color:black;}
Compatibility
CSS 2, 3 IE 8+ Firefox 1.5+ Opera 7+, Safari 1.2+
Notes
• OlderFirefox-andMozilla-basedbrowserslikeNetscape6+couldsetthisvalue
usingaproprietaryproperty–moz-outline-width.
• Asdescribedintheentryforoutline,whensettingoutline-widththeoutline
shouldnottakeupcanvasspaceandmayoverlapotherelements.
overflow
Thispropertydeterminesanelement’sbehaviorwhenitscontentdoesn’tfitintothespace
definedbytheelement’sotherproperties.
Syntax
overflow:auto|hidden|scroll|visible|inherit
Bydefault,contentwillbevisible,butavalueofhiddenwillclipcontentthatextendspast
thedefinedregionsize.Avalueofscrolladdsscrollbarsappropriatelysothatcontent
Chapter 5: CSS Syntax and Property Reference 591
canbeviewed.Avalueofautoallowstheuseragenttodecidehowtohandlecontent
thatoverflows.Thefollowingillustrationshouldmakethemeaningofthevaluesclear:
Visible Hidden
PART II
Scroll Auto
Examples
#div1{position:absolute;left:20px;top:20px;
width:100px;height:100px;overflow:scroll;}
#div2{height:100px;width:100px;overflow:hidden;}
Compatibility
CSS 2, 3 IE 4–5.5 (buggy), 6+ Netscape 4–4.8 (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
padding
Thepaddingpropertysetsthespacebetweenanelement’sborderanditscontent.
Syntax
padding:padding1[...padding4]|inherit
592 Part II: Core Style
whereeachpaddingvalueiseitheralength,percentage,auto,orinheritvalue.Asa
shorthandform,itispossibletosetthefourpaddingvalues(padding-top,padding-right,
padding-bottom,andpadding-left)independentlywiththisproperty:
margin
border
1 padding-top
4 2
padding-right
padding-left
Content
3 padding-bottom
Thepaddingshorthandpropertyissimilartomargin.Asinglevaluecreatesequal
paddingonallsides.Uptofourvaluescanbeused,inthefollowingclockwiseorder:
padding-top,padding-right,padding-bottom,andpadding-left.Anymissingvalue
defaultstothevaluedefinedforthesideoppositetoit.However,unlikethemargin
property,thepaddingpropertycannottakenegativevalues.
Examples
#div1{border-style:solid;padding:10px20px10px5px;}
/*allsidesdifferent*/
#div2{border-style:dashed;padding:50px;}
/*paddingof50pxonallsides*/
#div3{padding:10px20px;}
/*topandbottom10pxandleftandright20pxpadding*/
#div4{padding:5px10px15px;}
/*top5px,rightandleft10pxandbottom15px*/
Compatibility
CSS 1, 2, 3 IE 4+ (buggy), 5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Chapter 5: CSS Syntax and Property Reference 593
Note
• Elementsmayhavedefaultpaddingonthem,andthesevaluesmayvarybyuser
agent.Becauseofthisinconsistency,manydevelopersprefertoclearallpadding
valuesgloballywithawildcardrulelike*{padding:0;}andbuildup
individualvalues.
padding-bottom
Thispropertysetsthedistancebetweenanelement’sbottomborderandthebottomofits
containedcontent.
Syntax
PART II
padding-bottom:length|percentage|auto|inherit
wherethelengthismeasuredinanyfixedmeasurement,suchasinches(in)orpixels.A
percentagevalueisdeterminedasapercentageoftheheightofthecontainingblock.The
defaultvalueforthepropertyis0.
Examples
p{padding-bottom:10pt;}
.tight{padding-bottom:0;}
#ex2{padding-bottom:10%;}
Compatibility
CSS 1, 2, 3 IE 4+ (buggy), 5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Elementsmayhavedefaultpaddingsonthem,andthesevaluesmayvarybyuser
agent.Becauseofthisinconsistency,manydevelopersprefertoclearallpadding
valuesgloballywithawildcardrulelike*{padding:0;}andbuildup
individualvalues.
padding-left
Thispropertysetsthedistancebetweenanelement’sleftborderandtheleftedgeofits
content.
Syntax
padding-left:length|percentage|auto|inherit
wherethelengthismeasuredinanyfixedmeasurement,suchasinches(in)orpixels(px).A
percentagevalueisdeterminedasapercentageofthewidthofthecontainingblock.The
defaultvalueforthepropertyis0.
Example
p{padding-left:20px;}
.tight{padding-left:0;}
#ex8{padding-left:40%;}
594 Part II: Core Style
Compatibility
CSS 1, 2, 3 IE 4+ (buggy), 5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Elementsmayhavedefaultpaddingsonthem,andthesevaluesmayvarybyuser
agent.Becauseofthisinconsistency,manydevelopersprefertoclearallpadding
valuesgloballywithawildcardrulelike*{padding:0;}andbuildupindividual
values.
padding-right
Thispropertysetsthedistancebetweenanelement’srightborderandtherightmostedgeof
itscontent.
Syntax
padding-right:length|percentage|auto|inherit
wherethelengthismeasuredinanyfixedmeasurement,suchasinches(in)orpixels(px).A
percentagevalueisdeterminedasapercentageofthewidthofthecontainingblock.The
defaultvalueforthepropertyis0.
Example
p{padding-left:10px;padding-right:50px;}
.flush{padding-right:0;}
#demo{padding-right:50%;}
Compatibility
CSS 1, 2, 3 IE 4+ (buggy), 5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Elementsmayhavedefaultpaddingsonthem,andthesevaluesmayvarybyuser
agent.Becauseofthisinconsistency,manydevelopersprefertoclearallpadding
valuesgloballywithawildcardrulelike*{padding:0;}andbuildup
individualvalues.
padding-top
Thispropertysetsthedistancebetweenanelement’stopborderandthetopofitscontent.
Syntax
padding-top:length|percentage|auto|inherit
wherethelengthismeasuredinanyfixedmeasurement,suchasinches(in)orpixels(px).
Apercentagevalueisdeterminedasapercentageoftheheightofthecontainingblock.The
defaultvalueforthepropertyis0.
Chapter 5: CSS Syntax and Property Reference 595
Example
p{padding-top:10px;padding-bottom:100px;}
.flush{padding-top:0;}
#demo2{padding-top:50%;padding-left:10%}
Compatibility
CSS 1, 2, 3 IE 4+ (buggy), 5+ Netscape 4+ (buggy), 6+, Firefox 1+ Opera 4+, Safari 1+
Note
• Elementsmayhavedefaultpaddingsonthemandthesevaluesmayvarybyuser
PART II
agent.Becauseofthisinconsistency,manydevelopersprefertoclearallpadding
valuesgloballywithawildcardrulelike*{padding:0;}andbuildup
individualvalues.
page-break-after
Thispropertyisusedtocontrolpagebreakswhenprintingadocumentafterthebound
elementboxends.
Syntax
page-break-after:always|auto|avoid|left|right|inherit
Avalueofalwaysforcesapagebreakaftertheassociatedelement.Avalueofavoid
attemptstoavoidapagebreakaftertheelement.Avalueofleftforcesoneortwopage
breaksaftertheelementsothatthenextpageisconsideredaleftpage.Avalueofright
forcesoneortwopagebreaksaftertheelementsothenextpageisconsideredarightpage.
Thedefaultvalueofautoneitherforcesnorforbidsapagebreak,allowingtheuseragentto
decidehowtobreakthecontentduringprint.
Examples
#breakitdown{page-break-after:always;}
.getitright{page-break-after:right;}
Compatibility
CSS 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
page-break-before
Thispropertyisusedtocontrolpagebreakswhenprintingadocumentbeforethebound
elementboxstarts.
Syntax
page-break-before:always|auto|avoid|left|right|inherit
Avalueofalwaysforcesapagebreakbeforetheassociatedelementisencountered.Avalue
ofavoidattemptstoavoidapagebreakaftertheelement.Avalueofleftforcesoneor
twopagebreaksaftertheelementsothatthenextpageisconsideredaleftpage.Avalueof
596 Part II: Core Style
rightforcesoneortwopagebreaksaftertheelementsothenextpageisconsideredaright
page.Thedefaultvalueofautoneitherforcesnorforbidsapagebreak,allowingtheuser
agenttodecidehowtobreakthecontentduringprint.
Examples
#breakitdownagain{page-break-before:always;}
.lefty{page-break-before:left;}
Compatibility
CSS 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
page-break-inside
Thispropertyisusedtoforceorprohibitaprintingpagebreakwithinanelement.
Syntax
page-break-inside:always|auto|avoid|left|right|inherit
Avalueofalwaysforcesapagebreakatanyplacewithintheelementbound.Avalueof
avoidattemptstoavoidapagebreakaftertheelement.Avalueofleftforcesoneortwo
pagebreaksaftertheelementsothatthenextpageisconsideredaleftpage.Avalueof
rightforcesoneortwopagebreaksaftertheelementsothenextpageisconsideredaright
page.Thedefaultvalueofautoneitherforcesnorforbidsapagebreak,allowingtheuser
agenttodecidehowtobreakthecontentduringprint.
Examples
#breakitdownyetagain{page-break-inside:always;}
.nobreaks{page-break-inside:avoid;}
Compatibility
CSS 2, 3 IE 8+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
position
Thispropertydefineshowanelementispositionedrelativetootherelements.
Syntax
position:absolute|fixed|relative|static|inherit
Whenpositionedabsolute,theleft,right,top,andbottompropertiescanbeusedto
definetheelement’spreciselocation,usingtheaffectedelement’supper-leftcorner(0,0)as
reference.Becauseelementscancontainotherelements,apositionof0,0isnotnecessarily
theupper-leftcornerofthebrowser.Whenarelativepositionisused,offsetswillbe
relatedtotheobject’snaturalpositioninthedocumentflow.Anelementwithabsolute
positionmaybesettodefinedcoordinatesbutwillscrollwithawindow.However,an
objectwithafixedpositionvaluewillstayinpositiononscreenasthingsscroll.
Chapter 5: CSS Syntax and Property Reference 597
Thedefaultvalue,static,placeselementsaccordingtothenaturalorderinwhichthey
occurinadocument,andrelatedtop,right,left,andbottompropertiesdonotrelate.
Examples
#region1{position:relative;left:190px;top:30px;}
#region2{position:absolute;left:120px;top:50px;}
#left{position:absolute;bottom:10;right:500px;}
#norm{position:static;}
#navbar{position:fixed;left:0;top:0;}
Compatibility
PART II
CSS 2, 3 IE 4–6 (partial), IE 7+ Netscape 4–4.8 (partial), Opera 5+, Safari 1+
Netscape 6+, Firefox 1+
Notes
• Fixedregionscanbeusefulforpeggingnavigationelementsonscreentoavoid
needlessscrolling.
• ThefixedpositionvaluewasnotsupportedinInternetExplorer6without
JavaScriptoroddCSShacking.ThissignificantproblemwasaddressedinIE7+.
quotes
Thispropertydefinesthestyleofquotationmarkstobeusedwithembeddedquotations.
Syntax
quotes:quote-pair1...quote-pairN|none|inherit
whereeachquote-pairisasetoftwostrings,thefirstfortheopenquotevalueandthe
secondfortheclosequotevalue.Havingmorethanonequote-pairallowsdevelopersto
specifydifferentquotesymbolsforeachlevelofnesting.Avalueofnoneproducesno
quotationmarks.
Examples
blockquote{quotes:'<''>';}
q{quotes:none;}
p.exampleq{quotes:'['']''<''>';}
/*thefinalrulewouldaddress
nestedqtagslikebelow*/
<pclass='example'>Hey<q>Youcan<q>quote</q>me</q>onthis.</p>
Compatibility
CSS 2, 3 IE 8+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
Note
• Becarefulwiththeimplicitapplicationornotofquotesforqelements.
598 Part II: Core Style
right
Thispropertydefinesthex(horizontal)coordinateforapositionedelement,relativetothe
rightsideofeitherthecontainingelementorbrowserwindowifdirectlywithinthe<body>.
Syntax
right:length|percentage|auto|inherit
wherelengthcanbespecifiedinthestandardunitsoflength,suchasinches(in)andsoon,
butisnearlyalwayssetinpixels(px),andpercentagecorrespondstoapercentageofthe
containingobject’sdimensions.Thedefaultvalueautoletsthispropertyfunctionas
placingtheobjectwhereitnormallywouldfallinthedocumentflow.Forrelativeposition,
thiswilllikelybetreatedas0.Forabsoluteandfixedpositioning,itwillcalculateavalue
baseduponothersetproperties,particularlyleft.
Examples
#div1{position:absolute;right:100px;top:150px;}
#div2{position:absolute;right:50%;bottom:30%;}
#div3{position:absolute;left:10px;right:auto;}
/*rightwillevaluatetoapositioncalculatedofftheleftposition*/
#sideBar{position:fixed;right:0;top:0;width:200px;height:100%;}
Compatibility
CSS 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 6+, Safari 1+
Note
• Browserstendtoassumepixelmeasurementsifalengthunitisnotset.
table-layout
Thispropertycontrolsthealgorithmusedtolayoutthetablecells,rows,andcolumns.
Syntax
table-layout:auto|fixed|inherit
Avalueoffixedusesthefixedtablelayoutalgorithm,whichrelaysnotthecontentofthe
cellsbutsimplythewidthofthetables,columns,borders,anddefinedcellspacing.This
shouldresultinfasterpagerendering.Thedefaultvalueofautousesthestandardautomatic
tablelayoutalgorithm,whichmayrequiremultiplepassesortakeperceptibletimetocalculate,
particularlywhenthetableiscomplexorheavilynested.
Examples
table.fast{table-layout:fixed;}
table.slow{table-layout:auto;}
Chapter 5: CSS Syntax and Property Reference 599
Compatibility
CSS 2, 3 IE 5+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
text-align
Thispropertysetsthehorizontalalignmentofelements.
Syntax
text-align:center|justify|left|right|inherit
wherethekeywordvaluesalignthetextofanelementappropriatelyleft,rightorcenter.
PART II
Avalueofjustifywilljustifytextonleftorrightsidedependingondocumentreading
direction.Avalueofinheritwillderivethispropertyvaluefromanenclosingparent.
Examples
.goleft{text-align:left;}
p.just{text-align:justify;}
h1.centered{text-align:center;}
Compatibility
CSS 1, 2, 3 IE 3, 4 (no justify), 5+ Netscape 4 (quirky), 6+, Firefox 1+ Opera 4+, Safari 1+
Notes
• Thedefaultvalueforthepropertywilldependonlanguagereadingdirection,so
leftwhenitislefttorightandrightwhenitisrighttoleft.
• Thispropertyissimilartothealignattributeavailablewith(X)HTMLblock-level
tagssuchas<p>.
• Justificationmayproducepoorresults,showingwhitespace“rivers”inlargetext
bodiesbecauseofscreenresizing.
text-decoration
Thispropertydefinesorevenremovesvariousinlinetexteffects.
Syntax
text-decoration:blink|inherit|line-through|none|overline|underline
whereline-throughpresentsaffectedtextasstruck-thru,overlineastextwithaline
overit,underlineasunderlinedtext,andblink(whensupportedbyabrowser)blinks
thetext.Avalueofinheritwillderivethispropertyvaluefromanenclosingelement,
whileavalueofnonewilloverrideit.
Example
a{text-decoration:none;}
a:visited{text-decoration:line-through;}
a:hover{text-decoration:underline;}
600 Part II: Core Style
.onsale{text-decoration:blink;}
.underlined{text-decoration:underline;}
.struck{text-decoration:line-through;}
Compatibility
CSS 1, 2 IE 4+ Netscape 4+ (incomplete), Opera 4+, Safari 1+
Netscape 6+ (complete), Firefox 1+
Notes
• Manyuseragentschoosenottosupporttheblinkvalueforthisproperty.Actionis
topresentthetextnormally.Atthetimeofthiswriting,IEbrowsers(8orless)and
Safaribrowsers(3orless)donotsupporttheblinkvalue.
• Thetext-decorationpropertyisoftenusedwiththeaelementanditsassociated
pseudo-classes(a:active,a:hover,a:link,anda:visited)toturnofflink
underliningorsetdifferentlooksforhoverorvisitedstates.Pageauthorsconcerned
aboutaccessibilityshouldbecarefultoprovidealternateindicatorssuchasposition
orstyleifunderlinesareremoved.
text-indent
Thispropertyspecifiestheindentinthefirstlineofablock-levelelement.
Syntax
text-indent:length|percentage|inherit
wherelengthisastandardlengthunit(10px),apercentageisapercentagevaluerelativeto
theenclosingelement,andinheritderivesthevalueofthepropertyfromsomeparent
element.
Examples
p{text-indent:.5em;}
.bigDent{text-indent:50px;}
.negDent{text-indent:-20px;}
#section1{text-indent:15%;}
Compatibility
CSS 1, 2, 3 IE 3+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
Notes
• Thispropertyappliestoblockelements,tablecells,andinlineblocktypes.
• Thedefaultvalueis0,whichindicatesnoindentation.
text-transform
Thispropertytransformsthecaseoftheaffectedtext.
Chapter 5: CSS Syntax and Property Reference 601
Syntax
text-transform:capitalize|lowercase|none|uppercase
Avalueofcapitalizewilluppercasetheinitialletterofeveryspaceseparatedwordin
theelementappliedto,whilelowercaseanduppercasewillforceallaffectedletters
correspondingly.Avalueofnonewilloverrideanytext-transformvaluesthatmaybe
inherited,leavingthetextaswritteninthemarkup.
Examples
h1{text-transform:capitalize;}
h1.nocap{text-transform:none;}
PART II
.allsmall{text-transform:lowercase;}
#bigletters{text-transform:uppercase;font-size:larger;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4 (incomplete for Mac), 4.5+, Firefox 1+ Opera 6+, Safari 1+
Note
• Thevalueofnoneisusedtooverrideanyinheritedtext-transformvalues.
top
Thispropertydefinesthey(vertical)coordinateforapositionedelement,relativetothetop
oftheenclosingobjectorbrowserwindow.
Syntax
top:length|percentage|auto|inherit
wherelengthcanbespecifiedinthestandardunitsoflength,suchasinches(in)andsoon,
butisnearlyalwayssetinpixels(px),andpercentagecorrespondstoapercentageofthe
containingobject’sdimensions.Thedefaultvalueautoletsthispropertyfunctionas
placingtheobjectwhereitnormallywouldfallinthedocumentflow.Forrelativeposition,
thiswilllikelybetreatedas0.Forabsoluteandfixedpositioning,itwillcalculateavalue
baseduponothersetproperties,particularlybottom.
Examples
#div1{position:absolute;left:100px;top:150px;}
#div2{position:absolute;left:50%;top:30%;}
#div3{position:absolute;left:10px;bottom:5px;top:auto;}
/*topwillevaluatetoapositioncalculatedoffthebottomposition*/
#navBar{position:fixed;left:0;top:0;}
Compatibility
CSS 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 6+, Safari 1+
602 Part II: Core Style
Note
• Browserstendtoassumepixelmeasurementsifalengthunitisnotset.
unicode-bidi
Thispropertyallowsthetextdirectiontobeoverriddentosupportmultiplelanguagesand
textflowdirectionsinthesamedocument.
Syntax
unicode-bidi:bidi-override|embed|normal|inherit
Thevaluenormalusesthestandarddirectionandrendering.Avalueofembedallowsa
newlevelofembeddingtochangedirection,whilebidi-overrideallowsthedirection
propertytooverrideanypredefineddirection.
Example
<div>Iwasnormalandsuddenly<spanstyle="unicode-bidi:embed;
direction:rtl;background-color:yellow;">heredoingIamWhat!</span>
Thisistheendofthetest.</div>
Compatibility
CSS 2, 3 IE 4+ Netscape 6+, Firefox 1+ Opera 6+, Safari 1+
Note
• Unicodemaylimit61levelsofembedding,sodonotnestembedelementsdeeply.
vertical-align
Thispropertysetstheverticalpositioningoftextandimageswithrespecttothebaseline
setting.
Syntax
vertical-align:baseline|bottom|middle|sub|super|text-bottom|
text-top|top|percentage|length|inherit
Avalueoftopalignsthetopoftextorimageswiththetopofthetallestelement,relativeto
thebaseline.Avalueoftext-topalignsthetopoftextorimageswiththetopofthefontin
thecontainingelement,whiletext-bottomalignsthingswiththebottomofthefont.A
valueofmiddlealignsthemiddleoftextorimagestothemiddleofthex-heightofthe
containingelement.Avalueofbottomalignsthebottomoftextorimageswiththebottomof
thelowestelement,relativetothebaseline.Thesubandsupervaluesprovidesubscriptand
superscriptstyle.Positiveandnegativepercentagesandlengthvaluescanbeused,with
positivevaluesraisingthetextandnegativevaluesloweringthetextrelativetothebaseline.
Thedefaultvalueisbaseline,whichisalsoequivalentto0or0%.
Chapter 5: CSS Syntax and Property Reference 603
Examples
p{vertical-align:top;}
.dive{vertical-align:sub;}
.climb{vertical-align:super;}
#bump{vertical-align:10%;}
#lower{vertical-align:-1em;}
Compatibility
CSS 1, 2, 3 IE 4, 5 (problems), 5.5+ Netscape 4 (poor support), Opera 4+, Safari 1+
Netscape 6+, Firefox 1+
PART II
Note
• Evenwhenproperlysupportedinbrowsers,verticalalignmentchangeswill
potentiallybumplinesaboveorbelowthebaseline,causingpotentiallyundesirable
formattingchanges.
visibility
Thispropertydetermineswhetherornotanelementisvisible.
Syntax
visibility:collapse|hidden|inherit|visible
Examples
p{visibility:inherit;}
.invisible{visibility:hidden;}
.visible{visibility:visible;}
Compatibility
CSS 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
Notes
• Thedefaultvalueofinheritspecifiesthatthevisibilitystateisinheritedfromthe
containingparent.
• Thispropertyisnotthesameasdisplay:noneasitsimplymakestheiteminvisible;
itdoesnotcompletelyremoveitfromthedisplaycanvas.Thefollowingexample
demonstratesthis:
604 Part II: Core Style
However,thisdistinctionmaynotmatterwhenanappropriatez-indexvaluehasmade
thehiddenobject.
• ThispropertyiscommonlyusedwithJavaScripttoshow/hideanelementor
performcertaindynamiceffects.
• TheCSS2specificationintroducedthecollapsevalueforthispropertyforuse
withtablerowsandcolumnstocollapsecells.Whenthevalueisusedonother
elementsitshouldactlikethevalueofhidden.
white-space
Thispropertycontrolshowspaces,tabs,andnewlinecharactersarehandledinanelement.
Syntax
white-space:normal|pre|nowrap|pre-wrap|pre-line|inherit
Thenormalvaluecollapsesmultiplewhitespacecharactersintosinglespacesand
automaticallywrapslines,asinnormalHTML/XHTML.Theprevaluemakestheelement
actmuchlikea<pre>tagandpreservesallwhitespace.Thevalueofnowrappreventslines
fromwrappingiftheyexceedtheelement’scontentwidth.Thevalueofpre-linecollapses
whitespace,savenewlines,whicharepreserved.Thevalueofpre-wrapbreaksnewlines
thatwouldcausetexttobreakoutofanelement’sbox;otherwise,itactslikeaprevalue.
Examples
p{white-space:pre;}
pre{white-space:normal;}/*changepreabadidea*/
.sourcecode{white-space:nowrap;}
.lovereturns{white-space:pre-line;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4+ (partial), Firefox 1+ Opera 4+, Safari 1+
Note
• Thevaluesofpre-wrapandpre-linearenotsupportedinolderbrowsers.
widows
Thispropertydefinestheminimumnumberoflinesinaparagraphtobeleftatthetopof
apage.
Syntax
widows:integer|inherit
Chapter 5: CSS Syntax and Property Reference 605
Examples
#hatewidows{widows:5;}
.widowmaker{widows:1;}
Compatibility
CSS 2, 3 IE 8+ Netscape 6+, Firefox 1+ Opera 7+, Safari 1+
Notes
• Thispropertyisreallyonlymeaningfulinapagedenvironment,suchasprint
output.
PART II
• Thedefaultvalueshouldbe2ifunspecified.
• Negativevaluesmaynotbeused.
width
Thispropertysetsthewidthofanelement’scontentregion(excludingpadding,border,
andmargin).
Syntax
width:length|percentage|auto|inherit
Standardpositivelengthunitscanbeused,andpixels(px)isoftentheassumedmeasurement
inbrowsers.Percentagevalues,basedonthewidthofthecontainingelement,canalsobe
used.Thedefaultvalueofautoautomaticallycalculatesthewidthofanelement,basedon
thewidthofthecontainingelementandthesizeofthecontent.
Examples
p{width:400px;padding:10px;border:solid5px;}
#div1{width:80%;padding:10px;border:solid5px;}
Compatibility
CSS 1, 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
Notes
• Theactualsizeofanobjectonabrowsercanvasisnotsolelydefinedbythewidth
property,asvaluesforbordersandpaddingaffectthespacetaken.Forexample,
giventheCSSrulehere
#div1{width:200px;padding:30px;border:solid20px;}
606 Part II: Core Style
thewidthoftheboundcontentitselfmaybe200pxbuttheoverallcanvasspace
consumedis300pxtoaccountforthebordersandpadding:
20 30 30 20
200 px
px px px px
300 px
word-spacing
Thispropertysetsthespacingbetweenwords.
Syntax
word-spacing:length|normal|inherit
Lengthvaluescanbesetinanyallowedmeasurementlikeinches(in),centimeters(cm),
millimeters(mm),points(pt),picas(pc),emspaces(em),orpixels(px).Negativevaluesare
possiblewiththisproperty,andmaybeusedforinterestingtypographicaleffects.Thedefault
valueofnormalsetswordspacingtothestandardbrowsersetting.
Examples
p{font-family:Arial;font-size:16pt;word-spacing:3pt;}
p.normal{font-family:Helvetica;font-size:12pt;word-spacing:normal;}
.carson{word-spacing:-5px;}
Compatibility
CSS 1, 2, 3 IE 4–7 (partial or buggy), IE 8+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
Chapter 5: CSS Syntax and Property Reference 607
z-index
Thispropertydefinesalayeringorstackingcontextforpositionedelements.
Syntax
z-index:integer|auto|inherit
Bydefault,overlappingpositionedelementsstackintheorderinwhichtheyaredefinedin
amarkupdocument.Thispropertycanoverridedefaultlayeringbyassigningnumeric
layeringvaluestoanelement,withhighernumberslayeringabovelowernumbers.Negative
numbersareallowed.Theautovaluetriestodeterminethez-placementofanelement
automaticallybyitsmarkuppositioninthedocument.
PART II
Examples
#div1{position:absolute;top:20px;left:20px;height:50px;width:50px;
background-color:blue;z-index:2;}
#stayDown{z-index:-10;}
Compatibility
CSS 2, 3 IE 4+ Netscape 4+, Firefox 1+ Opera 4+, Safari 1+
Notes
• Whennestingobjectsarenestedposition-wise,notethateachindividualpositioned
boxmaintainsitsownstackingcontext,with0beingthedefaultz-indexlevel.
• Itisawiseideanottousecontiguousz-indexvalues,sothatitiseasytoinsert
betweenobjects.
Part II:
far-left|left| sound appears to emanate from
center-left|center| using a horizontal orientation. p.stage2{azimuth:320deg;}
center-right| An angle value is specified
right|far-right| using the unit deg (degrees)
right-side|behind| in a 360-degree circle, with
Core Style
leftwards|rightwards| keywords mapping to particular
inherit angle values.
cue cue-beforecue-after| A shorthand notation that #page{cue:url(enter.wav)
inherit allows both the cue-before url(exit.wav);}
and cue-after values to be
set at once. Generally, auditory
cues are used to alert listeners
to important content or other
context change.
cue-after url(soundfile)|none| Plays an auditory cue, specified #theEnd{cue-after:url
inherit by the URL, after reading the (exit.wav);}
bound element.
cue-before url(soundfile)|none| Plays an auditory cue, specified #page1{cue-before:url
inherit by the URL, before reading the (enter.wav);}
bound element.
elevation angle|below|level| Like azimuth, used in defining #voiceFromAbove
above|higher| the position of the sound, but {elevation:above;}
lower|inherit this time vertical orientation.
Elevation angles range from #above{elevation:90deg;}
-90deg to +90deg, with 0 being
straight ahead on the horizon.
Chapter 5:
value operates off the speech
rate.
pause- time|percentage| Defines how long a pause #jump{pause-before:2s;}
before inherit should happen before reading
some element. Time is
presented in seconds (s) or
609
PART II
610
Aural Property Allowed Values Description Example(s)
play-during url(soundfile)[mix| Defines a sound that should be play-during:url(holdmusic.wav)
Part II:
repeat]|auto|none| played in the background while mixrepeat;}
inherit an element is being spoken.
A value of none suppresses
any playing sound that may
have been inherited. A value
Core Style
of mix can be set to indicate
the playing sound may mix with
inherited sounds; otherwise,
the playing sound replaces any
currently playing sounds. When
a value of repeat is present,
the sound will repeat if the time
of reading is longer than the
background sound.
richness number|inherit Specifies the richness or power .boom{richness:80;}
of a speaking voice in a range
from 0 to 100. The higher the
value, the more powerful the
voice.
speak normal|none|spell- Defines if text should be .dictate{speak:spell-out;}
out|inherit spoken or not. A value of none .silent{speak:none;}
suppresses aural playback. A
value of normal is standard
reading, and spell-out has
individual letters spoken one at
a time, which is generally only
appropriate when spelling out
acronyms or abbreviations.
speak- once|always| Specifies if, when reading tableth{speak-header:once;}
header inherit tables, cell headers should be
spoken every time or only once
when the table is started.
Chapter 5:
faster|slower| and the keywords correspond
inherit to various numeric rates.
stress number|inherit Defines the height of local #tap{stress:90;}
peaks of intonation of a voice.
The number should range
between 0 and 100, with
611
PART II
612 Part II: Core Style
TIP Moredetailsonthesepropertiescanbefoundatwww.w3.org/TR/CSS21/aural.html.
TIP Whileauralpropertiesmayseemtohavelittleuseinvisualpresentation,someCSSauthorslike
touseauralstylesheetrulestoconfusecertainbrowserversionstooverloadproperties,suchas
whattheBoxModelhackdoes.Thistechniqueisnotsuggestedandscriptinglogicshouldbe
usedinstead.
CSS3hasalsotakenupthecauseofauralstylesheetswithitsSpeechmodule
(www.w3.org/TR/css3-speech/).Itintroducesnewvaluestoimprovepronunciation,like
phonemes,butalsoseemstosimplyrenamefeatures;forexample,stressbecomes
voice-stress,pitchbecomesvoice-pitch,andvolumebecomesvoice-volume.The
onlybrowsersthathaveanysenseofsupportforthisareexperimentalversionsofOpera
onWindows,andhereyoumayrequirea-xv-prefix;forexample,–xv-voice-stress
insteadofvoice-stress.
Therenamingeffortregardlessofprefixseemsonlyhelpfulinthefewplaceswhere
auraltermsmightbeambiguouswhenmixedwithotherpresentation.However,givenhow
littlespeech-browsingtechnologyexists,andnotingthatwhichdoesexistoftenignores
aural-focusedCSSproperties,lookingevenfurtheraheadtoCSS3mightseemtobeabitof
awasteoftime.
CHAPTER
6
CSS3 Proprietary and
Emerging Features Reference
T
hischapteraimstoprovideacompletereferencefortheemergingCSS3and
proprietaryCSSpropertiessupportedinmodernbrowsers.However,giventhe
constantfluxinCSSpropertysupportandthecontinuedintroductionofnew
features,readersaredulywarnedtousethismaterialasajumpingoffpointtoexplorethe
lateststylingfeatures.
CSS3 Selectors
CSS3hasgonesomewhatoverboardwithitsintroductionofnewselectors,makingselector
syntaxattimespotentiallyquiteconfusing,particularlywhenchainedexcessively.Table6-2
summarizestheselectorsyntaxfromtheCSS3SelectorSpecificationthatisdifferentfrom
CSS1and2.1selectorsyntax.ThestandardCSS1and2selectorsarenotrepeatedhere
becausethefocusissolelyonwhatisdifferentinCSS3.
613
614 Part II: Core Style
PART II
same name (<marquee>). See the entries
for marquee-direction, marquee-
play-count, marquee-speed, and
marquee-style later in the chapter.
Media Queries Defines CSS syntax for applying different www.w3.org/TR/css3-mediaqueries
style rules based upon media or device
characteristics, such as width or color
support, avoiding the use of JavaScript
to reapply style. See the section “Media
Queries” later in the chapter for syntax and
examples.
Multi-column Defines how to flow text into many columns. www.w3.org/TR/css3-multicol
Layout
Namespaces Defines syntax to allow the disambiguation www.w3.org/TR/css3-namespace
of elements from different markup
languages found within the same document
for styling purposes.
Paged Media Defines how pagination is performed, www.w3.org/TR/css3-page
particularly with print output.
Presentation Defines the concept of applying www.w3.org/TR/css3-preslev
Levels presentation levels to style elements in
different manners depending upon the
situation.
Ruby Defines the CSS-handling aspects of www.w3.org/TR/css3-ruby
Ruby texts, which are used to provide
pronunciation or alternate readings in East
Asian languages.
Selectors Defines the various selectors for standard www.w3.org/TR/css3-selectors
CSS1 and CSS2 and introduces numerous
complex tree- and attribute-specific syntax.
NOTE Version8InternetExplorerbrowsersstilldonotfullysupportmostCSS3properties,
including::before,::after,::first-letter,::first-line,:root,:last-
child,:only-child,:nth-child(),:nth-last-child(),:first-of-type,
:last-of-type,:only-of-type,:nth-of-type(),:nth-last-of-type(),:empty,
:not(),and:target.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 617
PART II
E[attr$=value] Selects all elements of E p[title$="!"]{color:red;}
that have the attribute attr /*setsthecolortoredifthetitle
that end with the given endswithanexclamationmark*/
value.
E[attr*=value] Selects all elements of E p[title*="CSS"]{font-style:italic;}
that have the attribute attr /*setsthefontstyletoitalicin
that contains the given anyptagthathasCSSinitstitle
value. */
::after Same as :after; div::after{content:url(sectionend
changed under CSS3 to .gif);}
make pseudo-elements /*insertsthesectionend.gifimage
obvious. immediatelyfollowingalldivtags*/
::before Same as :before; div::before{content:
changed under CSS3 to url(sectionstart.gif);}
make pseudo-elements /*insertsthesectionstart.gifimage
obvious. beforealldivtags*/
:checked Selects the elements that :checked{color:blue;}
are checked. /*setsthecolortoblueifan
elementischecked*/
:default Selects the elements that :default{background-color:red;}
are the default among a /*setsthebackgroundcolorofa
set of similar elements. defaultbuttonlikeasubmittored
*/
:disabled Selects the elements that input:disabled{background-color:
are currently disabled. gray;}
/*setsthebackgroundcolortogray
ondisabledinputelements*/
:empty Selects an element that div:empty{display:none;}
has no children. /*hidesthedivifithasno
children*/
PART II
the only child of its parent /*setsthepelementtobeboldif
with its type. itistheonlyptagchildofits
parent*/
:root Selects the element that is :root{background-color:blue;}
the root of the document. /*setsthebackgroundcolortoblue
fortherootelement*/
::selection Selects the part of the #test::selection{color:red;
element that is currently background-color:yellow;}
selected. Supported /*makesthetextredwithayellow
in Firefox as ::-moz- backgroundwhenselected*/
selection as well.
Use to set color and
background-color (or
background) only with
this selector.
:target Selects the element that :target{color:red;}
is the target of a referring /*iftheelementisthetargetof
URI. thereferringURI,thecolorisset
tored*/
PART II
the character 0 (zero) in the
current font.
deg Degrees transform:scale(1.0)rotate(0deg);
dpcm Dots per centimeter @mediaprintand(resolution:
100dpcm){/*somerules*/}
dpi Dots per inch (used in media @mediaprintand(resolution:300dpi)
queries). {/*somerules*/}
gr The distance between grid #img1{width:2gr;}
lines.
grad Grads #at90deg{elevation:100grad;}
Hz Hertz #barrywhite{pitch:70Hz;}
kHz Kilohertz #treble{pitch:6kHz;}
ms Milliseconds #a1{transition-property:color;
transition-duration:500ms;}
rad Radians #voiceAbove{elevation:50rad;}
rem The font size of the #innerP{font-size:1.5rem;}
document’s root element.
s Seconds #a2{transition-property:color;
transition-duration:1s;}
vh A value relative to the .halfHeight{width:50vh;}
viewport’s height. The full
viewport height is 100vh.
vm Either the viewport’s height or #halfBox{height:50vm;width:50vh;}
its width, whichever is smaller.
The minimum value is equal to
100vm.
vw A value relative to the viewport’s .halfWide{width:50vw;}
width. The viewport’s full width
is 100vw units.
NOTE AfewCSS3unitsthathavebeendiscussedonline,suchasgridunits(grorgd),fractions
(fr),andturns,arenotpresentedinTable6-4eitherbecausethereisalackofdocumentationor
becausethereisaclearindicationofinstabilityofthesevalues.
CSS3alsointroducesacalc()functionthatcanbeusedwhereverlengthvaluesare
allowed.Thefunctionisusedtocalculateavalueusingsomebasicmathematics.Forexample,
p{margin:calc(1rem-2px)calc(1.5rem-5px);}
wouldsetthemarginsoftheparagraphbasedupontherootelement’sfontminussome
smallpixelvalue.Browsersupportforthismeasurementisnonexistent,anditisinteresting
toseethatitissimilartoMicrosoft’sCSSexpressions,whichhavebeenmalignedandlater
disabledintheIEbrowserinsomeversionsandsettingsduetoperformanceconsiderations.
CSS3 Color
Feature Description Example(s) Support
currentColor Can be used as a macro for #currTest{color:red; Firefox 2+,
keyword whatever the current color border:1pxsolidblack; Chrome 1+,
is. This is useful if you want border-color:currentColor;} Safari 3+,
to dynamically change one /*ifsupported,borderred Opera 9.5+
color and have other related notblack*/
colors change.
HSL Color CSS3 introduces Hue #red{ Firefox 2+,
Saturation Lightness (HSL), color:hsl(0,100%,50%);} Safari 3+,
where color values are Chrome 1+,
specified as hsl(hue, #green{ Opera 9.5+
saturation,lightness). color:hsl(120,100%,50%);}
Hue is set as the degree on
the color wheel, where 0 or #blue{
360 if you wrap around is color:hsl(240,100%,50%);}
red, 120 is green, and 240
is blue, with the various
other colors found between.
Saturation is a percentage
value, with 100% being
the fully saturated color.
Lightness is a percentage,
with 0% being dark and 100%
light with the average 50%
being the norm.
CSS3 Color
Feature Description Example(s) Support
HSLa Color CSS3 HSL value with a #bluetrans{ Firefox 3+,
fourth value to set the color: Safari 3+,
alpha channel value for the hsla(240,100%,50%,0.5);} Chrome 1+,
color to define the opacity Opera 10+
of the element. An HSLa is
specified via a function style
hsla(hue,saturation,
lightness,alpha),
where hue, saturation, and
PART II
lightness are the same as
standard hsl() values, and
the alpha channel value for
defining opacity is a number
between 0 (fully transparent)
and 1 (fully opaque).
RGBa Color Like RGB color but adds #redtrans{ Firefox 3+,
an alpha channel value color:rgba(255,0,0,0.4);} Safari 3+,
to specify the opacity Chrome 1+,
of the color. An RGBa is Opera 10+
specified via a function style
rgba(r,g,b,a) value,
where colors r, g, and b
are specified as a decimal
value from 0 to 255 or a
percentage from 0 to 100%,
and the alpha channel
value for defining opacity is
a number between 0 (fully
transparent) and 1 (fully
opaque). Values outside this
range will be rounded up or
down to fit the closest value.
transparent CSS3 defines the color <pstyle="color: Firefox 3.5+,
keyword property to accept the transparent;">Whenworking Opera 10+,
keyword transparent, seemsinvisible</p> Chrome 1+
which is just a shorthand for
a value of rgba(0,0,0,0).
Obviously,ifthereisaconcernaboutusingCSS3colorvalues,ahexvalueshouldbe
usedinstead.Asimpletrickcanbeemployed,however,inthesituationwheresimplythe
opacityisnotsupportedbutthestandardcolorvalueis;justusethecascadeaspectofCSS
tostartwithaknownsupportedvalueandthenfollowitwiththenewercolorformatfor
supportingbrowsers:
#greentest{color:rgb(0,255,0);
color:rgba(0,255,0,0.4);}
Asthecurrentspecificationiswritten,littleisintroducedbythisCSS3module.Most
modernbrowsers,saveInternetExplorer8,supportthesefeatures.
NOTE Thespecificationalsoclearlycodifiesinoneplacemanyofthevariouscolorvaluesfrom
variousspecifications.SeeAppendixCforanoverviewofcolorvalues.
Namespaces
InXHTMLandXML,itispossibletointermixmarkuplanguagesinasingledocument.
Whenusingmixedvocabularies,itispossibletohavetagsthathavesimilarnamesbutare
fromdifferentvocabularies.Commonly,anexampleisgivenofhavingthetraditional
HTMLtag<table>beingconfusedwithsome<table>taginafictitiousFurniture
MarkupLanguage.Addingtheconceptofanamespacetoindicatewhatvocabularyatag
comesfromeliminatesconfusion,butthiswouldhavetobeextendedtoCSS.Forexample,
usingour<table>tagexample,whatwouldthefollowingruledo?
table{border:1pxsolidred;}
Woulditapplytheruletobothtypesoftagsorjustone.Whataboutifwewantedto
introduceadifferentlookforeach?EntertheCSS3@namespacedirective.Asanexample,
hereweintroduceaCSSruleforastandard<p>tagandonefora<p>taginourcustom
namespace:
<styletype="text/css">
p{color:red;}
</style>
<styletype="text/css">
@namespace"htmlref";
p{background-color:green;color:white;}
</style>
Then,dependingonsyntax,wemighthave
<p>Thisisastandardptagand<pxmlns="htmlref">anamedspaced
ptag</p>andbacktonormal.</p>
WhenwecaninvokeanXMLparser,thebrowsershouldapplydifferentstylestothe
differentlynamespacedtags:
Chapter 6: CSS3 Proprietary and Emerging Features Reference 625
Interestingly,thesupportforthisconstructismostproblematicduetobrowserhandlingof
XML/XHTMLdocuments,MIMEtypes,andthevaryingsyntaxesformixingtag
vocabularies.
NOTE Thisdemousesanxmlnsattribute,whichisdiscussedintheHTML5specification
somewhatcontroversiallyassomenonworking“talisman”attribute.Interestingly,thetestsuite
PART II
attheW3Cprovidestheinspirationforthebriefdemo,andthedemobasedupontheillustration
doesworkinmanycurrentlyshippingbrowsers.
Media Queries
AmediaquerytakestheCSSmediaattributeandextendsitwithconditions.Forexample,
commonlyWebdevelopersarefamiliarwithastyleruleforprintandoneforscreen.Media
queriesaddtothisaqueryuponthemedia,suchaswhatistheavailablewidthorcolor,to
thendeterminewhethertoapplyrulesornot.SuchaquerysystemallowsWebdevelopers
toeasilyapplydifferentstylestodifferentconditions,suchasonestyleforawidescreen
andoneforanarrowone,withoutresortingtoJavaScript.Asanexample,hereweemploya
stylesheetwide.cssifthescreenresolutionisatleast1024px,adifferentoneforamidrange
windowsize,andoneforasmallwindowsize:
<linkrel="stylesheet"media="screenand(min-width:1024px)"href="wide.
css">
<linkrel="stylesheet"media="screenand(min-width:641px)and(max-width:
1023px)"href="medium.css">
<linkrel="stylesheet"media="screenand(max-width:640px)"href="narrow.
css">
Interestingly,mostmodernbrowsers,withtheexceptionofInternetExplorerasof
version8,supportthis,asshowninFigure6-1.
O NLINE http://htmlref.com/ch6/mediaquery.html
Mediaqueriescanbeusedinline,aswell,withthe@mediasyntax,andmayalsoapply
todifferentmediums;forexample,herewemightapplydifferentCSSrulesdependingon
theprintstyle:
@mediaprintand(orientation:portrait){/*portraitlayoutrules*/}
@mediaprintand(orientation:landscape){/*landscaperules*/}
Table6-6detailsallofthemediaqueriesdefinedbythespecification,though
implementationscurrentlyfocusmostlyonwidth-relatedfeatures.
Whatyoudecidetodowithamediaqueryisuptoyourimagination.Aninteresting
possibilityisside-by-sidedisplayenvironmentsforwidemonitorsandstackedlayoutsfor
narrowones.
626 Part II: Core Style
Web Fonts
AnexcitingchangethatsomeincorrectlythinkwasintroducedbyCSS3istheinclusionof
Webfonts.Inreality,downloadablefontsusingCSSandevenHTMLhavebeenavailablein
browserssincethe4.xgeneration,thoughwiththedemiseofNetscape,onlyInternet
Explorercontinuedtosupportthemuntiltheirlaterreintroductioninmoremodern
browsers.Regardlessoftheirorigin,thesyntaxisfairlyconsistent.An“at”(@)ruleisused
toassociateafontnametobeusedinastylesheetwithsomedownloadablefont.Afont-
familypropertyisusedwithintheruletonamethefont,andansrcisassociatedwithan
externalfontname:
@font-face{font-family:fontname;src:url(fontfile);}
Later,thefontcanbeusedasanamewithinpropertieslikefont-familyandfont.
Makesuretospecifyotherfontnamesasafallbackincasedownloadablefonttechnologyis
notsupportedorthefontfailstoloadforsomereason.Asanexample:
@font-face{font-family:"handwriting";src:url(handwriting.ttf);}
body{font-family:"handwriting",cursive;font-size:5em;}
Chapter 6: CSS3 Proprietary and Emerging Features Reference 627
Support
Media Query Description max/min Allowed Values Example(s)
aspect-ratio The ratio of the width Yes Integer/ @mediascreen
to the height of the Integer and(aspect-
media. ratio:640/480)
{...}
color Describes the number Yes Integer @mediaalland
of bits of color the (color){...}
device supports, @mediaalland
or 0 if no color is (min-color:16)
supported. A presence
PART II
{...}
value can be used to
simply see if color is
supported.
color-index Describes number of Yes Integer @mediascreen
entries in the color and(color-
lookup table of the index:256)
output device or 0 if {...}
color is not supported.
device- The ratio of the device Yes Integer/ @mediascreen
aspect-ratio width to the device Integer and(device-
height of the media. aspect-ratio:
1024/768)
{...}
device- Describes the height Yes Typical CSS length units @mediascreen
height of the screen or full like px, em, in, and and(device-
height of the output so on height:768px)
page. {...}
device-width Describes the width Yes Typical CSS length units @mediascreen
of the screen or the like px, em, in, and and(device-
full width of the output so on width:1000px)
page. {...}
grid Determines if output No 1 or 0 (no value @mediascreen
is grid, like a simple required presence and(grid){...}
terminal or phone, style value)
or bitmap, like a
standard monitor or
printer.
height Describes the current Yes Typical CSS length units @mediascreen
supported width of like px, em, in, and and(height:
the device’s viewport so on 922px){...}
or paged media box @mediascreen
in the case of print and(max-height:
output. 800px)and(min-
height:400px)
{...}
Support
Media Query Description max/min Allowed Values Example(s)
monochrome Determines if output is Yes 0 or positive integer @mediascreen
monochrome and how and(monochrome)
many bits are used for {...}
gray display. A value of @mediascreen
0 indicates the output and(min-
is not monochrome. monochrome:4)
A presence value or 1 {...}
is used to indicate the
device is displaying in
monochrome.
orientation Output style portrait No portrait | @mediaprintand
if height is greater landscape (orientation:
than or equal to width, landscape)
landscape if the {...}
opposite.
resolution Describes the Yes Lengths in dpi (dots @mediaprintand
resolution of the per inch) or dpcm (dots (resolution:
output device. per centimeter) 300dpi){...}
scan Describes the No progressive | @mediatv
scanning method of interlaced and(scan:
a TV. progressive)
{...}
width Describes the current Yes Typical CSS length units @mediascreen
supported width of like px, em, in, and and(width:
the device’s viewport so on 1000px){...}
or paged media box @mediascreen
in the case of print and(min-width:
output. 300px)and(max-
width:480px)
{...}
Itisalsopossibletosetselectionofaparticulardownloadablefontwhenaparticularfont
characteristiclikeboldoritalicissetbyaddingthecorrespondingruletothe@font-facerule:
@font-face{font-family:"Mufferaw";src:url(MUFFERAW.ttf);}
@font-face{font-family:"Mufferaw";src:url(MUFFERAWBOLD.ttf);
font-weight:bold;}
p{font-family:"Mufferaw",serif;font-size:5em;}
em{font-weight:bold;}/*wouldspecifythemufferawboldfont*/
Thereareevenmorecharacteristicsthatcanbeset,includingwhatcharactersetsare
supported,butsofarquirksaboundeveninbasicsyntax.Readersareparticularlywarned
Chapter 6: CSS3 Proprietary and Emerging Features Reference 629
thattechnologiesfordownloadablefontsvarysignificantlybetweenbrowsers.AppendixB
discussessomeapproachestousingcustomfontsonline.
PART II
referencewhentheyweresupportedbybrowsers.Though,withoutlookingatallentries
globally,youmightnotseehowsomeCSS3changeshavewideeffect.Forexample,CSS3-
compliantbrowsersshouldsupportmultiplebackgrounds.Here,wespecifydifferentfiles
forthebackground,eachseparatedwithacomma:
body{background:whiteurl(donkey.gif)topleftno-repeat,
url(elephant.gif)bottomrightno-repeat;}
Thiswouldalsoworkonthebackground-imageproperty,ofcourse,given
backgroundisjustashorthandforallbackgroundcharacteristics.Soweseethatonceyou
canspecifymultiplebackgroundimages,thisripplesthroughnumerouspropertieslike
background-position.Forexample,whenusingbackground-positionondifferent
backgrounds,weapplythepositiontoeachbackgroundinorder,so
background-position:50px100px,200px200px;
wouldpositionthefirstbackgroundat50px,100pxandthesecondbackgroundat200px,
200px.Similarly,otherbackgroundpropertieslikebackground-repeatwouldchangein
asimilarmanner,so
background-repeat:no-repeat,repeat-x;
wouldapplyno-repeattothefirstbackgroundandrepeat-xtothesecond.
TheCSS3backgroundchangesaresupportedatthetimeofthisedition’swritingatleast
inWebKit-basedbrowsers.WefocusinthischaptermostlyonthoseareasofCSS3wherewe
haveaclose-to-finalspecification(forexample,Selectors)orhavesomeimplementationto
reference.WhilewehavesomegoodsenseaboutwhatCSS3featuresarelikelytobe
supportedbybrowsers,itmakeslittlesensetospeculatetoomuchuntilitissomething
implementedandactuallyusedbyaWebdeveloperordesigner.
Thissectiondetailsthepropertiesthataresupportedinsomemajorbrowsersshipping
circalate2009.Eachentrywillpresentthefollowingitems:
• Briefsummary
• Syntaxsummary
• Example(s)ofuse
• Compatibilityinformation
• Notesandspecialconsiderations
Theaimhereisforcompleteness,butgiventhemovingnatureofemergingand
proprietaryCSSfeatures,readersarewarnedthatthiscontentmaychangeorneverbe
widelyadopted.Awarenessofintentandpresentationofbasicsyntaxistheprimarygoal
here,astestinglikelywillberequiredtosafelyusetheseproperties.
NOTE Toprovideforthebestlong-termaccuracy,wherepossibleandwhenclear,CSS3syntaxis
presentedfirst.IfabrowsersupportsapropertyextensiontoemulatetheCSS3syntax,thatwill
bepresentedinthenotesandexamples.Noteverypossiblebrowserextensionispresented,
particularlythosepropertiesonlyimplementedinaminor-market-sharebrowserthathavenot
beendefinedatleastpartiallyinanyknownCSS3module.
@keyframes
ThisCSS“at”ruleisusedtodefinethepropertiesthatwillbeanimatedinananimationrule.
Syntax
@keyframes:keyframe-name
{percentage|from|to{cssrules}}*
whereeachblockstartswiththepercentageintotheanimationatwhichtherulesapply,
fromisakeywordfor0%,andtoisakeywordfor100%.
Example
@-webkit-keyframesmove{
from{
left:0;
top:0;
opacity:1;
}
50%{
left:500px;
top:0;
opacity:1;
}
to{
left:500px;
top:500px;
opacity:1;
}}
Chapter 6: CSS3 Proprietary and Emerging Features Reference 631
Compatibility
CSS3 Proposed Chrome 3+, Safari 3.1+
Notes
• WebKitsupportsthispropertyas@-webkit-keyframes.
accelerator
Thispropertyspecifieswhetheranelementisanacceleratorindicatorornot.
PART II
Syntax
accelerator:true|false
Whenthestandardunderlinestyleisappliedandacceleratorissettotrue,thestyle
shouldbetoggledwhentheALTkeyisdepressed,revealingthevariousaccesskeysinplay.
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>acceleratorTest</title>
<styletype="text/css"media="screen">
.accelerator{-ms-accelerator:true;
accelerator:true;
text-decoration:underline;}
</style>
</head>
<body>
<formaction="login.php"method="post">
<div>
<label>U<spanclass="accelerator">s</span>ername:
<inputtype="text"name="username"id="username"accesskey="s">
</label>
</div>
<div>
<label><spanclass="accelerator">P</span>assword:
<inputtype="password"name="userpass"id="userpass"accesskey="p">
</label>
</div>
<div>
<inputtype="submit"value="login">
</div>
</form>
</body>
</html>
O NLINE http://htmlref.com/ch6/accelerator.html
632 Part II: Core Style
Compatibility
No specification IE 5.5+
Notes
• UnderInternetExplorer8thispropertyshouldberepresentedas–ms-
accelerator.
• Atthetimeofthiswriting,thiswasnotworkinginIE8unlessincompatibility
mode,despitedocumentationstatementstothecontrary.
animation
Thisshorthandpropertyisusedtosetalloftheanimationpropertiesatonce.
Syntax
animation:animation-nameanimation-durationanimation-timing-function
animation-delayanimation-iteration-countanimation-direction
whereeachvalueisdefinedbyitsnamedproperty.Likeothershorthandproperties,values
maybeomitted.Theremaybeothershorthandanimationrulesthatfollowthefirst,
separatedbycommas.
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>CSSAnimations</title>
<styletype="text/css">
@-webkit-keyframesmove{
from{left:0;top:0;}
50%{left:500px;top:0;}
to{left:500px;top:500px;}
}
#anim1{-webkit-animation:move5sease-out0infinitealternate;
position:absolute;
height:100px;width:100px;
background-color:purple;}
</style>
</head>
<body>
<divid="anim1">Watchmemove!</div>
</body>
</html>
O NLINE http://htmlref.com/ch6/animation.html
Chapter 6: CSS3 Proprietary and Emerging Features Reference 633
Compatibility
CSS3 Proposed Chrome 3, Safari 3.1+
Notes
• WebKitsupportsthispropertyas–webkit-animation.
• Firefox3.7pre-releasesshowsupportforCSStransitionswhichareveryrelatedto
CSSanimation.Itisquitelikelythataformofthispropertyusingthe–mozprefix
maybesupportedinaFirefoxbrowserbythetimeyoureadthis.
animation-delay
PART II
Thispropertyisusedtodefineadelaybeforeananimationstarts.
Syntax
animation-delay:time1[,..timeN]
wheretimeisastandardCSStimevaluelike2sor4700ms.Thedefaultvalueis0,meaning
theanimationstartsimmediately.
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>CSSAnimations-animation-delay</title>
<styletype="text/css">
@-webkit-keyframesmove{
from{width:100px;height:300px;
left:0;top:0;}
50%{width:100px;height:300px;
left:300px;top:0;}
to{width:100px;height:300px;
left:300px;top:300px;}
}
@-webkit-keyframesresize{
from{width:100px;height:300px;
left:300px;top:300px;}
50%{width:100px;height:100px;
left:300px;top:300px;}
to{width:300px;height:100px;
left:300px;top:300px;}
}
#anim1{-webkit-animation-name:move,resize;
-webkit-animation-duration:4s,4s;
-webkit-animation-delay:0s,4s;
position:absolute;
background-color:purple;}
</style>
</head>
634 Part II: Core Style
<body>
<divid="anim1">Watchmemoveandchangesize!</div>
</body>
</html>
O NLINE http://htmlref.com/ch6/animationdelay.html
Compatibility
CSS3 Proposed Chrome 3+, Safari 3.1+
Notes
• WebKitsupportsthispropertyas–webkit-animation-delay.
• Becarefulstaggeringanimations,aspropertieswillreverttotheirnonanimation
valuesoncetheanimationcompletes.
• Firefox3.7pre-releasesshowsupportforCSStransitionswhichareveryrelatedto
CSSanimation.Itisquitelikelythataformofthispropertyusingthe–mozprefix
maybesupportedinaFirefoxbrowserbythetimeyoureadthis.
animation-direction
Thispropertyisusedtoindicateifananimationplaysinreverseorrepeatsitselfevery
otheriteration.
Syntax
animation-direction:normal|alternate[,normal|alternate]*
Thedefaultvalueisnormal.
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>CSSAnimations-animation-direction</title>
<styletype="text/css">
@-webkit-keyframesresize{
from{width:100px;height:300px;
left:0;top:0;}
50%{width:100px;height:100px;
left:300px;top:0;}
to{width:300px;height:100px;
left:300px;top:300px;}
}
#anim1{-webkit-animation-name:resize;
-webkit-animation-duration:4s;
-webkit-animation-iteration-count:5;
-webkit-animation-direction:alternate;
position:absolute;
background-color:purple;}
Chapter 6: CSS3 Proprietary and Emerging Features Reference 635
</style>
</head>
<body>
<divid="anim1">Watchmemoveandchangesize!</div>
</body>
</html>
O NLINE http://htmlref.com/ch6/animationdirection.html
Compatibility
CSS3 Proposed Chrome 3+, Safari 3.1+
PART II
Notes
• WebKitsupportsthispropertyas–webkit-animation-direction.
• Iftheanimation-directionisalternate,thetimingfunctionwillalsoalternate
ifappropriate.
• Firefox3.7pre-releasesshowsupportforCSStransitionswhichareveryrelatedto
CSSanimation.Itisquitelikelythataformofthispropertyusingthe–mozprefix
maybesupportedinaFirefoxbrowserbythetimeyoureadthis.
animation-duration
Thispropertyisusedtodefinethetimeittakesoneiterationofananimationtoplay.
Syntax
animation-duration:time[,time]*
wheretimeisavalidtimevaluelike5sor3500ms.Theinitialvalueoftimeis0,meaningno
animationplays.
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>CSSAnimations-animation-duration</title>
<styletype="text/css">
@-webkit-keyframesmove{
from{left:0;top:0;}
50%{left:300px;top:0;}
to{left:300px;top:300px;}
}
@-webkit-keyframesresize{
from{width:100px;height:300px;}
50%{width:100px;height:100px;}
to{width:300px;height:100px;}
}
#anim1{-webkit-animation-name:move,resize;
-webkit-animation-duration:4s,10s;
position:absolute;
background-color:purple;}
636 Part II: Core Style
</style>
</head>
<body>
<divid="anim1">Watchmemoveandchangesize!</div>
</body>
</html>
O NLINE http://htmlref.com/ch6/animationduration.html
Compatibility
CSS3 Proposed Chrome 3+, Safari 3.1+
Notes
• WebKitsupportsthispropertyas–webkit-animation-duration.
• Becarefulwithstaggeringdurations,astheshorteranimationwillreverttoits
nonanimationvaluesoncetheanimationcompletes.
• Firefox3.7pre-releasesshowsupportforCSStransitionswhichareveryrelatedto
CSSanimation.Itisquitelikelythataformofthispropertyusingthe–mozprefix
maybesupportedinaFirefoxbrowserbythetimeyoureadthis.
animation-iteration-count
Thispropertyisusedtodefinethenumberoftimesananimationshouldplay.
Syntax
animation-iteration-count:number|infinite[,number|infinite]*
wherenumberisapositiveintegerandthekeywordinfiniteindicatesacontinuous
animation.
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>CSSAnimations-animation-iteration-count</title>
<styletype="text/css">
@-webkit-keyframesresize{
from{height:300px;width:100px;
left:0;top:0;}
50%{height:100px;width:100px;
left:300px;top:0;}
to{height:100px;width:300px;
left:300px;top:300px;}
}
@-webkit-keyframesmove{
from{left:150px;top:150px;}
Chapter 6: CSS3 Proprietary and Emerging Features Reference 637
50%{left:300px;top:0;}
to{left:400px;top:200px;}
}
#anim1{-webkit-animation-name:resize;
-webkit-animation-duration:4s;
-webkit-animation-iteration-count:infinite;
position:absolute;
background-color:purple;}
#anim2{-webkit-animation-name:move;
-webkit-animation-duration:4s;
-webkit-animation-iteration-count:2;
PART II
position:absolute;top:150px;left:150px;
background-color:orange;}
</style>
</head>
<body>
<divid="anim1">Watchmemoveandchangesizeforever!</div>
<divid="anim2">Watchmemovetwotimes</div>
</body>
</html>
O NLINE http://htmlref.com/ch6/animationiterationcount.html
Compatibility
CSS3 Proposed Chrome 3+, Safari 3.1+
Notes
• WebKitsupportsthispropertyas–webkit-animation-iteration-count.
• Firefox3.7pre-releasesshowsupportforCSStransitionswhichareveryrelatedto
CSSanimation.Itisquitelikelythataformofthispropertyusingthe–mozprefix
maybesupportedinaFirefoxbrowserbythetimeyoureadthis.
animation-name
Thispropertyisusedtodefinetheanimationsthatshouldberun.The@keyframedirective
specifieddefinesthepropertiestoanimate.Thekeywordnonecanbeusedtooverride
acascade.
Syntax
animation-name:@keyframe-name|none[,@keyframe-name|none]*
where@keyframe-nameisthenameoftheanimationdefinedbyan@keyframedirective.
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
638 Part II: Core Style
<title>CSSAnimations-animation-name</title>
<styletype="text/css">
@-webkit-keyframesmove{
from{top:0;left:0;opacity:1;}
50%{top:0;left:500px;opacity:.5;}
to{top:500px;left:500px;opacity:.1;}
}
@-webkit-keyframesresize{
from{height:300px;width:100px;}
50%{height:100px;width:100px;}
to{height:100px;width:300px;}
}
@-webkit-keyframesfade{
from{opacity:1;}
50%{opacity:.5;}
to{opacity:.1;}
}
#anim1{-webkit-animation-name:move,resize,fade;
-webkit-animation-duration:10s;
position:absolute;
background-color:purple;}
</style>
</head>
<body>
<divid="anim1">Watchmemoveandvanish!</div>
</body>
</html>
O NLINE http://htmlref.com/ch6/animationname.html
Compatibility
CSS3 Proposed Chrome 3+, Safari 3.1+
Notes
• WebKitsupportsthispropertyas–webkit-animation-name.
• Firefox3.7pre-releasesshowsupportforCSStransitionswhichareveryrelatedto
CSSanimation.Itisquitelikelythataformofthispropertyusingthe–mozprefix
maybesupportedinaFirefoxbrowserbythetimeyoureadthis.
animation-timing-function
Thispropertyisusedtodescribehowtheanimationwillplay.
Syntax
animation-timing-function:timingfunction[,timingfunction2,...timingfunctionN]
Chapter 6: CSS3 Proprietary and Emerging Features Reference 639
wheretimingfunctionisoneofthefollowingvalues:
cubic-bezier(number,number,number,number)|ease|ease-in|ease-in-out
|ease-out|linear
Thedefaultvalueisease.
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
PART II
<title>CSSAnimations-animation-timing-function</title>
<styletype="text/css">
@-webkit-keyframesmove{
from{left:0;top:0;}
50%{left:300px;top:0;}
to{left:600px;top:0;}
}
#anim1{-webkit-animation-name:move;
-webkit-animation-duration:4s;
-webkit-animation-iteration-count:infinite;
-webkit-animation-timing-function:linear;
position:absolute;
background-color:purple;}
#controls{position:absolute;top:100px;left:10px;}
</style>
</head>
<body>
<divid="anim1">Watchmemove!</div>
<formid="controls"
onchange="document.getElementById('anim1').style.webkitAnimationTimingFunct
ion=this.options[this.selectedIndex].value;">
<select>
<optionvalue="cubic-bezier(110,120,210,280)">cubic-bezier</option>
<optionvalue="ease">ease</option>
<optionvalue="ease-in">ease-in</option>
<optionvalue="ease-in-out">ease-in-out</option>
<optionvalue="ease-out">ease-out</option>
<optionvalue="linear"selected>linear</option>
</select>
</form>
</body>
</html>
O NLINE http://htmlref.com/ch6/animationtimingfunction.html
640 Part II: Core Style
Compatibility
CSS3 Proposed Chrome 3+, Safari 3.1+
Notes
• WebKitsupportsthispropertyas–webkit-animation-timing-function.
• Ifapplicable,thetimingfunctionwillreverseifanimation-directionissetto
alternate.
• Firefox3.7pre-releasesshowsupportforCSStransitionswhichareveryrelatedto
CSSanimation.Itisquitelikelythataformofthispropertyusingthe–mozprefix
maybesupportedinaFirefoxbrowserbythetimeyoureadthis.
backface-visibility
Thispropertyisusedtoindicatewhetherthebacksideofanelementisvisibleiftheelement
isrotatedtodisplaytheback.
Syntax
backface-visibility:hidden|visible
Thedefaultvalueisvisible.Whenitissettohidden,theelementisnotvisibleifitisnot
facingthescreen.Whenitissettovisible,itisalwaysvisible,whichmaymeanyousee
thereverseofanimage.
Example
<imgsrc="logo.gif"border="1"style="-webkit-transform:rotateY(125deg);
-webkit-backface-visibility:visible;">
Compatibility
CSS3 Chrome 3+, Safari 4+
Note
• WebKitsupportsthispropertyas–webkit-backface-visibility,thoughatthe
timeofthisedition’swritingitisonlyavailableintheiPhoneandthedevelopment
buildsofSafari4+.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 641
background-clip
Thispropertyspecifieswhetherornotanelement’sbackgroundextendsallthewaytothe
element’sborder.
Syntax
background-clip:border|padding[,border|padding,..]
wherethedefaultisborder,causingthebackgroundtostopattheedgeoftheborderofan
elementorwherepaddingstopsthebackgroundatthestartofaborder.Theeffectofthis
propertyisnoticeablewhenborderswithtransparentregionsareused:
PART II
Examples
<divstyle="height:100px;width:200px;
background-color:red;
padding:20px;
border:5pxdashedblack;">
Clippedtoborder(default)
</div>
<divstyle="height:100px;width:200px;
background-color:red;
padding:20px;
border:5pxdashedblack;
-webkit-background-clip:padding;
-moz-background-clip:padding;
background-clip:padding;">
Clippedtopadding
</div>
O NLINE http://htmlref.com/ch6/backgroundclip.html
Compatibility
CSS3 Chrome 3+, Firefox 3.5+, Safari 3+
Notes
• Mozilla-basedbrowserslikeFirefoxsupportthispropertyas–moz-background-
clipandWebKit-basedbrowserslikeSafariandChromesupportitas–webkit-
background-clip.
642 Part II: Core Style
• WebKit-basedbrowsersalsospecifyavalueofcontentforits–webkit-
background-clipproperty,whichclipsbackgroundstothecontentregion
ofabox.
• WebKit-basedbrowsershaveexperimentedwithavalueoftextfortheir–webkit-
background-clippropertytocreateaclipoutlinefortexttocreateaninteresting
punch-outeffect.
background-origin
Thispropertyspecifieshowthepositionofabackgroundshouldbecalculatedbysetting
theoriginrelativetodifferentlocationswithinanelement’sbox.
Syntax
background-origin:border|padding|content[,border|padding|
content,...]
wherethedefaultispadding,causingthepositionofthebackgroundtoberelativetothe
outsideofthepaddingor,moreobviously,thestartoftheborder.Italsocanbesetrelative
totheoutsideoftheborderorthestartofthecontent.Theeffectofthispropertyisquite
noticeablewhenlookingatapositionedbackgroundwhereborderswithtransparent
regionsareused:
Chapter 6: CSS3 Proprietary and Emerging Features Reference 643
Examples
<divstyle="-webkit-background-origin:border;
-moz-background-origin:border;
background-origin:border;">
background-origin:border
</div>
<divstyle="-webkit-background-origin:padding;
-moz-background-origin:padding;
background-origin:padding;">
background-origin:padding
</div>
<divstyle="-webkit-background-origin:content;
PART II
-moz-background-origin:content;
background-origin:content;">
background-origin:content
</div>
O NLINE http://htmlref.com/ch6/backgroundorigin.html
Compatibility
CSS3 Chrome 3+, Firefox 3.5+, Safari 3+
Notes
• Mozilla-basedbrowserssuchasFirefoxsupportthispropertyas–moz-
background-originandWebKit-basedbrowserssuchasChromeandSafari
supportitas–webkit-background-origin.
• TheCSS3specificationcurrentlylistsborder-boxandpadding-box.Thissyntax
waschangedinotherareasofthespecification,andbrowservendorscurrently
don’tsupportsuchvalues.Thesupportedvaluesarepresentedinstead.
background-position-x
Thispropertydefinesthex-coordinateofthebackground-positionproperty.
Syntax
background-position-x:length|percentage|left|center|right
Example
<divstyle="background-image:url(background.gif);
background-repeat:no-repeat;
background-position-x:100px;background-position-y:25px;">
background-position-x
</div>
Compatibility
No spec Chrome 2+, IE 4+, Safari 1.3+
644 Part II: Core Style
Note
• UnderIE8thispropertyisknownas–ms-background-position-xtocorrectly
noteitasanextension.
background-position-y
Thispropertydefinesthey-coordinateofthebackground-positionproperty.
Syntax
background-position-y:length|percentage|top|center|bottom
Example
<divstyle="background-image:url(background.gif);
background-repeat:no-repeat;
background-position-x:100px;background-position-y:25px;">
background-position-y
</div>
Compatibility
No spec Chrome 2+, IE 4+, Safari 1.3+
Note
• UnderIE8thispropertyisknownas–ms-background-position-ytocorrectly
noteitasanextension.
background-size
Thispropertyallowsthebackgroundimageusedtobescaled.
Syntax
background-size:length|percentage[length|percentage]
wherelengthorpercentagevaluesmayhaveasingleordoublevalue.
Examples
<divstyle="-webkit-background-size:50px50px;
-moz-background-size:50px50px;
-o-background-size:50px50px;
background-size:50px50px;">
Smallerinpixels
</div>
<divstyle="-webkit-background-size:75px130px;
-moz-background-size:75px130px;
-o-background-size:75px130px;
background-size:75px130px;">
Scaledifferently
</div>
Chapter 6: CSS3 Proprietary and Emerging Features Reference 645
<divstyle="-webkit-background-size:200%200%;
-moz-background-size:200%200%;
-o-background-size:200%200%;
background-size:200%200%;">
Biggerbypercentage
</div>
PART II
O NLINE http://htmlref.com/ch6/backgroundsize.html
Compatibility
CSS3 Chrome 3+, Firefox 3.6+, Opera 9.5+, Safari 3+
Note
• Mozilla-basedbrowserssuchasFirefoxsupportthispropertyas–moz-background-
size,WebKit-basedbrowserslikeChromeorSafarisupportitas–webkit-
background-size,andOperabrowserssupportitas–o-background-size.
behavior
ThisMicrosoft-proposedCSSpropertyisusedtodefinetheURLforascriptproviding
DHTMLbehavior.ItissimilarinpurposeandfunctiontotheCSS3bindingproperty.
Syntax
behavior:url(defaultbehaviornameorURLofbehavior)
Microsofthasimplementedanumberofdefaultbehaviors.Theseareaccessibleby
specifyingtheurlas#default#behaviorname,suchasbehavior:url(#default#
clientCaps);.Oncethesebehaviorsareassociatedwithanelement,additionalproperties
willbeavailabletothatelementbasedonthedefaultbehaviorused.Table6-7showsa
summaryofthecommondefaultbehaviorssupportedbyInternetExplorerbrowsers.
646 Part II: Core Style
PART II
vAttrValue)
saveSnapshot Allows data to persist when the
page is saved.
userData Allows data to persist in user expires
data. XMLDocument
getAttribute(sAttrName)
load(sStoreName)
removeAttribute(sAttrName)
save(sStoreName)
setAttribute(sAttrName,
vAttrValue)
Examples
<styletype="text/css">
@mediaall{IE\:homepage{behavior:url(#default#homepage)}
</style>
</head>
<body>
<IE:homepageid="homepageEl">
<!--inlinebehavior-->
<h1style="behavior:url(colorchange.htc);">Whatadynamicheader!</h1>
ThefollowingfullexampleshowsthatitispossibletouseolderMicrosoftbehavior
syntaxwithnewerbindingstylesyntaxtoaddinteractivitytoelementsviaCSS:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>behaviorandbindingExample</title>
<styletype="text/css">
#clickable{behavior:url(hello.htc);-moz-binding:url(hello.xml);
binding:url(hello.xml);}
</style>
</head>
648 Part II: Core Style
<body>
<p>Justaregularparagraph.</p>
<pid="clickable">I'mspecialclickme.</p>
<p>Justaregularparagraph.</p>
</body>
</html>
Thespecifiedhello.htcfilelookslikethis:
<PUBLIC:COMPONENTURN="urn:msdn-microsoft-com:workshop"lightWeight="true">
<PUBLIC:ATTACHEVENT="onclick"FOR="element"ONEVENT="sayHi()"/>
<SCRIPTLANGUAGE="JScript">
functionsayHi(){alert("HelloWorldfromaboundHTC.");}
</SCRIPT>
</PUBLIC:COMPONENT>
O NLINE http://htmlref.com/ch6/behaviorbinding.html
Compatibility
No specification IE 5+
Notes
• StartingwithIE8thispropertyisproperlywrittenas–ms-behaviorbecauseitis
anextension.
• Mozilla-basedbrowserssuchasFirefoxsupportasimilarconceptusingthe
–moz-bindingproperty.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 649
• Amorecompletediscussionofbehaviors,andbuilt-inInternetExplorerbehaviors
inparticular,canbefoundattheMSDNsiteonline(http://msdn.microsoft.com),
butyoushouldnotethat,forsecurityconcerns,somebehaviorshavebeenremoved
ormodifiedovertime.
• Behaviorsareoftenboundtomade-upelementswhenused,butthisisnotrequired.
binding
Thispropertydefinesarelationshipbetweenboundelements(s)andsomecodeorcontent.
Generally,itisusedtoassociatesomescriptingtovariouselementsinadocument.
Syntax
PART II
binding:none|url(bindingfile)
wherebindingfileissometechnologysuchasXBLtoaddcontentorassociatemarkupwith
scriptcode.
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>behaviorandbindingExample</title>
<styletype="text/css">
#clickable{behavior:url(hello.htc);-moz-binding:url(hello.xml);
binding:url(hello.xml);}
</style>
</head>
<body>
<p>Justaregularparagraph.</p>
<pid="clickable">I'mspecialclickme.</p>
<p>Justaregularparagraph.</p>
</body>
</html>
TheboundXBLfile(hello.xml)lookslikethis:
<?xmlversion="1.0"encoding="utf-8"?>
<bindingsxmlns="http://www.mozilla.org/xbl"
xmlns:html="http://www.w3.org/1999/xhtml">
<bindingid="hello">
<handlers>
<handlerevent="click"action=
"alert('HelloworldfromtheboundXBL')"/>
</handlers>
</binding>
</bindings>
650 Part II: Core Style
O NLINE http://htmlref.com/ch6/behaviorbinding.html
Compatibility
CSS3 Firefox 1+
Notes
• Thispropertyissupportedas–moz-bindinginFirefoxbrowsers.
• ThepropertyissimilartoInternetExplorer’sbehaviorproperty.
border-bottom-left-radius
Thispropertyisusedtoroundthebottom-leftbordercornerspecifically.
Syntax
border-bottom-left-radius:horizontal-radiusvertical-radius
Example
<divstyle="border:1pxsolidred;-moz-border-radius-bottomleft:15px;
-webkit-border-bottom-left-radius:15px;border-bottom-left-radius:15px;">
Bottomleftcorner
</div>
Compatibility
CSS3 Chrome 2+, Firefox 3+, Safari 3+
Chapter 6: CSS3 Proprietary and Emerging Features Reference 651
Notes
• Mozillabrowsersdefinethispropertyas–moz-border-radius-bottomleft
whileWebKit-basedbrowsersdefineitmoretraditionallyas–webkit-border-
bottom-left-radius.Giventhedifferences,youshouldtestitcarefullyasthe
syntaxmaychange.
border-bottom-right-radius
Thispropertyisusedtoroundthebottom-rightbordercornerspecifically.
Syntax
PART II
border-bottom-right-radius:horizontal-radiusvertical-radius
Example
<divstyle="border:1pxsolidred;-moz-border-radius-bottomright:25px;
-webkit-border-bottom-right-radius:25px;border-bottom-right-radius:25px;">
Bottomrightcorner
</div>
Compatibility
CSS3 Chrome 2+, Firefox 3+, Safari 3+
Notes
• Mozilla-basedbrowserslikeFirefoxdefinethispropertyas–moz-border-radius-
bottomrightwhileWebKit-basedbrowserslikeChromeandSafaridefineitmore
traditionallyas–webkit-border-bottom-right-radius.Giventhedifferences,
youshouldtestitcarefullyassyntaxmaychange.
border-image
Thispropertydefinesanimagetobeusedfortheborderoftheelement.
Syntax
border-image:none|url(image)imagesection[/imagewidth]imagehandling
whereimagesectiondefinestheportionsoftheimagethatareusedforvariouspartsofthe
border.Theimagesectionvaluecanbecomposedofuptofourslicelinesontheimage,each
measuredinpixelsorpercentages,asshowninthisdiagram:
Slice 4
Slice 1
Slice 3
Slice 2
652 Part II: Core Style
Thefirstcutlineisacrossthetopanddefinestheheightofthetop-leftandtop-right
corners;thesecondcutlinedefinesthewidthofthetop-rightandbottom-rightcorners;the
thirdcutlinedefinestheheightofthebottomcorners;andthefourthcutlinedefinesthe
widthoftheleftcorners,topandbottom.Forexample,given
url(background-image)50px20px100px30px
youwouldsetcutslikethis:
50px
100px
30px 20px
A/allowsforthespecificationofimagewidthsforeachofthebordersfromtop,right,
bottom,andleft.Widthsaregenerallyinlengthunits,suchaspixels.Finally,three
keywordsasdefinedaboveasimagehandlingcanbeplacedtocontrolwhetherthemiddle
zonesofthecutlinesaretobestretched(stretch),repeated(repeat),orshowntothe
nearestwholeimage(round).Forexample,giventhisimage
thedifferencesbetweenarepeatableasopposedtoastretchedborderimageshouldbeclear:
Example
<divstyle="-moz-border-image:url(starborder.png)50px50px50px50px
stretchstretch;
-webkit-border-image:url(starborder.png)50px50px50px50px
stretchstretch;
Chapter 6: CSS3 Proprietary and Emerging Features Reference 653
border-image:url(starborder.png)50px50px50px50pxstretch
stretch;
color:red;background-color:red;height:150px;width:30%;
padding:10px;border:50pxdashedblack;">
<h1>4thofJuly</h1>
</div>
O NLINE http://htmlref.com/ch6/borderimage.html
Compatibility
PART II
CSS3 Firefox 3.5+ Safari 3+
Notes
• InMozilla-basedbrowserslikeFirefoxthispropertyis–moz-border-imageandin
WebKit-basedbrowserslikeChromeorSafariitis–webkit-border-image.
• Theborderimagewilltileoverthecenteroftheimageaswell,butifyoumakeit
transparent,youcanhaveabackgroundimageorcolorshowaswell.
• Theborderimagewillcoveradefinedstandardborder,soitisusefultohavea
fallbackincasebrowsersdonotsupportthisemergingproperty.
border-radius
Thispropertyisusedtoroundbordercorners.
Syntax
border-radius:horizontal-radiusvertical-radius
wheretheradiusvaluesaresetaslengths.Asinglelengthvaluedefinestheradiusofall
corners,oreachcanbespecifiedonebyonefromtop-left,top-right,bottom-right,and
finallybottom-left.
Examples
<divstyle="border:1pxsolidred;-moz-border-radius:15px;-webkit-border-
radius:15px;border-radius:15px;">
Allcorners
</div>
<divstyle="border:1pxsolidred;-moz-border-radius:15px30px5px70px;
-webkit-border-radius:15px30px5px70px;border-radius:15px30px5px
70px;">
VaryEach
</div>
<divstyle="border:1pxsolidred;-moz-border-radius-topleft:15px;-webkit-
border-top-left-radius:15px;border-top-left-radius:15px;">
Leftcorner
</div>
654 Part II: Core Style
O NLINE http://htmlref.com/ch6/borderradius.html
Compatibility
CSS3 Chrome 2+, Firefox 3+, Opera 9.5+, Safari 3+
Notes
• Mozilla-basedbrowserslikeFirefoxdefinethispropertyas–moz-border-radius
whileWebKit-basedbrowserslikeChromeandSafaridefineitas–webkit-
border-radius.
• ThereisadefinitionintheCSS3specificationonasecondsetofradiusvaluesbeing
appliedtosetverticalradiuspairwisewithhorizontalradius.Currently,the
browsersdonotsupportthiswellor,inmostcases,atall,andactuallyprovide
documentationthatcontradictsthespecification.Clearly,thisisaworkinprogress.
• Theindividualcornerscanbespecifiedindividuallyusingtheirownproperties,as
showninsubsequentlistings.WhiletheCSS3specificationdefinespropertieslike
border-top-right-radius,therearesyntaxdifferencesinearlysupporting
browsers,withMozilla-basedbrowserssupportingasyntaxlike-moz-border-
radius-toprightandWebKit-basedbrowserssupporting-webkit-border-
top-right-radius.
• Whenbackgroundimagesareemployed,weshouldexpectclippingtothecurved
cornerasshownnext,butthisisnotconsistentlyimplementedinbrowsersyet:
border-top-left-radius
Thispropertyisusedtoroundthetop-leftbordercornerspecifically.
Syntax
border-top-left-radius:horizontal-radiusvertical-radius
Chapter 6: CSS3 Proprietary and Emerging Features Reference 655
Example
<divstyle="border:1pxsolidred;-moz-border-radius-topleft:10px;-webkit-
border-top-left-radius:10px;border-top-left-radius:10px;">
Topleftcorner
</div>
Compatibility
CSS3 Firefox 3+, Safari 3+
Note
PART II
• Mozilla-basedbrowserslikeFirefoxdefinethispropertyas–moz-border-radius-
topleftwhileWebKit-basedbrowserslikeChromeandSafaridefineitmore
traditionallyas–webkit-border-top-left-radius.Giventhedifferences,you
shouldtestitcarefullyassyntaxmaychange.
border-top-right-radius
Thispropertyisusedtoroundthetop-rightbordercornerspecifically.
Syntax
border-top-right-radius:horizontal-radiusvertical-radius
Example
<divstyle="border:1pxsolidred;-moz-border-radius-topright:5px;-webkit-
border-top-right-radius:5px;border-top-right-radius:5px;">
Toprightcorner
</div>
Compatibility
CSS3 No IE support, Firefox 3+, Safari 3+
Note
• Mozillabrowsersdefinethispropertyas–moz-border-radius-toprightwhile
WebKit-basedbrowsersdefineitmoretraditionallyas–webkit-border-top-right-
radius.Giventhedifferences,youshouldtestitcarefullyassyntaxmaychange.
box-reflect
Thispropertyspecifiesthesizeofthemask.
Syntax
-webkit-box-reflect:directionoffsetmask-box-image
wheredirectioncanbeabove,right,below,orleftandindicateswherethereflection
shouldappear.offsetspecifiesthedistancefromtheoriginalimagetothereflectionand
canbealengthorpercentage.mask-box-imageisamaskfollowingtheformofthemask-
box-imagepropertythatoverlaysthereflection.
656 Part II: Core Style
Example
<imgid="logo"src="logo.gif"style="-webkit-box-reflect:below5px
-webkit-gradient(linear,lefttop,leftbottom,from(rgba(0,0,0,0)),
to(rgba(0,0,0,1)));">
O NLINE http://htmlref.com/ch6/boxreflect.html
Compatibility
No specification Chrome 2+, Safari 4+
Notes
• InWebKit-basedbrowsersthispropertyis–webkit-box-reflect.
• Thereflectionupdatesautomaticallyastheoriginalimagechanges.Thisincludes
tooltips.
• Thereflectionshouldhavenoeffectonlayout.
box-shadow
Thispropertysetstheshadowforaboxelement.
Syntax
box-shadow:shadow1[,...shadowN]|none|inherit
whereeachshadowisdefinedas
colorx-offsety-offsetblur-radiusspread-radius
wherecoloristhecoloroftheshadow.Whenunspecified,colormaybesetbytheuseragentor
inheritedfromthecurrentcolor.Thex-offsetandy-offsetdefinetheshadowpositionrelative
totheelement,wherepositivenumbersaretotherightanddownandnegativenumbersare
totheleftandup,respectively.Settingthesevaluesto0putstheshadowdirectlybehindthe
element.Theblur-radiusdefinesthedegreeofblur,withlargernumbersmakingtheshadow
moreblurry.Thespread-radiusdefinesthesizeoftheshadow.Apositivevaluemakesthe
shadowbiggerthantheobjectandanegativevaluemakesitsmallerthantheelement.
Whenunspecified,thespread-radiusis0,makingtheshadowthesamesizeastheelement.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 657
Examples
div{height:100px;width:100px;margin:100px;
border:1pxsolidblack;float:left;}
#box1{-moz-box-shadow:red10px10px;
-webkit-box-shadow:red10px10px;
box-shadow:red10px10px;}
#box2{-moz-box-shadow:green-10px-10px;
-webkit-box-shadow:green-10px-10px;
box-shadow:green-10px-10px;}
#box3{-moz-box-shadow:orange10px10px20px;
PART II
-webkit-box-shadow:orange10px10px20px;
box-shadow:orange10px10px20px;}
#box4{-moz-box-shadow:orange10px10px80px;
-webkit-box-shadow:orange10px10px80px;
box-shadow:orange10px10px80px;}
#box5{-moz-box-shadow:orange10px10px50px40px;
-webkit-box-shadow:orange10px10px50px40px;
box-shadow:orange10px10px50px40px;}
#box6{-moz-box-shadow:orange10px10px20px,green-10px-10px20px;
-webkit-box-shadow:orange10px10px20px,green-10px-10px20px;
box-shadow:orange10px10px20px,green-10px-10px20px;}
O NLINE http://htmlref.com/ch6/boxshadow.html
658 Part II: Core Style
Compatibility
CSS3 Chrome 3+, Firefox 3.5+, Safari 3+
Note
• Currently,thispropertyissupportedinMozilla-basedbrowserslikeFirefoxas
–moz-box-shadowandinWebKit-basedbrowserslikeChromeandSafarias
–webkit-box-shadow.
box-sizing
Thispropertychangesthecalculationformeasuringthewidthofelements.
Syntax
box-sizing:border-box|content-box|inherit
Thedefaultcontent-boxspecifiesthatelementsizeisdefinedbyaddingtheborder,
padding,andheight/widthtogethertodefinethesizeofthebox,whichiswhatistypically
seeninbrowsers.Whensettoborder-box,asupportingbrowserwillrendertheboxbythe
definedheightandwidthproperties,pullingtheborderandpaddingsizefromwithinthe
box,similartomucholderboxmodelthinking.
Examples
#ex1{-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
box-sizing:border-box;
height:100px;width:200px;
background-color:orange;
border:10pxsolidred;
padding:10px;}
#ex2{-moz-box-sizing:content-box;
-webkit-box-sizing:content-box;
box-sizing:content-box;
height:100px;width:200px;
background-color:orange;
border:10pxsolidred;
padding:10px;}
Chapter 6: CSS3 Proprietary and Emerging Features Reference 659
Compatibility
CSS3 IE 8+ Firefox 1+ Opera 8.5+, Safari 3+
Notes
• Firefoxbrowserssupportthispropertyas–moz-box-sizingandWebKit-based
browserssupportitas–webkit-box-sizing.
• IE8alsosupports–ms-box-sizingaswellasbox-sizinganditshouldbe
writtenwiththe–msprefixtoproperlyindicateitasanextension.
column-break-after
PART II
Thispropertyisusedtocontrolcolumnelementbreaksafteranassociatedelementwhen
flowingmulticolumntext.
Syntax
column-break-after:always|auto|avoid
Avalueofalwaysshouldforceacolumnbreakaftertheassociatedelement.Avalueof
avoidattemptstoavoidacolumnbreakaftertheelement.Thedefaultvalueofauto
neitherforcesnorforbidsacolumnbreak,allowingtheuseragenttodecidehowtobreak
thecontentduringflow.
Examples
.breakitdown{-webkit-column-break-after:always;column-break-after:always;}
.nobreaks{-webkit-column-break-after:avoid;column-break-after:avoid;}
Compatibility
CSS3 Chrome 2+, Safari 3+
Notes
• WebKit-basedbrowserssupportthispropertyas–webkit-column-break-after.
• WebKitalsodefinesleftandrightvalues,thoughtheirmeaningissomewhat
unclearinthiscontext.
• WebKitalsodefines–webkit-column-break-inside,thoughthisisnotcurrently
intheCSS3specification.
column-break-before
Thispropertyisusedtocontrolcolumnelementbreaksbeforetheassociatedelementwhen
flowingmulticolumntext.
Syntax
column-break-before:always|auto|avoid
Avalueofalwaysshouldforceacolumnbreakbeforetheassociatedelement.Avalueof
avoidattemptstoavoidacolumnbreakbeforetheelement.Thedefaultvalueofauto
660 Part II: Core Style
neitherforcesnorforbidsacolumnbreak,allowingtheuseragenttodecidehowtobreak
thecontentduringflow.
Examples
.breakitdown{-webkit-column-break-before:always;
column-break-before:always;}
.nobreaks{-webkit-column-break-before:avoid;column-break-before:avoid;}
Compatibility
CSS3 Chrome 2+, Safari 3+
Notes
• WebKit-basedbrowserssupportthispropertyas–webkit-column-break-before.
• WebKitalsodefinesleftandrightvalues,thoughtheirmeaningissomewhat
unclearinthiscontext.
• WebKitalsodefinescolumn-break-inside,thoughthisisnotcurrentlyinthe
CSS3specification.
column-count
Thispropertydefinesthenumberofcolumnsinamulticolumntextflow.
Syntax
column-count:integer|auto
whereintegerisapositivevalueforthenumberofcolumnstoflowthetextinto.
Examples
.two-column{-moz-column-count:2;-webkit-column-count:2;column-count:2;}
.three-column{-moz-column-count:3;-webkit-column-count:3;
column-count:3;}
O NLINE http://htmlref.com/ch6/columncount.html
Chapter 6: CSS3 Proprietary and Emerging Features Reference 661
Compatibility
CSS3 Chrome 2+, Firefox 1.5+, Safari 3+
Note
• Firefoxbrowserssupportthispropertyas–moz-column-countandWebKit-based
browserslikeChromeandSafarisupportitas–webkit-column-count.
column-gap
Thispropertydefinesthegapbetweencolumnsinamulticolumntextflow.
PART II
Syntax
column-gap:length|normal
wherelengthisanypositiveCSSmeasurementvalue.
Examples
.two-column{-moz-column-count:2;-webkit-column-count:2;column-count:2;
-moz-column-gap:100px;-webkit-column-gap:100px;
column-gap:100px;}
.three-column{-moz-column-count:3;-webkit-column-count:3;column-count:3;
-moz-column-gap:10em;-webkit-column-gap:10em;
column-gap:10em;}
Compatibility
CSS3 Chrome 2+, Firefox 1.5+, Safari 3+
Note
• Firefoxbrowserssupportthispropertyas–moz-column-gapandWebKit-based
browserslikeChromeandSafarisupportitas–webkit-column-gap.
column-rule
Thisshorthandpropertydefinesthestyle,width,andcoloroftheruledividerbetween
columnsinamulticolumntextflow.
Syntax
column-rule:rule-widthrule-stylecolor
whererule-widthisavalidmeasurementorkeywordasdefinedbycolumn-rule-width,
rule-styleisavalidstyleasdefinedbycolumn-rule-style,andcolorisaCSScolorvalue
alsosettablewithcolumn-rule-color.
662 Part II: Core Style
Examples
.two-column{-moz-column-count:2;-webkit-column-count:2;column-count:2;
-moz-column-gap:100px;-webkit-column-gap:100px;
column-gap:100px;
-moz-column-rule:5pxsolidred;
-webkit-column-rule:5pxsolidred;
column-rule:5pxsolidred;}
.three-column{-moz-column-count:3;-webkit-column-count:3;
column-count:3;
-moz-column-gap:2em;-webkit-column-gap:2em;
column-gap:2em;
-moz-column-rule:.5emdashedgreen;
-webkit-column-rule:.5emdashedgreen;
column-rule:.5emdashedgreen;}
O NLINE http://htmlref.com/ch6/columnrule.html
Compatibility
CSS3 Chrome 3+, Firefox 3.5+, Safari 4+
Note
• Firefoxbrowserssupportthispropertyas–moz-column-ruleandWebKit-based
browserslikeChromeandSafarisupportitas–webkit-column-rule.
column-rule-color
Thispropertydefinesthecolorofanyrulesbetweencolumnsinamulticolumntextflow.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 663
Syntax
column-rule-color:color
wherecolorisanyvalidCSScolorvalue.
Examples
.two-column{-moz-column-count:2;-webkit-column-count:2;column-count:2;
-moz-column-gap:100px;-webkit-column-gap:100px;
column-gap:100px;
-moz-column-rule-style:solid;
-webkit-column-rule-style:solid;
PART II
column-rule-style:solid;
-moz-column-rule-color:red;
-webkit-column-rule-color:red;
column-rule-color:red;}
.three-column{-moz-column-count:3;-webkit-column-count:3;
column-count:3;
-moz-column-gap:2em;-webkit-column-gap:2em;
column-gap:2em;
-moz-column-rule-style:dashed;
-webkit-column-rule-style:dashed;
column-rule-style:dashed;
-moz-column-rule-color:green;
-webkit-column-rule-color:green;
column-rule-color:green;}
Compatibility
CSS3 Chrome 2+, Firefox 3.5+, Safari 3+
Notes
• Firefoxbrowserssupportthispropertyas–moz-column-rule-colorandWebKit-
basedbrowserslikeChromeandSafarisupportitas–webkit-column-rule-
color.
• Acolumnrulestylemustatleastbesettoseetheeffectofthisproperty.
column-rule-style
Thispropertydefinesthestyleofthedividerrulebetweencolumnsinamulticolumn
textflow.
Syntax
column-rule-style:dashed|dotted|double|groove|hidden|inset|
inherit|none|outset|ridge|solid
wheretheinitialvalueisnone.
664 Part II: Core Style
Examples
.two-column{-moz-column-count:2;-webkit-column-count:2;column-count:2;
-moz-column-gap:100px;-webkit-column-gap:100px;
column-gap:100px;
-moz-column-rule-style:solid;
-webkit-column-rule-style:solid;
column-rule-style:solid;}
.three-column{-moz-column-count:3;-webkit-column-count:3;column-count:3;
-moz-column-gap:2em;-webkit-column-gap:2em;column-gap:2em;
-moz-column-rule-style:dashed;
-webkit-column-rule-style:dashed;
column-rule-style:dashed;}
Compatibility
CSS3 Chrome 2+, Firefox 3.5+, Safari 3+
Note
• Firefoxbrowserssupportthispropertyas–moz-column-rule-styleandWebKit-
basedbrowserslikeChromeandSafarisupportitas–webkit-column-rule-style.
column-rule-width
Thispropertydefinesthewidthofarulebetweencolumnsinamulticolumntextflow.
Syntax
column-rule-width:non-negativelength|medium|thick|thin|inherit
wherethewidthvaluesherematchstandardbordervalues,withthedefaultbeingmedium.
Examples
.two-column{-moz-column-count:2;-webkit-column-count:2;column-count:2;
-moz-column-gap:100px;-webkit-column-gap:100px;
column-gap:100px;
-moz-column-rule-style:solid;
-webkit-column-rule-style:solid;
column-rule-style:solid;
-moz-column-rule-width:25px;
-webkit-column-rule-width:25px;
column-rule-width:25px;}
.three-column{-moz-column-count:3;-webkit-column-count:3;column-count:3;
-moz-column-gap:2em;-webkit-column-gap:2em;column-gap:2em;
-moz-column-rule-style:dashed;
-webkit-column-rule-style:dashed;
column-rule-style:dashed;
-moz-column-rule-width:thin;
-webkit-column-rule-width:thin;
column-rule-width:thin;}
Compatibility
CSS3 Chrome 2+, Firefox 3.5+, Safari 3+
Chapter 6: CSS3 Proprietary and Emerging Features Reference 665
Note
• Firefoxbrowserssupportthispropertyas–moz-column-rule-widthandWebKit-
basedbrowserslikeChromeandSafarisupportitas–webkit-column-rule-width.
column-width
Thispropertydefinesthewidthofeachcolumninamulticolumntextflow.
Syntax
column-width:length|auto
PART II
wherelengthisapositivevalueforwidthbetweencolumnsinanyvalidCSSmeasurement.
Examples
.two-column{-moz-column-count:2;-webkit-column-count:2;column-count:2;
-moz-column-width:350px;
-webkit-column-width:350px;
column-width:350px;}
.three-column{-moz-column-count:3;-webkit-column-count:3;column-count:3;
-moz-column-width:6em;
-webkit-column-width:6em;
column-width:6em;}
Compatibility
CSS3 Chrome 2+, Firefox 1.5+, Safari 3+
Notes
• Firefoxbrowserssupportthispropertyas–moz-column-widthandWebKit-based
browserslikeChromeandSafarisupportitas–webkit-column-width.
• Ifcolumnwidthsaresettoosmallorlargeforthenumberofcolumnsandtext
provided,thebrowsercollapsestowhatmakessensetoflowthetext.
columns
Thispropertyisashorthanddefinitionofthenumberofcolumnsandtheirwidthsina
multicolumntextflow.
Syntax
columns:column-countwidth
wherecolumn-countisapositiveintegerforthenumberofcolumnstoflowthetextinto,and
widthisapositiveCSSlengthdefiningthewidthofeachcolumn.
Examples
.two-column{-webkit-columns:2100px;columns:2100px;}
.three-column{-webkit-columns:310em;columns:310em;}
666 Part II: Core Style
Compatibility
CSS3 Safari 3+
Notes
• WebKit-basedbrowserssupportthispropertyas–webkit-columns.
• SafaridocumentationcurrentlyreversesthevaluesfromtheCSS3specification,but
ineithercaseitdoesnotconsistentlysupportwidthvaluesregardlessofthe
positionofvalues.
filter
ThisMicrosoft-proprietarypropertyisusedtoapplyvisualeffectstoassociatedelements.
Syntax
filter:filtername(filtervalues)...filtername(filtervalues)
wherefilternamesisoneofthenumerousfiltersshowninTable6-8ortransitionsshownin
Table6-9.Itispossibletohavemultiplefilters.Theyneedtobeseparatedbyaspace.The
filtersareprocessedinorder.Alwaysplacetransitionslast.
Transitionsaredifferentfromfiltersinthattheytogglebetweentwodisplayblocksand
thetransitionneedstobeactivated.ThisisdonethroughJavaScriptbycallingtheApply()
functiononthefilter,updatingtheobject’svisibility,andthencallingplay()onthe
filter.Inthisexample,transitionistheidofadivwithimage1andimage2aschildren:
transition.filters[0].Apply();
image1.style.visibility="hidden";
image2.style.visibility="visible";
transition.filters[0].play();
Notethatalltransitionshavetheattributesduration,whichisanumberinseconds,and
enabled,whichistrueorfalse.
PART II
3. Call compositor.filters[0].Apply();.
4. Update the innerHTML of the region with inputB.
5. Call compositor.filters[0].Play();.
DropShadow filter:progid:DXImageTransform.Microsoft.DropShadow(Color
=999999,offX=3,offY=2,
positive=true);
Emboss filter:progid:DXImageTransform.Microsoft.Emboss();
Engrave filter:progid:DXImageTransform.Microsoft.Engrave();
Flip Horizontal filter:progid:DXImageTransform.Microsoft.
(Basic Image) BasicImage(rotation=2,mirror=1);
Flip Vertical (Basic filter:progid:DXImageTransform.Microsoft.
Image) BasicImage(mirror=1)
Glow filter:progid:DXImageTransform.Microsoft.Glow(
color=#ff4500,strength=5);
Gradient filter:progid:DXImageTransform.Microsoft.Gradient(gradien
tType=0,startColorStr=#0000ff,endColorStr=#ff8c00);
Grayscale (Basic filter:progid:DXImageTransform.Microsoft.
Image) BasicImage(grayscale=1);
ICMFilter filter:progid:DXImageTransform.Microsoft.ICMFilter(intent=
'Picture');
where intent can be Picture | Proof | Graphic | Match
Invert (Basic filter:progid:DXImageTransform.Microsoft.
Image) BasicImage(invert=1);
Light filter:progid:DXImageTransform.Microsoft.Light(enabled=1);
where the light source and color are defined by a function such as
addCone(iX1,iY1,iZ1,iX2,iY2,iRed,iGreen,iBlue,
iStrength,iSpread)
MaskFilter filter:progid:DXImageTransform.Microsoft.MaskFilter(color
=colorname)
where colorname is the color value (name or hex) to use as the mask.
PART II
squaresY: number indicating squares on the Y-axis
direction:up|down|right|left
Fade filter:progid:DXImageTransform.Microsoft.Fade(duration=2,
overlap=0.5);
where
overlap: number between 0 and 1 indicating fraction of time that both objects
are visible
GradientWipe filter:progid:DXImageTransform.Microsoft.
Wipe(GradientSize=0.7,wipeStyle=0,motion='forward');
GradientSize: number between 0 and 1 indicating fraction covered by the
gradient band
wipeStyle: 0 for left to right | 1 for top to bottom
motion:forward|reverse
Inset filter:progid:DXImageTransform.Microsoft.Inset();
Iris filter:progid:DXImageTransform.Microsoft.
Iris(irisStyle='star',motion='out');
where
irisStyle:circle|cross|plus|square|star
motion:in|out
Pixelate filter:progid:DXImageTransform.Microsoft.Pixelate(
MaxSquare=10,Duration=2);
where
MaxSquare: number indicating the max width of a pixel in the square
RadialWipe filter:progid:DXImageTransform.Microsoft.RadialWipe(
wipeStyle='clock');
where
wipeStyle:clock|wedge|radial
RandomBars filter:progid:DXImageTransform.Microsoft.RandomBars(
orientation='vertical');
where
orientation:horizontal|vertical
Examples
<h2style="filter:progid:DXImageTransform.Microsoft.Blur(Add=1,
Direction=90,Strength=20);width:100%;">Thisheaderisallblurry.</h2>
<pstyle="filter:progid:DXImageTransform.Microsoft.MotionBlur(strength=50)
progid:DXImageTransform.Microsoft.BasicImage(rotation=2,
mirror=1);">ITWASTHEBESToftimes,itwastheworstoftimes.</p>
PART II
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>filter-transitionsExample</title>
<metahttp-equiv="X-UA-Compatible"content="IE=7">
<styletype="text/css"media="screen">
div{padding:30px;}
#rd{filter:progid:DXImageTransform.Microsoft.RandomDissolve(duration=4);}
</style>
<scripttype="text/javascript">
window.onload=function(){
document.getElementById("rd").filters[0].Apply();
document.getElementById("rdimage1").style.visibility="hidden";
document.getElementById("rdimage2").style.visibility="visible";
document.getElementById("rd").filters[0].play();
};
</script>
<body>
<h2>RandomDissolve</h2>
<divid="rd"style="position:absolute;top:50px;left:10px;height:
250px;width:175px;">
<imgsrc="tucker.jpg"id="rdimage1"width="200"height="133"
style="position:absolute;top:0px;left:0px;">
<imgsrc="angus.jpg"id="rdimage2"width="200"height="133"
style="visibility:hidden;position:absolute;top:0px;left:0px;">
</div>
</body>
</html>
Compatibility
No standard IE 4+
672 Part II: Core Style
Notes
• UnderIE8thispropertyshouldbewrittenas–ms-filtertoshowitisan
extension.Youmayhavetousecompatibilitymodemanuallyorviaaheaderto
makefiltersandtransitionsworkotherwise.
• WhenusingthefilterpropertyforInternetExplorer,makesurethattheobject
haslayoutinthepagewhichisusuallyaccomplishedbysettingitssizeorposition.
• AcommonuseoffiltersthatseemstobeanacceptablehacktomanyWebdevelopers
istheuseofthealpha()filtertoemulatetheopacitypropertyinInternetExplorer:
.opacity{opacity:0.7;filter:alpha(opacity=70);zoom:1;}
gradient
ThisfunctioncreatesaCSSgradientimagethatcanbeusedanywhereanimageURLis
required,includingbackground-image,border-image,andlist-styleproperties.
Syntax
LinearSyntax:
gradient:linear,start_point,end_point,stop1[...stopN]
RadialSyntax:
gradient:radial,inner_center,inner_radius,outer_center,outer_radius,
stop1[...stopN]
Thesyntaxshowsthetypecanbelinearorradialandwilltakeslightlydifferentvalues
ineachcase.Whenstart_point,end_point,inner_center,andouter_centerare
used,theywillbeapairofvaluesthatcanbeanumber,percentage,orthekeywordstop,
bottom,left,andright.Thevaluesinner_radiusandouter_radiusarenumbersthat
canbespecifiedonlyifthetypeisradial.Thevaluesstop1(toN)areplaceholdersforthe
color-stop()functionthatindicateswhatthecolorshouldbeatagivenpointinthe
gradient.Thefunctioncolor-stop()takestwoarguments,thefirstofwhichisanumber
between0and1.0orapercentageindicatingthelocationofthestop.Thesecondargument
isthecoloratthatstopasastandardCSScolorvalue.Thefunctionsfrom(color-value)
andto(color-value)areshorthandforcolor-stop(0,color-value)andcolor-
stop(1,color-value),respectively,andcanbeusedinstead.
Examples
<divstyle="height:300px;width:200px;padding:20px;
border:5pxsolidblack;
background:-webkit-gradient(linear,lefttop,leftbottom,
from(#f00),to(rgba(0,255,0,0)),color-stop(.5,#00f));"></div>
<divstyle="height:300px;width:200px;padding:20px;
border:5pxsolidblack;
background:-webkit-gradient(radial,100100,20,200200,50,
from(#ff0),to(rgba(255,0,255,0)),color-stop(25%,#f00));"></div>
Chapter 6: CSS3 Proprietary and Emerging Features Reference 673
PART II
O NLINE http://htmlref.com/ch6/gradient.html
Compatibility
No specification Chrome 3+, Safari 4+
Notes
• InWebKit-basedbrowsersthispropertyisspecifiedas–webkit-gradient.
• GeneratedgradientscanbeusedanywherethatanimageURLisspecified.
image-rendering
Thispropertydefinestheresamplingmethodtousewhenstretchingimages.
Syntax
image-rendering:auto|inherit|optimizeSpeed|optimizeQuality
wherethedefaultvalueautousesabilinearresamplingschemetoprovidehighquality
withdecentspeed,avalueofoptimizeQualityemphasizesqualityoverspeed,and
optimizeSpeedrendersquicklywithsomelossofqualityintheresample.
Examples
<!--zoominbrowsertoseeeffect-->
<imgsrc="star.png">
<imgsrc="star.png"style="image-rendering:optimizeQuality;interpolation-
mode:bicubic;">
<imgsrc="star.png"style="image-rendering:optimizeSpeed;interpolation-
mode:nearest-neighbor;">
674 Part II: Core Style
Compatibility
No specification Firefox 3.6+
Notes
• ThispropertyisadoptedfromanSVGproperty.
• Thispropertyissimilartointerpolation-modeforInternetExplorer.
ime-mode
ThisMicrosoft-proposedCSSpropertyisusedtosetthestateofanInputMethodEditor
(IME),forusewithChinese,Japanese,andKoreancharactersets.
Syntax
ime-mode:auto|active|inactive|disabled
Example
<textareastyle="ime-mode:active;"></textarea>
Compatibility
No specification Firefox 3+, IE 5+
Notes
• UnderIE8thispropertyisknownas–ms-ime-modetocorrectlyshowitisan
extension.
• Firefox3alsosupportsthevalueofnormal.
interpolation-mode
Thispropertydefinestheresamplingmethodtousewhenstretchingimages.
Syntax
interpolation-mode:bicubic|nearest-neighbor
Example
<!--zoominbrowsertoseeeffect-->
<imgsrc="star.png">
<imgsrc="star.png"style="interpolation-mode:bicubic;image-rendering:
optimizeQuality;">
<imgsrc="star.png"style="interpolation-mode:nearest-neighbor;
image-rendering:optimizeSpeed;">
Compatibility
No specification IE 7+
Chapter 6: CSS3 Proprietary and Emerging Features Reference 675
Notes
• UnderIE8thispropertyisknownas–ms-interpolation-modetocorrectlyshow
itisanextension.
• Atstandardpagezoomnearest-neighborisused;otherwise,bicubicis
employedwhennotspecified.
• Thispropertyissimilartoimage-renderingforFirefox.
layout-grid
ThisMicrosoft-proposedCSSpropertydefinesagridtobeusedinlayingoutJapaneseor
ChinesecharactersinaWebdocument.Thisisashorthandpropertyforthemorespecific
PART II
layoutgridproperties.
Syntax
layout-grid:layout-grid-modelayout-grid-typelayout-grid-line
layout-grid-char
whereeachvaluecorrespondstothemorespecificproperty.
Example
<pstyle="layout-grid:charline12px12px.5in;">
Ashorttextsample.</p>
Compatibility
No specification IE 5+
Note
• UnderIE8thispropertyisknownas–ms-layout-gridtocorrectlyshowitis
anextension.
layout-grid-char
ThisMicrosoft-proposedCSSpropertydefinesthesizeofthecharactergridusedforlaying
outJapaneseorChinesecharactersinaWebdocument.
Syntax
layout-grid-char:none|auto|length|percentage
wherelengthisanypositivelengthunitandpercentageisavaluederivedfromthesizeofthe
parentelementtheruleisappliedto.
Example
<pstyle="layout-grid-char:50px">
Averyshorttextsample.</p>
Compatibility
No specification IE 5+
676 Part II: Core Style
Note
• UnderIEthispropertyisknownas–ms-layout-grid-chartocorrectlyshowitis
anextension.
layout-grid-line
ThisMicrosoft-proposedCSSpropertydefinesthegridlinevalueusedforlayingout
JapaneseorChinesecharactersinaWebdocument.
Syntax
layout-grid-line:none|auto|length|percentage
wherelengthisanypositivelengthunitandpercentageisavaluederivedfromthesizeofthe
parentelementtheruleisappliedto.
Example
<pstyle="layout-grid-line:100px;">
Ashorttextsample<br>
withlinebreaksso<br>
themeaningofthis<br>
propertywillbeobvious.</p>
Compatibility
No specification IE 5+
Note
• UnderIEthispropertyisknownas–ms-layout-grid-linetocorrectlyshowitis
anextension.
layout-grid-mode
ThisMicrosoft-proposedCSSpropertydefineswhetherthetextlayoutgridusesoneor
twodimensions.
Syntax
layout-grid-mode:both|none|line|char
wherelinespecifiestousealinegrid,charspecifiestouseacharactergrid,andboth
specifiestousebothgrids.Avalueofnoneturnsallgridsoff.Thedefaultisboth.
Example
<pstyle="layout-grid-mode:none;layout-grid-line:100px;">
Ashorttextsample<br>
withlayout-grid-mode<br>
settoavalueofnone<br>
toturnoffthegrid.</p>
Compatibility
No specification IE 5+
Chapter 6: CSS3 Proprietary and Emerging Features Reference 677
Note
• UnderIE8+thispropertyisknownas–ms-layout-grid-modetocorrectlyshowit
isanextension.
layout-grid-type
ThisMicrosoft-proposedCSSpropertydefinesthetypeofgridtobeusedforlayingout
JapaneseorChinesecharactersinaWebdocument.
Syntax
layout-grid-type:fixed|loose|strict
PART II
wherefixedisusedforamonospacefontlayout,strictisusedformostcomplex
ideographiccharactertypes,andlooseisusedformorealphabetictypeslikehiragana
inJapanese.
Example
<pstyle="layout-grid-type:strict;layout-grid-line:55px;">
AshorttextsamplewouldlikelybeinChinese,notEnglish.</p>
Compatibility
No specification IE 5+
Note
• UnderIE8+thispropertyisknownas–ms-layout-grid-typetocorrectlyshowit
isanextension.
line-break
Thispropertydefinesline-breakingrulesforAsiantext.
Syntax
line-break:normal|strict
Example
p{line-break:normal;}
Compatibility
No specification Chrome 1+, IE 5+, Safari 2+
Notes
• UnderIE8+thispropertyisknownas–ms-line-breaktocorrectlyshowitisan
extension.UnderWebKit-basedbrowsersthisiscalled–webkit-line-breaksince
Safari3.0and–khtml-line-breaksinceSafari2.0.
• ThispropertyisdeprecatedaccordingtoMicrosoftdocumentationandshouldbe
replacedbyword-breakpertheupcomingCSS3specification.
678 Part II: Core Style
marquee-direction
Thispropertyspecifiesthedirectioninwhichamarqueeshouldmove.
Syntax
marquee-direction:forward|reverse
Seethenotesforproprietaryequivalents.
Example
<pstyle="overflow:auto;
overflow-x:-webkit-marquee;
display:-wap-marquee;
overflow-style:marquee-line;
width:100px;
-webkit-marquee-direction:right;
-wap-marquee-dir:ltr;
marquee-direction:reverse;">
ABCDEFGHIJKLMNOPQRSTUVWXYZ
</p>
Compatibility
CSS3 Chrome 1+, Opera 8+, Safari 2+
Notes
• Thedefaultvalueisforward.
• ThispropertycanbereplicatedbyusingtheHTML<marquee>tagandsettingthe
directionattributetoleft|right|up|down.
• ThepropertywassupportedunderSafari2as–khtml-marquee-direction.
• Thispropertyissupportedas-webkit-marquee-directioninSafari3+.The
syntaxis
-webkit-marquee-direction:ahead|auto|backwards|down|forwards|
left|reverse|right|up
• Thispropertyissupportedas-wap-marquee-dirinOpera.Thesyntaxis
-wap-marquee-dir:ltr|rtl
• Accordingtothestandard,theactualdirectionofthemarqueemovementwill
dependontheoverflow-styleanddirectionoftextflowinthedocument
accordingtoTable6-10.
Ofcourse,ifthemarquee-styleissettoalternate,thedirectionswillflipback
andforth.
marquee-play-count
Thispropertydefineshowmanytimesthemarqueeruns.
Syntax
marquee-play-count:positivenumber|infinite
Example
<pstyle="overflow:auto;
PART II
overflow-x:-webkit-marquee;
display:-wap-marquee;
overflow-style:marquee-line;
width:100px;
-webkit-marquee-repetition:5;
-wap-marquee-loop:5;
marquee-play-count:5;">
ABCDEFGHIJKLMNOPQRSTUVWXYZ
</p>
Compatibility
CSS3 Chrome 1+, Opera 8+, Safari 2+
Notes
• Thispropertyisreplicableinmanybrowsersusinga<marquee>tag.
• Thedefaultvalueis1,meaningtheelementperformsitseffectonce.
• ThispropertycanbereplicatedusingtheHTMLmarqueetagandsettingtheloop
attributetoanumberorinfinite.
• Thispropertyissupportedas-webkit-marquee-repetitioninWebKit-based
browserslikeSafari.It’salsoknownas-khtml-marquee-repetitioninSafari2.0.
Inthesebrowsers,thedefaultisinfinite.Ifitisnotsettoinfinite,theelement
willdisappearafteritcompletestheloops.
• Thispropertyissupportedas-wap-marquee-loopinOperabrowsers.
• Forsomereason,youmayseeabrowserstopthemarqueeeffectafteracertain
numberofiterationsregardlessofsetting.
marquee-speed
Thispropertydefineshowfastthemarqueescrolls.
Syntax
marquee-speed:fast|normal|slow
Example
<pstyle="overflow:auto;
overflow-x:-webkit-marquee;
display:-wap-marquee;
680 Part II: Core Style
overflow-style:marquee-line;
width:100px;
-webkit-marquee-speed:fast;
-wap-marquee-speed:fast;
marquee-speed:fast;">
ABCDEFGHIJKLMNOPQRSTUVWXYZ
</p>
Compatibility
CSS3 Chrome 1+, Opera 8+, Safari 2+
Notes
• Thispropertyisreplicableinmanybrowsersusinga<marquee>tag.
• Thedefaultvalueisnormal.
• Thepropertyissupportedas–webkit-marquee-speedinSafari3+and-khtml-
marquee-speedinSafari2.0.
• InSafari,thereisanadditionalformat:
-webkit-marquee-speed:distance/time
• Thepropertyissupportedas–wap-marquee-speedinOperabrowsers.
marquee-style
Thispropertydefinesthemotionofthemarquee.
Syntax
marquee-style:alternate|scroll|slide
wherealternatecausesthemarqueetobouncebackandforth,scrollcausesthe
marqueetoscrollcompletelyoffofoneendbeforereappearingontheotherend,andslide
causesthemarqueetoresetassoonasallofthecontentisvisible.
Example
<pstyle="overflow:auto;
overflow-x:-webkit-marquee;
display:-wap-marquee;
overflow-style:marquee-line;
width:100px;
-webkit-marquee-style:alternate;
-wap-marquee-style:alternate;
-wap-marquee-loop:infinite;
marquee-style:alternate;">
ABCDEFGHIJKLMNOPQRSTUVWXYZ
</p>
Compatibility
CSS3 Chrome 1+, Opera 8+, Safari 2+
Chapter 6: CSS3 Proprietary and Emerging Features Reference 681
Notes
• Thispropertyisreplicableinmanybrowsersusinga<marquee>tag.
• Thedefaultvalueisscroll.
• ThispropertycanbereplicatedusingtheHTMLmarqueetagandsettingthe
behaviorattributetoalternate|scroll|slide.
• Thispropertyissupportedas-webkit-marquee-styleinSafari3+and–khtml-
marquee-styleinSafari2.
• Thispropertyissupportedas-wap-marquee-styleinOpera.
PART II
mask
Thispropertydefinesamasktobeusedasabox’soverlayinordertocliptheboxtoa
complexshape.Thisisashorthandpropertyforthemorespecificmaskproperties.
Syntax
mask:mask-attachment,mask-clip,mask-image,mask-repeat,mask-composite,
mask-box-image;
whereeachvaluecorrespondstothemorespecificproperty.
Example
<divstyle="height:100px;
width:200px;
background-color:red;
padding:20px;
border:5pxdashedblack;
-webkit-mask:scrollborder-webkit-gradient(linear,lefttop,
leftbottom,from(rgba(0,0,0,1)),to(rgba(0,0,0,0)))repeatborder;"></div>
O NLINE http://htmlref.com/ch6/mask.html
682 Part II: Core Style
Compatibility
No specification Safari 3.1+
Note
• InWebKit-basedbrowsersthispropertyis–webkit-mask.
mask-attachment
Thispropertyspecifieswhetherthemaskshouldscrollorstayfixedwhenthepageisscrolled.
Syntax
mask-attachment:fixed|scroll
wherethemaskwillscrollwiththepageonscrollandwillnotmoveonfixed.
Example
<imgsrc="main.jpg"style="-webkit-mask-image:-webkit-gradient(linear,
lefttop,rightbottom,from(rgba(0,0,0,1)),to(rgba(0,0,0,0)));
-webkit-mask-attachment:fixed;">
Compatibility
No specification Chrome 2+, Safari 3.1+
Note
• InWebKit-basedbrowsersthispropertyis–webkit-mask-attachment.
mask-box-image
Thispropertyspecifiesanimagetobeusedasamaskovertheborderboxofanelement.
Syntax
mask-box-image:[url()|function()]toprightbottomleftx_repeaty_repeat
whereurlisthelocationoftheimage,functionisafunctionthatgeneratesanimage,top,
right,bottom,andleftspecifythedistancesfromtheedgesoftheimage,andx_repeat
andy_repeatcanbesettorepeat,stretch,orroundtoindicatehowtheimageis
alteredtofitthedimensions.
Example
<imgsrc="main.jpg"style="-webkit-mask-box-image:url(mask.png)105050
10stretch;">
Compatibility
No specification Chrome 2+, Safari 3.1+
Note
• InWebKit-basedbrowsersthispropertyis–webkit-mask-box-image.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 683
mask-clip
Thispropertyspecifieswhetherthemaskclipstotheborder,padding,orcontent.
Syntax
mask-clip:border|padding|content
wherethemaskclipstothespecifiedoption.
Example
<!DOCTYPEhtml>
<html>
PART II
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>mask-clipExample</title>
<styletype="text/css">
div{height:50px;width:150px;
float:left;
margin:20px;padding:20px;
background-color:red;
font:boldxx-large;
border:15pxsolidblack;
-webkit-mask-image:url(starmask.png);
-webkit-mask-repeat:repeat;
-webkit-mask-size:20px20px;}
</style>
</head>
<body>
<divstyle="-webkit-mask-clip:content;">content</div>
<divstyle="-webkit-mask-clip:border;">border</div>
<divstyle="-webkit-mask-clip:padding;">padding</div>
</body>
</html>
O NLINE http://htmlref.com/ch6/maskclip.html
Compatibility
No specification Chrome 2+, Safari 3.1+
Note
• InWebKit-basedbrowsersthispropertyis–webkit-mask-clip.
684 Part II: Core Style
mask-composite
Thispropertyspecifiesthecompositingstyleforthemask.
Syntax
mask-composite:border|padding
wherethedefaultisborder.
Example
<divstyle="height:100px;width:200px;background-color:red;
padding:20px;border:5pxdashedblack;
-webkit-mask-image:-webkit-gradient(linear,lefttop,left
bottom,from(rgba(0,0,0,1)),to(rgba(0,0,0,0)));
-webkit-mask-composite:padding;"></div>
Compatibility
No specification Chrome 2+, Safari 3.1+
Note
• InWebKit-basedbrowsersthispropertyisspecifiedas–webkit-mask-composite.
mask-image
Thispropertyspecifiestheimagetobeusedfortheelement’smask.
Syntax
mask-image:url(image)|function
wherefunctionisafunctionthatgeneratesanimage.
Example
<imgsrc="tucker.jpg"width="200"height="133"
style="-webkit-mask-image:url(ovalmask.gif);">
O NLINE http://htmlref.com/ch6/maskimage.html
Chapter 6: CSS3 Proprietary and Emerging Features Reference 685
Compatibility
No specification Chrome 2+, Safari 3.1+
Note
• InWebKit-basedbrowsersthispropertyis–webkit-mask-image.
mask-origin
Thispropertyspecifieshowthepositionofthemaskshouldbecalculatedbysettingthe
originrelativetodifferentlocationswithinanelement’sbox.
PART II
Syntax
mask-origin:border|content|padding
wherethemaskwillbeanchoredtotheupper-leftcorneroftheelement’sborder,content,or
paddingbasedonthespecifiedoption.
Example
<divstyle="height:100px;width:200px;
background-color:red;
padding:20px;
border:5pxdashedblack;
-webkit-mask-image:-webkit-gradient(linear,lefttop,leftbottom,
from(rgba(0,0,0,1)),to(rgba(0,0,0,0)));
-webkit-mask-origin:padding;
-webkit-mask-clip:padding;">
</div>
Compatibility
No specification Chrome 3+, Safari 4+
Notes
• InWebKit-basedbrowsersthispropertyis–webkit-mask-origin.
• Ifmask-originissettopaddingandmask-clipissettoborder,itwillactasif
amaskwithalphavalue0isovertheborder,thereforerenderingitinvisible.
mask-position
Thispropertyspecifiesthepositionofthemask.
Syntax
mask-position:xposypos
686 Part II: Core Style
wherexposandyposaresetaccordingtothemorespecificmask-position-xandmask-
position-yproperties.
Examples
<imgsrc="tucker.jpg"width="200"height="133"
class="masked"style="-webkit-mask-position:10px10px;">
<imgsrc="tucker.jpg"width="200"height="133"
class="masked"style="-webkit-mask-position:righttop;">
<imgsrc="tucker.jpg"width="200"height="133"
class="masked"style="-webkit-mask-position:50%50%;">
O NLINE http://htmlref.com/ch6/maskposition.html
Compatibility
No specification Chrome 2+, Safari 3.1+
Note
• InWebKit-basedbrowsersthispropertyisknownas–webkit-mask-position.
mask-position-x
Thispropertyspecifiesthex-coordinateinthepositionofthemask.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 687
Syntax
mask-position-x:length|percentage|left|center|right
Example
<imgsrc="example.jpg"style="-webkit-mask-image:url(mask.png);
-webkit-mask-repeat:no-repeat;
-webkit-mask-position-x:180px;">
Compatibility
No specification Chrome 2+, Safari 3.1+
PART II
Note
• InWebKit-basedbrowsersthispropertyisknownas–webkit-mask-position-x.
mask-position-y
Thispropertyspecifiesthey-coordinateinthepositionofthemask.
Syntax
mask-position-y:length|percentage|top|center|bottom
Example
<imgsrc="example.jpg"style="-webkit-mask-image:url(mask.png);
-webkit-mask-repeat:no-repeat;
-webkit-mask-position-y:160px;">
Compatibility
No specification Chrome 2+, Safari 3.1+
Note
• InWebKit-basedbrowsersthispropertyisknownas–webkit-mask-position-y.
mask-repeat
Thispropertyspecifieshowthemaskimagewillrepeat.
Syntax
mask-repeat:repeat|repeat-x|repeat-y|no-repeat
wherethedefaultisrepeat.
Examples
<imgsrc="tucker.jpg"style="-webkit-mask-image:url(star.png);
-webkit-mask-repeat:repeat-x;">
<imgsrc="tucker.jpg"style="-webkit-mask-image:url(star.png);
-webkit-mask-repeat:no-repeat;">
688 Part II: Core Style
O NLINE http://htmlref.com/ch6/maskrepeat.html
Compatibility
No specification Chrome 2+, Safari 3.1+
Notes
• InWebKit-basedbrowsersthispropertyisknownas–webkit-mask-repeat.
• Ifthevalueisnotsettorepeat,anyareathatisnotcoveredbythemaskwillbe
treatedasifthereisamaskwithanalphavalueof0overitandthatareawillnot
display.
mask-size
Thispropertyspecifiesthesizeofamask.
Syntax
mask-size:length[length]
whereonelengthvalueindicatesboththewidthandheightandtwolengthvaluesindicate
thewidthfirstandthentheheight.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 689
Example
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>mask-sizeExample</title>
<styletype="text/css">
img.masked{-webkit-mask-image:url(starmask3.png);}
</style>
</head>
<body>
<imgsrc="tucker.jpg"width="200"height="133"
PART II
class="masked">
<imgsrc="tucker.jpg"width="200"height="133"
class="masked"style="-webkit-mask-size:10px;">
<imgsrc="tucker.jpg"width="200"height="133"
class="masked"style="-webkit-mask-size:50px50px;">
<imgsrc="tucker.jpg"width="200"height="133"
class="masked"style="-webkit-mask-size:200px133px;">
</body>
</html>
O NLINE http://htmlref.com/ch6/masksize.html
Compatibility
No specification Chrome 3+, Safari 4+
690 Part II: Core Style
Note
• InWebKit-basedbrowsersthispropertyis–webkit-mask-size.
opacity
Thispropertyspecifiesthetransparencyofanelement.
Syntax
opacity:alphavalue|inherit
wherealphavalueisanumberrangingfrom0.0,fullytransparent,to1.0,fullyopaque.
Examples
#tng{opacity:0.8;background-color:blue;}
#invisible{opacity:0;}
#blam{opacity:1;}
#ie2{opacity:0.7;filter:alpha(opacity=70);zoom:1;}
Compatibility
CSS3 Chrome 1+, Firefox 1+, IE 4+ (using filter property), Opera 9+, Safari 1.2+
Note
• WhenusingthefilterpropertyforInternetExplorer,makesurethattheopaque
objectthatyouwillapplytheeffecttohaslayout,whichisusuallyaccomplishedby
settingitssizeorposition.
outline-offset
Thispropertydefinestheoffsetfromanelement’sborderanditsoutline.
Syntax
outline-offset:length|inherit
wherelengthisanyvalidCSSlengthvalueusedtomovetheoutlineawayfromthe
element’sborder.Negativevaluesaresupportedandwillputtheoutlinewithinthe
element’sborder.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 691
Examples
#offset1{outline:dashed4pxgreen;border:solid10pxred;
outline-offset:15px;}
#offset2{outline:dashed4pxgreen;border:solid10pxred;
outline-offset:-45px;}
Compatibility
CSS3 Firefox 1.5+, Opera 9.5+, Safari 1.2+
Note
PART II
• BeforeFirefox1.5,Mozillabrowserssupportedtheequivalent–moz-outline-
offsetproperty.
outline-radius
Thispropertydefinestheroundingofthecornersonanoutline.
Syntax
outline-radius:lengths|inherit
wherelengthsisuptofourvalidCSSlengthorpercentagevaluestoroundthecornersofthe
outline.Whenmultiplevaluesareused,theyareappliedstartingwiththetopleftand
proceedingtotopright,bottomright,andfinallybottomleft.Thevaluescopyintothe
locationsopposite,similartohowmarginsandpaddingsarehandledinCSS.
Examples
#radius1{-moz-outline-radius:20px;}
#radius2{-moz-outline-radius:20px5px;}
#radius3{-moz-outline-radius:20px60px5px45px;}
Compatibility
CSS3 speculative Firefox 3+
Notes
• ThispropertyisalludedtoinCSS3discussions,thoughitisnotcurrently
documented.Thediscussionhereisbaseduponthecurrentimplementationin
Mozilla-basedbrowsers,whichsupportitas–moz-outline-radius.
• Mozillabrowsersalsodefine–moz-outline-radius-topleft,-moz-outline-
radius-topright,-moz-outline-radius-bottomright,and–moz-outline-
radius-bottomlefttosetthecornersindividually.
overflow-style
Thispropertyallowsamarqueetobeusedinthecaseofatextoverflow.
Syntax
overflow-style:auto|marquee-block|marquee-line
692 Part II: Core Style
Theinitialvalueisauto,whichallowstheuseragenttodeterminethescrollingeffect.A
valueofmarquee-lineemployshorizontalscrolling,andavalueofmarquee-block
employsverticalscrolling.Theparticulardirectionslefttorightorupanddownwill
dependonthetextdirectioninthedocument.
Example
<pstyle="overflow:auto;
overflow-x:-webkit-marquee;
display:-wap-marquee;
overflow-style:marquee-line;
width:100px;">
ABCDEFGHIJKLMNOPQRSTUVWXYZ
</p>
Compatibility
CSS3 Chrome 1+, Opera 8+, Safari 2+
Notes
• InSafari,itisnecessarytosetanelement’soverflow-xoroverflow-yto
-webkit-marqueetoactivatemarquee-stylefunctionality.
• InOpera,itisnecessarytosetanelement’sdisplayto-wap-marqueetoactivate
marqueeeffects.
overflow-x
Thispropertydefineshowcontentshouldbehavewhenitexceedsthewidthofitsenclosing
element.
Syntax
overflow-x:auto|hidden|scroll|visible
Example
<pstyle="overflow-x:scroll;width:100px;">
ABCDEFGHIJKLMNOPQRSTUVWXYZ
</p>
Compatibility
CSS3 Chrome 2+, Firefox 1+, IE 4+, Opera 9.5+, Safari 3+
Notes
• Thispropertyiscorrectlywrittenas–ms-overflow-xunderIE8toshowthatitis
anextension.
• ThisiscurrentlyintheCSS3specificationandalsosupportsvaluesofno-display
andno-content.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 693
overflow-y
Thispropertydefineshowcontentshouldbehavewhenitexceedstheheightofits
enclosingelement.
Syntax
overflow-y:auto|hidden|scroll|visible
Example
<pstyle="overflow-y:scroll;height:25px;width:50px;
background-color:#00f;">
ABC<br>
PART II
DEF<br>
GHI<br>
JKL<br>
MNO<br>
PQR<br>
STU<br>
VWXYZ</p>
Compatibility
CSS3 Chrome 2+, Firefox 1+, IE 4+, Opera 9.5+
Notes
• Thispropertyiscorrectlywrittenas–ms-overflow-yunderIE8toindicateitasan
extension.
• ThisiscurrentlyintheCSS3specificationandalsosupportsvaluesofno-display
andno-content.
• SomeFirefoxversionsputthescrollbarthewrongdirectionwiththisproperty.
perspective
Thispropertyisusedtogivea3-Dsenseofdepthtoanelement.Onlythechildrenofthe
elementaregiventhenotedperspective,nottheactualelementitself.
Syntax
perspective:none|number
wherenumberissettothedistanceofthez=0planefromtheviewer.Thedefaultisnone.
Examples
<divstyle="height:100px;width:180px;background-color:red;
-webkit-perspective:200;">Perspectiveset.<br><br>
<divstyle="height:50px;width:100px;background-color:blue;-webkit-
transform:rotateY(55deg);">
Childgainsperspective.
</div>
</div>
694 Part II: Core Style
<divstyle="height:100px;width:180px;background-color:red;">Noperspective
set.
<divstyle="height:50px;width:100px;background-color:blue;-webkit-
transform:rotateY(55deg);">
Noperspectiveused.
</div>
</div>
Compatibility
CSS3 Safari 4+
Notes
• WebKitsupportsthispropertyas–webkit-perspective,thoughitiscurrently
onlyavailableintheiPhoneandthedevelopmentbuildsofSafari4+onMacs.
• Thispropertyonlyworksinconjunctionwithanothertransformbecauseitalters
thewaytheothertransformacts.
perspective-origin
Thispropertyisusedtosetthexandyoriginsforthe–webkit-perspectiveproperty.
Syntax
perspective-origin:percentage|length|left|center|right[percentage|
length|top|center|bottom]
wherethedefaultvalueis50%50%.
Example
<divstyle="height:200px;width:200px;background-color:red;
-webkit-perspective:200;-webkit-perspective-origin:rightbottom;">
Perspectiveset.
<divstyle="position:relative;left:50px;top:50px;height:50px;
Chapter 6: CSS3 Proprietary and Emerging Features Reference 695
width:120px;background-color:blue;-webkit-transform:rotateY(55deg);">
Childgainsperspective.
</div>
</div>
PART II
Compatibility
CSS3 Safari 4+
Notes
• WebKitsupportsthispropertyas–webkit-perspective-origin,thoughitis
currentlyonlyavailableintheiPhoneandthedevelopmentbuildsofSafari4+on
Macs.
• Thispropertyonlyworksinconjunctionwiththe–webkit-perspectiveproperty.
resize
ThisCSS3propertyisusedtodefinewhetheranelementshouldberesizedand,ifso,upon
whataxis.
Syntax
resize:both|horizontal|none|vertical
Examples
<divstyle="height:100px;width:100px;margin:100px;border:1pxsolid
black;overflow:auto;resize:both;">Resizebothways</div>
<formaction="#"method="get">
<div><label>Username:
<inputtype="text"name="username"style="resize:horizontal;">
</label></div>
<div><label>Comments:
<textareaname="comments"style="resize:vertical;"></textarea>
</label>
</div>
</form>
696 Part II: Core Style
Thevisualpresentationofhowelementsshouldberesizedisnotset,butsofaritappears
thatsupportingbrowserspresentabottom-rightresizecornerindication.
Compatibility
CSS3 Chrome 3+, Safari 3+
Notes
• Thepropertyappliesonlytoelementsthatdonothaveanoverflowvalueof
visible.Ingeneral,thismeansthatoftenyoumaysetoverflow:autoon
elementsyouwishtoresize,asvisibleisthecommonvalue.Formfields,of
course,donothavethatvalueandrequirenoextraproperty.
• Thispropertyiscommonlyusedon<textarea>tags.
ruby-align
ThispropertydefinesthealignmentofRubytextasdefinedbya<rt>tag,inrelationto
basetextdefinedbya<ruby>tag.
Syntax
ruby-align:auto|center|distribute-letter|distribute-space|left|
line-edge|right
ThedefaultvalueofautoleavesittothebrowsertoaligntheRubytext.Avalueofcenter
centerstheRubytextinthecenterofthetextbelowifsmallerorcentersthereadingguide
textaboveiflarger.Thedistribute-letteranddistribute-spacevaluesdistributethe
readingguidetextevenlyacrossthetextbelow,addingspaceinthecaseofdistribute-
space.Valuesofleftandrightalignthereadingguidetextabovetotheleftorrightwhen
itissmallerthanthebasetext.Avalueofline-edgenormallycentersthereadingguidetext
unlessthetextisattheendoflinewhereinthatcaseitlinesituptotheedgeinstead.
Examples
<p>123<rubystyle="ruby-align:left;">日本語
<rp>(</rp><rt>にほんご</rt><rp>)</rp></ruby>456</p>
<p>123<rubystyle="ruby-align:right;">日本語<rp>(</rp><rt>にほんご</
rt><rp>)</rp></ruby>456</p>
<p>123<rubystyle="ruby-align:center;">日本語<rp>(</rp><rt>にほんご</
rt><rp>)</rp></ruby>456</p>
<p>123<rubystyle="ruby-align:distribute;">日本語<rp>(</rp><rt>にほんご</
rt><rp>)</rp></ruby>456</p>
Chapter 6: CSS3 Proprietary and Emerging Features Reference 697
PART II
Compatibility
CSS3 IE 5+
Note
• Thispropertywouldbecorrectlywrittenas–ms-ruby-alignunderIE8to
indicateitisanextension,butforsomereasonitisnotindicatedassuchinthe
documentation.
ruby-overhang
ThispropertydefinestheoverhangofRubytextasdefinedbya<rt>tag,inrelationtobase
textdefinedbya<ruby>taginregardtoadjacentcharacters.
Syntax
ruby-overhang:auto|none|whitespace
Examples
<p>123<rubystyle="ruby-overhang:whitespace;">
日本語<rp>(</rp><rt>にほんご</rt><rp>)</rp>
</ruby>456</p>
<p>123<rubystyle="ruby-overhang:auto;">
日本語<rp>(</rp><rt>にほんご</rt><rp>)</rp>
</ruby>456</p>
<p>123<rubystyle="ruby-overhang:none;">
日本語<rp>(</rp><rt>にほんご</rt><rp>)</rp>
</ruby>456</p>
Compatibility
CSS3 IE 5+
Notes
• Thispropertywouldbecorrectlywrittenas–ms-ruby-overhangunderIE8,but
forsomereasonthedocumentationdoesnotindicatethis.
• Thepositioningcanbequitesubtle.
698 Part II: Core Style
ruby-position
Thispropertydefinesthepositionofrubytextasdefinedbya<rt>tag,inrelationtobase
textdefinedbya<ruby>tag.
Syntax
ruby-position:above|inline
wherethecommonvalueisaboveandavalueofinlinerunstheguidetextaftertheitem.
Examples
<p>ruby-position:above<rubystyle="ruby-position:above;">日本語
<rp>(</rp><rt>にほんご</rt><rp>)</rp></ruby></p>
<p>ruby-position:inline<rubystyle="ruby-position:inline;">日本語
<rp>(</rp><rt>にほんご</rt><rp>)</rp></ruby></p>
Compatibility
CSS3 IE 5+
Note
• Thispropertywouldbecorrectlywrittenas–ms-ruby-positionunderIE8,but
forsomereasonthedocumentationdoesnotindicatethis.
scrollbar-3dlight-color
Thispropertyisusedtodefineacolorforthetopandleftedgesofthescrollboxin
ascrollbar.
Syntax
scrollbar-3dlight-color:color
wherecolorisastandardCSScolorvaluelike#f00,red,andsoon.
Example
<!--spaceintentionalforscrollbars-->
<form>
<div>
<textarearows="1"cols="20"style="scrollbar-3dlight-color:red;">
</textarea>
</div>
</form>
Chapter 6: CSS3 Proprietary and Emerging Features Reference 699
Compatibility
No specification IE 5.5+, Opera 9.5+
Notes
• Thispropertyiscorrectlywrittenas–ms-scrollbar-3dlight-colorunderIE8
toshowthatitisanextension.
• AmentionintheCSS3UIspecificationsaysthatthistypeoffeaturemaybe
consideredlater.
scrollbar-arrow-color
PART II
Thispropertyisusedtosetthecolorofthearrowiconwithinascrollbar.
Syntax
scrollbar-arrow-color:color
wherecolorisastandardCSScolorvaluelike#f00,red,andsoon.
Example
<!--spaceintentionalforscrollbars-->
<formaction="#"method="get">
<div>
<textarearows="1"cols="20"style="scrollbar-arrow-color:red;">
</textarea>
</div>
</form>
Compatibility
No specification IE 5.5+, Opera 9.5+
Notes
• Thispropertyiscorrectlywrittenas–ms-scrollbar-arrow-colorunderIE8to
showthatitisanextension.
• Thearrowswillnotcoloruntilthescrollregionisactiveandscrollingmaybe
needed.
• AmentionintheCSS3UIspecificationsaysthatthistypeoffeaturemaybe
consideredlater.
scrollbar-base-color
Thispropertysetsthebasecolorforascrollbar,whichwillincludethescrollbox,track,and
scrollarrows.
700 Part II: Core Style
Syntax
scrollbar-base-color:color
wherecolorisastandardCSScolorvaluelike#f00,red,andsoon.
Example
<!--spaceintentionalforscrollbars-->
<formaction="#"method="get">
<div>
<textarearows="1"cols="20"style="scrollbar-base-color:red;">
</textarea>
</div>
</form>
Compatibility
No specification IE 5.5+, Opera 9.5+
Notes
• Thispropertyiscorrectlywrittenas–ms-scrollbar-base-colorunderIE8to
showthatitisanextension.
• Settingthispropertytodefineabasecolorandthenoverridingindividualscroll
piecesmaybeuseful.
• AmentionintheCSS3UIspecificationsaysthatthistypeoffeaturemaybe
consideredlater.
scrollbar-darkshadow-color
Thispropertydefinesashadowcolorfortherightandbottomedgesofascrollbar.
Syntax
scrollbar-darkshadow-color:color
wherecolorisastandardCSScolorvaluelike#f00,red,andsoon.
Example
<formaction="#"method="get">
<div>
<textarearows="10"cols="20"style="scrollbar-darkshadow-color:red;">
</textarea>
</div>
</form>
Compatibility
No specification IE 5.5+, Opera 9.5+
Chapter 6: CSS3 Proprietary and Emerging Features Reference 701
Notes
• Thispropertyiscorrectlywrittenas–ms-scrollbar-darkshadow-colorunder
IE8toshowthatitisanextension.
• AmentionintheCSS3UIspecificationsaysthatthistypeoffeaturemaybe
consideredlater.
scrollbar-face-color
Thispropertydefinesacolorforthefaceofascrollbar,includingarrowregionsandthe
scrollbox.
PART II
Syntax
scrollbar-face-color:color
wherecolorisastandardCSScolorvaluelike#f00,red,andsoon.
Example
<formaction="#"method="get">
<div>
<textarearows="10"cols="20"style="scrollbar-face-color:red;">
</textarea>
</div>
</form>
Compatibility
No specification IE 5.5+, Opera 9.5+
Notes
• Thispropertyiscorrectlywrittenas–ms-scrollbar-face-colorunderIE8to
showthatitisanextension.
• Thereissomevariationinbrowserandversionastowhatpartsofthescrollbar
maybecoloredbytheproperty.
• AmentionintheCSS3UIspecificationsaysthatthistypeoffeaturemaybe
consideredlater.
scrollbar-highlight-color
Thispropertydefinesahighlightcolorforascrollbarandscrollarrows.
Syntax
scrollbar-highlight-color:color
wherecolorisastandardCSScolorvaluelike#f00,red,andsoon.
702 Part II: Core Style
Example
<formaction="#"method="get">
<div>
<textarearows="10"cols="20"style="scrollbar-highlight-color:red;">
</textarea>
</div>
</form>
Compatibility
No specification IE 5.5+, Opera 9.5+
Notes
• Thispropertyiscorrectlywrittenas–ms-scrollbar-highlight-colorunder
IE8toshowthatitisanextension.
• UndermodernversionsofInternetExplorer,thispropertyaffectsthescrolltrack
colorthatappliestothebottomofthetoparrow,andtotherightofthebottom
arrow.Inthissense,itisactingasthehighlightcolor.
• AmentionintheCSS3UIspecificationsaysthatthistypeoffeaturemaybe
consideredlater.
scrollbar-shadow-color
Thispropertydefinesacolorfortherightandbottomedgesofascrollbar.
Syntax
scrollbar-shadow-color:color
wherecolorisastandardCSScolorvaluelike#f00,red,andsoon.
Example
<formaction="#"method="get">
<div>
<textarearows="10"cols="20"style="scrollbar-shadow-color:red;">
</textarea>
</div>
</form>
Compatibility
No specification IE 5.5+, Opera 9.5+
Notes
• Thispropertyiscorrectlywrittenas–ms-scrollbar-shadow-colorunderIE8to
showthatitisanextension.
• AmentionintheCSS3UIspecificationsaysthatthistypeoffeaturemaybe
consideredlater.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 703
scrollbar-track-color
Thispropertydefinesthecolorofthescrollbarareauponwhichthescrollingboxtravels.
Syntax
scrollbar-track-color:color
wherecolorisastandardCSScolorvaluelike#f00,red,andsoon.
Example
<formaction="#"method="get">
<div>
PART II
<textarearows="10"cols="20"style="scrollbar-track-color:red;">
</textarea>
</div>
</form>
Compatibility
No specification IE 5.5+, Opera 9.5+
Notes
• Thispropertyiscorrectlywrittenas–ms-scrollbar-track-colorunderIE8to
showthatitisanextension.
• AmentionintheCSS3UIspecificationsaysthatthistypeoffeaturemaybe
consideredlater.
size
Thispropertyusedwithin@pagerulesspecifiesthesizeandorientationofapageboxfor
printing.
Syntax
size:lengthlength|auto|portrait|landscape|inherit
wheretheabsolutelengthunitsaregenerallydefinedastwovaluesforheightandwidth.
Relativevaluesincludelandscapeandportrait.Thedefaultvalueisauto.
Examples
@page{size:landscape;}
@page{size:8.5in11in;}/*standardUSpapersize*/
@page{size:6in10in;}/*funnywidthandheight*/
Compatibility
CSS2 only, 3 No browser support save buggy Opera implementation.
704 Part II: Core Style
Notes
• CSS2.1doesnotsupportthisproperty,thoughitisreintroducedinCSS3.
• Evenifabrowsersupportsthispropertytosomedegree,theprintdriverinteraction
maycausetrouble.Forexample,inOpera10,landscapemodedidnotforcethe
printdrivertoactuallychangepageorientation,socontentwasclipped.
text-align-last
Thispropertydefinesthetextalignmentrulesonthealignmentofthelastlineofanelement.
Syntax
text-align-last:auto|center|justify|left|right|inherit
Example
p{text-align:justify;text-align-last:left;}
.allRighty{text-align:justify;text-align-last:right;}
Compatibility
CSS3 IE 5+
Notes
• UnderIE8thispropertyisdefinedas–ms-text-align-lastasitiscurrentlyan
extension.
• Thispropertywouldapplytoanelementthathasonlyasinglelineinthesame
mannerastext-align.
text-autospace
Thispropertydefinesspacingvaluesforideographictext(forexample,Kanjicharacters)
whencombiningitwithdifferenttypesofcharacters,suchasWestern-languagetext,
numbers,andparentheses.
Syntax
text-autospace:ideograph-alpa|ideograph-numeric|ideograph-parenthesis|
ideograph-space|none
whereideograph-alphaindicatesthatextraspacingshouldbeplacedbetweenideographic
andnon-ideographictext,ideograph-numericaddsspacesbetweenideographictextand
numbers,ideographic-parenthesisaddsspaceswhenparenthesesareused,and
ideograph-spaceaddsextraspacewhenthespaceisfoundafteranideographiccharacter.
Examples
<pstyle="text-autospace:ideograph-alpha;">Japaneseis日本語inKanji.</p>
<pstyle="text-autospace:ideograph-numeric;">12345日本語678910</p>
Chapter 6: CSS3 Proprietary and Emerging Features Reference 705
Compatibility
CSS3 speculative IE 5+
Notes
• Asanextensionthispropertyiscorrectlywrittenas-ms-text-autospaceinIE8
andbeyond.
• ThecurrentCSS3specificationindicatesthispropertyisunderconsideration,butit
isnotcurrentlyfullydocumented.
• Theeffectofthispropertycanbeabitsubtle,soyoumayhavetoincreasefontsize
PART II
tonoticeitinplacesandcloselycompareittothesametextwithouttheproperty.
text-fill-color
Thispropertydefinesthecolorforfillinginatextblock.
Syntax
text-fill-color:colorvalue
wherecolorvalueisatypicalcolorvaluelike#f00orred.Bydefault,thefillcolorwillbe
whateverthecurrentcoloris.
Example
<h1style="font-size:70px;-webkit-text-fill-color:red;">
MerryChristmas</h1>
Compatibility
No specification Chrome 2+, Safari 3+
Notes
• UnderWebKit-basedbrowsersthispropertyisdefinedas-webkit-text-fill-
color.
• Thisisoftenusedinconjunctionwithtext-stroke.
text-justify
Thispropertyprovidesgreatercontroloverhowjustifiedtextshouldbealignedandspaced.
Syntax
text-justify:auto|distribute|distribute-all-lines|inter-cluster|
inter-ideograph|inter-word|kashida|newspaper
Thedefaultvalueofautoletsthebrowserdefinethejustificationalgorithmtouse.The
newspapervaluechangesthespacingbetweenlettersandwordstojustify.Ifyouset
inter-word,itsetsspacingsolelybetweenwords.Thevalueofdistributeissimilarto
newspaperbutoptimizedforAsianlanguages.Thevaluedistribute-all-linesisthe
706 Part II: Core Style
sameasdistributethoughitalsojustifiesthelastline.Avalueofinter-clusterisused
tojustifytextthatcontainsnointerwordspacingsuchasfoundinsomeAsianlanguages.
Avalueofinter-ideographcanjustifylinesofideographictextdealingwithspaces
betweenbothideogramsandwords.
Example
<pstyle="text-align:justify;text-justify:distribute-all-lines;
width:250px;">
Thisparagraphisnotonlyjustified,butthetext-justifyproperty
issettoavaluethatmakesthelastlinejustifyaswell.
</p>
Compatibility
CSS3 IE 5+
Notes
• UnderIE8thispropertyisknownas–ms-text-justifytocorrectlyshowitis
anextension.
• MSDNdocumentationpresentsavalueofdistribute-center-lastasbeing
defined,thoughitindicatesitisnotimplementedanddoesnotsaywhatitdoes.
However,itcouldbeinferredfromitsnamethatitdoesthesamethingas
distributebutcentersthefinalline.
• TheCSS3TextmoduledoessupportthispropertywithavalueofTibetanaswell.
Thereisconsiderabledetailinthejustificationalgorithms.Hopefully,thiscanbe
correctlyimplementedinuseragents,sojustifiedtextwillbecomedesirablebecause
ofits’improvedreadabilityandbemorecommonlyusedinWebdocuments.
text-kashida-space
ThisMicrosoft-proposedCSSpropertydefinestheratiobetweenKashidaexpansionand
whitespaceexpansioninjustifiedtext.KashidaisatypographiceffectusedwithArabic
writingsystemstoelongatecharactersduringthejustificationprocess.
Syntax
text-kashida-space:percentage|inherit
Example
.whiteOnly{text-align:justify;
text-kashida-space:0%;}
.stretchSome{text-align:justify;text-kashida-space:50%;}
.stretchAll{text-kashida-space:100%;}
Compatibility
No specification IE 5.5+
Chapter 6: CSS3 Proprietary and Emerging Features Reference 707
Notes
• UnderIE8thispropertyisknownas–ms-text-kashida-spacetocorrectlyshow
itisanextension.
• ThereisbriefallusiontothispropertyintheCSS3specificationsuggestingthatit
mayeventuallyendupintheCSS3Textmodule.
text-overflow
Thispropertydefineswhetherornotanellipsisshouldbedisplayedwhencontent
overflowsaregion.
PART II
Syntax
text-overflow:ellipsis|clip
Examples
p{width:200px;border:1pxsolidblack;
overflow:hidden;white-space:nowrap;
background-color:orange;}
.overflow{-ms-text-overflow:ellipsis;
-o-text-overflow:ellipsis;
-webkit-text-overflow:ellipsis;
text-overflow:ellipsis;}
Compatibility
CSS3 (see notes) Chrome 2+, IE 6+, Opera 9+, Safari 3+
Notes
• Forthispropertytowork,theoverflowpropertyoftheappliedelementshouldbe
settosomethingotherthanvisible.
• Thispropertyshouldbewrittenas–ms-text-overflowunderIE8asitisan
extension.Itissupportedas–o-text-overflowinOperaand–webkit-text-
overflowinWebKit-basedbrowsers.
• SomesitesontheWebindicate–moz-text-overflowassupportedbut,asof
Firefox3.5,documentationandtestingrevealsitisnot.Interestingly,scriptsexist
thattrytoimplementtheidea.
• TheCSS3specificationsuggeststhatthispropertyisshorthandfortext-
overflow-ellipsisandtext-overflow-mode.Thecurrentpropertyactsas
text-overflow-mode,whichsetshowoverflowshouldhappenwithanellipsis.
Thetext-overflow-ellipsispropertywouldbeusedtosetthestringorimage
tobeusedastheoverflowindicator.Atthetimeofthisedition’swriting,neither
propertyissupportedandthisportionofthespecificationisstillinprogress.
708 Part II: Core Style
text-rendering
ThisSVGinheritedpropertyprovidesinformationtothebrowserabouthowtextshouldbe
rendered.Generally,itisusedtospecifyatrade-offbetweenperformanceandquality.
Syntax
text-rendering:auto|optimizeSpeed|optimizeLegibility|
geometricPrecision|inherit
Thedefaultvalueisauto.AvalueofoptimizeSpeedtellsthebrowsertofocuson
renderingspeed,avalueofoptimizeLegibilitytellsthebrowsertofocusontextdetails
likekerningandligaturestoimprovereadability,andavalueofgeometricPrecisiontells
thebrowsertofocusonthegeometriclayoutoftextasopposedtospeedorreadability.
Examples
*{text-rendering:optimizeSpeed;}
.script{text-rendering:optimizeLegibility;}
Compatibility
No CSS specification (from SVG) Firefox 3+
Notes
• ThisisreallyanSVGpropertythatmayhaveapplicationswithinanHTMLdocument.
• IfusedinaCSSsetting,itwouldseemmoreappropriatelywrittenas–moz-text-
rendering,butthatcurrentlyisnotthecase.
text-shadow
Thispropertydefinesashadoweffectfortext.
Syntax
Theshadowisdefinedbyacomma-separatedlistofshadoweffectstobeappliedtothetext
oftheelement,
text-shadow:shadow1[,shadow2,...shadowN]
whereeachshadowvalueisdefinedas
horizontal-offsetvertical-offset[blur-radius]color
Theshadoweffectsareappliedintheorderspecifiedandmayoverlayeachother,butthey
willneveroverlaythetextitself.Eachshadoweffectmustspecifyashadowoffsethorizontally
andverticallyandmayoptionallyspecifyablurradiusandashadowcolor.
Ashadowoffsetisspecifiedwithtwolengthvalues,usuallyinabsolutemeasurement,
thatindicatethedistancefromthetext.Thehorizontaloffsetvaluespecifiesthehorizontal
distancetotherightofthetext.Anegativehorizontallengthvalueplacestheshadowto
Chapter 6: CSS3 Proprietary and Emerging Features Reference 709
theleftofthetext.Thesecondlengthvaluespecifiestheverticaldistancebelowthetext.
Anegativeverticallengthvalueplacestheshadowabovethetext.
Anoptionalblurradiusmaybespecifiedaftertheshadowoffset.Theblurradiusisa
lengthvaluethatindicatestheboundariesoftheblureffect.
Acolorvaluemayoptionallybespecifiedbeforeorafterthelengthvaluesofthe
shadoweffect.Thecolorvaluewillbeusedasthebasisfortheshadoweffect.Ifnocoloris
specified,thevalueofaninheritedcolorpropertyshouldbeused.
Examples
/*simplegrayshadowdrop*/
.dropShadow{text-shadow:2px2px0gray;}
PART II
/*redblurryshadowrightandbelow*/
.redblurry{text-shadow:3px3px5pxred;}
/*setsanoutlineeffectonthetext*/
.solar{background:white;color:white;text-shadow:black0px0px5px;}
/*multipleshadowsapplied*/
.ugly{text-shadow:2px2px0pxred,2px-2px0pxgreen,-4px-4px0pxblue;}
O NLINE http://htmlref.com/ch6/textshadow.html
Compatibility
CSS2, 3 Chrome 2+, Firefox 3.5+, Opera 9.5+, Safari 3+
Notes
• ThispropertywasdroppedfromCSS2.1butisincludedagaininCSS3.
• Theremaybelimitstotheapplicationofmultipleshadows,bybrowser.Someinitial
implementationsdidnotallowformorethanoneshadow,andsomecapped
shadowlimitsatvariousnumberslikesix.
• InternetExplorercansupporttextshadowsusingitsproprietaryCSSfilters
technology.Forexample,
<h1style="filter:progid:DXImageTransform.Microsoft.DropShadow(color
="gray",offX=2,offY=2);">IEDropShadow!</h1>
710 Part II: Core Style
wouldactsimilarlytothestandard
<h1style="text-shadow:2px2px0gray;">RegularDropShadow!</h1>
text-stroke
Thisisashorthandpropertytodefinethewidthandcolorfortheoutlineofatextblock.
Syntax
text-stroke:text-stroke-widthtext-stroke-color
Examples
<h1style="font-size:70px;-webkit-text-fill-color:red;
-webkit-text-stroke:2pxgreen;">MerryChristmas</h1>
<h1style="font-size:70px;-webkit-text-stroke:1pxblack;
color:white;">Outlined!</h1>
Compatibility
No specification Chrome 1+, Safari 3+
Notes
• UnderWebKit-basedbrowsersthispropertyisdefinedas-webkit-text-stroke.
• Thispropertyisoftenusedinconjunctionwithtext-fill-color.
text-stroke-color
Thispropertydefinesthecolorfortheoutlineofatextblock.
Syntax
text-stroke-color:colorvalue|currentColor
wherecolorvalueisatypicalCSScolorvaluelike#f00,red,andsoon.Thedefaultis
currentColor.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 711
Example
<h1style="font-size:70px;-webkit-text-stroke-color:red;
-webkit-text-stroke-width:1px;">MerryChristmas</h1>
Compatibility
No specification Chrome 2+, Safari 3+
Notes
• UnderWebKit-basedbrowsersthispropertyisdefinedas-webkit-text-stroke-
color.
PART II
• Thispropertyisusedinconjunctionwithtext-stroke-widthandoftenwith
text-fill-color.
text-stroke-width
Thispropertydefinesthewidthfortheoutlineofatextblock.
Syntax
text-stroke-width:length|thin|medium|thick
Thedefaultlengthis0,soitisnecessarytosetthispropertyifusingtext-stroke-color,
ortheoutlinewillnotdisplay.
Example
<h1style="font-size:70px;-webkit-text-stroke-color:red;
-webkit-text-stroke-width:1px;">MerryChristmas</h1>
Compatibility
No specification Chrome 2+, Safari 3+
Notes
• UnderWebKit-basedbrowsersthispropertyisdefinedas-webkit-text-stroke-
width.
• Thispropertyisusedinconjunctionwithtext-stroke-colorandoftenwith
text-fill-color.
text-underline-position
ThisMicrosoft-introducedpropertydefinesthepositionofunderliningsetbythetext-
decorationproperty.
Syntax
text-underline-position:above|auto|below
712 Part II: Core Style
Example
<pstyle="text-decoration:underline;
text-underline-position:above;">
Thisexampleusesthetext-underline-positionpropertyto
placetheunderliningontopofthetext.Whynotjustset
text-decorationtooverlineinstead?</p>
Compatibility
CSS3 preliminary IE 5+
Note
• UnderIE8thispropertyisalsoknownandshouldbesetas–ms-text-underline-
positiontocorrectlyidentifyitasanextensioninastandards-compliantmode.
• Thevalueofauto-posisalsounderstoodandisthesamefunctionasauto.
• ThispropertyhasmadesomeappearancesinCSS3,butsofaritsfutureisfarfrom
certainasanofficialstandard.
transform
Thispropertyallowselementstobeoffset,rotated,scaled,andskewedinavarietyof
differentways.
Syntax
transform:listoftransform-functions|none
wheretransform-functionsincludethevaluesinTable6-11.
Examples
#transform1{-moz-transform:scale(1.2,1.9);
-webkit-transform:scale(1.2,1.9);}
#transform2{-moz-transform:scaleX(.5);
-webkit-transform:scaleX(.5);}
#transform3{-moz-transform:scaleY(3.5);
-webkit-transform:scaleY(3.5);}
#transform4{-moz-transform:skew(120deg,45deg);
-webkit-transform:skew(120deg,45deg);}
#transform5{-moz-transform:skewX(45deg);
-webkit-transform:skewX(45deg);}
#transform6{-moz-transform:skewY(45deg);
-webkit-transform:skewY(45deg);}
#transform7{-moz-transform:rotate(90deg);
-webkit-transform:rotate(90deg);}
#transform8{-moz-transform:translate(20%,30%);
-webkit-transform:translate(20%,30%);
background-color:yellow;}
Chapter 6: CSS3 Proprietary and Emerging Features Reference 713
PART II
specified by x, y, and z.
rotateX(angle) In the 3-D realm. Rotates the object around the X axis.
rotateY(angle) In the 3-D realm. Rotates the object around the Y axis.
rotateZ(angle) In the 3-D realm. Rotates the object around the Z axis.
scale(number,number) Scales the object by the scale values specified. Where 1 is
the same scale of the object and numbers less than one
scale the objects smaller and greater than one larger. If the
second value for Y scale is omitted, it is assumed to be the
same as the first.
scale3d(number, In the 3-D realm. Same as the previous function, but adds a
number,number) parameter for the Z scale.
scaleX(number) Scales the object only on the X axis, keeping Y the same.
Same as scale(X,1).
scaleY(number) Scales the object only on the Y axis, keeping X the same.
Same as scale(1,Y).
scaleZ(number) In the 3-D realm. Scales the object only on the Z axis. Same
as scale3d(1,1,Z).
skew(angle,angle) Skews the element along the X and Y axes by the specified
angle values. The second value may be missing and
assumed to be 0.
skewX(angle) Skews the element along the X axis by the specified angle.
skewY(angle) Skews the element along the Y axis by the specified angle.
translate(translation-value- Specifies a translation by the vector translation-value-x,
x,translation-value-y) translation-value-y. The translation-value-y is optional and will
be 0 if not specified.
translate3d(translation- In the 3-D realm. Same as the previous entry except it includes
value-x,translation-value-x the Z axis. The translation-value-z cannot be a percentage.
y,translation-value-z)
translateX(translation-value) Specifies a translation by translation-value in the X direction.
translateY(translation-value) Specifies a translation by translation-value in the Y direction.
translateZ(translation-value) In the 3-D realm. Specifies a translation by translation-value
in the Z direction. Cannot be a percentage.
#transform9{-moz-transform:translateX(50px);
-webkit-transform:translateX(50px);
background-color:green;}
#transform10{-moz-transform:translateY(20px);
-webkit-transform:translateY(20px);
background-color:blue;}
Compatibility
CSS3 Chrome 2+, Firefox 3+, Safari 3.1+
Notes
• Firefoxsupportsthispropertyas–moz-transformandWebKitsupportsitas
–webkit-transform.
• Atthetimeofthisedition’swriting,Safarihasaddedin3-DsupporttotheiPhone
anditsdevelopmentbuilds.Currently,thetransformationfunctionsthatare
indicatedtobefor3-Donlyworkinthiscase.
• ManyofthesecapabilitiesaresupportedinIE5.5byusingthefilterpropertyand
applyingaMatrixfunction.
Chapter 6: CSS3 Proprietary and Emerging Features Reference 715
transform-origin
Thispropertyisusedtoestablishthepointoforiginwhenapplyingatransformationon
anelement.
Syntax
transform-origin:percentage|length|left|center|right[percentage|
length|top|center|bottom]
wherethefirstvalueiseitherapercentage,aCSSlength(whichmaybenegative),orakeyword
specifyingthehorizontalposition,andthesecondvaluespecifiestheverticalposition.
Ifasinglevalueisset,itisassumedtobehorizontalandtheverticalvalueissetto50%.
PART II
Examples
<imgsrc="logo.gif">
<p> </p>
<imgsrc="logo.gif"style="-moz-transform:skewX(55deg);-webkit-transform:
skewX(55deg);">
<p> </p>
<imgsrc="logo.gif"style="-moz-transform:skewX(55deg);-moz-transform-
origin:0%0%;-webkit-transform:skewX(55deg);-webkit-transform-origin:0%
0%;">
Original Skew
Original Changed
Compatibility
CSS3 Chrome 2+, Firefox 3.5+, Safari 3.1+
Notes
• Firefoxsupportsthispropertyas–moz-transform-originandWebKitsupportsit
as–webkit-transform-origin.
• Atthetimeofthisedition’swriting,Safarihasaddedin3-Dsupporttoits
developmentbuildsforMacs.Ifthetransformationisin3-D,athirdnumberis
expectedspecifyingthezorigin.Theformatisthesameasxandyorigins.
716 Part II: Core Style
transform-style
Thispropertyisusedtodefinehownesteditemsarerenderedina3-Dspace,thechoice
beingeitherflattenedorwiththeirdimensionspreserved.Thispropertyaffectsthechildren
oftheelementandnottheelementitself.Also,thepropertydoesnotcascade,soitis
necessarytoapplyitatalllevels.
Syntax
transform-style:flat|preserve-3d
wherethedefaultvalueisflat,indicatingthatallchildrenelementswillbeflattenedinto
the2-Dplane.Ifthevalueissettopreserve-3d,thenthechildrenwouldpreservetheir
dimensions.
Examples
<divstyle="height:200px;width:200px;background-color:red;
-webkit-perspective:200;">
Perspectiveset
<divstyle="height:100px;width:100px;background-color:blue;
-webkit-transform:rotateY(55deg);-webkit-transform-style:
preserve-3d;">
preserve-3d
<divstyle="height:60px;width:50px;background-color:green;
-webkit-transform:rotateY(25deg);">
preserved
</div>
</div>
</div>
<divstyle="height:200px;width:200px;background-color:red;
-webkit-perspective:200;">
Perspectiveset
<divstyle="height:100px;width:100px;background-color:blue;
-webkit-transform:rotateY(55deg);-webkit-transform-style:flat;">
flat
<divstyle="height:60px;width:50px;background-color:green;
-webkit-transform:rotateY(25deg);">
flat
</div>
</div>
</div>
Chapter 6: CSS3 Proprietary and Emerging Features Reference 717
Compatibility
CSS3 Safari 4+
Notes
• WebKitsupportsthispropertyas–webkit-transform-style,thoughitiscurrently
onlyavailableintheiPhoneandthedevelopmentbuildsofSafari4+.
• Sometimesitisnotpossibletopreserve3-D,suchaswhenanelementhasits
overflowpropertysettohidden.
transition
PART II
Thisshorthandpropertyisusedtodescribealltransition-relatedpropertiesatonce.
Syntax
transition:transition-propertytransition-duration
transition-timing-functiontransition-delay
wheretheindividualtransitionpropertiesaredefinedintheirownentries.Multiple
transitionscanbelistedseparatedbycommas.
Example
<divid="d1"style="
-webkit-transition:background-color3sease-out,
opacity5slinear3s;
transition:background-color3sease-out,opacity5slinear3s;
background-color:red;
height:100px;
width:100px;
text-align:center;">Clickme</div>
O NLINE http://htmlref.com/ch6/transition.html
Compatibility
Notes
• WebKitsupportsthispropertyas–webkit-transition.Firefoxbrowserswould
usea–mozprefix.
• ThesimilaritywithanimationpropertiessuggeststhatCSStransitionsmayinclude
similarsyntaxforkeyframesorthatonesyntaxwillbeeliminated.
transition-delay
Thispropertyisusedtodefineadelaybeforeananimationstarts.
718 Part II: Core Style
Syntax
transition-delay:time1[,..timeN]
wheretimeisastandardCSStimevaluelike2sor4700ms.Thedefaultvalueis0,meaning
theanimationstartsimmediately.Ifthedelayisanegativenumber,theanimationstarts
immediatelybutbeginsatthepointitwouldbeatifitwerealreadyrunningsincethe
negativenumber.
Example
<divid="d1"style="-webkit-transition-property:all;
-webkit-transition-delay:1s;
transition-property:all;
transition-delay:1s;
background-color:red;
height:100px;
width:100px;
text-align:center;">Clickme</div>
Compatibility
Note
• WebKitsupportsthispropertyas–webkit-transition-delay.Firefoxbrowsers
wouldusea–mozprefix.
• Firefoxsupportisbaseduponapre-releaseversioncurrentlynumberedas3.7,
thoughthisissubjecttochange.
transition-duration
Thispropertyisusedtodefinethetimeittakesoneiterationofananimationtoplay.
Syntax
transition-duration:time[,time]*
wheretimeisavalidtimevaluelike5sor3500ms.Thedefaultvalueoftimeis0,meaningno
animationplays.
Example
<divid="d1"style="-webkit-transition-property:height,width;
-webkit-transition-duration:1s,3s;
transition-property:height,width;
transition-duration:1s,3s;
background-color:red;
height:100px;
width:100px;
text-align:center;">Clickme</div>
Chapter 6: CSS3 Proprietary and Emerging Features Reference 719
Compatibility
CSS3 Proposed Chrome 2+, Firefox 3.7+, Safari 3.1+
Note
• WebKitsupportsthispropertyas–webkit-transition-duration.Firefox
browserswouldusea–mozprefix.
• Firefoxsupportisbaseduponapre-releaseversioncurrentlynumberedas3.7,
thoughthisissubjecttochange.
transition-property
PART II
Thispropertyisusedtodefinewhichpropertiesatransitionwillbeappliedto.
Syntax
transition-property:all|none|property-name-1[,...property-name-N]-
whereproperty-nameissimplyaCSSpropertynamelikecolor.Thedefaultvalueisall,
whichindicatesthatanypropertychangewillbeanimated.Multiplepropertiescanbe
listedinacomma-separatedlist.Ifthisisthecase,othertransitionpropertiescanalsobe
listedwithacomma-separatedlist,andthevalueswillmatchupinorder.
Example
<divid="d1"style="-webkit-transition-property:background-color,opacity;
-webkit-transition-duration:3s,5s;
transition-property:background-color,opacity;
transition-duration:3s,5s;
background-color:red;
height:100px;
width:100px;
text-align:center;">Clickme</div>
Compatibility
CSS3 Proposed Chrome 2+, Firefox 3.7+, Safari 3.1+
Notes
• WebKitsupportsthispropertyas–webkit-transition-property.Firefox
browserswouldusea–mozprefix.
• ThesimilaritywithanimationpropertiessuggeststhatCSStransitionsmayinclude
similarsyntaxorthatonesyntaxformmayprevail.
• Firefoxsupportisbaseduponapre-releaseversioncurrentlynumberedas3.7,
thoughthisissubjecttochange.
transition-timing-function
Thispropertyisusedtodescribehowtheanimationwillplay.
720 Part II: Core Style
Syntax
transition-timing-function:timingfunction[,timingfunction2,
...timingfunctionN]
wheretimingfunctionisoneofthefollowingvalues:
cubic-bezier(number,number,number,number)|ease|ease-in|ease-in-out|
ease-out|linear
Thedefaultvalueisease.
Example
<divid="d1"style="-webkit-transition-property:height,width;
-webkit-transition-duration:5s;
-webkit-transition-timing-function:ease-out,ease-in;
transition-property:height,width;
transition-duration:5s;
transition-timing-function:ease-out,ease-in;
background-color:red;
height:100px;
width:100px;
text-align:center;">Clickme</div>
O NLINE http://htmlref.com/ch6/transitiontiming.html
Compatibility
Notes
• WebKitsupportsthispropertyas–webkit-transition-timing-function.
Firefoxbrowserswouldusea–mozprefix.
• ThesimilaritywithanimationpropertiessuggeststhatCSStransitionsmayinclude
similarsyntaxorthatonesyntaxformmayprevaileventually.
• Firefoxsupportisbaseduponapre-releaseversioncurrentlynumberedas3.7,
thoughthisissubjecttochange.
user-select
Thispropertydefinesthetextselectionpolicyforvariousportionsofadocument.
Syntax
user-select:all|none|text
wherethedefaultvalueallallowsforselection.
Examples
<p>Thisisregulartextyoushouldbeabletoselectit.</p>
Chapter 6: CSS3 Proprietary and Emerging Features Reference 721
<pstyle="-webkit-user-select:none;-moz-user-select:none;user-select:
none;">ThistexthassomesimpleCSSpropertiestokeepyoufromselecting
it.</p>
<pstyle="-webkit-user-select:text;-moz-user-select:text;user-select:
text;">Thistextselectablebutnottheimagehere<imgsrc="logo.gif">
sorry!</p>
Compatibility
CSS3 Chrome 1+, Firefox 1+, Safari 3+
Notes
PART II
• CSS3specifiesnumerousothervalues,liketoggle,element,andelements,but
theyarenotcoveredherebecausetheyhaveyettobeimplemented.
• JavaScriptcanbeusedtocontrolselections,includingtodenythem.
• Firefoxsupports-moz-user-selectandSafari3+supports-webkit-user-select.
• Safari2supportedthispropertyas-khtml-user-select.
word-break
ThisMicrosoft-proposedCSSpropertynowfoundinCSS3canbeusedtoallowlinebreaks
withinwords.
Syntax
word-break:break-all|keep-all|normal
Example
<divstyle="word-break:break-all;width:50px;">
Wordscanbreakinthiscodeexample.Likethisone:
Sesquipedalianism</div>
Compatibility
CSS3 IE 5.5+
Notes
• ThispropertyisprimarilyusedforChinese/Japanese/Korean(CJK)text,
particularlywhenmultiplelanguageslikeEnglisharecombinedinaswell.
• UnderIE8thispropertyisalsoknownas–ms-word-breaktocorrectlyidentifyit
asanextensioninstandards-compliantmode.
• CSS3supportsloose(sameasnormal)andbreak-strict.
• Whenusedwithintables,thetable-layoutpropertymustbesettofixed
accordingtoMicrosoftforcorrectoperation.
722 Part II: Core Style
word-wrap
Thispropertycanbesettoallowlinebreakswithinwordswhencontentexceedsthelimits
ofitscontainingelement.
Syntax
word-wrap:break-word|normal
Example
<pstyle="word-wrap:break-word;width:30px;">
Wordscanbreakinthisexampleeveniftheyareveryveryverylong.Hereis
anotherlongone:Transcendentalismthismightgetsplitintwo!</p>
Compatibility
CSS3 IE 5.5+
Note
• UnderIE8thispropertyisalsoknownandshouldbesetas–ms-word-wrapto
correctlyidentifyitasanextensioninastandards-compliantmode.
writing-mode
ThisMicrosoft-proposedCSSpropertycanbeusedtosettextflowappropriateforEuropean
alphabetsorEastAsianalphabets.
Syntax
writing-mode:bt-lr|bt-rl|lr-bt|lr-tb|rl-tb|rl-bt|tb-rl|tb-lr
Valuesarebt(bottomtotop),lr(lefttoright),rl(righttoleft),andtb(toptobottom)and
arecombinedinavarietyofways.
Examples
<pstyle="writing-mode:tb-rl;">
Toptobottom,righttoleft.
</p>
<pstyle="writing-mode:tb-lr;">
Toptobottom,lefttoright.
</p>
Chapter 6: CSS3 Proprietary and Emerging Features Reference 723
PART II
Compatibility
CSS3 IE 5.5+
Notes
• ThecurrentCSS3specificationshowsonlylr-tb,rl-tb,tb-rl,andtb-lrvalues.
• UnderIE8thispropertyshouldbewritteninsteadas-ms-writing-modeto
specifyitasanextension.
• IE8addedtb-lr,bt-lr,lr-bt,andrl-bt.
• UnderIE8–ms-writing-modeshouldbeused,giventhepropertyisstillemerging.
724 Part II: Core Style
zoom
Thispropertyisusedtozoominoroutonanelement.
Syntax
zoom:float|percentage|normal
whereapercentagevalueof100%orafloatvalueof1.0isthesameasnormal.Avalueof
200%or2.0isequivalent,while0.5and50%isthesameaswell.
Examples
.double{zoom:200%;}
.double2{zoom:2.0;}
.reallysmall{zoom:0.10;}
.reallysmall2{zoom:10%;}
#zoomOff{zoom:normal;}
Compatibility
No specification IE 5.5+
Notes
• UnderIE8thisshouldbewrittenas-ms-zoomtospecifyitasanextension.
• Somedevelopersfindsettingthezoompropertyto1.0ausefulwaytoforcelayout
inInternetExplorerwhenanelementisnotshowingitselfproperly.
• Firefoxandotherbrowsersimplementuser-initiatedzoomingfeaturesatthe
browserlevel.Becauseofthiscapability,thispropertyorasimilarfeaturewillbe
likelyaddedtotheseotherbrowsersforcontrolbyCSSorJavaScriptsometimein
thefuture.
III PART
Appendixes APPENDIX A
CharacterEntities
APPENDIX B
Fonts
APPENDIX C
Colors
APPENDIX D
URLs
APPENDIX E
ReadingaDocument
TypeDefinition
This page intentionally left blank
APPENDIX
A
Character Entities
K
eyboardcharacterssuchas<and>havespecialmeaningsto(X)HTMLbecausethey
arepartofHTMLtagsandmustbeencoded.Othercharacters,suchascertain
foreignlanguageaccentcharactersandspecialsymbols,canbedifficulttospecify,
dependingonthekeyboardbeingused.Toaddressescapingofspecial-purposecharacters
andinsertingawiderangeofcharactersandsymbols,characterentitiesshouldbe
employed.
Theformatofcharacterentitiesisingeneral
&code;
wherecodemaybea
• AdecimalformlikeË
• AhexformlikeËorstrippedofleadingzeros,simply&xCB;
• Anamedvalueifavailable,suchasË
NOTE Whenusingahexform,eitheralowercaseoruppercasexmaybeusedaswellasupper-
andlowercasevaluesfordigitsA–F,soËandËandËandsoonareall
equivalent.Casesensitivityisnot,however,guaranteedfornamedentitiesandmayresultin
errorsorwrongcharacters.Goodstylewouldsuggestlowercaseforthehexsymbolanduppercase
forthedigits.
Asanexample,
<p>Numericentitydecimal:£</p>
<p>Numericentityhex:£</p>
<p>Namedentity:£</p>
727
728 Part III: Appendixes
wouldlooklikethis:
<p>Doesthis<ahref="http://www.pint.com/program?p1=foo&p2=bar">link</a>
validate?</p>
Themarkupwillnotvalidate.
Forthislinetovalidate,youmustencodethespecialcharactersinthelinklikeso:
<p>Doesthis<ahref="http://www.pint.com/program?p1=foo&p2=bar">link</a>
validate?</p>
Donot,however,takethisasadvicetochangeampersandsintypedURLseverywhereyou
encounterthem,suchaswithine-mailsorthebrowser’slocationbar.Typically,abrowser
willexchangeanentityforitscorrectvalue,butthischangemaynottakeplaceinother
environments.
Commonly,youwillalsohavetroublewhenusingcharactersthatarepartof(X)HTML
itself,particularlythelessthan(<)andgreaterthan(>)symbolsand,ofcourse,the
ampersandthatstartsentities.Asanexample,considerthiscontrivedexamplewitha
mathematicalexpression:
<p>Asillymathstatementaheadx<y>zisdangeroustovalidation.</p>
Appendix A: Character Entities 729
Forthegreatestsafety,themarkupshouldhavehadthespecialcharactersencodedlikeso:
<p>Asillymathstatementaheadx<y>zisnotdangerousto
validation.</p>
Wenotethatthisexampleisfairlycontrivedandoftenjustanextraspacewillallowthe
validator(andbrowser)totokenizethetextcorrectly.Forexample,
<p>Asillymathstatementaheadx<y>zisdangeroustovalidation?</p>
willlikelyvalidate.Thelooseenforcementofspecialcharacterhandlingisbothablessing
andacurse.Itleadstosloppyusageandsurprisingbugs.
Sloppysyntaxistroublingbecauseinterpretationmayvarybrowsertobrowser.
Considerthepointofcasesensitivityofnamedentitiesinbrowsers.Namedentitiesare
supposedtobecasesensitive.Forexample,àandÀaretwodifferent
characters.
PART III
Nowgiventhisfact,whatshouldabrowserdowhenfacedwith
<p>&POUND;and£</p>
Apparentlyittreatsthefirstastextandthesecondasanentity.
Butdoesthatholdforallcharacters?Apparentlynot—someentitieslike©are
generallycaseinsensitive,whileotherslike™mayvarybybrowser,andotherslike
¥willalwaysbecasesensitive.
InitialdraftsofHTML5attemptedtoformalizewhatnamedentitiesshouldbecase
insensitive;thesedraftsfocusedonthecommonlyusedandsupportedentities.Thecurrent
listofwhatshouldbecase-insensitivenamedentitiesisshowninTableA-1.
Bestpractice,however,wouldbenottorelyoncaseinsensitivityofnamedentities,itis
stillinconsistent.Ingeneral,laxsyntaxenforcementandpermissiveinterpretationof
entitiesinbrowsersjustleadstoallsortsofsmallquirks.Consider
<p>"E;and"e;</p>
730 Part III: Appendixes
UnderInternetExplorer,therenderingengineeveninastrictmodewill“fix”this
problemandeffectivelyconvertthisinto
<p>"E;and"e;</p>
whileotherbrowserswillcorrectlyleavethismistakealone.
WhileitturnsoutthatSGML(andthustraditionalHTML)doesallowthefinal
semicolontobeleftoffinanentityinsomecases,theprecedingexampleclearlyindicatesit
doesnotallowforthatlatitudeinthemiddleofwords.Justaswhendealingwithmarkup
andCSS,itisbesttogetsyntaxrightratherthanrelyonsomevariablefix-upappliedbya
browser’srenderingengine.
Therewillbeinstanceswhenyoumaygetthesyntaxcorrectbutthebrowsermaynotbe
abletorenderthecharactersmeaningfully.Thereasonsfornonsupportcanvaryandmay
bebecauseaparticularfontismissingortheoperatingenvironmentorbrowserisunableto
renderthecharacter.Generally,browserswillpresentthesefailuresasboxesordiamonds,
likeso:
Appendix A: Character Entities 731
Content-Type:text/html;charset=ISO-8859-1
Ormorecommonly,itwillappearina<meta>taglikeso:
<metahttp-equiv="content-type"content="text/html;charset=ISO-8859-1">
However,WebpageauthorsarealwaysencouragedtousetheUTF-8encodingset
eitherbyheader,
Content-Type:text/html;charset=utf-8
orbytag,
PART III
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
unlesstheyhavesomeoverridingreasonnotto.
RecognizingthemovetowardUnicode,weprovidethosevaluesaswellinalltables.
However,giventhevastrangeofthepossiblecharactersweonlypresentthoseUnicode
entitiesthatareexplicitlynamedinthe(X)HTMLspecificationscircalate2009.Formore
informationonUnicode,seethesectionentitled“EmbracingUnicode”laterinthe
appendix.
C AUTION Entityvaluesfrom127to159arenotassigned.Webpageauthorsareadvisednottouse
them.Interestingly,someoftheserenderingsarecommon,thoughtheymayworkforonlycertain
operatingsystemfontcombinations.TableA-2putsthesevaluesinitalicstoemphasizethey
shouldbeavoided.
NOTE Thetrademarkcharacter(™)mayhaveconcernsacrossbrowsersandoperatingsystem
combinations,particularlyarchaicones.Webpageauthorsconcernedwithperfectbackward
compatibilitymightwanttoconsiderusingaworkaroundsuchas<sup><small>TM
</small></sup>forthissymbol.
732 Part III: Appendixes
Intended
Named Entity Numbered Entity Unicode Entity Rendering Description
    Space
! ! ! Exclamation point
" " " “ Double quotes
# # # Number symbol
$ $ $ Dollar symbol
% % % Percent symbol
& & & & Ampersand
' ' ‘ Single quote
( ( ( Opening parenthesis
) ) ) Closing parenthesis
* * * Asterisk
+ + + Plus sign
, , , Comma
- - - Minus sign (hyphen)
. . . Period
/ / / Slash/virgule/bar
0 0 0 Zero
1 1 1 One
2 2 2 Two
3 3 3 Three
4 4 4 Four
5 5 5 Five
6 6 6 Six
7 7 7 Seven
8 8 8 Eight
9 9 9 Nine
: : : Colon
; ; ; Semicolon
< < < < Less-than symbol
= = = Equal sign
Intended
Named Entity Numbered Entity Unicode Entity Rendering Description
> > > > Greater-than symbol
? ? ? Question mark
@ @ @ At symbol
A A A Capital letter a
B B B Capital letter b
C C C Capital letter c
D D D Capital letter d
E E E Capital letter e
F F F Capital letter f
G G G Capital letter g
H H H Capital letter h
I I I Capital letter i
PART III
J J J Capital letter j
K K K Capital letter k
L L L Capital letter l
M M M Capital letter m
N N N Capital letter n
O O O Capital letter o
P P P Capital letter p
Q Q Q Capital letter q
R R R Capital letter r
S S S Capital letter s
T T T Capital letter t
U U U Capital letter u
V V V Capital letter v
W W W Capital letter w
X X X Capital letter x
Y Y Y Capital letter y
Z Z Z Capital letter z
[ [ [ Opening bracket
\ \ \ Backslash
Intended
Named Entity Numbered Entity Unicode Entity Rendering Description
] ] ] Closing bracket
^ ^ ^ Caret
_ _ _ Underscore
` ` ` Grave accent, no letter
a a a Lowercase letter a
b b b Lowercase letter b
c c c Lowercase letter c
d d d Lowercase letter d
e e e Lowercase letter e
f f f Lowercase letter f
g g g Lowercase letter g
h h h Lowercase letter h
i i i Lowercase letter i
j j j Lowercase letter j
k k k Lowercase letter k
l l l Lowercase letter l
m m m Lowercase letter m
n n n Lowercase letter n
o o o Lowercase letter o
p p p Lowercase letter p
q q q Lowercase letter q
r r r Lowercase letter r
s s s Lowercase letter s
t t t Lowercase letter t
u u u Lowercase letter u
v v v Lowercase letter v
w w w Lowercase letter w
x x x Lowercase letter x
y y y Lowercase letter y
z z z Lowercase letter z
{ { { Opening brace
Intended
Named Entity Numbered Entity Unicode Entity Rendering Description
| | | Vertical bar
} } } Closing brace
~ ~ ~ Equivalency symbol (tilde)
  No character
€ € € No character defined, typically
Euro. However € or
€ or € should
be used instead.
  No character defined.
Trademark symbol on some
systems (nonstandard). Use
™ or ™ instead.
‚ ‚ , Low-9 quote (nonstandard)
ƒ ƒ ƒ Small “f” with hook
PART III
(nonstandard)
„ „ „ Low-9 double quotes
(nonstandard)
… … … Ellipsis (nonstandard)
† † † Dagger (nonstandard)
‡ ‡ ‡ Double dagger (nonstandard)
ˆ ˆ ^ Circumflex accent, no letter
(nonstandard)
‰ ‰ ‰ Per mille (nonstandard)
Š Š Š Uppercase S with caron
(nonstandard)
‹ ‹ ‹ Opening single-angle quote
(nonstandard)
Œ Œ Œ Uppercase “OE” ligature
(nonstandard)
  Ÿ No character, though for
some uppercase “Y” with
umlaut (nonstandard)
Ž Ž Ž Uppercase “Z” with caron
  No character
  No character
Intended
Named Entity Numbered Entity Unicode Entity Rendering Description
‘ ‘ ` Opening “smart” single quote
(nonstandard)
’ ’ ‘ Closing “smart” single quote
(nonstandard)
“ “ “ Opening “smart” double
quote (nonstandard)
” ” ” Closing “smart” double quote
(nonstandard)
• • • Bullet (nonstandard)
– – – En dash (nonstandard)
— — — Em dash (nonstandard)
˜ ˜ ~ Tilde (nonstandard)
™ ™‡ ™ ™ Trademark symbol
(nonstandard) Use ™
or ™ instead
š š Š Lowercase S with caron
(nonstandard)
› › › Closing single-angle quote
(nonstandard)
œ œ œ Lowercase “oe” ligature
(nonstandard)
  No character
ž ž Ž Lowercase “z” with caron.
(nonstandard)
Ÿ Ÿ Ÿ Uppercase “Y” with umlaut
(nonstandard)
    Nonbreaking space
¡ ¡ ¡ ¡ Inverted exclamation point
¢ ¢ ¢ ¢ Cent symbol
£ £ £ £ Pound sterling symbol
¤ ¤ ¤ ¤ Currency symbol
¥ ¥ ¥ ¥ Japanese Yen
¦ ¦ ¦ ¦ Broken vertical bar
§ § § § Section symbol
Intended
Named Entity Numbered Entity Unicode Entity Rendering Description
¨ ¨ ¨ ¨ Umlaut, no letter
© © © © Copyright symbol
ª ª ª a Feminine ordinal indicator
« « « « Opening double-angle quote
¬ ¬ ¬ ¬ Logical “not” symbol
­ ­ ­ - Soft hyphen
® ® ® ® Registration mark
¯ ¯ ¯ – Macron
° ° ° ° Degree symbol
± ± ± ± Plus/minus symbol
² ² ² 2
Superscript 2
³ ³ ³ 3
Superscript 3
PART III
´ ´ ´ ´ Acute accent, no letter
µ µ µ µ Micron
¶ ¶ ¶ ¶ Paragraph symbol
· · · · Middle dot
¸ ¸ ¸ ¸ Cedilla
¹ ¹ ¹ 1
Superscript 1
º º º ° Masculine ordinal indicator
» » » » Closing double-angle quotes
¼ ¼ ¼ ¼ One-quarter fraction
½ ½ ½ ½ One-half fraction
¾ ¾ ¾ ¾ Three-fourths fraction
¿ ¿ ¿ ¿ Inverted question mark
À À À À Uppercase “A” with grave
accent
Á Á Á Á Uppercase “A” with acute
accent
    Uppercase “A” with
circumflex
à à à à Uppercase “A” with tilde
Ä Ä Ä Ä Uppercase “A” with umlaut
Intended
Named Entity Numbered Entity Unicode Entity Rendering Description
Å Å Å Å Uppercase “A” with ring
Æ Æ Æ Æ Uppercase “AE” ligature
Ç Ç Ç Ç Uppercase “C” with cedilla
È È È È Uppercase “E” with grave
accent
É É É É Uppercase “E” with acute
accent
Ê Ê Ê Ê Uppercase “E” with
circumflex
Ë Ë Ë Ë Uppercase “E” with umlaut
Ì Ì Ì Ì Uppercase “I” with grave
accent
Í Í Í Í Uppercase “I” with acute
accent
Î Î Î Î Uppercase “I” with circumflex
Ï Ï Ï Ï Uppercase “I” with umlaut
Ð Ð Ð Ð Capital “ETH”
Ñ Ñ Ñ Ñ Uppercase “N” with tilde
Ò Ò Ò Ò Uppercase “O” with grave
accent
Ó Ó Ó Ó Uppercase “O” with acute
accent
Ô Ô Ô Ô Uppercase “O” with
circumflex
Õ Õ Õ Õ Uppercase “O” with tilde
Ö Ö Ö Ö Uppercase “O” with umlaut
× × × × Multiplication symbol
Ø Ø Ø Ø Uppercase “O” with slash
Ù Ù Ù Ù Uppercase “U” with grave
accent
Ú Ú Ú Ú Uppercase “U” with acute
accent
Û Û Û Û Uppercase “U” with
circumflex accent
Intended
Named Entity Numbered Entity Unicode Entity Rendering Description
Ü Ü Ü Ü Uppercase “U” with umlaut
Ý Ý Ý Ý Uppercase “Y” with acute
accent
Þ Þ Þ þ Capital “thorn”
ß ß ß ß “SZ” ligature
à à à à Lowercase “a” with grave
accent
á á á á Lowercase “a” with acute
accent
â â â â Lowercase “a” with circumflex
ã ã ã ã Lowercase “a” with tilde
ä ä ä ä Lowercase “a” with umlaut
å å å å Lowercase “a” with ring
PART III
æ æ æ æ Lowercase “ae” ligature
ç ç ç ç Lowercase “c” with cedilla
è è è è Lowercase “e” with grave
accent
é é é é Lowercase “e” with acute
accent
ê ê ê ê Lowercase “e” with circumflex
ë ë ë ë Lowercase “e” with umlaut
ì ì ì ì Lowercase “i” with grave
accent
í í í í Lowercase “i” with acute
accent
î î î î Lowercase “i” with circumflex
ï ï ï ï Lowercase “i” with umlaut
ð ð ð ð Lowercase “eth”
ñ ñ ñ ñ Lowercase “n” with tilde
ò ò ò ò Lowercase “o” with grave
accent
ó ó ó ó Lowercase “o” with acute
accent
Intended
Named Entity Numbered Entity Unicode Entity Rendering Description
ô ô ô ô Lowercase “o” with circumflex
accent
õ õ õ õ Lowercase “o” with tilde
ö ö ö ö Lowercase “o” with umlaut
÷ ÷ ÷ ÷ Division symbol
ø ø ø ø Lowercase “o” with slash
ù ù ù ù Lowercase “u” with grave
accent
ú ú ú ú Lowercase “u” with acute
accent
û û û û Lowercase “u” with circumflex
ü ü ü ü Lowercase “u” with umlaut
ý ý ý ý Lowercase “y” with acute
accent
þ þ þ þ Lowercase “thorn”
ÿ ÿ ÿ ÿ Lowercase “y” with umlaut
Toaddressthisissue,someofthetablesthatfollowincludespecialnotesindicatingthe
lackofsupportbeforetheintroductionofIE8.
Foreaseofconsumption,theentitiesaregroupedmuchinthewaytheyarefoundinthe
HTML4specification.
Latin Extended-A
Numbered Unicode Intended
Named Entity Entity Entity Rendering Description
&Oelig; Œ Œ Œ Uppercase ligature “OE”
œ œ œ œ Lowercase ligature “oe”
Š Š Š Š Uppercase “S” with caron
š š š š Lowercase “s” with caron
Ÿ Ÿ Ÿ Ÿ Uppercase “Y” with
umlaut
PART III
Latin Extended-B
Named Entity Numbered Entity Unicode Entity Intended Rendering Description
ƒ ƒ ƒ ƒ Latin small “f” with
hook
General Punctuation
Greek
Unicode Intended
Named Entity Numbered Entity Entity Rendering Description
Α Α Α Α Greek capital letter alpha
Β Β Β Β Greek capital letter beta
Γ Γ Γ Γ Greek capital letter gamma
Δ Δ Δ ∆ Greek capital letter delta
Ε Ε Ε Ε Greek capital letter epsilon
Ζ Ζ Ζ Ζ Greek capital letter zeta
Η Η Η Η Greek capital letter eta
Θ Θ Θ Θ Greek capital letter theta
Ι Ι Ι Ι Greek capital letter iota
Κ Κ Κ Κ Greek capital letter kappa
Λ Λ Λ Λ Greek capital letter lambda
PART III
Μ Μ Μ Μ Greek capital letter mu
Ν Ν Ν Ν Greek capital letter nu
Ξ Ξ Ξ Ξ Greek capital letter xi
Ο Ο Ο Ο Greek capital letter omicron
Π Π Π Π Greek capital letter pi
Ρ Ρ Ρ Ρ Greek capital letter rho
Σ Σ Σ Σ Greek capital letter sigma
Τ Τ Τ Τ Greek capital letter tau
Υ Υ Υ Υ Greek capital letter upsilon
Φ Φ Φ Φ Greek capital letter phi
Χ Χ Χ Χ Greek capital letter chi
Ψ Ψ Ψ Ψ Greek capital letter psi
Ω Ω Ω Ω Greek capital letter omega
α α α α Greek small letter alpha
β β β β Greek small letter beta
γ γ γ γ Greek small letter gamma
δ δ δ δ Greek small letter delta
ε ε ε ε Greek small letter epsilon
ζ ζ ζ ζ Greek small letter zeta
744 Part III: Appendixes
Greek (continued)
Unicode Intended
Named Entity Numbered Entity Entity Rendering Description
η η η η Greek small letter eta
θ θ θ θ Greek small letter theta
ι ι ι ι Greek small letter iota
κ κ κ κ Greek small letter kappa
λ λ λ λ Greek small letter lambda
μ μ μ µ Greek small letter mu
ν ν ν ν Greek small letter nu
ξ ξ ξ ξ Greek small letter xi
ο ο ο ο Greek small letter omicron
π π π π Greek small letter pi
ρ ρ ρ ρ Greek small letter rho
ς ς ς ς Greek small letter final sigma
σ σ σ σ Greek small letter sigma
τ τ τ τ Greek small letter tau
υ υ υ υ Greek small letter upsilon
φ φ φ φ Greek small letter phi
χ χ χ χ Greek small letter chi
ψ ψ ψ ψ Greek small letter psi
ω ω ω ω Greek small letter omega
ϑ ϑ ϑ ϑ Greek small letter theta symbol
ϒ ϒ ϒ ϒ Greek upsilon with hook symbol
ϖ ϖ ϖ ϖ Greek pi symbol
Letter-like Symbols
Numbered Unicode Intended
Named Entity Entity Entity Rendering Description Notes
℘ ℘ ℘ ℘ Script capital P, No support pre-IE8
power set
ℑ ℑ ℑ ℑ Blackletter No support pre-IE8
capital I, or
imaginary part
symbol
Appendix A: Character Entities 745
Arrows
PART III
Numbered Unicode Intended
Named Entity Entity Entity Rendering Description Notes
← ← ← ← Leftward arrow
↑ ↑ ↑ ↑ Upward arrow
→ → → → Rightward arrow
↓ ↓ ↓ ↓ Downward arrow
↔ ↔ ↔ ↔ Left-right arrow
↵ ↵ ↵ ↵ Downward arrow No support
with corner leftward pre-IE8
⇐ ⇐ ⇐ ⇐ Leftward double No support
arrow pre-IE8
⇑ ⇑ ⇑ ⇑ Upward double No support
arrow pre-IE8
⇒ ⇒ ⇒ ⇒ Rightward double No support
arrow pre-IE8
⇓ ⇓ ⇓ ⇓ Downward double No support
arrow pre-IE8
⇔ ⇔ ⇔ ⇔ Left-right double No support
arrow pre-IE8
746 Part III: Appendixes
Mathematical Operators
PART III
⊇ ⊇ ⊇ ⊇ Superset of or No support pre-IE8
equal to
⊕ ⊕ ⊕ ⊕ Circled plus, No support pre-IE8
direct sum
⊗ ⊗ ⊗ ⊗ Circled times, No support pre-IE8
vector product
⊥ ⊥ ⊥ ⊥ Perpendicular No support pre-IE8
⋅ ⋅ ⋅ · Dot operator No support pre-IE8
Technical Symbols
Named Numbered Intended
Entity Entity Unicode Entity Rendering Description Notes
⌈ ⌈ ⌈ Left ceiling
⌉ ⌉ ⌉ Right ceiling
⌊ ⌊ ⌊ Left floor
⌋ ⌋ ⌋ Right floor
⟨ 〈 〈 (also < Left-pointing No support pre-IE8
⟨) angle bracket
⟩ 〉 〉 (also > Right-pointing No support pre-IE8
⟩) angle bracket
748 Part III: Appendixes
Geometric Shapes
Intended
Named Entity Numbered Entity Unicode Entity Rendering Description Notes
◊ ◊ ◊ ◊ Lozenge
Miscellaneous Symbols
Numbered Unicode Intended
Named Entity Entity Entity Rendering Description Notes
♠ ♠ ♠ ♠ Spade suit
♣ ♣ ♣ ♣ Club suit
♥ ♥ ♥ ♥ Heart suit
♦ ♦ ♦ ♦ Diamond suit
Embracing Unicode
Therearemorespecialcharactersbesideswhatisdefinedinthe(X)HTMLspecifications.
WhenlookingattheHTML4entities,youcanseeamappingbetweenUnicodecharacters
(suchasthediamondsuitcharacterrepresentedbyUnicodeU+02666andanamedentity
like♦),whichhintsatthelargercharactersetavailable.
ToproperlysupportUnicodecharacters,(X)HTMLshouldbedeliveredwiththe
appropriateHTTPresponseheader:
Content-Type:text/html;charset=utf-8
orwitha<meta>tagintheheadelementofsimilarvalue:
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
Inafewcaseswhenamarkupelementsupportsacharsetattribute,youcansetthe
characterencodingvaluethereaswell.
<ahref="sushimenu.html"charset="utf-8">SushiMenu</a>
However,theheaderor<meta>tagsolutionisfavoredoverthisaccordingtothe
specification.
UnicodecharactersbeyondwhatisdefinedunderHTML4andXHTML1couldbe
named.Tothisend,theW3ChasstartedtodefineentitynamesforXML(www.w3.org/TR/
xml-entity-names/),butthesenamedentitiesarenotcurrentlysupported,asillustratedby
thissmallexample:
<p>☎☎</p>
Appendix A: Character Entities 749
wherebrowserswillunderstandthenumericcode,butnotthenamedentity.
YoucouldpullinanXMLentitydeclarationinanXSLstylesheettobindtheitemsof
interest,butthatisnotreasonableandwouldgetquitelarge,somostWebdeveloperswill
waituntilsuchnamedentitiesarenative.
NOTE HTML5doesdocumentmanyUnicodeentities,forexample,▾but
thesituationisnodifferentforHTML5thaninpreviousefforts;littleornosupportisfoundat
thetimeofthisedition’swriting.
Atthistimeandlikelyforsometimeinthefuture,itispreferabletousenumericentities
toinsertanyUnicodecharacterintoanysupportingbrowser.Forexample,here
<p>日本語</p>
theentitiesproducetheKanjifor“nihongo”or“Japaneselanguage”shownnext:
PART III
ItshouldbenotedthattheappearanceofUnicodecharactersmaychangedramatically
acrossbrowsersandsystems,dependingonthefontsupported.Forexample,noticethe
obviousvariationintherenderingofthepreviousexampleacrossthefourmostpopular
browsers.
Dependingonthefontinplace,insomecasestheUnicodecharactersmaynotbe
supportedatallandmostbrowserswillpresenttheunsupportedcharactericon,butnotice
howsomemayindicatewithinittheUnicodevaluethatismissing,whichisslightlymore
informative.
This page intentionally left blank
APPENDIX
B
Fonts
T
hisappendixcontainsaquickreferenceforcommonlyavailablefontsandbrief
discussionsofdownloadablefontsandvarioustextreplacementtechniquesto
improveonlinetypography.
Specifying Fonts
UnderHTML4.01andtransitionalXHTML1.0,youcanusethe<font>tagtosetafontin
apagebysettingthefaceattribute:
<p>Thisisstandardtext.<fontface="BritannicBold">Thisistextin
BritannicBold?</font>Morestandardtext.</p>
AWebbrowserthatreadsthisHTMLfragmentshouldrenderthetextinthefontnamedin
thefaceattribute,butonlyforuserswhohavethefontinstalledontheirsystems.To
addressthepossibilityofmissingfonts,multiplefontnamescanbelistedusingtheface
attribute:
<p>Thisisstandardtext.<fontface="Arial,Helvetica,sans-serif">
ThisshouldbeinoneoftheSansSeriffontslistedordefaulttothe
standardsans-seriffontinstalled</font>Thisismorestandardtext.</p>
Here,thebrowserreadsthecomma-delimitedlistoffontsuntilitfindsafontitsupports.If
nomatchisfound,thebrowserwilldefaulttothefontcurrentlyinuse.
Strictvariantsof(X)HTMLaswellastheupcomingHTML5specificationremovethe
roleofmarkupinsettingfonts.OfcourseCSSsupportsthesamebasicapproachtosetting
751
752 Part III: Appendixes
fontsusingfont-familyandfontproperties.Forexample,tosetthefontmoreorlessas
wedidinpreviousHTMLexamples,youwouldusearulelikethefollowing:
<p>Thisisstandardtext.<spanstyle="font-family:BritannicBold;">Thisis
textinBritannicBold?</span>Morestandardtext.</p>
Ofcourse,thesamerestrictionoffontsavailableonthelocalsystemapplies,soa
comma-delimitedlistoffontsshouldbespecifiedlikeso:
<p>Thisisstandardtext.<spanstyle="font-family:Arial,Helvetica,sans-
serif;">ThisshouldbeinoneoftheSansSeriffontslistedordefaultto
thestandardsans-seriffontinstalled</span>Thisismorestandardtext.</
p>
Clearlytheseexamplesaremoreillustrativethanappropriate,asweshoulduseexternal
stylesheetsandthelike.Ourmainaiminthisappendixistoshowthatregardlessofthe
approachtakentoeffectivelyusefontsinthismanner,wemustprovideanequivalentlistof
fonts,oratleastroughlyso,acrossMacintosh,Windows,andLinuxsystemsifweaimto
provideasimilartextrendering.Thefollowingsectionspresentthefontsofthesevarious
systemssothatwecandeterminewhatfontsmaybeused;laterwe’llreviewwaysto
specifyfontsthataredownloadedtoremovethissearchforcross-platformsimilarity.
FIGURE B-1
Font families
available for
Microsoft browsers
and systems
Appendix B: Fonts 753
Font Systems
Andale Mono Internet Explorer 4.5 and 5
Arial Windows Vista, Windows Vista, Windows XP, Windows 2000, Windows ME,
Windows 98, Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x,
Internet Explorer 4.5, 5, and 6
Arial Bold Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
Arial Italic Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
Arial Bold Italic Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
Arial Black Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Internet Explorer 3, 4, 5, and 6
Cambria Windows Vista
Calibri Windows Vista
PART III
Candara Windows Vista
Consolas Windows Vista
Constantia Windows Vista
Corbel Windows Vista
Comic Sans MS Windows Vista, Windows XP, Windows 2000, Windows ME, Internet Explorer
3, 4, 5, and 6
Comic Sans MS Windows Vista, Windows XP, Windows 2000, Windows ME, Internet Explorer
Bold 3, 4, 5, and 6
Courier New Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
Courier New Bold Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
Courier New Italic Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
Courier New Bold Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Italic Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
Georgia Windows Vista, Windows XP, Windows 2000, IE4, IE5, and IE6 (add-on)
Georgia Bold Windows Vista, Windows XP, Windows 2000, IE4, IE5, and IE6 (add-on)
Georgia Italic Windows Vista, Windows XP, Windows 2000, IE4, IE5, and IE6 (add-on)
Georgia Bold Italic Windows Vista, Windows XP, Windows 2000, IE4, IE5 & IE6 (add-on)
Impact Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Internet Explorer 3, 4, 5, and 6
Font Systems
Lucida Console Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Windows NT 3.x (except NT 3.0), Windows NT 4.x
Lucida Sans Windows Vista, Windows XP, Windows 2000, Windows 98, Windows NT 3.x
Unicode (except NT 3.0), Windows NT 4.x
Marlett Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Windows 95, Windows NT 4.x
Minion Web Microsoft lists this as one of its “core fonts,” but it seems to be available
(Adobe) (for sale) only from Adobe (www.adobe.com)
Monotype.com Old version of Andale Mono, still available for Windows 3.1 and 3.11 (add-on)
Symbol Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
Times New Roman Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
Times New Roman Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Bold Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
Times New Roman Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Italic Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
Times New Roman Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Bold Italic Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
Tahoma Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98
Trebuchet MS Windows Vista, Windows XP, Windows 2000, IE4, IE5, and IE6 (add-on)
Trebuchet MS Bold Windows Vista, Windows XP, Windows 2000, Windows 2000, IE4, IE5, and
IE6 (add-on)
Trebuchet MS Italic Windows Vista, Windows XP, Windows 2000, IE4, IE5, and IE6 (add-on)
Trebuchet MS Bold Windows Vista, Windows XP, Windows 2000, IE4, IE5, and IE6 (add-on)
Italic
Verdana Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Internet Explorer 3, 4, 5, and 6
Verdana Bold Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Internet Explorer 3, 4, 5, and 6
Verdana Italic Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Internet Explorer 3, 4, 5, and 6
Verdana Bold Italic Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Internet Explorer 3, 4, 5, and 6
Webdings Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Internet Explorer 4, 5, and 6
Wingdings Windows Vista, Windows XP, Windows 2000, Windows ME, Windows 98,
Windows 95, Windows 3.1x, Windows NT 3.x, Windows NT 4.x
FIGURE B-2
New font families
available for
Microsoft
Windows Vista
PART III
AslistedinTableB-1,WindowsVistaintroducedsixnewsystemfonts,shownin
FigureB-2.
NOTE FormoreinformationonMicrosoft-relatedfonts,pleaseseewww.microsoft.com/typography/
fonts.
Font Systems
American Typewriter OS X
Andale Mono OS X
Apple Chancery System 8+
Arial OS X
Arial Black OS X
Baskerville OS X
Big Caslon OS X
Font Systems
Brush Script OS X
Capitals System 8.5+
Chalkboard OS X
Charcoal System 8.5+
Chicago System 7+
Comics Sans MS OS X
Copperplate OS X
Courier System 7+
Courier New OS X
Didot OS X
Gadget System 8.5+
Geneva System 7+
Georgia OS X
Gill Sans OS X
Futura OS X
Helvetica System 7+
Herculanum OS X
Hoefler Text System 8+
Hoefler Text Ornaments System 8+
Impact OS X
Lucida Grande OS X
Marker Felt OS X
Monaco System 7+
New York System 7+
Optima OS X
Palatino System 7+
Papyrus OS X
Sand System 8.5+
Skia System 8+
Symbol System 7+
Techno System 8.5+
Font Systems
Textile System 8.5+
Times System 7+
Times New Roman OS X
Trebuchet MS OS X
Verdana OS X
Webdings OS X
Zapf Dingbats OS X
Zapfino OS X
PART III
FIGURE B-3
Font families
available for
Macintosh
Systems
758 Part III: Appendixes
AdetailedlistofthecommonfontcombinationsisshowninTableB-3.
WhilethefontlistinTableB-3iscommonlyused,therealityofrenderingsacrosssystems
isabitvariable.Obviousfontdifferencesareclearwhenweseesomesecondaryfonts
chosen.Forexample,thedifferencebetweenComicSansMSandCursiveisprettyobvious.
Windows Macintosh
Inothercases,werunintoamoretroublingsituationwherethefontissupportedonan
operatingsystembutonlyinsomebrowsers.Forexample,WebdingsandSymbolwillvary
dramaticallyintheirbrowsersupport,asshownhere:
Appendix B: Fonts 759
PART III
MS Serif, New York, serif
Palatino Linotype, Palatino, Book
Antiqua, serif
Symbol
Webdings
Documentingthesevariationsisabittroubling,soasimpletestexamplecanbebuiltas
showninFigureB-4withsamplerenderingstocompareagainst.
O NLINE http://htmlref.com/AppB/fontfamily.html
Obviously,leavingfontrenderinguptochanceisnotdesirable,soweexaminesome
othersolutionstobringfontstoWebpages.
760 Part III: Appendixes
Downloadable Fonts
ThebestsolutionforfontsontheWebistocomeupwithacross-platformfontthatcouldbe
downloadedtothebrowseronthefly.Bothofthemajorbrowservendorshavedeveloped
theirownversionsofdownloadablefonts.Microsoft’ssolutionwascalledDynamicFonts
andNetscape’ssolutionwascalledTrueDoc,butthistechnologywasdiscontinuedwith
version6.0oftheNetscapebrowserandshouldbeavoided.Later,similartechnologybased
uponTrueTypeandOpenTypefontswasaddedinbrowserslikeSafari3.1+,Opera10+,and
Firefox3.5+browsers.Thenextsectionbrieflydiscussestheviabledownloadablefont
technologyinuseatthetimeofthisedition’swriting.
@font-face{font-family:"MufferawEOT";
font-style:normal;
font-weight:normal;
src:url(mufferaw.eot);}
1
FortheWebEmbeddingFontTool(WEFT),seetheMicrosoftTypographysite(www.microsoft.com/
typography/web/embedding/weft3/),butbeware:ithasnotbeenupdatedformodernoperating
systems,soproceedwithcaution.
Appendix B: Fonts 761
Nowanyplaceyouwanttousethefont,justspecifythenewlyembeddedoneasthe
firstfontinyourfontlistwithbackupfontsafterward:
p#mufferaw{font-family:"Mufferaw",serif;}
Ofcourseaswithanything,otherbrowsershaveslightlydifferentwaysofembedding
fonts.
@font-face{font-family:"Mufferaw";
src:url(MUFFERAW.ttf);}
andnowwesetitjustasbefore:
p#mufferaw{font-family:"Mufferaw",serif;}
PART III
Theimportantquestionremains:Canweusethetwoformstogether?
@font-face{font-family:"Mufferaw";
src:url(MUFFERAW.ttf);}
@font-face{font-family:"MufferawEOT";
font-style:normal;
font-weight:normal;
src:url(mufferaw.eot);}
p#muff{font-family:"MufferwaEOT","Mufferaw",serif;}
Interestingly,InternetExplorer8doesnotlikethisconcept.Currently,however,itiseasy
enoughtoworkaroundthisusingExplorer’sconditionalcomments;justusethesamename
andoverridethedownloadablefontformatornot,dependingonwhetherExplorerisused.
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>CrossbrowserDownloadableFontsExample</title>
<styletype="text/css">
@font-face{font-family:"Mufferaw";
src:url(MUFFERAW.ttf);}
p{font-family:serif;font-size:5em;}
p#muff{font-family:"Mufferaw",serif;}
</style>
762 Part III: Appendixes
<!--[ifIE]>
<styletype="text/css"media="screen">
/*@font-faceIEEOTrules*/
@font-face{font-family:"Mufferaw";
font-style:normal;
font-weight:normal;
src:url(mufferaw.eot);}
</style>
<![endif]-->
</head>
<body>
<pid="muff">ThisshouldbeMufferawaTrueTypefont.</p>
<p>Thisshouldbethestandardseriffont.</p>
</body>
</html>
O NLINE http://htmlref.com/appB/downloadablefonts.html
ApossiblerenderingoffontembeddingisshowninFigureB-5.
FIGURE B-5 Embedded fonts can work across modern browsers. (This example will not appear the
same online. The font choice is to show obvious difference. The online version may opt to use a
font free of license concerns.)
Appendix B: Fonts 763
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>FontImageReplacementExample</title>
<styletype="text/css">
h1.replace{background:#fffurl(hello.gif)no-repeat;width:88px;
height:24px;}
h1.replacespan{display:none;}
</style>
</head>
PART III
<body>
<h1class="replace"><span>Hello</span></h1>
</body>
</html>
O NLINE http://htmlref.com/AppB/imagereplacement.html
Whilethetechniquereliesonusinganimagetoreplacetext,itdoeshavetheadvantage
ofdegradinggracefullywhenCSSisnotbeingusedbytheenduser,asshownhere:
CSS ON
CSS OFF
Somevendorshavetriedtoautomatetheproductionofimagereplacementfontsusing
server-sideprograms,butsofarsuchanapproachisnotcommonplaceandisgenerally
performedbyhandandonlyonselecttextitemslikeheadings.
764 Part III: Appendixes
T
hisappendixprovidesbasicinformationabouttheuseofcolorontheWeb.The
referencenotonlycoversthedefinedcolorsformats,names,andvaluesfromthe
(X)HTMLspecificationsandCSSbutpresentslessobviouslystandardizedbut
commonlyusedcolornames.Abriefdiscussionofthebrowser-safecolorpaletteisalso
presented.
(X)HTML Colors
TransitionalversionsofHTMLandXHTMLsupportcolorsettingsfortextaswellasthe
backgroundcolorofthedocument,frameborders,tables,orevenindividualtablecells.
Thereare16widelyknowncolornamesdefinedinHTML.Thesenamesandtheir
associatedhexRGBvaluesareshowninTableC-1.
NOTE Colornamesandvaluesarecaseinsensitive,soredandREDareequivalent,asare#FF0000
and#ff0000.
765
766 Part III: Appendixes
with1beingthelightestand4thedarkest.SomebrowserssuchasOperamaysupport
thisconcept,butmostwillnot.
Somebrowsers,notablyOpera,alsosupportnumericvariationsforgray,potentiallyup
to100variations,likegray10,gray50,gray90,andsoforth.
Appendix C: Colors 767
PART III
cadetblue #5F9EA0 95,158,160
chartreuse #7FFF00 127,255,0
chocolate #D2691E 210,105,30
coral #FF7F50 255,127,80
cornflowerblue #6495ED 100,149,237
cornsilk #FFF8DC 255,248,220
crimson #DC143C 220,20,60
cyan #00FFFF 0,255,255
darkblue #00008B 0,0,139
darkcyan #008B8B 0,139,139
darkgoldenrod #B8860B 184,134,11
darkgray #A9A9A9 169,169,169
darkgreen #006400 0,100,0
darkkhaki #BDB76B 189,183,107
darkmagenta #8B008B 139,0,139
darkolivegreen #556B2F 85,107,47
darkorange #FF8C00 255,140,0
darkorchid #9932CC 153,50,204
PART III
lime #00FF00 0,255,0
limegreen #32CD32 50,205,50
linen #FAF0E6 250,240,230
magenta #FF00FF 255,0,255
maroon #800000 128,0,0
mediumaquamarine #66CDAA 102,205,170
mediumblue #0000CD 0,0,205
mediumorchid #BA55D3 186,85,211
mediumpurple #9370DB 147,112,219
mediumseagreen #3CB371 60,179,113
mediumslateblue #7B68EE 123,104,238
mediumspringgreen #00FA9A 0,250,154
mediumturquoise #48D1CC 72,209,204
mediumvioletred #C71585 199,21,133
midnightblue #191970 25,25,112
mintcream #F5FFFA 245,255,250
mistyrose #FFE4E1 255,228,225
moccasin #FFE4B5 255,228,181
navajowhite #FFDEAD 255,222,173
PART III
yellowgreen #9ACD32 139,205,50
Unfortunately,testingrevealsthatthiscolorvariationschemedoesnotworkunderother
majorbrowsers.
Ingeneral,Webpageauthorsshouldbecarefulwhenusingnonstandardcolornames.
Insomecases,theunknownnameswillbeinterpretedasvalues,andothercases,the
browserwillsimplysetthecolorasblack.
Givenallthepossibilityoferror,Webpageauthorsshouldthinktwicebeforeemployingad
hoccolornames,thoughthoseinTableC-2aresafeinpractice.
PART III
</tr>
<tr><td>Cell</td></tr>
</table>
tr <tableborder="1"> Border color attributes
<trbgcolor="yellow"bordercolor="blue" are Internet Explorer–
bordercolorlight="orange" introduced syntax
bordercolordark="red">
<td>Cell1</td><td>Cell2</td>
</tr>
</table>
maroon (#800000)
red (#ff0000)
orange (#ffA500)
yellow (#ffff00)
olive (#808000)
purple (#800080)
fuchsia (#ff00ff)
white (#ffffff)
lime (#00ff00)
green #008000)
navy (#000080)
blue (#0000ff)
aqua (#00ffff)
teal (#008080)
black (#000000)
silver (#c0c0c0)
gray (#808080)
PART III
specified as hsl(hue,saturation, 50%);}
lightness). Hue is set as the degree
on the color wheel, where if you wrap #green{
around 0 or 360 is red, 120 is green, color:
and 240 is blue, with the various other hsl(120,100%,50%);}
colors found between. Saturation is
a percentage value, with 100% the #blue{
fully saturated color. Lightness is a color:
percentage, with 0% being dark and hsl(240,100%,50%);}
100% light, with the average 50% being
the norm.
HSLa Color This is a CSS3 Hue Saturation #bluetrans{color:hsla
Lightness (HSL) value with a fourth (240,100%,50%,0.5);}
value to set the alpha channel
value for the color to define the
opacity of the element. An HSLa
is specified via a function style
hsla(hue,saturation,
lightness,alpha), where hue,
saturation, and lightness are the
same as standard hsl() values and
the alpha channel value for defining
opacity is a number between 0 (fully
transparent) and 1 (fully opaque).
NOTE Testingrevealsthatdependingonoperatingsystemcolorchanges,somebrowsersmaynot
maptheseUIcolornamescorrectlyandoftendefaulttoblack.
NOTE Somedetailsaboutbrowserandversionsupport,particularlyinregardtotheCSS3+related
properties,areomittedfromTableC-6.Thepurposehereistoprovideasimplecross-reference.
SeeChapters5and6foracompletediscussionofeachproperty.
Appendix C: Colors 777
PART III
InactiveBorder Inactive window border color
InactiveCaption Inactive window caption background color
InactiveCaptionText Color of text in an inactive caption
InfoBackground Background color for tooltips
InfoText Color for tooltip text
Menu Menu background color
MenuText Text in menu color
Scrollbar Scroll bar background color
ThreeDDarkShadow Dark shadow for three-dimensional UI elements
ThreeDFace Face color for three-dimensional UI elements
ThreeDHighlight Highlight color for three-dimensional UI elements
ThreeDLightShadow Light color for three-dimensional UI elements
ThreeDShadow Dark shadow for three-dimensional UI elements
Window Window background color
WindowFrame Window frame color
WindowText Text in window color
CSS
Property Example Version
background #redFlame{background:#f00;} CSS 1+
background-color #blueFlame{background-color:#00f;} CSS 1+
border div{border:2pxdoublered;} CSS 1+
border-bottom #redBottom{border-bottom:thin CSS 1+
solidred;}
border-bottom-color div{border:1pxsolidred; CSS 2+
border-bottom-color:
orange;}
border-color #rainbow{border-color:redgreen CSS 1+
blueorange;}
border-left #leftOut{border-left:thindashed CSS 1+
red;}
border-left-color #blueLeft{border-left-color: CSS 2+
#0000FF;}
border-right #rightOn{border-right:thindashed CSS 1+
#f00;}
border-right-color #rightRed{border-right-color: CSS 2+
rgb(255,0,0);}
border-top #boxTop{border-top:thinsolid CSS 1+
blue;}
border-top-color #bluetop{border-top-color:#00f;} CSS 2+
box-shadow #box1{box-shadow:#f0010px10px CSS 3+
50px40px;}
color #july4{color:red;} CSS 1+
column-rule-color #greenRule{column-rule-color: CSS 3+
green;}
outline #coupon{outline:greendashed CSS 2+
10px;}
outline-color a:hover{outline-style:dashed; CSS 2+
outline-color:red;
outline-width:1px;}
scrollbar-3dlight-color #scroll2{scrollbar-3dlight-color: No Spec
red;}
scrollbar-arrow-color #greenArrow{scrollbar-arrow-color: No Spec
green;}
CSS
Property Example Version
scrollbar-base-color #scroll3{scrollbar-base-color: No Spec
orange;}
scrollbar-darkshadow-color #scroll4{scrollbar-darkshadow-color: No Spec
#FF0000;}
scrollbar-face-color #scroll5{scrollbar-face-color: No Spec
green;}
scrollbar-highlight-color #scroll6{scrollbar-highlight-color: No Spec
blue;}
scrollbar-shadow-color #scroll7{scrollbar-shadow-color: No Spec
yellow;}
scrollbar-track-color #scroll8{scrollbar-track-color: No Spec
orange;}
text-shadow .redBlur{text-shadow:3px3px5px CSS 3+
red;}
PART III
TABLE C-6 CSS Properties Supporting Color Values (continued)
Browser-Safe Colors
Earlyoninthedaysof256-colorreproductionacrossbrowsersandoperatingsystems,a
specialpaletteofonly216colorsthatare“safe”wasdefined.ThisgroupofWeb-safecolors
isoftencalledthebrowser-safepalette.Intheory,useofothercolorsbeyondthissafesetcan
leadtocolorshifting,particularlyunderlimitedcolorconditionslikeVGA,whichsupports
8-bitcolors,providingamere256colors.TherealitytodayisthattheWeb-safepaletteis
morehistoricalthanworrisome,especiallyconsideringhowfewdevicesarelimitedtoan
8-bitpalette.However,manytoolsanddesignerscontinuetopromotetheuseofthis
palette,sowepresentitanditsdesignforcompleteness.1
NOTE BecauseitisdifficulttopresenttheWeb-safecolorsvisuallyinablackandwhitebook,the
palettecanbeviewedonlineatwww.htmlref.com/AppC/browserpalette.html.
Theselectionofthe216safecolorsisfairlyunderstandableifyouconsidertheadditive
natureofRGBcolor.Consideracolortobemadeupofvaryingamountsofred,green,or
bluethatcouldbesetbyadjustinganimaginarycolordialfromtheextremesofnocolorto
1
TheirrelevanceoftheWeb-safepalettehasbeendiscussedsincelate2000;seewww.morecrayons.comfor
referencesonthistopic.
780 Part III: Appendixes
maximumcolorsaturation.Thesafecolorsusesixpossibleintensitysettingsforeachvalue
ofred,green,orblue.Thesettingsare0%,20%,40%,60%,80%,and100%.Avalueof0%,
0%,0%ontheimaginarycolordialisequivalenttoblack.Avalueof100%,100%,100%
indicatespurewhite,whileavalueof100%,0%,0%ispurered,andsoon.Thesafecolors
arethosethathaveanRGBvaluesetonlyatoneofthesafeintensitysettings.Thehex
conversionsforsaturationareshowninTableC-7.
Settingasafecolorissimplyamatterofselectingacombinationofsafehexvalues.In
thiscase,#9966FFisasafehexcolor;#9370DBisnot.MostWebeditingtoolslikeAdobe
DreamweaverandMicrosoftExpressioncontainsafecolorpickers;asdoimagingtoolssuch
asAdobePhotoShop.However,directlymappingan“unsafe”colortoitsnearestsafecolor
isfairlyeasy—justroundeachparticularred,green,orbluevalueupordowntothenearest
safevalue.AcompleteconversionofhextodecimalvaluesisshowninTableC-8;safe
valuesareindicatedinbold.
PART III
168=A8 169=A9 170=AA 171=AB 172=AC 173=AD
174=AE 175=AF 176=B0 177=B1 178=B2 179=B3
180=B4 181=B5 182=B6 183=B7 184=B8 185=B9
186=BA 187=BB 188=BC 189=BD 190=BE 191=BF
192=C0 193=C1 194=C2 195=C3 196=C4 197=C5
198=C6 199=C7 200=C8 201=C9 202=CA 203=CB
204=CC 205=CD 206=CE 207=CF 208=D0 209=D1
210=D2 211=D3 212=D4 213=D5 214=D6 215=D7
216=D8 217=D9 218=DA 219=DB 220=DC 221=DD
222=DE 223=DF 224=E0 225=E1 226=E2 227=E3
228=E4 229=E5 230=E6 231=E7 232=E8 233=E9
234=EA 235=EB 236=EC 237=ED 238=EE 239=EF
240=F0 241=F1 242=F2 243=F3 244=F4 245=F5
246=F6 247=F7 248=F8 249=F9 250=FA 251=FB
252=FC 253=FD 254=FE 255=FF
A
URL(uniformresourcelocator)1isauniformwaytorefertoobjectsandserviceson
theInternet.EvennoviceusersshouldbefamiliarwithtypingaURL,suchas
http://www.htmlref.com,inabrowserdialogbox,togettoaWebsite.However,
URLscanbeusedforfarmorethanjustretrievingaWebpageandcanbeusedtoinvoke
otherInternetservices,suchastransferringfilesviaFTPorsendinge-mail.Despiteits
potentiallyconfusingcollectionofslashesandcolons,URLsyntaxisdesignedtoprovide
aclear,simplenotationthatpeoplecaneasilyunderstand.Theconceptsinthissectionwill
helpyoutobetterunderstandthesyntaxofURLs,whichiskeytolinkingdocumentsinand
beyondaWebsite.
NOTE TheW3CoftencallswhatenduserstermaURLaURI.TheW3Cisworkingfrom
amoreadvancedviewofWebaddressingdiscussedlaterinthechapter.Forthisdiscussionwe
alwaysuseURL,whichismorebroadlyunderstood.InterestinglytheHTML5specification
dropsURIinfavorofthemorewidelyunderstoodtermURL.
Basic Concepts
TolocateanyarbitraryobjectontheInternet,youneedtofindoutthefollowinginformation:
1. First,youneedtolocateandaccessthemachineonthenetworkonwhichtheobject
resides.LocatingthesitemightbeamatterofspecifyingitsdomainnameorIP
address,whereasaccessingthemachinemightrequireausernameandpassword.
2. Afteryouaccessthemachine,youneedtodeterminethenameofthedesiredfile,
wherethefileislocated,thepositioninthefileasspecifiedbyafragmentidentifier,
andwhatprotocolwillbeusedtoretrievetheinformationoraccesstheobject.
Inotherwords,aURLdescribeswheresomethingisandhowitwillberetrieved.The
whereisspecifiedbythemachinename,thedirectoryname,thefilename,andpotentiallymore.
1
SomepeoplecallURLs“universalresourcelocators.”Exceptforahistoricalreferenceto“universal
resourcelocators”indocumentationfrommanyyearsago,thecurrentstandardwordingis“uniform
resourcelocator.”
783
784 Part III: Appendixes
Thehowisspecifiedbytheprotocol(forexample,HTTP).Slashesandothercharactersare
usedtoseparatethepartsoftheaddressintomachine-readablepieces.Thebasicstructure
oftheURLisshownhere:
protocol://siteaddress/directory/filename#fragmentid
ThenextseveralsectionslookattheindividualpiecesofaURLincloserdetail.
Server Address
AdocumentexistsonsomeservingcomputersomewhereontheglobalInternetorwithina
privateintranet.Thefirststepinfindingadocumentistoidentifyitsserver.Thismaybe
performedbyasite’sIPaddress,
http://10.0.0.1
thoughitismorelikelythatanalphanumericdomainnameisemployed,
http://www.htmlref.com
Thenamemaybefullyqualifiedwithamachinename,adomain,anorganizationtype,
andpotentially,acountrycode.Forexample,
http://www.htmlref.com
wouldspecifythenameofamachinecalled“www”inthedomainhtmlref,whichisinthe
top-levelCOMdomain.Bycontrast,
http://dev.htmlref.com
wouldreferenceamachineknownas“dev”inthesamedomain.
VeryoftenforprimaryWebsiteswithinadomainthemachinenameisomitted,sowe
simplywrite
http://htmlref.com
However,suchconfigurationisuptotheownerofthedomain.Thisshort-handform
shouldbeemployedasmostsitesarereachablewithoutawwwprefix.
Historically,top-leveldomainssuchasthosefoundinTableD-1areused.
However,startingaround2001,thetop-leveldomainspaceexpandedquiteabit.A
sampleofthetop-leveldomainsthathavebeenaddedbeyondthecommonlyknownones
isshowninTableD-2.PotentiallymoredomainsmaybefoundattheInternetAssigned
NumbersAuthority(IANA)Website(iana.org).
Atthetimeofthisedition’swritingin2009,thereisadistinctpossibilitythatarbitrary
domainscouldbeintroduced.Forexample,.googlemightbetop-leveldomainforallGoogle
properties.Evenwithoutthishappening,thetop-leveldomainspaceisclearlyamess,and
withgenericdomainsonthehorizon,thesituationseemsunlikelytogetmuchbettersoon.
GeographicdomainsareparticularlycommonoutsidetheUnitedStates;suchadomain
nametypicallycontainsmoreinformationthantheorganizationtype,withafullyqualified
domainname(FQDN)includingacountrycodeaswell.Itgenerallyiswrittenasfollows:
machinename.domainname.domaintype.countrycode
ZoneidentifiersoutsidetheU.S.useatwo-charactercodetoindicatethecountry
hostingtheserver.Theseinclude.caforCanada,.mxforMexico,.jpforJapan,andsoon.A
fewexamplesareshownhere.
www.unam.edu.mx
www.mcgill.ca
PART III
www.bbc.co.uk
www.ox.ac.uk
www.sony.co.jp
AcompletelistofcountrycodescanbefoundattheIANAsite(iana.org).
NOTE Onespecialtop-leveldomain,.int,isreservedfororganizationsestablishedbyinternational
treatiesbetweengovernments,suchastheEuropeanUnion(eu.int).
Withineachcountry,thelocalnamingauthoritiesmightcreatedomaintypesattheir
owndiscretion,butthesedomaintypescan’tcorrespondtoAmericanextensions.For
example,weseethatwww.sony.co.jpspecifiesaWebserverforSonyinthecozoneofJapan.
Inthiscase,.co,ratherthan.com,indicatesacommercialventure.IntheUnitedKingdom,
theeducationaldomainspacehasadifferentname,ac.OxfordUniversity’sWebserveris
www.ox.ac.uk,whereby.acindicatesacademic,comparedtotheU.S..eduextensionfor
education.
TheUnitedStatesalsousesthe.usextension,althoughithasonlyrecentlycaughton
outsideoflocalgovernmentandk–12educationalenvironments.Forexample,www.sdcoe
.k12.ca.usisthecurrentaddressoftheCountyOfficeofEducationinSanDiego.However,
theschooldistrictoptstousea.netdomain(sandi.net),andindividualhighschoolshave
evenregistered.comnames.Asinmanyorganizationsthathaveachoiceofaregional
domain,theshortertop-leveldomainispreferred,andunfortunately,the.comspaceseems
tobethemostdesirablewhetheritisappropriateornot.
Directory
Onceyoureachaserver,youmayaccessaparticulardirectory.TheWebsitedirectorythat
containsallothersisknownastherootdirectoryandisspecifiedwithasingleforwardslash.
SoaURLlike
http://htmlref.com/
wouldselecttherootdirectoryofthebooksite.Veryoftenusersanddeveloperswillleave
offthefinaltrailingslashwhenreferencingadirectory.Itissyntacticallycorrectforittobe
included,andifyoudon’tincludeit,yourbrowsersorthereceivingWebserverwilllikely
additin.
Directoriesmaycontainotherdirectories
http://htmlref.com/ch1/
toarbitrarydepth
http://htmlref.com/really/long/fake/directory/path/
Onoccasionyoumayseeoperatingsystem–specificaspectstodirectoryselection.For
example,conventionallyonUNIXsystems~usernamewillresolvetoauser’shomedirectory
path,so
http://htmlref.com/~tpowell
mightbeapossibleURLonaUNIXsystemusingsuchaconvention.Wewillalsonotethat
thecasesensitivityrulesofthedirectoryportionofaURLwilldependonthehostWeb
server.Forexample,UNIX-basedWebserverswilltreathttp://htmlref.com/Ch1and
http://htmlref.com/CH1/astwodifferentpaths,whereasthesameURLsreferencingaWeb
serverusingacase-insensitiveoperatingsystemlikeWindowswouldresolvetoasinglepath.
Appendix D: URLs 787
However,donotassumethattheWebserver’soperatingsystemdictateseverything;for
example,URLsdonotuseWindows-stylebackslashes.
Filename
Afteryouspecifytheserverandthedirectorypathforadocument,thenextsteptoward
locatingitistospecifyitsfilename.Commonly,whenasimpledirectory-basedURLis
givenlike
http://htmlref.com/ch1/
adefaultfileinthatdirectory,oftennamedindex.html,willbereturnedbytheWebserver.
However,thisfilecouldbereferenceddirectlylikeso:
http://htmlref.com/ch1/index.html
Filenamesarearbitrary,
http://htmlref.com/ch1/reallylongfilename.html
andmaybecasesensitive,dependingonthehostoperatingsystem.Thus
PART III
http://htmlref.com/ch1/reallylongfilename.html
and
http://htmlref.com/ch1/REALLYLONGFILENAME.html
mayreferencethesameobjectornot,dependingontheoperatingsystem.Filenamesmay
includespecialcharacterslikedashesandunderscores,
http://htmlref.com/ch1/really_long_file_name.html
http://htmlref.com/ch1/another-really-long-file-name.html
However,dependingonthespecialcharactersused,theymaybeencoded(seetheupcoming
section“Encoding”formoreinformation).Asanexample,thefilename“reallylongfile
name.html”withspacesshouldencodeas
http://htmlref.com/ch1/another%20really%20long%20file%20name.html
Adotseparatesthefilenameandtheextension,whichisacode,generallycomposedof
threeorfourlettersthatidentifiesthetypeofinformationcontainedinthefile.Forexample,
HTMLsourcefilesgenerallyhavea.htmor.htmlextension,CSSfiles,a.cssextension,
JavaScriptfiles,a.jsextension,JPEGimageshavea.jpgextension,andsoon.
http://htmlref.com/ch1/site.css
http://htmlref.com/ch1/bigimage.jpg
http://htmlref.com/ch1/jquery.js
Afile’sextensioniscriticallyimportantforWebapplicationsbecauseitistheprimary
indicationoftheinformationtypethatafilecontains.However,itispossibletoremovefile
788 Part III: Appendixes
extensionsfromURLs,asitisreallytheunderlyingMIMEheaderthattellsabrowserwhat
itisgetting,soitmightbequitepossibletoserveURLslike
http//htmlref.com/ch1/listexamples
ratherthan
http://htmlref.com/ch1/listexamples.php
Removingextensionswillaidinportabilityandhideimplementationdetailsfromendusers.
NOTE UsingaURLrewritingmechanismlikeApache’smod_rewriteistheprimaryweaponin
cleaningURLs.
Fragment Identifier
Besidesreferencingafile,itmaybedesirabletosendauserdirectlytoaparticularpoint
withinthefile.BecauseyoucansetupnamedlinksundertraditionalHTMLandnameany
tagusingtheidattributefromHTML4onward,youcanprovidelinksdirectlytodifferent
pointswithinafile.Tojumptoaparticularnamedlink,theURLmustincludeahash
symbol(#)followedbythelinkname,whichindicatesthatthevalueisafragmentidentifier.
Forexample,given<pid="#middle">foundinthefilefragmentids.htmlinthech1
directoryofthebooksupportsite,wewouldusetheURL
http://htmlref.com/ch1/fragmentids.html#middle
Protocol
Finally,weneedtospecifyhowtoretrieveinformationfromthespecifiedlocation.Thisis
indicatedintheURLbytheprotocolvalue.Aprotocolisthestructureddiscussionthat
computersfollowtonegotiateresource-specificservices.Forexample,theprotocolthat
makestheWebpossibleistheHypertextTransferProtocol(HTTP).Whenyouclicka
hyperlinkinaWebdocument,yourbrowserusestheHTTPprotocoltocontactaWebserver
andretrievetheappropriatedocument.
NOTE AlthoughHTTPstandsforHypertextTransferProtocol,itdoesn’tspecifyhowafileis
transportedfromaservertoabrowser,onlyhowthediscussionbetweentheserverandbrowserwill
takeplacetogetthefile.Theactualtransportoffilesusuallyistheresponsibilityofalower-layer
networkprotocol,suchastheTransmissionControlProtocol(TCP).OntheInternet,the
combinationofTCPandIPmakesrawcommunicationpossible.Althoughasubtlepoint,many
Internetprofessionalsareunawareoflower-levelprotocolsbelowapplicationprotocolssuchas
HTTP,whicharepartofURLs.
AlthoughlessfrequentlyusedthanHTTP,severalotherprotocolsareimportanttoWeb
pageauthorsbecausetheyareofteninvokedbyhyperlinks.TableD-3listssomeexamples.
NOTE Sometimestheprotocoljavascript:isusedinaURL;forexample,javascript:alert(‘hi’).This
isnotanetworkprotocolperse,butthisformofpseudo-URLtoinvoketheexecutionofJavaScript
iscommonlyfoundinWebpages.
Appendix D: URLs 789
PART III
Thesearethecommonprotocols,butavarietyofnewprotocolsandURLformsare
beingdebatedallthetime.We’llpresentadiscussionofemergingURLformstowardthe
endofthisappendix.
ftp://username:password@server-address
ThepasswordcouldbeoptionalorunspecifiedintheURL,makingtheformsimply:
ftp://username@server-address
Regardlessoftheprotocol,weshouldavoidputtingloginidentifiersandespeciallypasswords
inURLs.Ifitisnotspecifiedandtheresourceisprotected,lettheserverissueachallengeso
thatusersprovideitdirectly.
790 Part III: Appendixes
Port
Althoughnotoftenused,thecommunicationportnumberinaURLalsocanbespecified.
Browsersspeakingaparticularprotocolcommunicatewithserversthroughentrypoints,
knownasports,whichgenerallyareidentifiedbynumericaddresses.Associatedwitheach
protocolisadefaultportnumber.Forexample,anHTTPrequestdefaultstoportnumber80.
Youcouldsay
http://htmlref.com:80/ch1/fakeexample.html
butthereisnopoint,asthebrowserwillusethedefaultportforHTTPtrafficanyway.
However,aserveradministratorcanconfigureaservertohandleprotocolrequestsatports
otherthanthedefaultnumbers.Usuallythisoccursforexperimentalorsecureapplications.
Inthesecases,theintendedportmustbeexplicitlyaddressedinaURL.Forexample,ifwe
rananotherserveronport8080,wewoulduse
http://notgoingtowork.htmlref.com:8080/ch1/fakeexample.html
Portnumber–basedaccessisnotterriblyuserfriendly,anditintrinsicallyprovidesno
extrasecurityotherthanobscurity.
Query String
ManyURLscontainquerystringsindicatedbythequestionmark(?).WhenaURLrequests
aprogramtoberunratherthanafiletobereturned,aquerystringmightbepassedinthe
URLtoindicatethevariousargumentstobegiventotheserver-sideprogram.Consider,for
example,
http://www.htmlref.com/fakeexample/registration.php?
Name=Matt+Folely&Age=32&Sex=male
Inthissituation,theprogramregistration.phpishandedaquerystringthathasaname
valuesetto“MattFolely,”anAgevaluesetto“32,”andaSexvaluesetto“male.”Query
stringsaregenerallyencodedasdiscussedinthenextsection.Spacesinthiscaseare
mappedtotheplussign(+),whileallothercharactersareinthe%hexvalueform.The
variousname-valuepairsareseparatedbyampersands(&).Theencodinganddecodingof
URLsisimportantforWebdeveloperstounderstand,andalooseattitudetowardallowed
encodingscanquicklyleadtosecurityproblems.
Encoding
SomecharactersmayhavespecialmeaningwithinthecontextofaURLortheoperating
systemoftheserveronwhichtheresourceisfound.Ifanyunsafe,reserved,ornonprintable
charactersoccurinaURL,theymustbeencodedinaspecialformdefinedbytheMIMEtype
x-www-form-urlencoded.Failuretoencodespecialcharactersmayleadtoerrors,
particularlyinthepresenceofWebserversecuritysystemssuchasWebapplicationfirewalls.
Theformofencodingconsistsofapercentsignandtwohexadecimaldigitscorresponding
tothevalueofthecharacterintheASCIIcharacterset.Onlyalphanumericvaluesandsome
specialcharacters($-_.+!*'),includingparentheses,maybeusedinaURL;other
charactersshouldbeencoded.Ingeneral,specialcharacterssuchasaccents,spaces,andsome
punctuationmarkshavetobeencoded,dependingonthecharactersetinplay.TableD-4
showsthereservedandpotentiallydangerouscharactersforURLs.
Appendix D: URLs 791
PART III
} %7D
[ %5B
] %5D
" %22
` %27
' %60
^^ %5E
~ %7E
\ %5C
| %7C
NOTE ManyofthecharactersinTableD-4don’thavetobeencoded,butencodingacharacternever
causesproblems,sowhenindoubt,encodeit.
Data URIs
Oneformofaddressthathasbeenoverlookedforyearsbutisnowviabletouseisthe
data:URI.AdataURIallowsdatatobeencodeddirectlyintotheaddress.Thegeneral
syntaxofadataURIis
data:[MIMEtype][;charset="encoding"][;base64],data
792 Part III: Appendixes
Giventhissyntax,wecanincludethedataofthissmallWebpage:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>dataURIEncodedPage</title>
</head>
<body>
<h1>IwasencodedinadataURI!</h1>
</body>
</html>
as
data:text/html;base64,PCFET0NUWVBFIGh0bWw+DQo8aHRtbD4NCjxoZWFkPg0KPG1ldGEga
HR0cC1lcXVpdj0iQ29udGVudC1UeXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9dXRm
LTgiPg0KPHRpdGxlPmRhdGEgVVJJIEVuY29kZWQgUGFnZTwvdGl0bGU+DQo8L2hlYWQ+DQo8Ym9
keT4NCjxoMT5JIHdhcyBlbmNvZGVkIGluIGEgZGF0YSBVUkkhPC9oMT4NCjwvYm9keT4NCjwvaH
RtbD4NCg==
WecanthenloadtheaddressintoadataURI–supportingbrowser,anditrendersthe
HTMLpage.
Sinceitisavalidaddress,wecanevenusethisvalueinalinklikeso:
<p>
<ahref="data:text/html;base64,PCFET0NUWVBFIGh0bWw+DQo8aHRtbD4NCjxoZWFkPg
0KPG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudC1UeXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGN
oYXJzZXQ9dXRmLTgiPg0KPHRpdGxlPmRhdGEgVVJJIEVuY29kZWQgUGFnZTwvdGl0bGU+DQo8
L2hlYWQ+DQo8Ym9keT4NCjxoMT5kYXRhIFVSSXMhPC9oMT4NCjwvYm9keT4NCjwvaHRtbD4NCg=
=">Whatdoesthisload?</a>
</p>
Commonly,thisaddressformisusedtoincludesmallimagesandicons.Herearedicon
imageisplacedviaadataURI:
<p><imgsrc="data:image/gif;base64,R0lGODlhCgAKAKIAAP8AAP////+/v/9vb/
9AQP+Pj//MzP8QECH5BAAHAP8ALAAAAAAKAAoAAAMeGLrMIm0R0kwZAIxilDlZdnReCJCL2QjE0
zIAHEUJADs="width="10"height="10"alt="*"></p>
Appendix D: URLs 793
AnywhereaURLcanbeused,socanadataURI.Forexample,herewedefinesomeCSS
rulesforunorderedlisticons:
<styletype="text/css"media="all">
ulli.pro{list-style-image:url(data:image/gif;base64,R0lGODlhDQARAMIAAP////
7+/gAAAAEBAf39/QAAAAAAAAAAACH5BAEKAAcALAAAAAANABEAAAM8eHoAASsyIIaTijoBsdZSA1j
fsgkclWbDMz6V+MlqqtJ0atMB5+IiFLBB0A1vOWEDVWEOUIEJk/nLABcJADs=);}
ulli.con{list-style-image:url(data:image/gif;base64,R0lGODlhDQARAMIAAP////
7+/gAAAAEBAQAAAAAAAAAAAAAAACH5BAEKAAQALAAAAAANABEAAANBSAQMEUwpJ4a4ojXM63BWAwF
WBpimpl2qFgwjE2/M1zbWPKcre8oo3snnkzhOkExAIgmglsyJUgCNMi6QqPEYTQAAOw==);}
</style>
ThenwemightusethemtoindicatetheprosandconsofdataURIs:
<h2>DataURIPoints</h2>
<ul>
<liclass="pro">Compactandself-contained</li>
<liclass="pro">Noextrafetches<br><br></li>
<liclass="con">IE8+Required</li>
<liclass="con">SizeLimits</li>
PART III
</ul>
SomecautionshouldbeemployedwithdataURIs,astheyarenotsupportedin
allbrowsers.Themostnotableproblemsarewithpre–InternetExplorer8browsers.
Furthermore,evenwhendataURIsaresupported,theremaybealimittotheirsize,
dependingoncontext.
AfewdemonstrationsofdataURIsareshowninFigureD-1.
O NLINE http://htmlref.com/AppD/datauris.html
794 Part III: Appendixes
FIGURE D-1
Data URIs in action
<ahref="tel:+1-212-555-1212">
NewYorkCityDirectoryAssistance
</a>
ThissyntaxisalreadysupportedbybrowsersintegratedwithmobiledeviceslikeApple’s
iPhone.
AtelevisionchannelURLformmightlookliketv://channel,wherebychanneliseither
analphanumericname(suchasnbcornbc7-39)oranumericchannelnumber.Avarietyof
esotericschemesareouttherealready.IfyouareinterestedinnewURLschemes,takea
lookattheW3Careaonaddressing(www.w3.org/Addressing)formoreinformation.
Appendix D: URLs 795
Relative URLs
Uptothispoint,thediscussionhasfocusedonaspecificformofURL,typicallytermedan
absoluteURL.AbsoluteURLscompletelyspellouttheprotocol,host,directory,and
filename.ProvidingsuchdetailthroughoutaWebsitecanbetediousandunnecessary,
whichiswhereashortenedformofURL,termedarelativeURL,comesintouse.With
relativeURLs,thevariouspartsoftheaddress—thesite,directory,andprotocol—canbe
inferredfromtheURLofthecurrentdocument,orthroughthe<base>tag.Thebestwayto
illustratetheideaofrelativeURLsisbyexample.
IfaWebsitehasanaddressofwww.democompany.com,ausercanaccessthehome
pagewithaURLsuchashttp://www.democompany.com/.Alinktothispagefroman
outsidesystemalsowouldcontaintheaddresshttp://www.democompany.com/.Onceat
thesite,however,thereisnoreasontocontinuespellingoutthefulladdressofthesite.A
fullyqualifiedlinkfromthehomepagetoastaffpageintherootdirectorycalledstaff.html
wouldbehttp://www.democompany.com/staff.html.Theprotocol,address,anddirectory
namecanbeinferred,soallthatisneededistheaddressstaff.html.Thisrelativescheme
worksbecausehttp://www.democompany.com/isinferredasthebaseofallfuturelinks
thatomitprotocolanddomain,thusallowingfortheshorthandrelativenotation.The
relativenotationcanbeusedwithfilenamesanddirectories,asshownbytheexamplesin
PART III
TableD-5.
WhenrelativeURLsareusedwithinaWebsite,thesitebecomestransportable.Bynot
spellingouttheservernameineverylink,youcandevelopaWebsiteononeserverand
moveittoanother.IfyouuseabsoluteURLs,however,alllinkshavetobechangedifaserver
changesnamesorthefilesaremovedtoanothersite.
tousesymboliclinksontheWebservertoreferenceonecopyofthefilefrommultiple
locations.However,becauseHTMListhesubjecthere,wefocusontheformersolution
usingthebaseelement.
ThebaseelementdefinesthebaseforallrelativeURLswithinadocument.Settingthe
hrefattributeofthiselementtoafullyqualifiedURLenablesallotherrelativereferencesto
usethedefinedbase.Forexample,if<base>issetas<basehref="http://www.htmlref
.com/">,thenalltheanchorsinthedocumentthataren’tfullyqualifiedwillprefixhttp://
www.htmlref.com/tothedestinationURL.Becausebaseisanemptyelement,itwouldhave
tobewrittenas<basehref="http://www.htmlref.com/"/>tobeXHTML-compliant.
Asimpleexampleispresentedhere:
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>BaseURLExample</title>
<basehref="http://htmlref.com/">
</head>
<body>
<ul>
<li><ahref="AppD/basiclink.html">Basiclinkingexample</a></li>
<li><ahref="AppD/base.html">Baseexample</a></li>
<li><ahref=".">BookSiteHomePage</a></li>
<li><ahref="http://htmlref.com">BookSiteHomePageAlternate</a></li>
<li><ahref="http://www.google.com">Google</a></li>
</ul>
</body>
</html>
O NLINE http://htmlref.com/AppD/base.html
Itismostinterestingtorunthisexamplefromanotherserverorlocallyoffyourdisk,asyou
willnotethattherelativeURLswillresolvetothebooksupportsitepertheaddressinthe
<base>tag.
Sincea<base>tagcanoccuronlyonceinanHTMLdocument—withinthehead
element—creatingsectionsofadocumentwithdifferentbaseURLvaluesisimpossible.
Suchafeaturemightsomedaybeaddedtoasectioningelement,butuntilthen,HTML
authorshavetodealwiththefactthatshorthandnotationisusefulonlyinsomeplaces.See
theentryinChapter3formoreinformationonthe<base>tag.
URL Challenges
WhileweallknowanduseURLs,wedon’tnecessarilyunderstandalltheirlittlequirks.We
enumerateafewofthemorecommonchallengesfacedwhenworkingwithURLshere.
Appendix D: URLs 797
PART III
authorsshouldassumetheworstanduseshortURLs,255charsorlowerifatallpossible.
Persistence Concerns
Documentsmovearound,serverschangenames,anddocumentsmighteventuallybe
deleted.ThisisthenatureoftheWeb,andthereasonwhythe404NotFoundmessageisso
common.Whenusershitabrokenlink,theymightbeatalosstodeterminewhathappened
tothedocumentandhowtolocateitsnewhome.Wouldn’titbeniceif,nomatterwhat
happened,auniqueidentifierindicatedwheretogetacopyoftheinformation?Linkscan
bemaintainedanderrorscarefullytracked,buthowmanydevelopersarereallythatcareful
withtheirURLs?
http://www.democompany.com/about/press/pressdetail.php?id=7&view=screen
Firmsarealreadyscramblingforshortdomainnamesandpathstoimprovethetype-
abilityofURLs,andmostfolkstendtoomittheprotocolwhendiscussingthings.Despite
theseminorclean-ups,manyURLsareverylongand“dirty,”filledwithallsortsofspecial
characters,encouragingfiddlingbythemischievous.
doesn’ttellusmuchaboutwherewearegoing.WecouldbevisitinganHTMLexample,
a1980spop-videoofRickAstley,orsomehorriddrive-bymalwaredownload.ShortURLs
maysavespace,buttheyarenotonlycrypticbutpotentiallydangerous.Further,wemust
hopethattheservicethatpowersourshortenedURLlivesonandthattheusagedatathey
gleanfromwatchinguserstraversethelinkisnotusedfortroublingends.
Beyond URLs
Talkingaboutwhatadocumentisratherthanwhereitismakessensewhenyouconsider
howinformationisorganizedoutsidetheInternet.Ingeneral,fewpeopletalkaboutwhich
librarycarriesaparticularbook,orwhatshelfitison.Therelevantinformationisthetitleof
thebook,itsauthor,andperhapssomeotherinformation.Butwhathappensiftwoormore
bookshavethesametitle,ortwoauthorshavethesamename?Thisactuallyisquitecommon.
Generally,abookshouldhaveauniqueidentifiersuchasanISBNnumberthat,when
combinedwithotherdescriptiveinformation,suchastheauthor,publisher,andpublication
date,uniquelydescribesthebook.Thisnamingschemeenablespeopletospecifyaparticular
bookandthenhuntitdown.
TheWeb,however,isn’tasorderlyasalibrary.OntheWeb,peoplenametheirdocuments
whatevertheylike,andsearchrobotsorganizetheirindexeshowevertheylike.Categorizing
thingsisdifficult.TheonlyuniqueitemfordocumentsistheURL,whichsimplysayswhere
thedocumentlives.ButhowmanyURLsdoestheHTML5specificationhave?Adocument
mightexistinmanyplaces.Evenworsethanadocumentwithmultiplelocations,what
happenswhenthecontentatthelocationchanges?PerhapsaparticularURLaddresspoints
toinformationaboutdogsonedayandcatsthenext.ThisishowtheWebreallyis.While
searchengineslikeGoogledoagreatdealtosortthismessout,thereisstillagreatdealtofix,
andthusthereisagreatdealofresearchbeingperformedtoaddresssomeoftheshortcomings
ofWebaddressinganddatameaning.
author,copyright,publisher,andsoon.Finally,thebookcanbefoundinnumerousplaces
online.Itmayhaveacanonicallocation,buttherearelikelymanyothers.
Information Resource
Unique ID
ISBN: 0-07-222942-X
Characteristics
Examples
Cost: 39.99
Author: Thomas A. Powell
Copyright: 2009
Locations
Examples
http://htmlref.com/
http://http://www.amazon.com/HTML-XHTML…
Anewsetofaddressingideasaddressesthesegenericconcepts.First,auniformresource
PART III
name(URN)canlocatearesourcebygivingitauniquesymbolicnameratherthanaunique
address.Second,uniformresourcecharacteristics(URC),describesasetofattribute/value
pairsthatdefinessomeaspectofaninformationresource.Forexample,inthecaseofa
book,aURCmightdescribeapublicationdate,numberofpages,author,andsoon.The
formofaURCisstillunderdiscussion;however,logicallywhattheywouldprovideis
alreadybeingusedoftenintheformofsimple<meta>tags.Finally,theresourcemayhave
location(s)ontheWebwhereitlives.Takenalltogether,aparticularinformationresource
hasbeenidentified.Thecollectionofinformation,whichisusedtoidentifythisdocument
specifically,istermedauniformresourceidentifier(URI).
NOTE Occasionally,URIisusedinterchangeablywithURL.Althoughthisisacceptable,research
intothetheoriesbehindthenamessuggeststhatthetermURIismoregenericthanURLand
encompassestheidealofaninformationresource.Currently,aURListheonlycommonwayto
identifyaninformationresourceontheInternet.AlthoughtechnicallyaURLcouldbeconsidered
aURI,thisconfusestheissueandobscurestheultimategoaloftryingtotalkaboutinformation
moregenerallythanintermsofanetworklocation.
Althoughmanyoftheideascoveredherearestillbeingdiscussed,someexisting
systemsalreadyimplementmanyofthefeaturesofURNsandURCs.Furthermore,many
browservendorsandlargeWebsitesareimplementingspecialkeywordnavigation
schemesthatmimicmanyoftheideasofURNsandURCs.Unfortunately,asofthewriting
ofthisbook,noneoftheseapproachesarewidelyimplementedoraccepted.URLsarelikely
toremainthemostcommonwaytodescribeinformationontheWebfortheforeseeable
future.
This page intentionally left blank
APPENDIX
E
Reading a Document
Type Definition
T
hisappendixpresentstheDocumentTypeDefinitions(DTDs)forHTML4.01and
XHTML1.0.TraditionalHTML“dialects”aredefinedusingSGML(Standard
GeneralizedMarkupLanguage),acomplexlanguagewithmanynuances.XHTML
dialectsaredevelopedinXML(ExtensibleMarkupLanguage),whichisasubsetofSGML
andslightlyeasiertoworkwith.ThisappendixpresentsthesmallamountofSGMLor
XMLknowledgeneededtoreadthevariousDTDsfoundonlinedirectly.
1. Theelementtype’sname,alsoknownasitsgenericidentifier.
2. Whetherstartandendtagsarerequired,areforbidden(endtagsonemptyelements),
ormaybeomitted.
3. Theelementtype’scontentmodel,orwhatcontentitcanenclose.
AllelementtypedeclarationsbeginwiththekeywordELEMENTandhavethe
followingform:
<!ELEMENTnamecontent_model>
ThedeclarationfortheXHTMLbrelementgivesasimpleexample:
<!ELEMENTbrEMPTY>
Thiscasesayswehaveabrelementthatcontainsnocontentatall—itisempty,asshown
bythekeywordEMPTY.
801
802 Part III: Appendixes
InthecaseoftraditionalHTML,whichisdefinedusingSGML,weseeadifferentsyntax
thatdefines
<!ELEMENTnameminimizationcontent_model>
InthetraditionalDTD,wesee
<!ELEMENTBR-OEMPTY>
Here,tagminimizationisdeclaredbytwoparametersthatindicatethestartandend
tags.Theseparametersmaytakeoneoftwovalues.Ahyphenindicatesthetagisrequired.
AnuppercaseOindicatesitmaybeomitted.ThecombinationofOfortheendtagandthe
contentmodelEMPTYmeanstheendtagisforbidden.Thus,undertraditionalHTMLa<br>
tagrequiresastarttagbutnotanendtag.Becausea<br>tagdoesnotcontaincontent,its
contentmodelisdefinedbythekeywordEMPTY,justasitdidintheXHTMLspecification.
NOTE UnderstandardHTML,theelementsintheDTDareactuallyuppercase.WhileolderHTML
wasalmostalwaysinuppercase,newerHTMLeffortsarenearlyalwaysinlowercase,giventhe
influenceofXHTML;thuswewillusethecommonlowercaseformswhendiscussingtagsinthis
appendix,thoughtherelatedsyntaxwillshowuppercase.
MostHTMLandXHTMLelementsenclosecontent.Ifacontentmodelisdeclared,itis
enclosedwithinparenthesesandknownasamodelgroup.TheHTML4.0declarationfora
selectionlistoptiongivesanexample:
<!ELEMENTOPTION-O(#PCDATA)*>
TheXHTMLequivalentisalmostidentical,savethecasingoftheelementitselfandthe
lackoftheminimizationinformation.
<!ELEMENToption(#PCDATA)>
Noteinbothcasesthecontentmodelgroupcontainsthekeyword#PCDATA.Thisstandsfor
parsedcharacterdata—charactercontentthatcontainsnoelementmarkupbutthatmay
containentitysymbolsforspecialcharacters.Keywordssuchas#PCDATAandCDATAare
discussedinthesection“SGMLandXMLKeywords.”
Occurrence Indicators
Inapreviousexample,notetheasteriskappendedtothemodelgroup.Thisisanoccurrence
indicator—aspecialsymbolthatqualifiestheelementtypeormodelgrouptowhichitis
appended,indicatinghowmanytimesitmayoccur.Therearethreeoccurrenceindicators:
• ? Meansoptionalandatmostoneoccurrence(zerooroneoccurrence)
• * Meansoptionalandanynumberofoccurrences(zeroormoreoccurrences)
• + Meansatleastoneoccurrencerequired(oneormoreoccurrences)
Appendix E: R e a d i n g a D o c u m e n t Ty p e D e f i n i t i o n 803
Contentmodelscanalsodefineanelementtypeascontainingelementcontent,
illustratedbytheSGMLdeclarationforadefinitionlist(<dl>)underHTML4.01:
<!ELEMENTDL--(DT|DD)+>
TheXMLdeclarationfordlunderXHTMLisagainonlyslightlydifferent,asitomitsthe
minimizationinformationandcasestheelementsdifferently:
<!ELEMENTdl(dt|dd)+>
Logical Connectors
Amodelgroupcontainsthenamesoftheelementsthatatagmayenclose;forexample,dt
andddarefoundwithin<dl>tags.Inthisexamplewenotetheverticalbarseparatingdt
anddd.Thisisalogicalconnector—aspecialsymbolindicatinghowthecontentunitsit
connectsrelatetoeachother.Therearethreelogicalconnectorsandonegrouping
connector:
• | Means“or”(oneandonlyoneoftheconnectedcontentunitsmustoccur)
PART III
• & Means“and”(alloftheconnectedcontentunitsmustoccur)
• , Means“sequence”(theconnectedcontentunitsmustoccurinthespecified
order)
• () Usedtogroupcontentunitstogether.
Thus,thecontentmodelforadefinitionlistsaysthatthe<dl>tagmustcontaineithera
<dt>ora<dl>tagandcancontainanyadditionalnumberof<dt>or<dd>tags.
Modelgroupscanbenestedinsideothermodelgroups.Veryflexiblecontentmodels
canbedeclaredbycombiningthiswiththecapabilitytoqualifycontentunitswith
occurrenceindicatorsandlogicaloperators.TheXHTMLdeclarationforthe<table>tag
illustratesthispoint:
<!ELEMENTtable(caption?,(col*|colgroup*),thead?,tfoot?,(tbody+|tr+))>
Thecontentmodelforthetableelementtypereadsasfollows:
• Tablecontentbeginswithzeroorone<caption>tags.
• Thismustbefollowedbyacontentgroup.
• Thecontentgroupmustcontainzeroormore<col>tagsorzeroormore
<colgroup>tags.
• Thismustbefollowedbyzeroorone<thead>tags.
• Thismustbefollowedbyzeroorone<tfoot>tags.
• Thismustbefollowedbyoneormore<tbody>or<tr>tags.
804 Part III: Appendixes
(modelgroup)-(excludedtags)
Arelatedspecialneedisthecapabilitytodeclarethatanelementtypecanoccuranywhere
insideacontentmodel.Thisisknownasacontentinclusion.Theincludedtagsfollowthe
modelgroupandareenclosedbyparenthesesandprecededbytheplussign:
(modelgroup)+(includedtags)
Asanexample,theHTML4.01declarationforthebodyelementillustratesboth
excludedandincludedelements:
<!ELEMENTBODYOO(%block;)-(BODY)+(INS|DEL)>
Whyareinsertionsanddeletionsusedinthisdeclaration?Thecontentinclusionsays
that<ins>and<del>tagscanoccuranywhereinthecontentenclosedby<body>and
</body>tags.Whilethecontentexclusionsaysthatabodyelementcannotcontainanother
bodyelement,inthiscaseit’snecessarybecauseofthecurious“%block”declarationused
inthemodelgroup.Theleading%characteridentifiesthisasaparameterentity,essentially
amacrosymbolthatreferstoalongercharacterstringdeclaredelsewhereintheDTD.
Parameterentities,whichcommonlyoccurinDTDs,arediscussedshortly(seethesection
“ParameterEntities”).The“%block”entityreferenceisashorthandwayofreferringtoall
blockelementtypesthathappentoinclude<body>.Itiseasiertoexclude<body>fromthe
listofblockelementsthantodefineaspecial-purposedeclaration.Interestingly,XML
eliminatestheuseofcontentinclusionandexclusionfromtheXHTMLDTD,andthusitis
bothmoreverboseandinsomewayssimplertoread.
Attribute Declarations
Onceanelement’ssyntaxhasbeendefined,wehavetoaddressitsattributes.Allattribute
declarationsbeginwiththekeywordATTLIST,followedbytheelementname,attribute
name,attributetype,anddefaultdatainformation,asyoucanseeinthefollowing:
<!ATTLISTelement-nameattribute-nameattribute-typedefault-data>
TheHTML4.01<bdo>tagtypeillustratesasmallattributedeclaration:
<!ATTLISTBDO
%coreattrs;
langNAME#IMPLIED
dir(ltr|rtl)#REQUIRED
>
Appendix E: R e a d i n g a D o c u m e n t Ty p e D e f i n i t i o n 805
TheXMLsyntaxthatdefinesthe<bdo>tagunderXHTMLissimilar,thoughyoushould
noticethatmanymoreattributesarenowavailableforthistag:
<!ATTLISTbdo
%coreattrs;
%events;
lang%LanguageCode;#IMPLIED
xml:lang%LanguageCode;#IMPLIED
dir(ltr|rtl)#REQUIRED
>
WenotethatcommonlyrepeatedattributesandvaluesunderbothHTMLandXHTMLtend
tobeminimizedwithparameterentitieslike%coreattrs,whichwillexpandtoid,class,
style,andtitleattributes.
PART III
• CDATA Unparsedcharacterdata
• ID Adocument-wideuniqueidentifier
• IDREF Areferencetoadocument-wideidentifier
• NAME Analphabeticcharacterstringplusahyphenandaperiod
• NMTOKEN Analphanumericcharacterstringplusahyphenandaperiod
• NUMBER Acharacterstringcontainingdecimalnumbers
NoticethatinthepreviousDTDfragmentexamplefor<bdo>thatthedirattributedid
notdeclareitstypeusingakeyword.Instead,thetypeisspecifiedusinganenumeratedlist
containingtwopossiblevalues,ltrandrtl.
InthepreviousexampleforeitherSGMLorXML,thedirattribute’sdefaultbehavioris
specifiedwithakeywordlikeoneofthese:
• #REQUIRED Avaluemustbesuppliedfortheattribute.
• #IMPLIED Theattributeisoptional.
• #FIXED Theattributehasafixedvaluethatisdeclaredinquotesusinganadditional
parameter.Becausetheattribute/valuepairisassumedtobeconstant,itdoesnot
needtobeusedinthedocumentinstance.
Adefaultvaluemayalsobespecifiedusingaquotedstring;forexample,theenctype
attributeonaformelementhastheMIMEtypeshowninthestringthatfollowsbydefault:
enctype%ContentType;"application/x-www-form-urlencoded"
806 Part III: Appendixes
Parameter Entities
Anentityisessentiallyamacrothatallowsashortnametobeassociatedwithreplacement
text.ParameterentitiesdefinereplacementtextusedinDTDdeclarations.Syntactically,a
parameterentityisdistinguishedbyusingthepercent(%)symbol.Itsgeneralformis
shownhere:
<!ENTITY%name"replacementtext">
ItisusedinDTDsasfollows:
%name;
ParameterentitiesareaconvenientwaytodefinecommonlyoccurringpiecesofaDTD
sothatchangesonlyneedtobemadeinoneplace.WeseeinXHTMLaparameterentityto
definethecoreattributescommontomostelements.
<!ENTITY%coreattrs
"idID#IMPLIED
classCDATA#IMPLIED
style%StyleSheet;#IMPLIED
title%Text;#IMPLIED"
>
Noticethatentity%coreattrsfurtherreferencesentities(%StyleSheet;and%Text;)
todefinevaluesforthestyleandtitleattributes.Oncedefined,thecoreattributescouldbe
addedtoanattributelistdeclarationforanelementasfollows:
<!ATTLISTsome-element%coreattrs;>
Oftentimes,youwillseeentitiesthatinturncontainfurtherentities.Forexample,under
HTML4.0,thecoreattrsparameterentityisusedwiththei18nandeventsparameter
entitiestodefinetheexpansiontextforanaggregateentitycalledattrs.
<!ENTITY%attrs"%coreattrs%i18n%events">
Comments
DTDsinbothSGMLandXMLcontaincommentsfamiliartoWebpageauthors:
<!--thisisacomment-->
Generallythesecommentsareusedtosegmentthespecification
<!--================Forms=============================================-->
butinsomecases,theymaybeusedtoprovideexplanationsofparticularelementsortheiruse.
<!--INS/DELarehandledbyinclusiononBODY-->
Appendix E: R e a d i n g a D o c u m e n t Ty p e D e f i n i t i o n 807
CommentscanalsobeembeddedinsideSGMLdeclarationsforexplanatorypurposes.
Embeddedcommentsaredelimitedbytwodashes,andasingledeclarationmaycontain
manyembeddedcomments:
<!ATTLISTPARAM
nameCDATA#REQUIRED--propertyname--
valueCDATA#IMPLIED--propertyvalue--
valuetype(DATA|REF|OBJECT)DATA--Howtointerpretvalue--
typeCDATA#IMPLIED--Internetmediatype--
>
NOTE XMLdoesnotusethis“--”commentstyle,soyouwillnotseeitintheXHTML
specification.
The DTDs
NowthatyouunderstandthefundamentalsofreadingaDTD,youshouldconsultoneto
seetheprecisesyntaxof(X)HTMLdirectlyforyourself.ThelatestversionsoftheseDTDs
canberetrievedfromtheW3C:
PART III
• HTML4.01Transitional www.w3.org/TR/html4/sgml/loosedtd.html
• HTML4.01Strict www.w3.org/TR/REC-html40/sgml/dtd.html
• HTML4.01Frameset www.w3.org/TR/html4/sgml/framesetdtd.html
• XHTML1Transitional www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
• XHTML1Strict www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd
• XHTML1Frameset www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd
• XHTML1.1 www.w3.org/TR/xhtml11/
OlderDTDscanalsobefoundonline,including
• HTML2 www.w3.org/MarkUp/html-spec/html.dtd
• HTML3 www.w3.org/TR/REC-html32#dtd
NOTE Aspreviouslymentioned,HTML5doesnotsupportaDTDsyntaxdefinitionapproach.
Althoughwhenauthoringinthislanguage,youmayincludeasimpledoctypelike<!DOCTYPE
html>,asof2009thedefinitionofthisvariationofHTMLisnotactuallyspecifiedinSGMLor
XMLsyntax.
NOTE XHTML2doeshaveaDTDcurrentlyfoundatwww.w3.org/MarkUp/DTD/xhtml2.dtd.
However,thespecificationisfarfromcomplete,andthereisindicationthatthelanguagemay
eventuallybedefinedasanXMLschemaratherthanaDTD.Furthermore,circalate2009there
isastrongindicationthattheXHTML2specificationisunlikelytoeverbecompleted.
This page intentionally left blank
Index
Symbols and Numbers activity-relatedpseudo-classes,CSS,490–491
&(and)logicalconnector,803 <address>(address)element,168–169
%character,forparameterentities,804 addressingschemes,798–799.SeealsoURLs(uniform
()(group)logicalconnector,803 resourcelocators)
*(zeroormoreoccurrences)occurrenceindicator,802 adjacentsiblingselector(+),CSS,478
,(sequence)logicalconnector,803 AdobeDreamweaver
"..."(doublequotes),instringsyntax,529 colorpickersin,780
'...'(singlequotes),instringsyntax,529 loading/previewingmarkupwith,9–10
?(zerooroneoccurrence)occurrenceindicator,802 AdobePhotoshop,780
|(or)logicalconnector,803 :afterpseudo-elementselectors,CSS,485–486
~(generalsiblingselectors),CSS,479 ::afterselector,CSS3,617
+(adjacentsiblingselector),CSS,478 alignattribute
+(oneormoreoccurrences)occurrenceindicator,802 <caption>(tablecaption)element,209
>(childselector),CSS,478 <colgroup>(tablecolumngroup)element,218
2DTransforms,CSS3modules,614 commonelementattributesreference,140
3DTransforms,CSS3modules,614 <embed>(embeddedobject)element,241
<ilayer>(inflowlayer)element,277
<input>(inputformcontrol)element,282
A <legend>(descriptivelegend)element,299–300
<a>(anchor)element,158–164 <object>(embeddedobject)element,333
compatibilityandexamples,164 <p>(paragraph)element,344
element-specificattributes,159–163 inpresentationalHTML,429
eventattributes,159 <select>(selectionlist)element,368
IEandHTML5and,158–159 <spacer>(extraspace)element,373
syntaxof,158 <table>(table)element,386
<abbr>(abbreviation)element,164–166 <tbody>(tablebody)element,391
abbrattribute <td>(tabledata)element,394
<td>(tabledata)element,394 <tfoot>(tablefooter)element,401,404
<tfoot>(tablefooter)element,403 <thead>(tableheader)element,407
aboveattribute,<layer>(positionedlayer)element <tr>(tablerow)element,413
and,296 alignment,<center>(centeralignment)element,
acceleratorproperty,CSS3browser-specific 210–211
features,630–631 alinkattribute,<body>(documentbody)element,191
acceptattribute,<input>(inputformcontrol) allow-same-origin,iframeelement,111
element,282 allowtransparencyattribute
accesskeyattribute <frame>(windowregion)element,253
commonelementattributesreference,139–140 <iframe>(inlineframe)element,272
commonHTML5elementattributesreference, altattribute
142–143 <applet>(Javaapplet)element,170
<legend>(descriptivelegend)element,299 <area>(ImageMapArea)element,173
Acid2,430–432 <embed>(embeddedobject)element,241
<acronym>(acronym)element,166–167 <ilayer>(inflowlayer)element,277
actionattribute <input>(inputformcontrol)element,282
<form>(formforuserinput)element,251 alternativestyles,CSS,464–465
<isindex>(indexprompt)attributes,290 anchorelement.See<a>(anchor)element
809
810 HTML & CSS: The Complete Reference
animation-delayproperty,CSS3browser-specific autocompletelists,105
features,633–634 autofocusattribute
animation-directionproperty,CSS3browser-specific <button>(button)element,196
features,634–635 HTML5formfields,106
animation-durationproperty,CSS3browser-specific <input>(inputformcontrol)element,282
features,635–636 <select>(selectionlist)element,368
animation-iterationproperty,CSS3browser-specific <textarea>(multilinetextinput)element,
features,636–637 397–398
animation-nameproperty,CSS3browser-specific autoplay
features,637–638 audio,81
animationproperty,CSS3browser-specificfeatures, video,80
632–633 autoplayattribute,<video>(video)element,422
animation-timing-functionproperty,CSS3browser- axisattribute
specificfeatures,638–640 <td>(tabledata)element,394
animations,CSS3modules,614 <tfoot>(tablefooter)element,404
APIs(applicationprogramminginterfaces),HTML5
APIfordrawingoncanvas,85
<applet>(Javaapplet)element,169–171
applicationattribute B
<frame>(windowregion)element,253–254 <b>(bold)element,28,179–181
<iframe>(inlineframe)element,272 backface-visibilityproperty,CSS3browser-specific
applicationlanguages,17 features,640
applicationprogramminginterfaces(APIs),HTML5 background-attachmentproperty,CSS,543–544
APIfordrawingoncanvas,85 backgroundattribute
archiveattribute <body>(documentbody)element,191
<applet>(Javaapplet)element,170 <layer>(positionedlayer)element,296
<object>(embeddedobject)element,333 <table>(table)element,387
arcs,drawinginHTML5,90–93 <td>(tabledata)element,394
<area>(ImageMapArea)element,171–174 <tfoot>(tablefooter)element,404
arrows,characterentitiesfor,745 background-clipproperty,CSS3browser-specific
<article>(article)element,73–74,175–176 features,641–642
<aside>(aside)element,74–75,176–177 background-colorproperty,CSS,544
aspect-ratio,CSS3mediaqueryvalues,627 background-imageproperty,CSS,544–545
asyncattribute,<script>(scripting)element,363 background-originproperty,CSS3browser-specific
ATTLISTkeyword,forattributedeclarations,804 features,642–643
attributeselectors background-positionproperty,CSS,545–546
CSS,479–481 background-position-xproperty,CSS3browser-
CSS3,481–482 specificfeatures,643–644
listof,483 background-position-yproperty,CSS3browser-
multiple,482 specificfeatures,644
attributes backgroundproperty,CSS,543
browsersignoringunknown,44–45 background-repeatproperty,CSS,546
casesensitivityof,42 background-sizeproperty,CSS3browser-specific
declarations,804–805 features,644–645
newinHTML5,66 backgroundsmodule,CSS3,614
quotesusedwith,44,59 balanceattribute,<bgsound>(backgroundsound)
removedfromHTML5,65 element,185
intraditionalHTML/XHTMLsyntax,5–6 <base>(baseURL)element
<audio>(audio)element,80–81,177–179 elementsallowedwithinheadelement,25–26
auralstyleproperties,CSS2x,607–612 overviewof,181–182
authenticatedservices,HTTPandFTPas,789 relativeURLsand,795–796
autobuffer <basefont>(basefont)element,182–183
audio,81 <bdo>(bidirectionaloverride)element,183–185
video,80 :beforepseudo-elementselectors,CSS,485–486
autobufferattribute ::beforeselector,CSS3,617
<area>(ImageMapArea)element,178 behaviorattribute,<marquee>(marqueedisplay)
<video>(video)element,422 element,316–317
autocompleteattribute behaviorproperty,CSS3browser-specificfeatures,
<form>(formforuserinput)element,251 645–649
<input>(inputformcontrol)element,282 behavioralextensionsmodule,CSS3,614
Index 811
bgcolorattribute border-topproperty,CSS,556
<body>(documentbody)element,191 border-top-right-radiusproperty,CSS3browser-
<col>(tablecolumn)element,215 specificfeatures,655
<colgroup>(tablecolumngroup)element,218 border-top-styleproperty,CSS,557
<marquee>(marqueedisplay)element,317 border-top-widthproperty,CSS,557
<table>(table)element,387 border-widthproperty,CSS,557–558
<tbody>(tablebody)element,391 bordercolorattribute
<td>(tabledata)element,394 <frame>(windowregion)element,254
<tfoot>(tablefooter)element,404 <frameset>(framesetdefinition)element,256
<tr>(tablerow)element,413 <iframe>(inlineframe)element,272
bgpropertiesattribute,<body>(documentbody) <table>(table)element,387
element,191 <td>(tabledata)element,394
<bgsound>(backgroundsound)element,185–186 <tfoot>(tablefooter)element,404
<big>(bigfont)element,186–187 <tr>(tablerow)element,413
bindingproperty,CSS3browser-specificfeatures, bordercolordarkattribute
649–650 <table>(table)element,387
bitmapimages,oncanvaselement,97–98 <td>(tabledata)element,394
<blink>(blinkingtext)element,187–188 <tfoot>(tablefooter)element,404
block-levelelements,inbodyelement,28 <tr>(tablerow)element,413
<blockquote>(blockquote)element,188–189 bordercolorlightattribute
<body>(documentbody)element <table>(table)element,387
diagramofelementsin,30–31 <td>(tabledata)element,394
inHTMLandXHTMLdocuments,7 <tfoot>(tablefooter)element,404
overviewof,190–193 <tr>(tablerow)element,413
intraditionalHTML/XHTML,28–31 bordersmodule,CSS3,614
bold(<b>)element,28,179–181 bordersstyleskeyword,529
borderattribute bottomproperty,CSS,559
<embed>(embeddedobject)element,241 bottommarginattribute,<body>(documentbody)
<frameset>(framesetdefinition)element,256 element,192
<iframe>(inlineframe)element,272 boxmodelhack,450–452
<ilayer>(inflowlayer)element,277 boxmodelmodule,CSS3,614
<object>(embeddedobject)element,333 box-reflectproperty,CSS3browser-specificfeatures,
<table>(table)element,387 655–656
border-bottom-colorproperty,CSS,548 box-shadowproperty,CSS3browser-specific
border-bottom-left-radiusproperty,CSS3browser- features,656–658
specificfeatures,650–651 box-sizingproperty,CSS3browser-specificfeatures,
border-bottomproperty,CSS,547 658–659
border-bottom-right-radiusproperty,CSS3browser- <br>(linebreak)element,193–195
specificfeatures,651–653 browser-safecolors,779–781
border-bottom-styleproperty,CSS,548 browsers
border-bottom-widthproperty,CSS,548 colorsupportand,766,771,779–781
border-collapseproperty,CSS,549 contentediting(contenteditableattribute)in,
border-colorproperty,CSS,549–550 114–115
border-left-colorproperty,CSS,551 CSSand,430,517
border-leftproperty,CSS,550–551 doctypeswitchandbrowserrendering
border-left-styleproperty,CSS,551–552 modes,39–41
border-left-widthproperty,CSS,552 draganddropfunctionality(draggable
borderproperty,CSS,547 attribute),112–114
border-radiusproperty,CSS3browser-specific Firefox.SeeFirefox
features,653–654 handlingfileextensionsandMIMEtypes,13–14
border-right-colorproperty,CSS,552–553 IE(InternetExplorer).SeeIE(InternetExplorer)
border-rightproperty,CSS,552 ignoringunknownelementsand
border-right-styleproperty,CSS,553 attributes,44–45
border-right-widthproperty,CSS,553 Netscape.SeeNetscape
border-spacingproperty,CSS,553–554 parsing(X)HTMLdocuments,31–36
border-styleproperty,CSS,554–555 renderingmodes,39
border-top-colorproperty,CSS,556 spellchecking(spellcheckattribute)in,115–116
border-top-left-radiusproperty,CSS3browser- standardscomplianceand,518
specificfeatures,654–655 videosupportin,79
812 HTML & CSS: The Complete Reference
browsers,CSS3features mask-sizeproperty,688–690
@keyframes,630–631 opacityproperty,690
acceleratorproperty,630–631 outline-offsetproperty,690–691
animation-delayproperty,633–634 outline-radiusproperty,691
animation-directionproperty,634–635 overflow-styleproperty,691–692
animation-durationproperty,635–636 overflow-xproperty,692
animation-iterationproperty,636–637 overflow-yproperty,693
animation-nameproperty,637–638 perspective-originproperty,694–695
animationproperty,632–633 perspectiveproperty,693–694
animation-timing-functionproperty,638–640 resizeproperty,695–696
backface-visibilityproperty,640 ruby-alignproperty,696–697
background-clipproperty,641–642 ruby-overhangproperty,697
background-originproperty,642–643 ruby-positionproperty,698
background-position-xproperty,643–644 scrollbar-3dlight-colorproperty,698–699
background-position-yproperty,644 scrollbar-arrow-colorproperty,699
background-sizeproperty,644–645 scrollbar-base-colorproperty,699–700
behaviorproperty,645–649 scrollbar-darkshadow-colorproperty,700–701
bindingproperty,649–650 scrollbar-face-colorproperty,701
border-bottom-left-radiusproperty,650–651 scrollbar-highlight-colorproperty,701–702
border-bottom-right-radiusproperty,651–653 scrollbar-shadow-colorproperty,702
border-radiusproperty,653–654 scrollbar-track-colorproperty,703
border-top-left-radiusproperty,654–655 sizeproperty,703–704
border-top-right-radiusproperty,655 text-align-lastproperty,704
box-reflectproperty,655–656 text-autospaceproperty,704–705
box-shadowproperty,656–658 text-fill-colorproperty,705
box-sizingproperty,658–659 text-justifyproperty,705–706
column-break-afterproperty,659 text-kashida-spaceproperty,706–707
column-break-beforeproperty,659–660 text-overflowproperty,707
column-countproperty,660–661 text-renderingproperty,708
column-gapproperty,661 text-shadowproperty,708–710
column-rule-colorproperty,662–663 text-stroke-colorproperty,710–711
column-ruleproperty,661–662 text-stroke-widthproperty,711
column-rule-styleproperty,663–664 text-underline-positionproperty,711–712
column-rule-widthproperty,664–665 transform-originproperty,715
column-widthproperty,665 transformproperty,712–714
columnsproperty,665 transform-styleproperty,716–717
filterproperty,666–672 transition-delayproperty,717–718
gradientproperty,672–673 transition-durationproperty,718–719
image-renderingproperty,673–674 transitionproperty,717
ime-modeproperty,674 transition-propertyproperty,719
interpolation-modeproperty,674–675 transition-timing-functionproperty,719–720
layout-grid-charproperty,675–676 user-selectproperty,720–721
layout-grid-lineproperty,676 word-breakproperty,721
layout-grid-modeproperty,676–677 word-wrapproperty,722
layout-gridproperty,675 writing-modeproperty,722–723
line-breakproperty,677 zoomproperty,724
marquee-directionproperty,678–679 <button>(button)element,195–198
marquee-play-countproperty,679
marquee-speedproperty,679–680
marquee-styleproperty,680–681 C
mask-attachmentproperty,682 <canvas>(canvasfordrawing)element,198–208
mask-clipproperty,683 addingperspective,88–90
mask-compositeproperty,684 bitmapimagesusedon,97–98
mask-originproperty,685 colorandstylepropertiesandmethods,202
mask-positionproperty,685–686 compositingpropertiesandoptions,201
mask-position-xproperty,686–687 drawingandstylinglinesandshapes,85–88
mask-position-yproperty,687 drawingarcsandcurves,90–93
maskproperty,681–682 gradientmethods,200
mask-repeatproperty,687–688 HTML5and,198–199
Index 813
ImageDataAPImethodsandproperties,207 <meta>(meta-information)element,321
lineproperties,203 <script>(scripting)element,363
overviewof,82–85 @charsetrule,CSS,540
pathAPImethods,204–205 checkedattribute,<input>(inputformcontrol)
rectanglemethods,204 element,282
scaling,rotating,andtranslating :checkedselector,CSS3,617
drawings,93–97 childselector(>),CSS,478
shadowproperties,203 citeattribute
statepreservationmethods,200 <blockquote>(blockquote)element,189
textAPImethodsandproperties,206 <del>(deletedtext)element,225
textsupportin,98–100 <ins>(insertedtext)element,288
transformationmethods,200 <quote>(quote)attributes,353
caption-sideproperty,CSS,559–560 <cite>(citation)element,211–213
<caption>(tablecaption)element,208–210 classattribute,coreelementattributes,136
casesensitivity classattribute,CSSselectors,473–476
CSS,434 classidattribute,<object>(embeddedobject)
HTML/XHTML,rules,41–42 element,333
HTML5,730 clearattribute,<br>(linebreak)element,194
URLsand,797 clearproperty,CSS,560
cellpaddingattribute,<table>(table)element,387 client-sidegraphics(canvas).See<canvas>(canvas
cellspacingattribute,<table>(table)element,387 fordrawing)element
<center>(centeralignment)element,210–211 clipattribute,<layer>(positionedlayer)element,297
chunits,CSSS3,621 clipproperty,CSS,560–561
charattribute closingtags,rulesinHTML/XHTML,43
<col>(tablecolumn)element,215 code
<tbody>(tablebody)element,391 <code>(codelisting)element,213–214
<td>(tabledata)element,394 <listing>(codelisting)element,311–312
<tfoot>(tablefooter)element,401,404 codeattribute
<thead>(tableheader)element,407 <applet>(Javaapplet)element,170
<tr>(tablerow)element,413 <embed>(embeddedobject)element,241
characterentities <object>(embeddedobject)element,333
arrows,745 <code>(codelisting)element,213–214
caseinsensitiveinHTML5,730 codebaseattribute
encoding,728–730 <applet>(Javaapplet)element,170
formatof,727 <embed>(embeddedobject)element,241
generalpunctuation,741–742 <object>(embeddedobject)element,333
geometricshapes,748 codetypeattribute,<object>(embeddedobject)
Greek,743–744 element,333
HTML4andXHTML1.x,740–741 <col>(tablecolumn)element,214–216
LatinExtended-AandLatinExtended-B,741 <colgroup>(tablecolumngroup)element,216–218
letter-likesymbols,744–745 colorandstylepropertiesandmethods,canvas
mathematicaloperators,746–747 element,202
miscellaneoussymbols,748 colorattribute
spacingmodifiers,741 <basefont>(basefont)element,183
technicalsymbols,747 <font>(fontdefinition)element,247
traditionalHTML,731–740 <hr>(horizontalrule)attributes,261
Unicodeand,748–749 color,CSS3mediaqueryvalues,627
charoffattribute color-index,CSS3mediaqueryvalues,627
<col>(tablecolumn)element,216 colormodule,CSS3,614
<colgroup>(tablecolumngroup)element,218 colorproperty,CSS,561–562
<tbody>(tablebody)element,391 colorvalues,CSS,530–532,773–776
<td>(tabledata)element,394 colors,browser-safe,779–781
<tfoot>(tablefooter)element,401,404 colors,CSS
<thead>(tableheader)element,407 color-relatedproperties,776,778–779
<tr>(tablerow)element,414 listofcolorvalues,773–776
charsetattribute UIcolornames,777
<a>(anchor)element,159 colors,(X)HTML
<link>(linktoexternalfilesorset elementssupportingcolor,772–773
relationships)element,304 namesandhexequivalents,766
814 HTML & CSS: The Complete Reference
colors,(X)HTML(Continued) contentmodels
namesandnumericalequivalents,767–771 elements,801
nonstandardnamesandnumerical HTML/XHTMLfollowing,43
equivalents,765 HTML5following,59
overviewof,765 overviewof,17
colsattribute contentproperty,CSS,562–563
<frameset>(framesetdefinition)element,256 contenteditableattribute
<multicol>(multiplecolumntext)element,325 commonelementattributesreference,140
<table>(table)element,387 commonHTML5elementattributes
<textarea>(multilinetextinput)element,398 reference,143
colspanattribute contextmenuattribute,inHTML5,108,143
<td>(tabledata)element,395 contextualselection,creatingCSSrulesfor,476–478
<tfoot>(tablefooter)element,404 controlsattribute
column-break-afterproperty,CSS3browser-specific <area>(ImageMapArea)element,178
features,659 <video>(video)element,422
column-break-beforeproperty,CSS3browser- coordsattribute
specificfeatures,659–660 <a>(anchor)element,159
column-countproperty,CSS3browser-specific <area>(ImageMapArea)element,173
features,660–661 counter-incrementproperty,CSS,564
column-gapproperty,CSS3browser-specific counter-resetproperty,CSS,564–565
features,661 counters,CSS,530
column-rule-colorproperty,CSS3browser-specific countrycodes,domainsand,785–786
features,662–663 CSS(CascadingStyleSheets)
column-ruleproperty,CSS3browser-specific activity-relatedpseudo-classes,490–491
features,661–662 adjacentsiblingselectors,478
column-rule-styleproperty,CSS3browser-specific alternativestyles,464–465
features,663–664 applyingstylestodocuments,452
column-rule-widthproperty,CSS3browser-specific attributeselectors,479–483
features,664–665 auralstyleproperties,607–612
column-widthproperty,CSS3browser-specific breakingCSSrulesintentionally,450–452
features,665 browsersand,517
columnsproperty,CSS3browser-specific classrules,473–476
features,665 colorvalues,530–532
commandelement,108 colorvaluesandgradientsusedoncanvas
<comment>(commentinformation)element,220 element,86–87
comments comments(/*comment/*),539–542
inbodyelement,29 contextualselection,476–478
CSSsyntax,434,539–542 counters,530
DTDscontaining,806–807 directdescendentselector,478
inheadelement,26–27 displaypropertyforchangingelementtypes,
HTMLsyntax,26,155–157 508–512
compactattribute documentstructureandinheritance,468–470
<dir>(directorylist)element,231 documenttreepseudo-classes,492–496
<dl>(definitionlist)element,235 elementselectors,471
<menu>(menulistorcommandmenu) embeddedstyles,456–458,526
element,319 errorhandling,445–447
<ol>(orderedlist)element,336 generalsiblingselectors,479
<ul>(unorderedlist)attributes,418 helloworldexample,438–440
compositingpropertiesandoptions,canvas HTMLelementsdivandspan,507–508
element,201 idselectors,471–473
conditionalcomments(</!--.[]..-->),155–157 importedstyles,458–459,526–527
conformancecheckers inlinestyles,459–461
Acid2,430–432 interfacestatepseudo-classes,491–492
HTML5,57 languagepseudoclass,497
contentattribute,<meta>(meta-information) link-relatedpseudo-classes,489–490
element,321 linkedstyles,452–456,524–526
contentediting(contenteditableattribute),in markupand,442–443
browsers,114–115 measurements,502–505,527–528
contentexclusion,SGML,804 mediatypes,461–463
Index 815
mythsandmisconceptions,517–519 datafldattribute,141
negationpseudoclass,497 dataformatasattribute,141
pageandmediaselectors,538–539 <datalist>(listofprefilldata)element,220–221
physicalmarkupandoverridingexpected datapagesizeattribute,<table>(table)element,387
results,506–507 datasrcattribute,141
presentationalHTMLand,429–430 datecontrols,definingformfields,102
printer-specificstyles,463–464 datetimeattribute
properties,500–502 <del>(deletedtext)element,225
propertiesforCSS1andCSS2.1,542 <ins>(insertedtext)element,288–289
proprietaryaspectof,440,442 <time>(time)element,409
pseudo-classselectors,487,498–500 <dd>(definitiondescriptioninadefinitionlist)
pseudo-elementselectors,484–488 element,222–224
reference,519 declareattribute,<object>(embeddedobject)
selectors,470,533–538 element,334
separationofstructureandstylein,514–515 :defaultselector,CSS3,617,620
slowriseinpopularity,430–432 deferattribute
specificationof,443–445 HTML5,121
stringsandkeywords,529–530 <script>(scripting)element,363
styleelementand,26 degunits,CSS3,621
summaryof,519 <del>(deletedtext)element,224–227
syntaxof,432–438,521,523–524 <details>(additionaldetails)element,109–110,
userstyles,466–467 227–228
validating,447–450 device-aspect-ratio,CSS3mediaqueryvalues,627
valueofstylesheetsinpresentation,516–517 device-height,CSS3mediaqueryvalues,627
versions,440–441,522 device-width,CSS3mediaqueryvalues,627
white-spacepropertyforcontrollingwhite <dfn>(definition)element,228–229
space,512–513 dirattribute,languageattributesreference,138
(X)HTMLand,506 <dir>(directorylist)element,230–231
CSS1,522 directdescendentselector(>),CSS,478
CSS2x directionattribute,<marquee>(marqueedisplay)
auralstyleproperties,607–612 element,317
descriptionof,522 directories
CSS3 <dir>(directorylist)element,230–231
attributeselectors,481 inURLs,786–787
browser-specificfeatures.Seebrowsers, disabledattribute
CSS3features commonelementattributesreference,141
colorvalues,622–624 CSSinterfacestatepseudo-classesand,491
descriptionof,522 <input>(inputformcontrol)element,282
emergingselectors,619–620 <link>(linktoexternalfilesorset
futuredirectionofCSS,440 relationships)element,304
mediaqueries,625–628 <optgroup>(optiongrouping)element,339
modules,614–616 <option>(optioninselectionlist)element,340
namespaces,624–625 <select>(selectionlist)element,368
overviewof,613 <style>(styleinformation)element,380
selectors,613,617–619 <textarea>(multilinetextinput)element,398
unitsofmeasurement,621–622 :disabledselector,CSS3,617
webfonts,626,628–629 displayproperty,CSS,508–512,568–570
currentColorkeyword,CSS3,622 <div>(division)element,231–233,507–508
cursorproperty,CSS,565–568 <dl>(definitionlist)element,233–236
curves,drawinginHTML5,90–93 <!DOCTYPE>(DocumentTypeDefinition)statement
changesinHTML5,69
commonelementsinHTMLandXHTML
D documents,7
dataattribute doctypeswitchandbrowserrendering
<comment>(commentinformation) modes,39–41
element,220 inHTMLelementreference,157
<object>(embeddedobject)element,334 listofcommon(X)HTML,19
dataURIs,791–794 usedtobegindocuments,18
data-X(CustomDataAttributes),116–117,143–144 validationofDTDrulesand,37
816 HTML & CSS: The Complete Reference
doctypeswitch,browserrenderingmodesand,39–41 dynsrcattribute
documenttreepseudo-classes,CSS,492–496 <ilayer>(inflowlayer)element,278
documents,HTML5 <input>(inputformcontrol)element,282
indicatingtimeanddates(time),76
insertingfigures(fig),76–77
markingtext(mark),75–76 E
overviewof,69–75 E~Fselector,CSS3,617
semanticsadded,75 E[attr^=value]selector,CSS3,617
specifyingnavigation(nav),77 E[attr$=value]selector,CSS3,617
documents,(X)HTML E[attr*=value]selector,CSS3,617
applyingstylesto,452 ELEMENTkeyword,801
<body>(documentbody)element,28–31, elementselectors,CSS,471
190–193 elementtypedeclarations,DTDs,801–802
exampleofheadelementandelements elements
containedin,27–28 colorsupport,772–773
<head>(documenthead)element,23,260–261 keywordsformeaningof,529
inheritanceand,468–470 newinHTML5,66–67
<meta>(meta-information)element,24–25, refinedinHTML5,64
320–323 removedfromHTML5,63–64,66
otherelementsallowedwithinhead elements,markup
element,25–26 browsersignoringunknown,44–45
overviewof,20–23 minimizingunused,43
<title>(documenttitle)element,23–24,410–411 nesting,43–44
useofcommentsin,26–27 rulesregardingclosingtagsinHTML/
DOM(DocumentObjectModel) XHTML,43
JavaScriptinterfaceforHTML,121–124 startandendtags,4
parsetrees,33 <em>(emphasis)element,8,28,238–240
domains <embed>(embeddedobject)element,240–242
countrycodesand,785–786 embeddedcomments,inSGMLdeclarations,807
Top-Level,784–786 embeddedmedia,328–329
downloads,CSSandeaseof,518–519 embeddedobjects,331–335
dpcm,CSS3units,621 embeddedstyles,456–458,526
dpi,CSS3units,621 empty-cellsproperty,CSS,570–571
draggableattribute emptyelements
addingdraganddropfunctionalityto closingtagsand,43
browsers,112–114 overviewof,5
commonHTML5elementattributes :emptyselector,CSS3,617
reference,144 enabledattribute,CSSinterfacestate
drawImage(img,x,y),creatingbitmapdrawingin pseudo-classes,491
HTML5,97 :enabledselector,CSS3,618
drawing,oncanvas encoding
arcsandcurves,90–93 characterentities,728–730
linesandshapes,85–88 inURLs,790–791
Dreamweaver enctypeattribute,<form>(formforuserinput)
colorpickersin,780 element,251
loading/previewingmarkupwith,9–10 entities
<dt>(terminadefinitionlistorcaptioninfiguresor %characterforparameterentity,804
details)element,236–238 asmacro,806
DTDs(documenttypedefinitions) specialcharacters,29,44
attributedeclarations,804–805 errorhandling,CSS,445–447
comments,806–807 eventattribute,<script>(scripting)element,363
elementtypedeclarations,801–802
logicalconnectors,803
occurrenceindicators,802–803
overviewof,16–18,801 F
parameterentities,806 faceattribute
SGMLandXMLkeywords,805 <basefont>(basefont)element,183
SGMLcontentexclusionandinclusion,804 <font>(fontdefinition)element,247
validationofDTDrules,37–39 <fieldset>(formfieldgrouping)element,242–244
W3Candonlinereferencesfor,807 <figure>(figure)element,76–77,244–246
Index 817
fileextensions formmethodattribute
browserhandlingof,13–14 <button>(button)element,197
URLsand,787 <input>(inputformcontrol)element,283
fileprotocol,789 formnovalidateattribute
FileTransferProtocol(FTP),789 <button>(button)element,197
filenames,inURLs,787–788 <input>(inputformcontrol)element,283
fillmethods,canvaselementand,83,85–86 forms
filterproperty <fieldset>(formfieldgrouping)element,
CSS3browser-specificfeatures,666–672 242–244
transitionsand,668–669 <input>(inputformcontrol)element,279–287
filters,breakingCSSrulesintentionally,450–452 <label>(formcontrollabel)element,294–296
Firefox.Seealsobrowsers <output>(formoutput)element,341–343
CSSsupportand,430–432 forms,changesinHTML5
handlingfileextensionsandMIME autocompletelists,105
types,13–14 newfieldtypes,101–104
videosupportin,79 overviewof,101
:first-child,CSSdocumenttreepseudo-class, usabilityimprovements,105–106
492–493 validatingdataentryon,104–105
:first-letterpseudo-elementselector,CSS,484–485 formtargetattribute
::first-letterselector,CSS3,618 <button>(button)element,197
:first-linepseudo-elementselector,CSS,484–485 <input>(inputformcontrol)element,283
::first-lineselector,CSS3,618 FQDN(fullyqualifieddomainname),785
:first-of-typeselector,CSS3,618 fragmentidentifiers,inURLs,788
floatproperty,CSS,571–572 frameattribute,<table>(table)element,387–388
:focus,CSSactivity-relatedpseudo-classes,490–491 <frame>(windowregion)element,110,252–255
font-familyproperty,CSS,572–573 frameborderattribute
<font>(fontdefinition)element,246–247 <frame>(windowregion)element,254
fontproperty,CSS,572 <frameset>(framesetdefinition)
font-sizeproperty,CSS,573–574 element,256
font-styleproperty,CSS,574–575 <iframe>(inlineframe)element,272
font-variantproperty,CSS,575 frames
font-weightproperty,CSS,575–576 <frame>(windowregion)element,
@fontfacerule,CSS,540–541 110,252–255
fonts futureof,110–112
<basefont>(basefont)element,182–183 <iframe>(inlineframe)element,270–274
<big>(bigfont)element,186–187 <noframes>(noframesupportcontent)
fontsmodule,CSS3,614 element,329–330
<footer>(footer)element <frameset>(framesetdefinition)element,110,255–257
changesinHTML5,69 framespacingattribute
overviewof,248–249 <frameset>(framesetdefinition)element,256
sectionelementcontaining,70–71 <iframe>(inlineframe)element,272
footers,<tfoot>(tablefooter)element,399–402 FTP(FileTransferProtocol),789
forattribute fullyqualifieddomainname(FQDN),785
<label>(formcontrollabel)element,295
<output>(formoutput)element,341
<script>(scripting)element,363 G
formattribute galleryingattribute,<ilayer>(inflowlayer)
<button>(button)element,196 element,278
<input>(inputformcontrol)element,282 generalsiblingselectors(~),CSS,479
<output>(formoutput)element,341 generatedandreplacedcontentmodule,CSS3,614
<select>(selectionlist)element,368 generatedcontentforpagedmediamodule,CSS3,614
<textarea>(multilinetextinput)element,398 genericidentifiers,DTDelementtypedeclarations,801
<form>(formforuserinput)element,249–252 geometricshapes,characterentitiesfor,748
formactionattribute grunits,CSS3,621
<button>(button)element,196 gradunits,CSS3,621
<input>(inputformcontrol)element,282 gradientmethods,canvaselement,200
formenctypeattribute gradientproperty,CSS3browser-specificfeatures,
<button>(button)element,196–197 672–673
<input>(inputformcontrol)element,282–283 Greek,characterentitiesfor,743–744
818 HTML & CSS: The Complete Reference
grid,CSS3mediaqueryvalues,627 <base>(baseURL)element,182
gridpositioningmodule,CSS3,614 <link>(linktoexternalfilesorset
gutterattribute,<multicol>(multiplecolumntext) relationships)element,304
element,325 hreflangattribute
<a>(anchor)elementand,159
<area>(ImageMapArea)element,173
H <link>(linktoexternalfilesorset
<h1>through<h6>(headings)element,8,28,258–260 relationships)element,304
hacks,breakingCSSrulesintentionally,450–452 HSLcolor,CSS3colorunits,622
hand-codingHTML,48 HSLacolor,CSS3colorunits,623
<head>(documenthead)element hspaceattribute
commonelementsinHTMLandXHTML commonelementattributesreference,141
documents,7 <input>(inputformcontrol)element,283
embeddingstylesin,526 <table>(table)element,388
exampleofheadelementandelements HTML,flavorsof,133–135
containedin,27–28 <html>(HTMLdocument)element,7,267–269
<meta>tagsforspecifyingcontenttype, HTML2
characterset,andotherinformation,24–25 <listing>(codelisting)element,311
otherelementsallowedwithin,25–26 <plaintext>(plaintext)element,347
overviewof,23,260–261 HTML4.Seealso(X)HTML
<title>(documenttitle)elementand,23–24 attributesremovedfromHTML5,65
<header>(header)element characterentities,740–741
inHTML5,69–72 elementsrefinedinHTML5,64
overviewof,261–263 elementsremovedfromHTML5,63–64,66
sectionelementcontaining,70–71 HTML4attributesreference
headers <a>(anchor)attributes,159
<th>(tableheader)element,402–405 <abbr>(abbreviation)attributes,165
<thead>(tableheader)element,405–408 <acronym>(acronym)attributes,167
headersattribute <address>(address)attributes,168
<td>(tabledata)element,395 <area>(ImageMapArea)attributes,172
<tfoot>(tablefooter)element,404 <b>(bold)attributes,180
headings.See<h1>through<h6>(headings)element <bdo>(bidirectionaloverride)attributes,184
heightattribute <big>(bigfont)attributes,187
<canvas>elementand,83 <blockquote>(blockquote)attributes,189
commonelementattributesreference,141 <body>(documentbody)attributes,191
<ilayer>(inflowlayer)element,275 <button>(button)attributes,196
<input>(inputformcontrol)element,283 <caption>(tablecaption)attributes,209
<layer>(positionedlayer)element,297 <center>(centeralignment)attributes,210
<spacer>(extraspace)element,373 <cite>(citation)attributes,212
<table>(table)element,388 <code>(codelisting)attributes,213
<td>(tabledata)element,395 <col>(tablecolumn)attributes,215
<tfoot>(tablefooter)element,404 <colgroup>(tablecolumngroup)
heightproperty,CSS,576–577,627 attributes,217
helloworldexample <dd>(definitiondescriptioninadefinition
CSS,438–440 list)attributes,223
HTML/XHTML,6–8 <del>(deletedtext)attributes,225
hexequivalents,(X)HTMLcolornamesand,766 <dfn>(definition)attributes,229
<hgroup>(headergroup)element,72–73,263–265 <dir>(directorylist)attributes,230
hiddenattribute,144 <div>(division)attributes,232
hidefocusattribute,141 <dl>(definitionlist)attributes,234
:hover,CSSactivity-relatedpseudo-classes,490–491 <dt>(terminadefinitionlistorcaptionin
<hr>(horizontalrule)element figuresordetails)attributes,236
commonelementsinHTMLandXHTML <em>(emphasis)attributes,239
documents,8 <fieldset>(formfieldgrouping)attributes,243
DTDdefiningsyntaxof,17 <form>(formforuserinput)attributes,250
overviewof,265–367 <h1>through<h6>(headings)attributes,258
hrefattribute <hr>(horizontalrule)attributes,266
<a>(anchor)elementand,159 <i>(italic)attributes,269
<area>(ImageMapArea)element,173 <img>(image)attributes,277
Index 819
<ins>(insertedtext)attributes,288 documentstructurechanges,69–75
<kbd>(keyboardinput)attributes,291 DOMJavaScriptinterfaceforHTMLand,
<label>(formcontrollabel)attributes,294 121–124
<li>(listitem)attributes,301 draganddropfunctionality(draggable
<link>(linktoexternalfilesorset attribute)addedtobrowsers,112–114
relationships)attributes,303 drawingandstylinglinesandshapeson
<map>(client-sideimagemap)attributes,313 canvaselement,85–88
<menu>(menulistorcommandmenu) drawingarcsandcurvesoncanvas,90–93
attributes,318 extendedevents,151–154
<noframes>(noframesupportcontent) formchanges,101
attributes,329 futureofframesand,110–112
<noscript>(noscriptsupportcontent) goalsof,63
attributes,330 HTML4attributesremovedfromHTML5,65
<object>(embeddedobject)attributes,332 HTML4elementsrefinedinHTML5,64
<ol>(orderedlist)attributes,335–336 HTML4elementsremovedfrom
<optgroup>(optiongrouping)attributes,338 HTML5,63–64,66
<option>(optioninselectionlist) imperfectionsof,131–132
attributes,340 indicatingtimeanddates(time),76
<p>(paragraph)attributes,343 insertingaudio(audio),80–81
<pre>(preformattedtext)attributes,349 insertingfigures(fig),76–77
<quote>(quote)attributes,352 insertingvideo(video),78–80
<s>(strikethrough)attributes,360 internationalizationand,116
<samp>(sampletext)attributes,361 loosesyntaxreturnsin,58–60
<select>(selectionlist)attributes,367 markingtext(mark),75–76
<strike>(strikeouttext)attributes,376 menuelementrepurposedforbettersupport
<strong>(strongemphasis)attributes,378 ofwebapplications,106–108
<sub>(subscript)attributes,382 metadatachanges,116
<sup>(superscript)attributes,384 meterandprogresselementssupportingof
<table>(table)attributes,386 webapplications,109
<tbody>(tablebody)attributes,390 microdataaddedto,117–120
<td>(tabledata)attributes,393 newattributesin,66,68
<textarea>(multilinetextinput) newelementsin,66–67
attributes,397 newformfieldtypes,101–104
<tfoot>(tablefooter)attributes,400 newwebapplicationelementsand
<th>(tableheader)attributes,403 attributes,106
<thead>(tableheader)attributes,406 openmediafeaturesin,78,82
<tt>(teletypetext)attributes,415 outputelementsupportingofweb
<u>(underline)attributes,416 applications,110
<ul>(unorderedlist)attributes,418 overviewof,55
<var>(variable)attributes,420 readyforusenow?,126–130
<xmp>(example)attributes,425–426 scaling,rotating,andtranslatingdrawingson
HTML5.Seealso(X)HTML canvas,93–97
addingperspectivetocanvas,88–90 semanticsadded,75
autocompletelists,105 specifyingnavigation(nav),77
backtothefuturewith,52–53 spellchecking(spellcheckattribute)in
beyondmarkupfeaturesin,120–121 browsers,115–116
bitmapimagesusedindrawingsoncanvas, standardizingandextendingadhoc
97–98 JavaScriptconventions,125–126
catch-allnatureof,130–131 summary,132
client-sidegraphics(canvas),82–85 syntaxof,55–58
commandelementsupportingofweb textsupportincanvas,98–100
applications,108 usabilityimprovementsin,105–106
commonelementattributesreference,142–146 usingXMLsyntaxwith,60–61
contentediting(contenteditableattribute)in validatingdataentryonforms,104–105
browsers,114–115 webmarkupwith,62–63
coreevents,146–151 Webpoliticsandcompetitionand,131
data-Xattributes,116–117 HTML5attributesreference
deferattribute,121 <a>(anchor)attributes,158–159
detailselementsupportingofweb <abbr>attributes,165
applications,109–110 <address>(address)attributes,168
820 HTML & CSS: The Complete Reference
HTML5attributesreference(Continued) <map>(client-sideimagemap)
<area>(ImageMapArea)attributes,172 attributes,313
<article>(article)attributes,175–176 <mark>(markedtext)attributes,314–315
<aside>(aside)attributes,176–177 <menu>(menulistorcommandmenu)
<audio>(audio)attributes,177–178 attributes,318–319
<b>(bold)attributes,179–180 <meta>(meta-information)attributes,320–321
<base>(baseURL)attributes,181 <meter>(scalargauge)attributes,323–324
<bdo>(bidirectionaloverride)attributes,184 <nav>(navigation)attributes,326–327
<blockquote>(blockquote)attributes,188–189 <noscript>(noscriptsupportcontent)
<body>(documentbody)attributes,190–191 attributes,330
<br>(linebreak)attributes,193–194 <object>(embeddedobject)
<button>(button)attributes,195–196 attributes,332–333
<canvas>(canvasfordrawing)attributes, <ol>(orderedlist)attributes,335–336
198–199 <optgroup>(optiongrouping)attributes,
<caption>(tablecaption)attributes,208–209 338–339
<cite>(citation)attributes,211–212 <option>(optioninselectionlist)
<code>(codelisting)attributes,213 attributes,340
<col>(tablecolumn)attributes,215 <output>(formoutput)attributes,341–342
<colgroup>(tablecolumngroup)attributes,217 <p>(paragraph)attributes,343–344
<command>(command)attributes,219–220 <param>(objectparameter)
<datalist>(listofprefilldata)attributes,221 attributes,345–346
<dd>(definitiondescriptioninadefinition <pre>(preformattedtext)attributes,348–349
list)attributes,222–223 <progress>(progressindicator)attributes,
<del>(deletedtext)attributes,225 350–351
<details>(additionaldetails) <quote>(quote)attributes,352
attributes,227–228 <rp>(Rubyparentheses)attributes,354
<dfn>(definition)attributes,228–229 <rt>(Rubytext)attributes,355–356
<div>(division)attributes,231–232 <ruby>(Rubyannotation)attributes,357–358
<dl>(definitionlist)attributes,234–235 <samp>(sampletext)attributes,361
<dt>(terminadefinitionlistorcaptionin <script>(scripting)attributes,362–363
figuresordetails)attributes,236–237 <section>(section)attributes,365
<em>(emphasis)attributes,238–239 <select>(selectionlist)attributes,367
<embed>(embeddedobject) <smalltext>(smalltext)attributes,370
attributes,240–241 <source>(source)attributes,371–372
<fieldset>(formfieldgrouping)attributes,243 <span>(textspan)attributes,374–375
<figure>(figure)attributes,244–245 <strong>(strongemphasis)
<footer>(footer)attributes,248–249 attributes,377–378
<form>(formforuserinput)attributes,250 <style>(styleinformation)
<h1>through<h2>(headings)attributes, attributes,379–380
258–259 <sub>(subscript)attributes,382
<head>(documenthead)attributes,260 <sup>(superscript)attributes,383–384
<header>(header)attributes,262–263 <table>(table)attributes,385–386
<hgroup>(headergroup)attributes,263–264 <tbody>(tablebody)attributes,390–391
<hr>(horizontalrule)attributes,265–266 <td>(tabledata)attributes,393
<html>(HTMLdocument)attributes,267–268 <textarea>(multilinetextinput)attributes,
<i>(italic)attributes,269–270 396–397
<iframe>(inlineframe)attributes,271–272 <tfoot>(tablefooter)attributes,400
<img>(image)attributes,276 <th>(tableheader)attributes,402–403
<input>(inputformcontrol) <thead>(tableheader)attributes,406
attributes,280–281 <time>(time)attributes,408
<ins>(insertedtext)attributes,287–288 <title>(documenttitle)attributes,410–411
<kbd>(keyboardinput)attributes,291–292 <tr>(tablerow)attributes,412–413
<keygen>(keypairgeneration)attributes, <ul>(unorderedlist)attributes,417–418
292–293 <var>(variable)attributes,420
<label>(formcontrollabel)attributes,294–295 <video>(video)attributes,421–422
<legend>(descriptivelegend) http-equivattribute,<meta>(meta-information)
attributes,298–299 element,321
<li>(listitem)attributes,301 HTTP(HypertextTransferProtocol),788–789
<link>(linktoexternalfilesorset hyperlinkpresentationmodule,CSS3,614
relationships)attributes,303–304 Hzunits,CSS3,621
Index 821
I <head>(documenthead)attributes,260–261
<hr>(horizontalrule)attributes,265–266
<i>(italic)element,28,269–270
<html>(HTMLdocument)attributes,267–268
IANA(InternetAssignedNumbersAuthority),785
<i>(italic)attributes,269
idattribute
<iframe>(inlineframe)attributes,271–272
coreelementattributes,136–137
<img>(image)attributes,276–277
CSSselectors,471–473
<input>(inputformcontrol)
elementnamesand,435
attributes,281–282
IE(InternetExplorer).Seealsobrowsers
<ins>(insertedtext)attributes,288
CSSsupportand,430–432
<isindex>(indexprompt)attributes,290
extendedeventattributes,147–154
<kbd>(keyboardinput)attributes,291–292
handlingfileextensionsandMIME
<label>(formcontrollabel)attributes,294–295
types,13–14
<legend>(descriptivelegend)attributes,299
IE8supportofCSS3properties,616
<li>(listitem)attributes,301
videosupportin,79
<link>(linktoexternalfilesorset
IE(InternetExplorer),elementattributes
relationships)attributes,304
<a>(anchor)relatedattributes,158–159
<listing>(codelisting)attributes,312
<abbr>elementattributes,165–166
<map>(client-sideimagemap)
<acronym>(acronym)element,167
attributes,313–314
<address>(address)attributes,168–169
<marquee>(marqueedisplay)attributes,316
<applet>(Javaapplet)attributes,169–170
<menu>(menulistorcommandmenu)
<area>(ImageMapArea)attributes,172–173
attributes,318–319
<base>(baseURL)attributes,181
<meta>(meta-information)attributes,321
<basefont>(basefont)attributes,183
<nobr>(nolinebreaks)element,327
<bdo>(bidirectionaloverride)attributes,185
<noframes>(noframesupportcontent)
<bgsound>(backgroundsound)
attributes,329
attributes,185
<noscript>(noscriptsupportcontent)
<big>(bigfont)attributes,186–187
attributes,331
<blockquote>(blockquote)attributes,188–189
<object>(embeddedobject)attributes,332–333
<body>(documentbody)attributes,190–191
<ol>(orderedlist)attributes,335–336
<br>(linebreak)attributes,194
<option>(optioninselectionlist)
<button>(button)attributes,196
attributes,340
<caption>(tablecaption)attributes,208–209
<p>(paragraph)attributes,343–344
<center>(centeralignment)attributes,210
<param>(objectparameter)attributes,345
<cite>(citation)attributes,212
<plaintext>(plaintext)attributes,347
<code>(codelisting)attributes,213–214
<pre>(preformattedtext)attributes,349
<col>(tablecolumn)attributes,215
<quote>(quote)attributes,352–353
<colgroup>(tablecolumngroup)
<rt>(Rubytext)attributes,356
attributes,217
<ruby>(Rubyannotation)attributes,358
<comment>(commentinformation)
<s>(strikethrough)attributes,359–360
attributes,220
<samp>(sampletext)attributes,361
<dd>(definitiondescriptioninadefinition
<script>(scripting)attributes,362–363
list)attributes,223
<select>(selectionlist)attributes,367–368
<del>(deletedtext)attributes,225
<smalltext>(smalltext)attributes,370–371
<dfn>(definition)attributes,229
<span>(textspan)attributes,374–375
<dir>(directorylist)attributes,230
<strike>(strikeouttext)attributes,376
<div>(division)attributes,232
<strong>(strongemphasis)attributes,378
<dl>(definitionlist)attributes,235
<style>(styleinformation)attributes,380
<dt>(terminadefinitionlistorcaptionin
<sub>(subscript)attributes,382–383
figuresordetails)attributes,236–237
<sup>(superscript)attributes,384
<em>(emphasis)attributes,239
<table>(table)attributes,386
<embed>(embeddedobject)attributes,241
<tbody>(tablebody)attributes,390–391
<fieldset>(formfieldgrouping)attributes,
<td>(tabledata)attributes,393–394
243–244
<textarea>(multilinetextinput)attributes,397
<font>(fontdefinition)attributes,246
<tfoot>(tablefooter)attributes,400–401
<form>(formforuserinput)attributes,250
<th>(tableheader)attributes,403
<frame>(windowregion)attributes,253
<thead>(tableheader)attributes,406–407
<frameset>(framesetdefinition)attributes,
<title>(documenttitle)attributes,411
255–256
<tr>(tablerow)attributes,412–413
<h1>through<h2>(headings)attributes,259
822 HTML & CSS: The Complete Reference
IE(InternetExplorer),elementattributes(Continued) itemscopeattribute,commonHTML5element
<tt>(teletypetext)attributes,415 attributesreference,145
<u>(underline)attributes,416 itemtypeattribute,commonHTML5element
<ul>(unorderedlist)attributes,417–418 attributesreference,146
<var>(variable)attributes,420
<xml>(XMLdataisland)attributes,424
<xmp>(example)attributes,425–426 J
IETF(InternetEngineeringTaskForce),14 Javaapplet,169–171
iframeelement,inHTML5,110–112 JavaScript
<iframe>(inlineframe)element,270–274 DOMinterfaceforHTML,121–124
<ilayer>(inflowlayer)element,274–275 standardizingandextendingadhoc
imagemaps,<area>(ImageMapArea)element, JavaScriptconventions,125–126
171–174 usinginURLs,788
image-renderingproperty,CSS3browser-specific
features,673–674
ImageDataAPImethodsandproperties,canvas
K
<kbd>(keyboardinput)element,291–294
element,207
@keyframes,CSS3browser-specificfeatures,630–631
ime-modeproperty,CSS3browser-specific
<keygen>(keypairgeneration)element,292–294
features,674
keywords
<img>(image)element,29,276–279
CSS,529–530
@import,importingstylesheets,458–459,526–527
SGMLandXML,805
!important,indicatingrulethatshouldnotbe
kHzunits,CSS3,621
overridden,470,542
:in-rangeselector,CSS3,620
indexes,<isindex>(indexprompt)element,289–291
inferredelements,4
L
labelattribute
inheritance,documentstructureand,468–470 <menu>(menulistorcommandmenu)
inlineelements,28 element,319
inlineframes,<iframe>(inlineframe) <optgroup>(optiongrouping)element,339
element,270–274 <option>(optioninselectionlist)element,341
inlinestyles <label>(formcontrollabel)element,294–296
limitationsof,433 langattribute,languageattributesreference,139
markupinCSSand,442–443 :lang,CSS,497
overviewof,459–461 languageattribute
input,formsfor,249–252 commonelementattributesreference,141
<input>(inputformcontrol)element <script>(scripting)element,363
definingformfieldswith,101 languagepseudoclass,CSS,497
listattribute,105 :last-child,CSSdocumenttreepseudo-class,493
overviewof,279–287 :last-childselector,CSS3,618
<ins>(insertedtext)element,287–289 :last-of-typeselector,CSS3,618
interactivity,CSSand,519 LatinExtended-Acharacterentities,741
interfacestatepseudo-classes,CSS,491–492 LatinExtended-Bcharacterentities,741
internationalization,inHTML5,116 <layer>(positionedlayer)element,296–298
InternetAssignedNumbersAuthority(IANA),785 layout-grid-charproperty,CSS3browser-specific
InternetEngineeringTaskForce(IETF),14 features,675–676
InternetExplorer.SeeIE(InternetExplorer) layout-grid-lineproperty,CSS3browser-specific
Internet,locatingobjectson,783–784 features,676
interpolation-modeproperty,CSS3browser-specific layout-grid-modeproperty,CSS3browser-specific
features,674–675 features,676–677
:invalidselector,CSS3,620 layout-gridproperty,CSS3browser-specific
<isindex>(indexprompt)element,289–291 features,675
ismapattribute,<ilayer>(inflowlayer)element,278 layoutkeyword,529
italics.See<i>(italic)element leftattribute
itemidattribute,commonHTML5elementattributes <ilayer>(inflowlayer)element,275
reference,144 <layer>(positionedlayer)element,297
itempropattribute,commonHTML5element leftproperty,CSS,577–578
attributesreference,144–145 leftmarginattribute,<body>(documentbody)
itemrefattribute,commonHTML5element element,192
attributesreference,145 <legend>(descriptivelegend)element,298–300
Index 823
lengthlimits,forURLs,797
length,unitsofmeasurementinCSS,
M
mailto,789
502–505,527–528
manifestattribute,<html>(HTMLdocument)
letter-likesymbols,characterentitiesfor,744–745
element,268
letter-spacingproperty,CSS,578
<map>(client-sideimagemap)element,
<li>(listitem)element,300–302
312–314
linebreaks
margin-bottomproperty,CSS,582
<br>(linebreak)element,193–195
margin-leftproperty,CSS,582–583
line-breakproperty,CSS3,677
marginproperty,CSS,581–582
<nobr>(nolinebreaks)element,327–328
margin-rightproperty,CSS,583
line-heightproperty,CSS,578–579
margin-topproperty,CSS,583–584
linelayoutmodule,CSS3,615
marginheightattribute
lineproperties,canvaselement,203
<body>(documentbody)element,192
lines,drawingandstylinginHTML5,85–88
<frame>(windowregion)element,254
linkattribute,<body>(documentbody)element,192
<iframe>(inlineframe)element,272
<link>(linktoexternalfilesorsetrelationships)
marginwidthattribute
element
<body>(documentbody)element,192
elementsallowedwithinheadelement,25–26
<frame>(windowregion)element,254
linkingtostylesheets,452–456
<iframe>(inlineframe)element,272
overviewof,303–311
<mark>(markedtext)element,75–76,314–315
link-relatedpseudo-classes,CSS,489–490
markup
linkedstyles,CSS,452–456,524–526
CSSsyntax,442–443
listattribute,<input>(inputformcontrol)element,
easeofCSSlayoutvs.,518
105,283
HTML/XHTMLsyntax,3–6
list-style-imageproperty,CSS,579
physicalvs.logical,45–46
list-style-positionproperty,CSS,579–580
viewinglocally,8–10
list-styleproperty,CSS,579
viewingwithWebserver,10–14
list-style-typeproperty,CSS,580–581
marquee-directionproperty,CSS3browser-specific
<listing>(codelisting)element,311–312
features,678–679
lists
<marquee>(marqueedisplay)element,316–317
autocomplete,105
marquee-play-countproperty,CSS3browser-specific
CSS3modules,615
features,679
<datalist>(listofprefilldata)
marquee-speedproperty,CSS3browser-specific
element,220–221
features,679–680
<dd>(definitiondescriptioninadefinition
marquee-styleproperty,CSS3browser-specific
list)element,222–224
features,680–681
<dl>(definitionlist)element,233–236
marqueesmodule,CSS3,615
<li>(listitem)element,300–302
mask-attachmentproperty,CSS3browser-specific
<ol>(orderedlist)element,335–338
features,682
<select>(selectionlist)element,366–369
mask-clipproperty,CSS3browser-specific
<ul>(unorderedlist)attributes,417–419
features,683
logicalandphysicalmarkup,HTML/XHTML,45–46
mask-compositeproperty,CSS3browser-specific
logicalconnectors,DTDsand,803
features,684
logicalmarkup,vs.physicalmarkup,45–46
mask-originproperty,CSS3browser-specific
longdescattribute
features,685
<frame>(windowregion)element,254
mask-positionproperty,CSS3browser-specific
<iframe>(inlineframe)element,272
features,685–686
<ilayer>(inflowlayer)element,278
mask-position-xproperty,CSS3browser-specific
loopattribute
features,686–687
<area>(ImageMapArea)element,178
mask-position-yproperty,CSS3browser-specific
<bgsound>(backgroundsound)element,185
features,687
<ilayer>(inflowlayer)element,278
maskproperty,CSS3browser-specific
<input>(inputformcontrol)element,283
features,681–682
<marquee>(marqueedisplay)element,317
mask-repeatproperty,CSS3browser-specific
<video>(video)element,422
features,687–688
lowattribute,<meter>(scalargauge)attributes,324
mask-sizeproperty,CSS3browser-specificfeatures,
lowsrcattribute
688–690
<ilayer>(inflowlayer)element,278
mathematicaloperators,characterentities
<input>(inputformcontrol)element,283
for,746–747
824 HTML & CSS: The Complete Reference
maxattribute multi-columnlayoutmodule,CSS3,615
<input>(inputformcontrol)element,283 <multicol>(multiplecolumntext)element,325–326
<meter>(scalargauge)element,324 multipleattribute
max-heightproperty,CSS,584 <input>(inputformcontrol)element,284
max-widthproperty,CSS,584–585 <select>(selectionlist)element,368
maxlengthattribute,<input>(inputformcontrol)
element,284
mayscriptattribute,<applet>(Javaapplet) N
element,170 nameattribute
measurements,CSS,502–505,527–528 <a>(anchor)elementand,160
mediaattribute <applet>(Javaapplet)element,171
<a>(anchor)elementand,160 <area>(ImageMapArea)element,173
<area>(ImageMapArea)element,173 <button>(button)element,197
<link>(linktoexternalfilesorset <embed>(embeddedobject)element,241
relationships)element,304 <form>(formforuserinput)element,251
<source>(source)attributes,372 <frame>(windowregion)element,254
<style>(styleinformation)element,380 <iframe>(inlineframe)element,272
mediaattribute,CSS2.1,462 <ilayer>(inflowlayer)element,275,278
media,inHTML5.Seeopenmediafeatures,in <input>(inputformcontrol)element,284
HTML5 <layer>(positionedlayer)element,297
mediaqueriesmodule,CSS3,615 <map>(client-sideimagemap)element,314
@mediarule,CSS,541 <meta>(meta-information)element,321
mediaselectors,CSS,538–539 <object>(embeddedobject)element,334
mediatypes <output>(formoutput)element,341
CSSselectorsfor,538 <param>(objectparameter)element,346
CSS2.1,461,525 <ruby>(Rubyannotation)element,358
definingforstylesheets,462–463 <select>(selectionlist)element,368
handlingmedia-relatederrors,447 <textarea>(multilinetextinput)element,398
<menu>(menulistorcommandmenu)element, NAMEkeyword,805
106–108,318–320 namespaces,CSS3,624–625
<meta>(meta-information)element namespacesmodule,CSS3,615
inHTMLandXHTMLdocuments,7 <nav>(navigation)element,77,326–327
overviewof,320–323 negationpseudoclass,CSS,497
forspecifyingcontenttype,characterset,and nestingelements
otherinformation,24–25 conformancetoHTML5specification,59
metadatachanges,inHTML5 markupand,43–44
data-Xattributes,116–117 Netscape
microdataadded,117–120 <applet>(Javaapplet)attributes,169–170
overviewof,116 <blink>(blinkingtext)element,187–188
meterelement,HTML5,109 <body>(documentbody)attributes,191
<meter>(scalargauge)element,323–325 <font>(fontdefinition)attributes,246
methodattribute <ilayer>(inflowlayer)attributes,274–275
<a>(anchor)elementand,160 <layer>(positionedlayer)attributes,296
<form>(formforuserinput)element,251 <multicol>(multiplecolumntext)
microdata,addedtoHTML5,117–120 attributes,325
Microsoft <noembed>(noembeddedmediasupport)
Expression,780 element,328
ExtendedEventmodel,151–154 <spacer>(extraspace)attributes,373
VML(VectorMarkupLanguage),82 <textarea>(multilinetextinput)
MIMEtypes attributes,397
<meta>tagsforspecifying,25 networkfailures,errorhandlinginCSS,447
browserhandlingof,13–14 <nobr>(nolinebreaks)element,327–328
minattribute <noembed>(noembeddedmediasupport)element,
<input>(inputformcontrol)element,284 328–329
<meter>(scalargauge)element,324 <noframes>(noframesupportcontent)element,
min-heightproperty,CSS,585 329–330
min-widthproperty,CSS,585–586 nohrefattribute,<area>(ImageMapArea)
monochrome,CSS3mediaqueryvalues,628 element,173
msunit,CSS3,621 noresizeattribute,<frame>(windowregion)
element,254
Index 825
<noscript>(noscriptsupportcontent) overflowattribute,<layer>(positionedlayer)
element,330–331 element,297
noshadeattribute,<hr>(horizontalrule) overflowproperty,CSS,590–591
attributes,261 overflow-styleproperty,CSS3browser-specific
:not,CSSnegationpseudoclass,497 features,691–692
:not(s)selector,CSS3,618 overflow-xproperty,CSS3browser-specific
novalidateattribute,<form>(formforuserinput) features,692
element,251 overflow-yproperty,CSS3browser-specific
nowrapattribute features,693
<body>(documentbody)element,192
<dd>(definitiondescriptioninadefinition
list)element,223 P
<div>(division)element,232 <p>(paragraph)element
<dt>(terminadefinitionlistorcaptionin block-levelelements,28
figuresordetails)element,237 diagramofelementsin,31
<td>(tabledata)element,395 DTDdefiningsyntaxof,16
<tfoot>(tablefooter)element,404 inHTMLandXHTMLdocument,8
:nth-child(n)selector,CSS3,618 overviewof,343–345
:nth-type(n)selector,CSS3,619 padding-bottomproperty,CSS,593
numericalequivalents,(X)HTMLcolornamesand, padding-leftproperty,CSS,593–594
765,767–771 paddingproperty,CSS,591–593
padding-rightproperty,CSS,594
padding-topproperty,CSS,594–595
O page-break-afterproperty,CSS,595
objectattribute,<applet>(Javaapplet)element,171 page-break-beforeproperty,CSS,595–596
objects page-break-insideproperty,CSS,596
<object>(embeddedobject)element,25–26, @pagerule,CSS,541–542
331–335 pageselectors,CSS,538–539
<param>(objectparameter)element,345–347 pagedmediamodule,CSS3,615
occurrenceindicators,DTDs,802–803 pagexattribute
<ol>(orderedlist)element,335–338 <ilayer>(inflowlayer)element,275
:only-childselector,CSS3,619 <layer>(positionedlayer)element,297
:only-of-typeselector,CSS3,619 pageyattribute
opacityproperty,CSS3browser-specificfeatures,690 <ilayer>(inflowlayer)element,275
openmediafeatures,inHTML5 <layer>(positionedlayer)element,297
considerationsregarding,82 paletteattribute,<embed>(embeddedobject)
insertingaudio(audio),80–81 element,241
insertingvideo(video),78–80 paragraphs.See<p>(paragraph)element
parsetrees,78 <param>(objectparameter)element,345–347
Operabrowser,colorsupportin,766.Seealso parameterentities,804,806
browsers parseerrors,62
<optgroup>(optiongrouping)element,338–339 parsetrees,32–33
optimumattribute,<meter>(scalargauge) passwords,inURLs,789
element,324 pathAPImethods,canvaselement,204–205
<option>(optioninselectionlist)element,339–341 patternattribute
:optionalselector,CSS3,620 enforcingdatatoconformtoregular
orientation,CSS3mediaqueryvalues,628 expression,104–105
orphansproperty,CSS,586 <input>(inputformcontrol)element,284
:out-of-rangeselector,CSS3,620 <textarea>(multilinetextinput)element,398
outline-colorproperty,CSS,588–589 persistence,ofURLs,797
outline-offsetproperty,CSS3browser-specific perspective,for3DeffectonHTML5canvas,88–90
features,690–691 perspective-originproperty,CSS3browser-specific
outlineproperty,CSS,586–588 features,694–695
outline-radiusproperty,CSS3browser-specific perspectiveproperty,CSS3browser-specificfeatures,
features,691 693–694
outline-styleproperty,CSS,589–590 Photoshop,780
outline-widthproperty,CSS,590 physicalmarkup
outputelement,HTML5,110 CSSand,506–507
<output>(formoutput)element,341–343 vs.logicalmarkup,45–46
826 HTML & CSS: The Complete Reference
pingattribute overviewof,484
<a>(anchor)element,160 ::selection,485–486
<area>(ImageMapArea)element,173 pubdateattribute,<time>(time)element,409
placeholderattribute punctuation,characterentitiesfor,741–742
<input>(inputformcontrol)element,284
<textarea>(multilinetextinput)
element,398 Q
<plaintext>(plaintext)element,347–348 querystrings,inURLs,790
playbackcontrols,forvideo,78–79 quirksmode,browserrenderingmodes,39
pluginspageattribute,<embed>(embeddedobject) <quote>(quote)element,351–353
element,241 quotesproperty,CSS,597
point-sizeattribute,<font>(fontdefinition)
element,247
ports,specifyinginURLs,790
R
radunits,CSS3,621
positionproperty,CSS,596–597
:read-onlyselector,CSS3,620
posterattribute,<video>(video)element,422
:read-writeselector,CSS3,620
practices,vs.standards,46–47
readonlyattribute
<pre>(preformattedtext)element,348–350
<input>(inputformcontrol)element,284
presentation
<textarea>(multilinetextinput)element,398
CSSasalternativetopresentationalHTML,
rectanglemethods,canvaselement,204
429–430
redesign,CSSand,519
valueofCSSfor,516–517
relattribute
presentationelements,removedfrom
<a>(anchor)element,160
HTML5,63–64
<area>(ImageMapArea)element,173
presentationlevelsmodule,CSS3,615
<link>(linktoexternalfilesorset
printers,printer-specificCSSstyles,463–464
relationships)element,304–310
profileattribute,<head>(documenthead)
relativeURLs
attributes,261
<base>tagand,795–796
programminglanguages,47
overviewof,795
progresselement,webapplicationfeatures
requiredattribute
supportedinHTML5,109
<input>(inputformcontrol)element,284
<progress>(progressindicator)element,350–351
<textarea>(multilinetextinput)
promptattribute,<isindex>(indexprompt)
element,398
attributes,290
validationand,104–105
properties,CSS
:requiredselector,CSS3,620
auralstyleproperties,607–612
resizeproperty,CSS3browser-specific
color-related,776
features,695–696
CSS1andCSS2.1,542
resolution,CSS3mediaqueryvalues,628
handlingillegalorunknownpropertyvalues,
revattribute
446–447
<a>(anchor)elementand,160
handlingunknown,445
<link>(linktoexternalfilesorset
overviewof,500–502
relationships)element,310
protocols,fornegotiatingresource-specificservices,
reversedattribute,<ol>(orderedlist)element,337
788–789
RGBcolor,browser-safecolorand,779–781
pseudo-classselectors,CSS
RGBacolor,CSS3,623
activity-related,490–491
rightproperty,CSS,598
documenttree,492–496
rightmarginattribute,<body>(documentbody)
inlinestylesand,460
element,192
interfacestate,491–492
rootdirectory,Websites,786
language,497
:rootselector,CSS3,619
link-related,489–490
rotate(angle)function,rotatingdrawingsin
negation,497
HTML5,94
overviewof,487
rowsattribute
summaryof,498–500
<frameset>(framesetdefinition)element,256
pseudo-elementselectors,CSS,484–488
<textarea>(multilinetextinput)element,398
:beforeand:after,485–486
rows,<tr>(tablerow)element,411–414
:first-letterand:first-line,484–485
rowspanattribute
inlinestylesand,460
<td>(tabledata)element,395
listof,488
<tfoot>(tablefooter)element,404
Index 827
<rp>(Rubyparentheses)element,353–355 scrollbar-shadow-colorproperty,CSS3browser-
<rt>(Rubytext)element,355–357 specificfeatures,702
ruby-alignproperty,CSS3browser-specificfeatures, scrollbar-track-colorproperty,CSS3browser-specific
696–697 features,703
Rubyelements scrolldelayattribute,<marquee>(marqueedisplay)
<rp>(Rubyparentheses)element,353–355 element,317
<rt>(Rubytext)element,355–357 scrollingattribute
<ruby>(Rubyannotation)element,357–359 <frame>(windowregion)element,254
Rubymodule,CSS3,615 <iframe>(inlineframe)element,273
ruby-overhangproperty,CSS3browser-specific seamlessattribute,<iframe>(inlineframe)
features,697 element,273
ruby-positionproperty,CSS3browser-specific <section>(section)element,69–70,365–366
features,698 securityattribute
<ruby>(Rubyannotation)element,357–359 <frame>(windowregion)element,254
rulesattribute,<table>(table)element,388 <iframe>(inlineframe)element,273
rules,CSS,432–433 <select>(selectionlist)element,366–369
handlingmalformed,445–446 selectedattribute,<option>(optioninselectionlist)
overviewof,521,523–524 element,341
::selection,CSSpseudo-elementselectors,485–486
::selectionselector,CSS3,619
S selectors,CSS,533–538
activity-relatedpseudo-classes,490–491
<s>(strikethrough)element,359–360
sunits,CSS3,621 adjacentsiblingselectors,478
<samp>(sampletext)element,360–362 attributeselectors,479–483
sandboxattribute,<iframe>(inlineframe)element, classrules,473–476
111,273 contextualselection,476–478
scale(x,y)function,scalingdrawingsin directdescendentselector,478
HTML5,93–94 documenttreepseudo-classes,492–496
scan,CSS3mediaqueryvalues,628 elementselectors,471
schemeattribute,<meta>(meta-information) generalsiblingselectors,479
element,321 idselectors,471–473
scopeattribute interfacestatepseudo-classes,491–492
<td>(tabledata)element,395 languagepseudoclass,497
<tfoot>(tablefooter)element,405 link-relatedpseudo-classes,489–490
scopedattribute,<style>(styleinformation) listof,533–538
element,380 listofcore,480
<script>(scripting)element negationpseudoclass,497
elementsallowedwithinheadelement,25–26 overviewof,470,533
overviewof,362–365 pageandmediaselectors,538–539
scripts,<noscript>(noscriptsupportcontent) pseudo-classselectors,487,498–500
element,330–331 pseudo-elementselectors,484–488
scrollattribute selectorsmodule,CSS3,615
<body>(documentbody)element,192 semantics,inHTML5
<html>(HTMLdocument)element,268 indicatingtimeanddates(time),76
scrollamountattribute,<marquee>(marquee insertingfigures(fig),76–77
display)element,317 markingtextin(mark),75–76
scrollbar-3dlight-colorproperty,CSS3browser- forseparatingstylefromstructure,75
specificfeatures,698–699 specifyingnavigation(nav),77
scrollbar-arrow-colorproperty,CSS3browser- serveraddresses,inURLs,784–786
specificfeatures,699 SGML(StandardGeneralizedMarkupLanguage)
scrollbar-base-colorproperty,CSS3browser-specific contentexclusionandinclusion,804
features,699–700 HTMLdialectsdefinedusing,801
scrollbar-darkshadow-colorproperty,CSS3browser- keywords,805
specificfeatures,700–701 markuplanguagesdefinedwith,17
scrollbar-face-colorproperty,CSS3browser-specific overviewof,16
features,701 shadowproperties,canvaselement,203
scrollbar-highlight-colorproperty,CSS3browser- shapeattribute
specificfeatures,701–702 <a>(anchor)element,160
<area>(ImageMapArea)element,174
828 HTML & CSS: The Complete Reference
shapes,drawingandstylinginHTML5,85–88 standards
siblingselectors,CSS HTML/XHTML,14
adjacentsiblingselectors,478 vs.practices,46–47
generalsiblingselectors,479 variabilityand,518
sizeattribute webstandards,16–17
<basefont>(basefont)element,183 standardscompliancemode
<font>(fontdefinition)element,247 browserrenderingmodes,39
<hr>(horizontalrule)element,261 HTML5and,58
<input>(inputformcontrol)element,284 limitationsof,48
<select>(selectionlist)element,368 standbyattribute,<object>(embeddedobject)
<spacer>(extraspace)element,373 element,334
sizeproperty,CSS3browser-specificfeatures, startattribute
703–704 <ilayer>(inflowlayer)element,278
sizerelationships,CSS-HTML,608–611 <ol>(orderedlist)element,337
sizesattribute,<link>(linktoexternalfilesorset statepreservationmethods,canvaselement,200
relationships)element,310 stepattribute,<input>(inputformcontrol)
sizeskeyword,529 element,284
<smalltext>(smalltext)element,369–371 <strike>(strikeouttext)element,376–377
sound,<bgsound>(backgroundsound)element, strings,CSS,529–530
185–186 strokemethods,canvaselementand,85–86
<source>(source)element,371–373 <strong>(strongemphasis)element,28,377–379
<spacer>(extraspace)element,373–374 structure,separatingstructureandstylein
spacingmodifiers,characterentitiesfor,741 CSS,514–515
spanattribute styleattribute,coreelementattributes,137
<col>(tablecolumn)element,216 style,separatingstructureandstyleinCSS,514–515
<colgroup>(tablecolumngroup) stylesheets
element,218 alternative,464–465
<span>(textspan)element comparingstylesheetapproaches,453
overviewof,374–376,507–508 definingmediatypesfor,462–463
usingwithdocumenttreepseudoclasses, embedding,456–458
494–496 importing,458–459
specialcharacters.Seealsocharacterentities linkingto,452–456
encodinginURLs,790–791 usingforpresentation,516–517
entitiesusedfor,44 <style>(styleinformation)element
escapecodes,29 embeddingstylesheets,456–458
infilenames,787 embeddingstylesindocumenthead
inHTML5,60 element,526
speechmodule,CSS3,616 importingstylesheets,458–459,526–527
spellchecking(spellcheckattribute),inbrowsers, otherelementsallowedwithinhead
115–116 element,25–26
spellcheckattribute,commonHTML5element overviewof,379–381
attributesreference,146 <sub>(subscript)element,381–383
spinboxes,103 summaryattribute,<table>(table)element,388
srcattribute <sup>(superscript)element,383–385
<applet>(Javaapplet)element,171 symbols
<area>(ImageMapArea)element,178 characterentitiesforletter-likesymbols,744–745
<bgsound>(backgroundsound) characterentitiesformiscellaneous
element,186 symbols,748
<embed>(embeddedobject)element,241 characterentitiesfortechnicalsymbols,747
<frame>(windowregion)element,254 syntax,CSS,432–438,521,523–524
<iframe>(inlineframe)element,273 syntax,HTML5
<ilayer>(inflowlayer)element,275,278 loosesyntax,58–60
<input>(inputformcontrol)element,284 overviewof,55–58
<layer>(positionedlayer)element,297 syntax,traditionalHTML/XHTML,3–6
<script>(scripting)element,363
<source>(source)element,372
<video>(video)element,422 T
<xml>(XMLdataisland)element,424 tabindexattribute
StandardGeneralizedMarkupLanguage.SeeSGML commonelementattributesreference,142
(StandardGeneralizedMarkupLanguage) commonHTML5elementattributes
reference,146
Index 829
<input>(inputformcontrol)element,284–285 textattribute,<body>(documentbody)element,192
<select>(selectionlist)element,368–369 text-autospaceproperty,CSS3browser-specific
table-layoutproperty,CSS,598–599 features,704–705
<table>(table)element,385–389 text-decorationproperty,CSS,599–600
tables texteditors,forviewingmarkuplocally,8–10
<caption>(tablecaption)element,208–210 text-fill-colorproperty,CSS3browser-specific
<col>(tablecolumn)element,214–216 features,705
<table>(table)element,385–389 text-indentproperty,CSS,600
<tbody>(tablebody)element,389–392 text-justifyproperty,CSS3browser-specificfeatures,
<td>(tabledata)element,392–396 705–706
<tfoot>(tablefooter)element,399–402 text-kashida-spaceproperty,CSS3browser-specific
<th>(tableheader)element,402–405 features,706–707
<thead>(tableheader)element,405–408 text-overflowproperty,CSS3browser-specific
<tr>(tablerow)element,411–414 features,707
tags text-renderingproperty,CSS3browser-specific
notusinginvented,60 features,708
rulesregardingclosingtagsinHTML/ text-shadowproperty,CSS3browser-specific
XHTML,43 features,708–710
intraditionHTML/XHTML,4 text-stroke-colorproperty,CSS3browser-specific
targetattribute features,710–711
<a>(anchor)elementand,163 text-stroke-widthproperty,CSS3browser-specific
<area>(ImageMapArea)element,174 features,711
<base>(baseURL)element,182 text-transformproperty,CSS,600–601
<form>(formforuserinput)element,251–252 text-underline-positionproperty,CSS3browser-
<link>(linktoexternalfilesorset specificfeatures,711–712
relationships)element,311 <textarea>(multilinetextinput)element,396–399
:targetselector,CSS3,619 <tfoot>(tablefooter)element,399–402
<tbody>(tablebody)element,389–392 <th>(tableheader)element,402–405
<td>(tabledata)element,392–396 <thead>(tableheader)element,405–408
technicalsymbols,characterentitiesfor,747 <time>(time)element,76,408–410
televisionchannels,URLformof,794 titleattribute,coreelementattributes,138
telnet,789 <title>(documenttitle)element,7,23–24,410–411
templatelayoutmodule,CSS3,616 topattribute
text <ilayer>(inflowlayer)element,275
<blink>(blinkingtext)element,187–188 <layer>(positionedlayer)element,297
canvasAPImethodsandproperties,206 Top-Leveldomains,784–786
CSS3modules,616 topproperty,CSS,601–602
<del>(deletedtext)element,224–227 topmarginattribute,<body>(documentbody)
<ins>(insertedtext)element,287–289 element,192
keywords,529 <tr>(tablerow)element,411–414
<mark>(markedtext)element,75–76,314–315 transform-originproperty,CSS3browser-specific
markinginHTML5,75–76 features,715
<multicol>(multiplecolumntext)element, transformproperty,CSS3browser-specificfeatures,
325–326 712–714
<p>(paragraph)element,343–345 transform-styleproperty,CSS3browser-specific
<plaintext>(plaintext)element,347–348 features,716–717
<pre>(preformattedtext)element,348–350 transformationmethods,canvaselement,200
<rt>(Rubytext)element,355–357 transforms,inHTML5,95–96
<samp>(sampletext)element,360–362 transition-delayproperty,CSS3browser-specific
<smalltext>(smalltext)element,369–371 features,717–718
<span>(textspan)element,374–376,494–496, transition-durationproperty,CSS3browser-specific
507–508 features,718–719
<strike>(strikeouttext)element,376–377 transitionproperty,CSS3browser-specific
supportincanvaselement,98–100 features,717
<textarea>(multilinetextinput)element, transition-propertyproperty,CSS3browser-specific
396–399 features,719
<tt>(teletypetext)element,414–415 transition-timing-functionproperty,CSS3browser-
text-align-lastproperty,CSS3browser-specific specificfeatures,719–720
features,704 transitions,filterpropertyand,668–669
text-alignproperty,CSS,599 transitionsmodule,CSS3,616
830 HTML & CSS: The Complete Reference
translate(x,y)function,translatingdrawingsin otheraddressingschemes,798–799
HTML5,93–97 overviewof,783
transparentkeyword,CSS3colorunits,623 ports,790
truespeedattribute,<marquee>(marqueedisplay) protocols,788–789
element,317 querystrings,790
<tt>(teletypetext)element,414–415 relativeURLs,795–796
typeattribute serveraddresses,784–786
<a>(anchor)elementand,163 usernamesandpasswords,789
<area>(ImageMapArea)element,174 urnattribute,<a>(anchor)element,163
<button>(button)element,197 URNs(uniformresourcenames),799
<embed>(embeddedobject)element,241 usemapattribute
<input>(inputformcontrol)element,285 <ilayer>(inflowlayer)element,279
<li>(listitem)element,302 <input>(inputformcontrol)element,285
<link>(linktoexternalfilesorset <object>(embeddedobject)element,334
relationships)element,311 userinput,formsfor,249–252
<menu>(menulistorcommandmenu) userinterfacemodule,CSS3,616
element,319 userinterface(UI),CSS,777
<object>(embeddedobject)element,334 user-selectproperty,CSS3browser-specificfeatures,
<ol>(orderedlist)element,337 720–721
<param>(objectparameter)element,346 usernames,inURLs,789
<script>(scripting)element,364 users,CSSstyles,466–467
<source>(source)element,372 UTF-8characterset,25
<spacer>(extraspace)element,373
<style>(styleinformation)element,380
<ul>(unorderedlist)attributes,418 V
:validselector,CSS3,620
validation
U CSS,447–450
<u>(underline)element,415–417 ofdataentryonforms,104–105
UI(userinterface),CSS,777 ofDTDrules,37–39
<ul>(unorderedlist)element,28,417–419 ofwebsites,62
unclosedstructures,handlinginCSS,446 valignattribute
Unicode,748–749 <caption>(tablecaption)element,209
unicode-bidiproperty,CSS,602 <col>(tablecolumn)element,216
uniformresourcecharacteristics(URCs),799 <colgroup>(tablecolumngroup)element,218
UniformResourceIdentifiers.SeeURIs(Uniform <tbody>(tablebody)element,391
ResourceIdentifiers) <td>(tabledata)element,395
uniformresourcelocators.SeeURLs(uniform <tfoot>(tablefooter)element,401,405
resourcelocators) <thead>(tableheader)element,407
uniformresourcenames(URNs),799 <tr>(tablerow)element,414
unitsattribute,<embed>(embeddedobject) valueattribute
element,241 <button>(button)element,197
unitsofmeasurement,CSS,502–505,527–528 HTML5formfields,105–106
unorderedlists,28,417–419 <input>(inputformcontrol)element,285
URCs(uniformresourcecharacteristics),799 <li>(listitem)element,302
URIs(UniformResourceIdentifiers) <meter>(scalargauge)element,324
<!DOCTYPE>statementspecifying,18 <option>(optioninselectionlist)element,341
dataURIs,791–794 <param>(objectparameter)element,346
overviewof,799 valuesandunitsmodule,CSS3,616
URLs(uniformresourcelocators),783–799 values,CSS,502–505
<base>(baseURL)element,181–182 valuetypeattribute,<param>(objectparameter)
basicsoflocatingobjectsonInternet,783–784 element,346
challengesinuseof,796–798 <var>(variable)element,419–421
dataURIs,791–794 VectorMarkupLanguage(VML),82
directories,786–787 versionattribute,<html>(HTMLdocument)
emergingformsof,794 element,268
encoding,790–791 versionhistory
filenames,787–788 CSS,440–442,522
fragmentidentifiers,788 HTML/XHTML,14–16
Index 831
vertical-alignproperty,CSS,602–603 viewingwithWebserver,10–14
VGAdisplay,779 XMLstyleusingXHTML,49–52
vhunits,CSS3,621 Websitedirectories,786–787
<video>(video)element,78–80,421–423 weightattribute,<font>(fontdefinition)element,247
visibilityattribute WHATWG(WebHypertextApplicationTechnology
<ilayer>(inflowlayer)element,275 WorkingGroup),101
<layer>(positionedlayer)element,297 whitespacecharacters,HTML/XHTML
visibilityproperty,CSS,603–604 sensitivityto,42
vlinkattribute,<body>(documentbody)element,192 white-spaceproperty,CSS,512–513,604
vmunits,CSS3,621 widthattribute
VML(VectorMarkupLanguage),82 canvaselementand,83
volumeattribute,<bgsound>(backgroundsound) <col>(tablecolumn)element,216
element,186 <colgroup>(tablecolumngroup)element,218
vspaceattribute <hr>(horizontalrule)element,261
<embed>(embeddedobject)element,241 <ilayer>(inflowlayer)element,275
<input>(inputformcontrol)element,285 <input>(inputformcontrol)element,286
<object>(embeddedobject)element,334 widthattribute
<table>(table)element,388 <layer>(positionedlayer)element,297
vwunits,CSS3,621 <multicol>(multiplecolumntext)element,325
widthattribute
<pre>(preformattedtext)attributes,349
W <spacer>(extraspace)element,373
W3CMarkupValidationService,37–38,57 <table>(table)element,388
W3C(WorldWideWebConsortium) <td>(tabledata)element,395
addressingareaof,794 <tfoot>(tablefooter)element,405
coreevents,147 width,CSS3mediaqueryvalues,628
CSSvalidator,447 widthproperty,CSS,605–606
onlinereferencesforDTDs,807 windowsproperty,CSS,604–605
webstandards,16 word-breakproperty,CSS3browser-specific
XHTMLstandard,49 features,721
WAVfiles,audiosupportinHTML5,80 word-spacingproperty,CSS,606
<wbr>(wordbreak)element,423 word-wrapproperty,CSS3browser-specific
webapplications,supportinHTML5 features,722
commandelement,108 workbreak,<wbr>(wordbreak)element,423
contentediting(contenteditableattribute)in WorldWideWebConsortium.SeeW3C(WorldWide
browsers,114–115 WebConsortium)
detailselement,109–110 wrapattribute
draganddropfunctionality(draggable <pre>(preformattedtext)element,349
attribute)addedtobrowsers,112–114 <textarea>(multilinetextinput)element,
futureofframes,110–112 398–399
menuelementrepurposed,106–108 writing-modeproperty,CSS3browser-specific
meterandprogresselements,109 features,722–723
outputelement,110 WYSIWYG,47
overviewof,106
spellchecking(spellcheckattribute)in
browsers,115–116 X
Webbrowsers.Seebrowsers xcoordinates,canvaselementand,83
webfontsmodule,CSS3,616 (X)HTML.SeealsoHTML4;HTML5
WebHypertextApplicationTechnologyWorking applyingstylestodocuments,452
Group(WHATWG),101 <body>(documentbody)element,28–31
webmarkup browsersand,28–31
withHTML5,62–63 browsersignoringunknownelementsand
madness,62 attributes,44–45
XMLstyleusingXHTML,49–52 casesensitivity,41–42
Webpages characterentities,731–741
careinuseofnonstandardcoloron,771 commonelementattributesreference,139–142
CSSandeaseofdownload,518–519 commonHTML5elementattributesreference,
handlingpagelayout,47 142–146
viewingmarkuplocally,8–10 contentmodelsand,43
832 HTML & CSS: The Complete Reference
(X)HTML.SeealsoHTML4;HTML5(Continued) quotesusedwithattributes,44
coreattributesreference,135–138 standardsvs.practices,46–47
CSSand,506 structuresmovedtoCSS,443
CSSasalternativetopesentationalHTML, <title>(documenttitle)element,23–24
429–430 useofclosingtags,43
CSS-HTMLsizerelationships,608–611 validationofDTDrules,37–39
divandspanelements,507–508 versionhistory,14–16
<!DOCTYPE>statementusedtobegin whitespacecharactersand,42
documents,18–19 XMLwebpagemarkupstylewith
doctypeswitchandbrowserrendering XHTML,49–52
modes,39–41 xminsattribute,<html>(HTMLdocument)
documentstructure,20–23 element,268
DTDs(documenttypedefinitions),16–18 XML
embeddedstyles,456–458,526 keywords,805
entitiesusedforspecialcharacters,44 markuplanguagesdefinedwith,17
eventattributesreference,146–154 usingwithHTML5,60–61
flavorsof,133–135 webpagemarkupstyle,49–52
futureof,48 XHTMLdialectsdefinedusing,801
headelement,23 <xml>(XMLdataisland)element,424–425
helloworldexample,6–8 xml:spaceattribute
vs.HTMLinfuture,47–48 <pre>(preformattedtext)element,349
importedstyles,459–459,526–527 <script>(scripting)element,364
languageattributesreference,138 <style>(styleinformation)element,380
linkedstyles,452–456,524–526 <xmp>(example)element,425–426
logicalandphysicalmarkup,45–46
markupsyntaxin,3–6
<meta>tagsforspecifyingcontenttype, Y
characterset,andotherinformation,24–25 ycoordinates,canvaselementand,83
methodsforincludingCSSstylesin,524
minimizingunusedelements,43
mythsandmisconceptions,47–49
Z
z-indexattribute
nestingelements,43–44
<ilayer>(inflowlayer)element,275
otherelementsallowedwithinhead
<layer>(positionedlayer)element,297
element,25–26
z-indexproperty,CSS,607
overviewof,41
zoomproperty,CSS3browser-specificfeatures,724
presentational,429–430