mass media in nigerian democracy

Post on 11-Sep-2021

16 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

The HTML

PocketGuide

BruceHyslop

Ginormous knowledge, pocket-sized.

TheHTMLPocketGuideBruceHyslopPeachpitPress1249EighthStreetBerkeley,CA94710510/524-2178510/524-2221(fax)FindusontheWebat:www.peachpit.comToreporterrors,pleasesendanoteto:errata@peachpit.comPeachpitPressisadivisionofPearsonEducation.Copyright©2010byBruceHyslop

ExecutiveEditor:CliffordColbyEditor:KimWimpsettTechnicalEditor:MichaelBesterProductionEditor:TraceyCroomCompositor:DavidVanNessIndexer:JamesMinkinCoverDesign:PeachpitPressInteriorDesign:PeachpitPressNoticeofRightsAllrightsreserved.Nopartofthisbookmaybereproducedortransmittedinanyformbyanymeans,electronic,mechanical,photocopying,recording,orotherwise,withoutthepriorwrittenpermissionofthepublisher.Forinformationongettingpermissionforreprintsandexcerpts,contactpermissions@peachpit.com.NoticeofLiabilityTheinformationinthisbookisdistributedonan“AsIs”basiswithoutwarranty.Whileeveryprecautionhasbeentakeninthepreparationofthebook,neithertheauthornorPeachpitshallhaveanyliabilitytoanypersonorentitywithrespecttoanylossordamagecausedorallegedtobecauseddirectlyorindirectlybytheinstructionscon-tainedinthisbookorbythecomputersoftwareandhardwareproductsdescribedinit.TrademarksManyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirprod-uctsareclaimedastrademarks.Wherethosedesignationsappearinthisbook,andPeachpitwasawareofatrademarkclaim,thedesignationsappearasrequestedbytheownerofthetrademark.Allotherproductnamesandservicesidentiiedthroughoutthisbookareusedineditorialfashiononlyandforthebeneitofsuchcompanieswithnointentionofinfringementofthetrademark.Nosuchuse,ortheuseofanytradename,isintendedtoconveyendorsementorotherafiliationwiththisbook.ISBN-13: 978-0-321-69974-9ISBN-10: 0-321-69974-2987654321PrintedandboundintheUnitedStatesofAmerica

Contents

Introduction. .................................................................................................................vii

Part1: HTMLBasics . .........................................................................................1Chapter1: HTMLBasics. .........................................................................................3

Part2: HTMLElementsandGuidance ..................................25Chapter2: PrimaryStructureandSections . ........................................27

Chapter3: DocumentHead...................................... 43

Chapter4: Lists . ........................................................................................................69

Chapter5: Text . .........................................................................................................93

Chapter6: EmbeddedContent(ImagesandObjects) ...............141

Chapter7: Forms .....................................................................................................157

Chapter8: TabularData . ..................................................................................185

Chapter9: Scripting ...........................................................................................203

TheHTMLPocketGuidevi

Part3: HTML5ElementsandGuidance . ......................... 221Chapter11: PrimaryStructureandSections . ...................................223

Chapter12: Text . ...................................................................................................245

Chapter13: EmbeddedContent(Images,Media,andMore). ..............................................263

Chapter14: Forms. ............................................................................................... 277

Chapter15: InteractiveElements . ............................................................285

Appendix:AlphabeticalHTMLElementsPageListing . ........... 294

Index . ........................................................................................................................... 296

Part1

Thispartofthebookcontainsonechapter,“HTMLBasics,”whichprovidesanoverviewofHTML5,discussestheversionsofHTML,recommendssomebestpractices,listscommonattributes,andmore.

HTMLBasics

Part1Contents

Chapter1: HTMLBasics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

ThischapterprovidesfoundationalinformationforParts2and3ofthebook.(Ifyou’vebeenaroundHTMLforawhile,muchofitwillbeoldhat.)

Icoverafewstandards-basedbestpractices,basicHTMLdocumentstruc-tureforalllavorsofthelanguage(includingHTML5),differencesamongtheversions,DOCTYPEs,basicdatatypes,commonattributes,anoteaboutobsoleteanddeprecateditems,andmore.

note Iencourageallreaderstoreviewthe“HowAttributesAreNotedinThisBook”box.

Let’sbeginwithanoverviewofHTML5incasethisversionofHTMLisnewtoyou.

HTMLBasics

1

Part1:HTMLBasics4

AnHTML5OverviewHTML5isanaturalevolutionofHTML4thataccountsfortherapidgrowthofmedia,richonlineexperiences,andsophisticatedWebapplica-tiondevelopmentsinceHTML4.01becameaspeciicationattheendof1999.

Atthetimeofthiswriting,HTML5isstillunderdevelopmentandsubjecttochange.However,itisonstablefooting,andbrowsershavealreadyaddedmany—andcontinuetoaddmore—ofitsfeatures.(Pleaseseehttp://www.htmlfiver.com/html5-browser-support/formoreinformation.)

ThisbookincludesinformationfromtheHTML5editor’sWorkingDraftdatedApril26,2010.HerearesomekeylinkssoyoucankeepupwithHTML5’sprogress:n W3CWorkingDraft:http://www.w3.org/TR/html5/.n Latesteditor’sWorkingDraft(typicallymorerecent):http://www.

whatwg.org/specs/web-apps/current-work/multipage/.n HTML,TheMarkupLanguage:http://www.w3.org/TR/html-markup/.

ThisbrielysummarizeseachHTML5elementandattribute.n HTML5differencesfromHTML4:http://www.w3.org/TR/html5-diff/.

SnapshotViewHTML5breaksdownlikethis:n Newelementsandattributes:HTML5inheritsnearlyeveryelement

fromHTML4(pleaseseePart2ofthebook).Italsoincludesnearly30newelements,allofwhichIdetailinPart3ofthebook.Highlightsincludeaudio,video,canvas,datalist,andawholehostofnew

Part1:HTMLBasics Chapter1:HTMLBasics 5

semanticssuchasarticle,nav,header,andfooter.AsdiscussedinChapter7,HTML5alsoincludesbigadvancementsintheformsdepart-mentwithnewattributesandinputtypesthatmakerichformseasiertodevelop,moreaccessible,andmoreconsistentforusersandthatcanvalidateinthebrowserwithoutJavaScript.

n Newfeatures:Featuresisabitofabroadterm,butitmostlyspeakstonewfunctionalityinHTML5andrelatedin-progressspecsthatfallunderHTML5froma“marketing”sense,ifnotliterallypartofHTML5.(Asidefromtheoccasionalcoverage,thisbookleavesin-depthdiscus-sionsofthenewfeaturesforanotherday.)Someofthesefeaturesare:– Canvas(viatheaforementionedcanvaselement)– Cross-documentmessaging– Draganddrop– EmbeddingofScalableVectorGraphics(SVG)directlyinHTML– Geolocation– History(browser)management– Microdata– Nativemediaplaybackscripting(viatheaforementionedaudioand

videoelements)– OflineWebApplications– WebStorage(akaDOMstorage)– WebWorkers

CodeFormattingSyntax:ARecommendationHTML5isextremelyforgivingconcerninghowyoumaystructurethecode.Youmayincludeoromitclosingtags,useuppercaseorlowercaseelementsandattributes,quoteornotquoteattributevalues,andmore.Thatlexibilityhasbeenthesourceofsomecontroversy,butitremains.

Part1:HTMLBasics6

Havingsaidthat,myrecommendationistocodeHTML5ineitheroneofthesetwoways:n Usealllowercaseforcode,double-quoteallattributevalues,useattri-

buteminimization,alwaysuseanelement’sendtagifithasone,anddon’tterminateelementsthatdon’thaveanendtag(thatis,emptyorvoidelements).

n

Or,useXHTMLsyntax,whichisexactlythesameasthepreviousbullet,exceptyoudon'tuseattributeminimizationanddoterminateemptyelements.Yes,HTML5acceptsXHTMLsyntax.

Allthecodeexamplesinthisbookconformtooneofthese(mostlythesecond)soyoucangetasenseofhowtoreplicatethemifyou’renewtocoding.(Pleasesee"DifferencesBetweenHTML4andXHTML"laterinthischapterforexplanationsofattributeminimizationandterminatingemptyelements.TheirdescriptionsarerelevanttoHTML5usage,too.)

note WhydoIrecommendfollowingoneoftheseformats?Ielaborateabitonthisathttp://www.htmlfiver.com/extras/html5-code-syntax/,but

theshortansweristhey’reinlinewiththewayseasoneddevelopersanddesignershavecodedforthebetterpartofthepastdecadeasaresultoftheWebstandardsmovement.So,thesesyntaxformatswillbecomedefactoHTML5codingstandards,inmyview,iftheyaren’talready.

note UnlikeHTML5,XHTML5syntaxdoeshavefirmrules,justlikeXHTML1.However,unlikeXHTML1,anXHTML5pagemustbeservedwithan

XMLMIMEtype,andifthereisasingleinvalidportionofcode,thepagewon’trender.Forthisreason,HTML5willhavewidespreaduse,whileXHTML5willlikelyfindalimitedaudience.

HowtoStyleNewElementsAlthoughit'struethatyoucan'tuseHTML5featuressuchastheaddi-tionalinputtypesandthedetailselementunlessabrowsersupportstheirbehavior,youcanusethenewsemanticelementssuchasarticle,aside,

Part1:HTMLBasics Chapter1:HTMLBasics 7

navandmostoftheothersrightaway.Plus,withjustalittleextrahelp,mostbrowsersallowyoutostylethemevenwhentheydon'tyetsupportthemnatively.I'vedetailedthethreeeasystepsrequiredtostyletheseelementsathttp://www.htmliver.com/extras/style-html5-elements/.

So,that’sabird’seyeviewofHTML5.PleasedigintoParts2and3tolearnthenitty-grittyconcerningHTML5elementusage,andvisithttp://www.htmlfiver.com/using-html5-today/tolearnmoreaboutwhatyoucanuseinHTML5today.

AFewBestPracticesIcouldeasilydedicatechapterstoWebstandardsandbestpracticesbuthavesynthesizedthemintothesekeypoints:n AlwaysuseaDOCTYPE:ADOCTYPEtellsthebrowserwhatmodein

whichtorender,improvesinteroperability,andmakesyourlifeaheckofaloteasierwhendevelopinganddebuggingyourcode.Pleaseseethe“DOCTYPEs”sectionformoreinformation.

n Separatecontent,presentation,andbehavior:Alongwiththenextitem,thisisoneofthekeytenetsofWebstandards.Separationofcontent(HTML),presentation(CSS),andbehavior(JavaScript)meansnotinterminglingthemintheHTML.Usuallyit’sbesttoplaceyourCSSandJavaScriptinseparateilesandloadthemintoyourpages.Amongotherbeneits,thismakesdevelopment,reusability,andmaintenancefareasier.(MakeoneCSSorJavaScriptupdate,anditcanspillacrossyourwholesite.)

n Usepropersemantics:ThisreferstowrappingyourcontentwiththeHTMLelement(s)thatbestrelectsthenatureofthecontent.Forexam-ple,puteachparagraphoftextinaparagraphelement(<p></p>).Placealistofitemsinadeinitionlist(<dl></dl>),orderedlist(<ol></ol>),or

Part1:HTMLBasics8

unorderedlist(<ul></ul>)asismostappropriate;it’sthesameprincipleforothertypesofcontentandtheirrelatedelements.Thisimprovesaccessibility,improvessearchengineoptimization(SEO),tendstomakepageslighter,andusuallymakesstylingwithCSSeasieraswell.

n Validateyourpages:HTMLvalidatorscheckyourcodeforsyntaxerrors.Byvalidatingyourpages,you’llbesurethey’reincompliancewiththeirDOCTYPE.Thishelpsyoucreatemoreconsistentcodeandtrackdowntheoccasionalnettlesomebug.ValidateyourX/HTMLpagesathttp://validator.w3.org/andyourHTML5pagesthereorathttp://html5.validator.nu/toreceivethekindofpersonalvalidationandsatis-factionthatonlyanautomatedprogramcanprovide!

BasicHTMLDocumentStructureNomatterwhatlavorofHTMLyou’rewriting—HTML4,XHTML1,orHTML5—thebasicstructureremainsthesame.Onlyafewofthedetailsaredifferent.Let’stakealook.

Example1(atypicalXHTML1Strictpage):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"

lang="en">

<head>

<title>Your document title</title>

<meta http-equiv="Content-type" content="text/html;

charset=utf-8" />

</head>

<body>

. . . [your page content] . . .

Part1:HTMLBasics Chapter1:HTMLBasics 9

</body>

</html>

I’vehighlightedtheportionsthatchangefromoneversionofthelanguagetoanother.Theyareasfollows:n TheDOCTYPE:IncludeaDOCTYPEineverypage.Seethe“DOCTYPEs”

sectioninthischapterformoreinformation,includingalistofavail-ableDOCTYPEs.

n Thehtmlelement:Thisissimply<htmllang="en">forHTML4andHTML5documents,wherelangiscustomizedaccordinglytoitthelanguageofyourpagecontent.(Pleasesee“LanguageCodes”inthischapter.)Englishisspeciiedintheexample.

n Themetaelementthatincludesthecharacterencoding:AnHTML4documentdoesn’thavethetrailingslash(/>).AnHTML5documentmayhavethetrailingslashifyou’dlikebutisotherwisesimpliiedto<metacharset="utf-8">,assumingtheencodingisUTF-8.It’salsopreferabletoputitbeforethetitle.(SeethemetaelementinChapter3.)

Forcomparison,Example2showsatypicalHTML5document.

Example2:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8" />

<title>Your document title</title>

</head>

<body>

. . . [your page content] . . .

</body>

</html>

Part1:HTMLBasics10

DifferencesBetweenHTML4andXHTMLInadditiontothebasicstructuraldifferencesjustdiscussed,thereareanumberofotherdifferencesbetweenHTML4andXHTML1(they’retrueofXHTML5,too).They’realleasytogetahandleon;thissectionoftheXHTML1specsummarizesthemnicely:http://www.w3.org/TR/xhtml1/#diffs.

Idowanttocallouttwoofthekeydifferences,though,sinceyou’llcomeacrossthemfrequentlyinParts2and3ofthebook:n Terminateemptyelements:Someelementsareclassiiedasempty

elements(alsocalledvoid).Anemptyelementisonethatcan’tcontaincontent,soitdoesn’thaveanendtag.Examplesare<img>and<br>.InXHTML,emptyelementsmustbeself-closing,whichissimplyamatterofendingthemwith/>,asin<img/>and<br/>.MostofmycodesamplesthroughoutthebookuseXHTMLsyntax(whichisalsovalidinHTML5),butyouwillseenotessuchas“<area>or<area/>”inthesummaryofrelevantelementsasareminderofthetwoformats.

n Anattributemusthaveavalue(evenBooleans):Someattributesdon’thaveavalue,liketheselectedattributeon<optionselected></option>.Thissyntaxisreferredtoasattributeminimization.MostoftheseareBooleanattributes,meaningthatiftheyarepresent,theconditionistrue(theoptionisselected),andiftheyaren’t,itisfalse.XHTMLdocumentsdon’tallowattributeminimization,soyousimplyassignthenameoftheattributeastheattributevalue,makingtheexamplebecome<optionselected="selected"></option>.(NotethatHTML5allowseitherselected,selected="",orselected="selected",allofwhichbrowsersshouldtreatthesameway.)

tip Pleasealsosee“CodeFormattingSyntax:ARecommendation”earlierinthischapter.

Part1:HTMLBasics Chapter1:HTMLBasics 11

DifferencesBetweenHTML4andHTML5SomeelementsaredifferentwhenusedinHTML4orXHTML1docu-mentsversusinHTML5.IdetailthesedifferencesthroughoutPart2ofthebook.PleaseseetheintroductiontoPart2regardinghowItypicallyconveythatinformation.IalsorecommendyourefertothehandyW3Csummaryathttp://www.w3.org/TR/html5-diff/.

tip Pleasealsosee“CodeFormattingSyntax:ARecommendation”earlierinthischapter.

DOCTYPEsHTMLcomesinafewlavors,asdictatedbyapage’sDOCTYPE(always

includeoneinyourdocuments!).ThissectionincludesareferenceoftheavailableDOCTYPESandabriefsummaryofwhateachallows.

Standards-savvydevelopersanddesignershavetendedtouseXHTML1StrictorTransitionaland,insomecases,HTML4.01Strict.However,youcanusetheHTML5DOCTYPEtoday,andyourpageswillworkasexpected(thatdoesn’tmeanallofHTML5’snewelementswillworksincethatdependsonthebrowser,butyoucancodeyourpagesasyounormallywouldotherwise).

HTML4.01Strict<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"

"http://www.w3.org/TR/html4/strict.dtd">

Deprecatedelementsandattributes,frames,andthetargetattributeonlinksarenotallowed.

Part1:HTMLBasics12

HTML4.01Transitional(akaLoose)<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

Deprecatedelementsandattributesareallowed.

HTML4.01Frameset<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"

"http://www.w3.org/TR/html4/frameset.dtd">

AvariantofHTML4.01Transitionalthatisusedforframesonly.

HTML5andXHTML5<!DOCTYPE html>

UsedforallHTML5documents.

XHTML1Strict<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

YoumustfollowXHTMLsyntaxrules;plus,deprecatedelementsandattributes,frames,andthetargetattributeonlinksarenotallowed.

XHTML1Transitional<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

YoumustfollowXHTMLsyntaxrules.Deprecatedelementsandattri-butesareallowed.

Part1:HTMLBasics Chapter1:HTMLBasics 13

XHTML1Frameset<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

AvariantofXHTML1Transitionalusedforframesonly.

XHTML1.1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

EqualtoXHTML1Strictbutallowsyoutoincludeadditionalmodules.

Inlinevs.Block-levelElementsAblock-levelelementmaycontainmostotherblock-levelelementsandallinlineelements.Inlineelementsmostlydescribebriefstringsoftextandmayincludeotherinlineelements.Forinstance,thepelementisablock-levelelement,andtheemelementisinline:<p>Thisisa<em>great</em>example!</p>.Block-levelelementsoccupyatleastonefulllinewhenrendering,whileinlineelementstakeuponlyasmuchspaceastheircontentrequires.ThisdefaultbehaviormaybeoverriddenwiththeCSSdisplayproperty.

HTML5doesn’tusethetermsblock-levelandinline,thoughitselementsdorenderbydefaultinoneofthetwoways.Pleasesee“Contentmodels”athttp://www.w3.org/TR/html5/dom.html#content-modelsfordetails.

HTMLCommentsHTMLcommentsdon'trenderinthepage,justinthecode.Theymuststartwith<!--andendwith -->andtheymaycoverseverallinesofcode.Irecommendcommentingatleastthebeginningandendofmajorsectionsofyourpagestomakeyourcodeeasiertoread.

Part1:HTMLBasics14

AttributesAnHTMLelement’sattributedeinesapropertyofthatelement.Theyareoptionalinmostcases,sousethemonlyasneeded.Forexample,hereyouseeboththehrefandtitleattributesappliedtoahyperlink:

<p>They saw a <a href="ducks.html" title="Essay and

photos">family of ducks</a> by the stream.</p>

Youmayplaceattributesinanyorderyoulike,butIencourageyoutobeconsistentinyourapproachinordertomakeyourcodeeasiertoreadandmanage.

I’lldetailcommonattributesinjustabit,butirstpleaseindulgemeasIexplainhowattributesarenotedinthisbook.

HowAttributesAreNotedinThisBook

ManyHTMLelementssharethesameattributes.TheX/HTMLspeci-icationsusethetermsCore,I18n,andEventstocategorizethese.(Coreconsistsofmostlyunrelatedcommonattributes,I18nconsistsoftheinternationalization-relatedattributes,andEventsaretheevent-relatedattributes.)Meanwhile,HTML5usesonetermonly,Global,whichrepresentsalltheCore,I18n,andEventsattributesfromX/HTMLplusabunchjustforHTML5.(Iexplaineachoftheseattributegroupingsindetailafterthisbox.)

IusethesetermsthroughoutParts2and3ofthebook.Namely,thebeginningofeachHTMLelemententryincludesalistofitsattri-butesinthisformat:

Attributes Core,I18n,Events,accesskey,alt,href,nohref*,shape,HTML5Only:Global,hreflang,media,ping

(continuesonnextpage)

Part1:HTMLBasics Chapter1:HTMLBasics 15

HowAttributesAreNotedinThisBook(continued)

An“AttributesinDetail”sectionthatdetailstheirusageappearstowardtheendofanHTMLelement’sentry.

So,inthisexample,theelementsupportsalltheCore,I18n,Events,and(inHTML5only)Globalattributes.Inaddition,theattributeslistedbyname(accesskey,alt,href,nohref*,shape,hreflang,media,andping)arecustomattributesthattheelementsupports,depend-ingontheversionofHTML.Incaseit’snotclear,allattributespriortoHTML5OnlyapplytoHTML4,XHTML1,andHTML5(exceptwhennotedotherwisein“AttributesinDetail”),andallattributesafterHTML5OnlyapplytoHTML5only,asyouwouldexpect.

Ifanattributehasanasterisk,asnohrefdoesintheexample,thenthatindicatesanexceptionisnotedin“AttributesinDetail.”Forinstance,itmightsaythis:nohref:*ObsoleteinHTML5.

note The

accesskeyandtabindexattributesaresharedbyahandfulofelementsinX/HTMLthougharenotpartoftheCore,I18n,orEvents

attributegroupings.TheyarepartofHTML5’sGlobalattributes,though,sopleasefindtheirdescriptionsinthatsection.ThesamedefinitionsapplytotheiruseinX/HTMLdocuments.

OK,let’slookattheattributegroupings.

CoreTheseattributesarebothpartofX/HTML’sCoregroupandHTML5’sGlobalgroupofcommonattributes:n class="classnames":Usethistoassignoneormorespace-separated

classnamestoanelementforstylingorscriptingpurposes.Youmay

Part1:HTMLBasics16

deineyourownclassnames,suchas<pclass="newssynopsis">... </p>.Aclassmayberepeatedinapage,whetherit’stothesameordifferentelementtypes.

n id="uniqueidentifier":ThisassignsauniqueIDforfunctional,styling,andscriptingpurposes.Itmaynotberepeatedwithinthesamepage.

n style="inlinestylesheet":ThisassignsinlineCSStoanelement.Avoidusingthiswheneverpossiblesinceitisabestpracticenottomixyourpresentation(CSS)andcontent(HTML).

n title="descriptivetext":Thisprovidesashortdescriptionthatdoesn’tappearon-screen,thoughmostbrowsersrenderitasatooltipwhenthemouseorotherpointerishoveredontheelement.Screenreadersmayannouncethetextaswell.

I18n(Internationalization)Thesetwoattributesallowyoutospecifythelanguageanddirectionoftextinyourdocument.n dir="ltr|rtl":Thisspeciiesthebasedirectionalityoftheelement’s

textcontentandtables.Typically,youdon’tneedtosetitanywhereonyourpagesincethedefaultisltr(left-to-right).However,ifyourcontent’sbasedirectionalityisright-to-left,suchasinHebrew,set<html...dir="rtl"lang="he">(sansellipses)sotherestofthepageinheritsthesetting.(Note:Youshouldspecifylang,too,asshown,butuseragentsdon’tdeterminetextdirectionalityfromthat).Ifyouareinterminglingleft-to-rightandright-to-leftcontent,suchasEnglishandArabic,respectively,setdirandlangontheelement(aparagraph,forinstance)thatcontainsthecontentthatdeviatesfromthedirectionalityofthepageatlarge.PleasealsoseethebdoelementinChapter5forarelateddiscussion.

n lang="languagecode":Thisspeciiesthelanguageoftheelement’scontent.Besuretoalwayssetitonthehtmlelement;elementson

Part1:HTMLBasics Chapter1:HTMLBasics 17

therestofthepageinheritthatvalueunlessyouoverrideitatamoregranularlevel.Forinstance,set<html...lang="en">(sansellipses)onadocumentinEnglish.IfaparagraphwithinthatsamepageisinFrench,set<plang="fr">...</p>tooverrideit.Pleaseseethe“LanguageCodes”sectionofthischaptertoaccessmorecodes.

EventsThesecommoneventattributesallowyoutoassignJavaScripttoarangeofpagebehaviors.Asabestpractice,don’tapplytheseattributestoyourHTMLinlineasyoudowithotherattributes.Meaning,avoidthis:<ahref="some-page.html"onclick="someFunction();returnfalse">linktext</a>.Instead,useJavaScripttoapplythemunobtru-sively;thisisinkeepingwiththeseparationofcontentandbehaviorbestpracticedescribedin“AFewBestPractices”earlierinthischapter.SearchonlineforunobtrusiveJavaScripttolearnmoreandseecodeexamples.n onclick="script":Eventireswhentheuserclicksamousebuttonor

hitsReturnorEnteronthekeyboard.(Mousemeanspointingdeviceforeacheventinthislist.)

n ondblclick="script":Eventireswhentheuserdouble-clicksamousebutton.

n onmousedown="script":Eventireswhentheuserholdsthemousebuttondown.Thisistheoppositeofonmouseup.

n onmouseup="script":Eventireswhentheuserreleasesthemousebutton.Thisistheoppositeofonmousedown.

n onmouseover="script":Eventireswhentheusermovesthemousecursorontopofanelement.Thisistheoppositeofonmouseout.

n onmousemove="script":Eventireswhentheusermovesthemousecursor.

Part1:HTMLBasics18

n onmouseout="script":Eventireswhentheusermovesthemousecursorawayfromanitem.Thisistheoppositeofonmouseover.

n onkeypress="script":Eventireswhentheuserpressesandreleasesakey.

n onkeydown="script":Eventireswhentheuserpressesdownonakey.Thisistheoppositeofonkeyup.

n onkeyup="script":Eventireswhentheuserreleasesakey.Thisistheoppositeofonkeydown.

Global(HTML5)Asdiscussedinthe“HowAttributesAreNotedinThisBook”box,theattributesthatHTML5classiiesasGlobalincludeX/HTML’sCore,I18n,andEvents,plustheuniqueoneslistedhere.TheGlobalattributesmaybeappliedtonearlyeveryelementinHTML5.n accesskey="keyboardcharacter":(Note:SomeX/HTMLelements

supporttabindex,asnotedintheirentriesinPart2ofthebook.)Thisattributeassignsacharacterasashortcuttosettingfocusonanelement,asin<inputtype="text"name="search"accesskey="4"/>.Browsersandplatformsvaryonwhatkeyorkeysyoumustpressincombinationwiththeaccesskeytoactivateit.WhilepressingCtrlplustheaccesskeyonaMactypicallyactivatestheshortcut,onaWindowscomputerit’sAltforInternetExplorerandChrome,Shift+AltforFirefox,andShift+EscforOpera.Behaviorvariesperelementandbrowser.Seehttp://www.webaim.org/techniques/keyboard/accesskey.phpformoreinformation,includingreasonswhyithasn’tgainedwideradoption.

n class:Pleaseseethedescriptioninthe“Core”section.n contenteditable="true|false":HTML5allowsuserstoeditan

element’scontentiftheelementhascontenteditable="true".Ifcontenteditableisnotset,anelementinheritsthevaluefromits

Part1:HTMLBasics Chapter1:HTMLBasics 19

nearestparent.Asettingoffalsepreventsanelementfrombeingedited.Thedefaultstateistoinherit.Formoreinformation,seehttp://blog.whatwg.org/the-road-to-html-5-contenteditableandademoathttp://html5demos.com/contenteditable.

n contextmenu="idofmenu":Thisassignstheelement’scontextmenuwhenitsvaluematchestheidofamenuelement(pleaseseeChapter15).

n dir:Pleaseseethedescriptioninthe“I18n”section.n draggable="true|false":HTML5providesadraganddropAPI.Set

draggable="true"onanelementtomakeitdraggable(falsedoestheopposite).Ifdraggableisundeined,thedefaultstateisauto,whichdeferstothedefaultstateoftheuseragent.

n hidden:Whenpresent,thisBooleanattribute“indicatesthattheelementisnotyet,orisnolonger,relevant,”anduseragentsshouldn’tshowthecontent.Itaffectspresentationonly;scriptsandformcontrolsinhiddencontentstillwork.

n id:Pleaseseethedescriptioninthe“Core”section.n itemid,itemprop,itemref,itemscope,anditemtype:Theseattributes

arerelatedtodeiningmicrodata.Pleaseseehttp://dev.w3.org/html5/md/.n lang:Pleaseseethedescriptioninthe“I18n”section.n spellcheck="true|false":Setspellcheck="true"onanelement

whosecontentshouldhaveitsspellingandgrammarchecked(falsedoestheopposite).HTML5suggeststhedefaultstatecouldbefortheelementtoinheritthesettingofitsparentbutdoesn’tdeineitoutright.Italsodoesn’tdeinehowauseragentshouldperformspell-andgrammar-checking.

n style:Pleaseseethedescriptioninthe“Core”section.

Part1:HTMLBasics20

n tabindex="number":(Note:SomeX/HTMLelementssupporttabindex,asnotedintheirentriesinPart2ofthebook.)SomeusersprefertonavigateapagewiththeTabkey(andShift+Tabtomovebackward).EachtimeyoupressTabinasupportingbrowser,thefocusshiftstothenextaelement(ahyperlinkoranchor)orformcontrolaccordingtotheorderinwhichitappearsintheHTMLsource,notnecessarilytheon-screenorder(becauseofCSSmovingit).Youmaychangetheorderbyassigningatabindextoanelement,suchas<ahref="trees.html"tabindex="5">Trees</a>.Elementswithtabindexgainpriority,sotheyaretabbedtoirst(1isthehigh-estpriority)beforeanyotherelements,regardlessofsourceorder.Thenumbersmaybeinanyorderorincrementyou’dlike.TheHTMLsourceorderdeterminesthepriorityofelementswiththesamenumber.tabindex="0"hasspecialmeaning;itmakesanelementfocusablebykeyboardbutplacesitinthenormaldocumenttabbingsequence.Also,tabindexonadisabledelementhasnoeffectsinceitcan’tgainfocus.InHTML5,anynegativenumbermeansyoucan’ttabtotheelement,butyoucansetfocustoitwithJavaScriptviafocus().ManybrowsersapplythissamebehaviortoX/HTMLdocumentswhentabindex="-1".Istronglyrecommendyouavoidusingtabindexinmostcasesandmakeyournaturaltabbingorderlogicalforusers.

n title:Pleaseseethedescriptioninthe“Core”section.

DataAttributesDataattributesareanotherofHTML5’sparticularlyusefuladditions—they’recustomattributesthatyoumayapplytoanyelementtostoredatainyourHTML.Theyarehelpfulincaseswhereanotherattributeorelementisn’tappropriateforcontainingtheinformation.Youmaynameyourattributesasyouwishaslongastheybeginwithdata-.Adataattribute'svaluedoesn’tappearinthepage;instead,youleverageitwithJavaScript.Forexample,imagineyourpageincludesalistofproducts

Part1:HTMLBasics Chapter1:HTMLBasics 21

formalesandfemalesofallages.Byincludingdataattributes,youcouldwriteascriptthatsortsoriltersthelistbasedontheuser’schoices.

Example:

<li data-gender=”female” data-agerange=”55-67”>Product Name</

➥ li>

Youmayaddasmanydataattributesasnecessary.Forinstance,theexamplecouldincludeanotheronecalleddata-pricerange.Bestofall,youcanusedataattributestodayacrossbrowsersaslongasyourpagehasanHTML5DOCTYPE.Pleaseseehttp://www.htmlfiver.com/data-attri-butes/foranexampleofhowtoaccessyourcustomdatawithJavaScript.

EventsThatArePartofGlobalTheHTML5GlobalattributesetincludestheX/HTMLEventsattri-butes.Theyareonclick,ondblclick,onkeydown,onkeypress,onkeyup,onmousedown,onmousemove,onmouseout,onmouseover,andonmouseup.Pleaseseethe“Events”sectioninthischapterfordetails.HTML5alsoincludesthefollowingevent-relatedattributesaspartofGlobal:

onabort,onblur*,oncanplay,oncanplaythrough,onchange,oncontextmenu,ondrag,ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,onerror*,onfocus*,onformchange,onforminput,oninput,oninvalid,onload*,onloadeddata,onloadedmetadata,onloadstart,onmousewheel,onpause,onplay,onplaying,onprogress,onratechange,onreadystatechange,onscroll,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,onsuspend,ontimeupdate,onvolumechange,andonwaiting

Thosewithanasteriskhaveadifferentmeaningwhenappliedtothebodyelement.

Part1:HTMLBasics22

PleaseseetheinputelementinChapter7fordetailsaboutonblurandonfocus.Descriptionsfortheothershavebeenleftoutforspaceconsider-ationsandbecausemanygobeyondthescopeofthisbook(forinstance,manyrelatetoscriptingtheaudioandvideoelements).Youcanlearnmoreathttp://www.w3.org/TR/html5/dom.html#global-attributes.

BasicDataTypesThissectiondescribesbasicHTMLdatatypesreferencedbyelementsinParts2and3.Pleasealsoseehttp://www.w3.org/TR/html4/types.html.

CDATA,andidandnameAttributeValuesThedescriptionsofmanyattributesindicatethatCDATAistheacceptedvalue,asinname="cdata"forforminputs.CDATA,intheseinstances,isafancynameforatextstringthatacceptsavarietyofcharacters.Speciically,forid,name,andotherattributesthataccepttext,theirvalue“mustbeginwithaletter([A–Za–z])andmaybefollowedbyanynumberofletters,digits([0-9]),hyphens(‘-’),underscores(‘_’),colons(‘:’),andperiods(‘.’).”

CharacterEncodingThecharsetattributedeinesthecharacterencoding,suchaswhatyoushoulddeineintheheadelementofeachdocument(see“BasicHTMLDocumentStructure”earlierinthischapterandthemetaelemententryinChapter3).Mostcommonly,charsetissettoutf-8.TheW3Cprovidesathoroughdiscussiononthetopicathttp://www.w3.org/International/tutorials/tutorial-char-enc/.

ContentTypes(MIMETypes)Acontenttypespeciiesthenatureofalinkedorembeddedresource,suchasassignedtothetypeattributeofthelinkelementthatloadsa

Part1:HTMLBasics Chapter1:HTMLBasics 23

stylesheet.Amongthecommoncontenttypesareimage/gif,image/png,image/svg+xml,text/css,text/javascript,text/html,andvideo/mpeg.AcompletelistofregisteredMIMEtypesisavailableathttp://www.w3.org/TR/html4/references.html#ref-MIMETYPES.

LanguageCodesAlanguagecodeisassignedtothelangattributetodescribethelanguageofanelement’scontent,asinlang="dl"forDutch.Pleaseseethe“I18n”sectionofthischapterformoredetailsaboutlang.Languagecodesmayhaveasubcode,too,asincn-zh.Pleaseseehttp://www.anglistikguide.de/info/tools/languagecode.htmlforalistofcodes.

LinkTypesThedeinedX/HTMLlinktypesarealternate,stylesheet,start*,next,prev,contents*,glossary*,copyright*,chapter*,section*,subsection*,appendix*,help,andbookmark.Pleaseseehttp://www.w3.org/TR/html4/types.html#h-6.12fordescriptions.

HTML5includestheonesnotmarkedwithanasteriskandalsoincludesthese:archives,author,external,icon,license,nofollow,noreferrer,pingback,prefetch,search,sidebar,tag,index,up,first,andlast.Pleaseseehttp://www.w3.org/TR/html5/interactive-elements.html#linkTypesfordescriptions.Additionally,HTML5allowsyoutodeinenewlinktypesbydeiningthemathttp://wiki.whatwg.org/wiki/RelExtensions.

Thea(Chapter5),link(Chapter3),andarea(Chapter6)elementsuselinktypes.

CharacterEntitiesAcharacterentityrepresentsacharacterinadocument’scharacterset.Somecommoncharacterentitiesare&amp;foranampersand,&nbsp;for

Part1:HTMLBasics24

anonbreakingspace,&lt;foraless-thansign,&gt;foragreater-thansign,&quot;forastraightquotationmark,&lsquo;foracurlyopeningsinglequotationmark,&rsquo;foracurlyclosingsinglequotationmark,&ldquo;foracurlyopeningdoublequotationmark,and&rdquo;foracurlyclosingdoublequotationmark.Therearedozensmore.Here’salist,courtesyofElizabethCastro:http://www.elizabethcastro.com/html/extras/entities.html.

DeprecatedandObsoleteElementsandAttributesAdeprecatedelementorattributeisonethatyoushouldn’tusebutthatbrowsersstillsupportforbackward-compatibilityreasons.MostofthedeprecateditemsarepresentationalinnatureandhavebeenreplacedbyCSS.Anobsoleteelementorattributeisonethatyoushouldnotuseandthatbrowsersshouldnotsupport.

ThedeprecatedelementsinX/HTMLareapplet,basefont,center,dir,font,isindex,menu,s,strike,andu.

Thegoalofthisbookistobeapracticalreferencetostandards-basedcodingtodayandintothefuture.Tothatend,Ideliberatelyleftoutobsoleteanddeprecatedelementsandobsoleteattributes,sinceyoushouldn’tusethemanyway.Similarly,Iomittedproprietary(thatis,nonstandard)elementsthatcertainbrowserssupportbutthataren’tpartofanyHTMLspeciication,eitherinalorintheworks.

However,throughoutParts2(especially)andPart3,Idonotedeprecatedattributesandwhatyoushoulduseinstead,whichusuallymeansusingCSStoreplaceapresentationalattribute.Ialsonoteelementsandattri-butesthatarevalidinX/HTMLbutnotinHTML5(they’reobsolete).

Part2

ThispartofthebookcoversallnondeprecatedelementsthataresharedamongHTML4,XHTML1,andHTML5(thoughsomeareobsoleteinHTML5,asnoted).ElementsuniquetoHTML5arecoveredinPart3.

Insomecases,analreadyexistingelementisdifferentinHTML5,whetherit’stheelement’smeaning,theavailabilityofanattribute,ortheadditionofnewattributes.Inotethesedifferencesthroughout.Inparticular,keepaneyeonthe“AttributesinDetail”sectionsandtheHTML5boxesattheendofrelevantentries.Eachboxdetailsdifferentusesand/orattributesfortheelement,allowingyoutounderstandtheirapplicationinHTML5ataglance.

HTMLElementsandGuidance

Chapter2: PrimaryStructureandSections . . . . . . . . . . . . . . . . . . . . 27Chapter3: DocumentHead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43Chapter4: Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69Chapter5: Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93Chapter6: EmbeddedContent(ImagesandObjects) . . . . . . . 141Chapter7: Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157Chapter8: TabularData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .185Chapter9: Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203Chapter10: Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

Part2Contents

TheelementsinthischapterrepresentanHTMLdocument’shigh-levelstructuralandoutlinecomponents.Someareessential(afterall,youcan’twriteanHTMLdocumentwithoutthehtmlelement),whileothersareeitherusedsparingly(thehrelement)orhaveseentheirusagedeclineinHTML5(thedivelement).

ThischapterisacounterparttoChapter11,whichdescribesrelatedelementsuniquetoHTML5.Ifyou’rewritingX/HTMLdocuments,thenyoudon’tneedtohoponoverthere.But,ifyou’rewritingHTML5,thenthischapterandChapter11combinetodetailalltheprimarystructuralandsectioningelementsatyourdisposal.

PrimaryStructureandSections

2

Part2:HTMLElementsandGuidance28

addressAuthorcontactinformation

Syntax <address></address>Attributes Core,I18n,Events,HTML5Only:Global

Descriptionaddressisoneofthemostmisleadingelementsbyname.You’dlogi-callythinkit’sformarkingupapostaladdress,butitisn’t(exceptforonecircumstancedescribedinalittlebit).Infact,surprisingly,thereisn’tanHTMLelementexplicitlydesignedforthat.

Instead,addressdeinescontactinformationfortheauthorofanHTMLdocumentorpartofadocument.Ittypicallygoesateitherthebeginningor,moreoften,theendofapage.However,ifasectionofapagehasanauthor,placetheaddressincontextofthatsection.

Mostofthetime,contactinformationtakestheformoftheauthor’se-mailaddressoralinktoapagewithmorecontactinformation.

Example:

<address>

Page maintained by <a href=”mailto:taylor.rose@yourdomain.com">

➥ Taylor Rose</a> and <a href=”/contact-us/katherine-whitney.

➥ html”>Katherine Whitney</a>.

</address>

Browserstypicallyrenderaddresscontentinitalicsbydefault,likethis:Page maintained by Taylor Rose and Katherine Whitney.

Part2:HTMLElementsandGuidance Chapter2:PrimaryStructureandSections 29

Additionally,thecontactinformationcouldverywellbethedocumentauthor’spostaladdress,inwhichcasemarkingitupwithaddresswouldbevalid.But,ifyou’recreatingtheContactUspageforyourbusinessandwanttoincludeyouroficelocations,itwouldbeincorrecttocodethosewithaddress.So,it’sthecontextthatmatters.

HTML5andtheaddressElementInHTML5,addresspertainstothenearestarticleelementancestor,orthebodyifnoarticleispresent.It’scustomarytoplaceaddressinanHTML5footerelementwhendocumentingauthorcontactinfor-mationforthepageatlarge.

Anaddressinanarticleprovidescontactinformationfortheauthorofthatarticlewithinadocument.PleaseseethearticleentryinChapter11foranexample.

HTML5stipulatesthataddressmaycontainauthorcontactinforma-tiononly,notanythingelsesuchasthedocumentorarticle’slastmodiieddate.Additionally,HTML5forbidsnestinganyofthefollow-ingelementsinsideaddress:h1–h6,address,article,aside,footer,header,hgroup,nav,andsection.

Part2:HTMLElementsandGuidance30

bodyDocumentcontentcontainer

Syntax <body> . . . [document content] . . .

</body>

Attributes Core,I18n,Events,onload,onunload,HTML5Only:Global,onafterprint,onbeforeprint,onbeforeunload,onblur,onerror,onfocus,onhashchange,onmessage,onoffline,ononline,onpagehide,onpageshow,onpopstate,onredo,onresize,onstorage,onundo

DescriptionThebodyelementcontainsallcoderelatedtoapage’scontentandmayalsocontainoneormorescriptblocks.bodyisrequiredforeveryHTMLdocumentexceptonethatdeinesframesets,inwhichcaseitcanappearonlyinsidethenoframeselement.(PleaseseeChapter10.)OnlyonebodyisallowedperHTMLdocument.

Example:

. . .

</head>

<body>

<h1>All about <code>body</code></h1>

<p>The <code>body</code> element contains your page’s

content, which may include <em>nearly</em> every

element.</p>

. . .

</body>

</html>

Part2:HTMLElementsandGuidance Chapter2:PrimaryStructureandSections 31

bodymaycontaintext,images,objects,scripts,tables,andforms—inshort,nearlyeveryHTMLelement,whetherblock-levelorinline.However,iftheDOCTYPEisStrict(whichIrecommend),eachinlineelementmustbecontainedinablock-levelelement.Forinstance,thecodeandemelementsintheexamplecouldnotsitdirectlyinsidebodybecausebothareinlineelements.

AttributesinDetailInadditiontothecommonevents,bodyhastwospecialeventattributes(seethe“HTML5andthebodyElement”box,too):n onload=”script”:Fireswhenallthedocument’scontenthasinished

loading.Thisincludesallimages,objects,andscripts(whethertheyarelocaltothesiteorexternal,third-partyscripts).Consequently,thetimeittakesforonloadtoirecanvarygreatlyfrompagetopagedepend-ingonthecontent,howcontentisserved,networklatency,auser’sbrowsercachesettings,andmore.

n onunload=”script”:Fireswhentheuserleavesthedocument,suchaswhennavigatingtoanotherpageviaalink.

DeprecatedAttributesThefollowingattributesareallpresentationalinnature,souseCSSinsteadtoachievetheequivalenteffect.n alink:ObsoleteinHTML5.Thiscolorappearsastheuserisselecting

alink.UsetheCSSa:activepseudo-selectortodeinetheactivelinkcolorinstead.

n background:ObsoleteinHTML5.UsetheCSSbackground-imageprop-ertytodeinethebodybackgroundimageinstead.

n bgcolor:ObsoleteinHTML5.UsetheCSSbackground-colorpropertytodeinethebodybackgroundcolorinstead.

Part2:HTMLElementsandGuidance32

n link:ObsoleteinHTML5.UsetheCSSa:linkpseudo-selectortodeinetheunvisited(thatis,default)linkcolorinstead.

n text:ObsoleteinHTML5.UsetheCSScolorattributetodeinethedefaulttextcolorinstead.

n vlink:ObsoleteinHTML5.UsetheCSSa:visitedpseudo-selectortodeinethevisitedlinkcolorinstead.

HTML5andthebodyElementHTML5introducesseveralneweventattributestobody.Aswithotherevents,it’sbesttoapplytheseunobtrusivelywithJavaScriptratherthanincludetheminyourHTML.

AttributesinDetailn onafterprint=”script”:Thisireswhenthebrowserinishesprint-

ingthedocument.n onbeforeprint=”script”:Thisireswhenthebrowser’sPrintfunc-

tionalityisengaged,suchaswhenyouchoosePrintfromthemenubutbeforethedocumenthasprinted.

n onbeforeunload=”script”:Thisiresjustbeforethedocumentunloads,whichhappenseachtimeausersubmitsaformornavi-gatesawayfromthecurrentpage.Useitifyouwantuserstocon-irmtheyintendtoleavethepage.

n onblur=”script”:Thisireswhenbodylosesfocus,suchaswhentheuserclicksthemousepointeroutsidebody.It’stheoppositeofonfocus.

n onerror=”script”:Thisireswhenanuncaughtruntimescripterroroccurs.

n onfocus=”script”:Thisireswhenthebodyachievesfocusafterhavinglostit.It’stheoppositeofonblur.

Part2:HTMLElementsandGuidance Chapter2:PrimaryStructureandSections 33

HTML5andthebodyElement(continued)

n onhashchange=”script”:Thisireswhenonlythehash(#)portionoftheURLchanges.Forinstance,ifyouarecurrentlybrowsinghttp://www.yourdomain.com/meteor-showers.htmlandselectalinkthatanchorstothe#photosidelsewhereonthepage,theURLchangestohttp://www.yourdomain.com/meteor-showers.html#photosandonhashchangeiresifit’sdeined.Itiresagainifyounavigatetoanotheranchororbacktotheinitialstatethathadnohash.

n onmessage=”script”:Thisireswhenadocumentreceivesamessageviaserver-sentevents,Websockets,cross-documentmessaging,andchannelmessaging.Forexample,HTML5’sCross-DocumentMessagingallowstwodocumentstocommunicateregardlessoftheirsourcedomains.onmessageireswhenonedoc-umentreceivesamessagefromtheotheroneviapostMessage().Afulldiscussionofmessagingisbeyondthescopeofthisbook.

n onoffline=”script”:Thisireswhenthenavigator.onLineattri-butevaluechangesfromtruetofalse,whichoccurswhenthebrowsercannotcontactthenetworkuponauser-initiatedorprogrammaticrequestforaremotepageorile.

n ononline=”script”:Theoppositeofonoffline,thisireswhenthevalueofnavigator.onLinechangesfromfalsetotrue.

n onpagehide=”script”:Thisireswhennavigatingfromabrowser’ssessionhistoryentry,whichisanindividualURLand/orstateobjectplusothercontextualinformation.Looselyput,thesessionhistoryrepresentsthefullsetofpagesaccessedduringabrowsingsession.

n onpageshow=”script”:Theoppositeofonpagehide,thisireswhennavigatingtoabrowser’ssessionhistoryentry.

(continuesonnextpage)

Part2:HTMLElementsandGuidance34

HTML5andthebodyElement(continued)

n onpopstate=”script”:HTML5allowsyoutomanipulatetheses-sionhistorybyrecordinganinterfacestate(astateobject)inthehistoryprogrammatically.onpopstateireswhennavigatingtoabrowser’ssessionhistoryentrythatisastateobject.Pleaseseehttps://developer.mozilla.org/en/DOM/window.onpopstateandhttps://developer.mozilla.org/en/DOM/Manipulating_the_browser_historyformoreinformationandexamples.

n onredo=”script”:HTML5’sundo/redohistoryfunctionalityisjustoneofitsfeaturesthatmakesiteasiertobuildrobustWebappli-cations.Theconceptissimilartotheundoandredofeaturesinwordprocessorsandothersoftware.onredoireswhenaredooperationtakesplaceonanundoobject.Thespeciicsarebeyondthescopeofthisbook.

n onresize=”script”:Thisireswhenthebodychangessize.n onstorage=”script”:TheW3C’sWebStorageAPI(http://www.

w3.org/TR/webstorage/),alsoreferredtoas“DOMStorage,”allowsyoutostorealargeamountofdatasecurelyinthebrowser.onstorageireswhenastorageeventoccurs.ThespeciicsofWebStoragearebeyondthescopeofthisbook.Pleaseseehttp://dev.opera.com/articles/view/web-storage/formoreinformation.

n onundo=”script”:Thisistheoppositeofonredo,iringwhenanundooperationtakesplaceonanundoobject.

Also,whencommoneventsonblur,onerror,onfocus,andonloadappearonbody,theyexposethesame-namedeventhandlersoftheWindowobject.Pleasesee“Attributes”inChapter1formoredetailsaboutthesefourevents.

Part2:HTMLElementsandGuidance Chapter2:PrimaryStructureandSections 35

divAgenericcontainer

Syntax <div></div>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionThedivelementservesasageneric,block-levelcontainerandhasnosemanticmeaning.Asisthecasewithanymeaninglesselement,usedivonlywhenapropersemanticchoicedoesn’texist.

DeveloperstypicallyuseitinX/HTMLasthewrapperaroundmostprimaryblocksofcontentandthencontrolthewidth,placement,andotherpresentationcharacteristicswithCSS.divmaycontainbothblock-levelandinlineelements,includingotherdivs.

Example:

<body>

<div id=”container”>

<div id=”header”> . . . </div>

<div id=”content”>

<div id=”main”> . . . </div>

<div id=”sidebar”> . . . </div>

</div>

<div id=”footer”> . . . </div>

</div>

</body>

note div’scousinisthespanelement,whichisageneric,inlinecontainerwithnosemanticmeaning.

Part2:HTMLElementsandGuidance36

DeprecatedAttributesn align:ObsoleteinHTML5.alignispresentationalinnature,soinstead

usetheCSStext-alignproperty(withavalueofcenter,justify,left,orright)toalignadiv’scontent.

HTML5andthedivElementYou’llindfewerinstancestousedivinHTML5becausethatversionofthelanguagecontainsseveralcontainersthatdohavemeaning,suchasarticle,aside,header,footer,nav,andsection(seeChapter11).Usedivonlywhenasemanticelementisn’trequired.

h1,h2,h3,h4,h5,h6Aheading

Syntax <h1></h1> <h2></h2><h3></h3><h4></h4><h5></h5><h6></h6>

Attributes Core,I18n,Events,HTML5Only:Global

DescriptionTheh1–h6elementsrepresentcontentheadingsofvaryingdegreesofimportance.Theh1isthemostimportant,andtheh6istheleast.Eachheadingdescribesthecontentorfunctionalitythatfollows,whetherit’s

Part2:HTMLElementsandGuidance Chapter2:PrimaryStructureandSections 37

anarticle,asign-upform,amodulewithagroupoflinks,thetitleaboveanembeddedvideo,andsoon.

Yourh1–h6headingsareamongthemostimportantelementsinanyHTMLdocument,becausetheyareintegraltodeiningyourpage’soutline.Planthemwithoutregardforhowyouwantthemtolook;focusonwhatheadinghierarchyisappropriateforyourcontent.ThisbeneitsbothSEOandaccessibility.

Searchenginesweighyourheadingsheavily,particularlythelikesofh1.Screenreaderusersoftennavigateapagebyheadings,too,becauseitallowsthemtoquicklyassessapage’scontentwithouthavingtolistenthrougheverypieceofcontent.

Opinionsvaryconcerningwhetherit’sappropriatetoskipaheadinglevelinadocument—tomovefromh1toh3withinaparticularcontentarea,forinstance.Mostpeopleinthecommunitythinkyoushouldnotskipalevel,aviewIshare.Havingsaidthat,thereisnoirmruleineitherX/HTMLorHTML5aboutthis.

Bydefault,headingstypicallyrenderatasizecomparabletoitsimpor-tanceandinbold.However,aspreviouslynoted,don’tuseaparticularheadingleveljustbecauseyouwantittolookacertainway.YoucancontrolallofthatwithCSS.

Example:

<h1>This is a heading level one</h1>

<h2>This is a heading level two</h2>

<h3>This is a heading level three</h3>

<h4>This is a heading level four</h4>

<h5>This is a heading level five</h5>

<h6>This is a heading level six</h6>

Part2:HTMLElementsandGuidance38

Pleasenotethatthefollowingrenderingisn’ttoscale.

This is a heading level oneThis is a heading level two

This is a heading level three

This is a heading level four

This is a heading level five

This is a heading level six

DeprecatedAttributesn align:ObsoleteinHTML5.alignispresentationalinnature,soinstead

usetheCSStext-alignproperty(withavalueofcenter,justify,left,orright)toalignaheading’scontent.

tip Youareallowedtousemorethanh1perpage,thoughitisn’tcommontodosoandismostlydiscouragedinX/HTMLbecausetheusecases

arelimited.Google’sMattCuttshasgoneonrecordsayingGoogleallowsitwithoutasearchrankingpenaltyaslongasit’scontent-appropriateandwithinreason.However,youshoulduseh1moreofteninanHTML5document.Seethe“HTML5andtheh1–h6Elements”box.

tip You’lloftenseetheh1usedtowrapasite’slogo,butIdon’trecom-mendthispracticeinX/HTML.Saveyourh1forthemainheading(or

two)withinyourcontent.

HTML5andtheh1–h6ElementsHTML5’sarticle,aside,nav,section,andhgroupelementsgreatlyimpactthewayinwhichyouuseh1–h6headings.Pleaseseethe“HTML5’sDocumentOutline”sectionandtheelements’entriesinChapter11.

Part2:HTMLElementsandGuidance Chapter2:PrimaryStructureandSections 39

hrAhorizontalrule

Syntax <hr>or<hr />

Attributes Core,I18n,Events,HTML5Only:Global

DescriptionThehrelementdoesnotcontainanycontent;itrendersasahorizontalrule,actingasaseparator.

Example:

<p>This is a paragraph.</p>

<hr />

<p>This is another paragraph.</p>

Bydefault,useragentstypicallyrenderitasatwo-color(gray),2-pixel-highbarthatextendsthefullwidthofthecontentcontainerinwhichitsits.Thespaceaboveandbelowanhrtendstovaryamongbrowsers.

This is a paragraph.

This is another paragraph.

DeprecatedAttributesn align:ObsoleteinHTML5.UsetheCSSwidthand,optionally,margin

propertiestodictatethealignmentofanhrrelativetothecontentaroundit.

n noshade:ObsoleteinHTML5.ThisBooleanattribute,whenpresent,turnsoffthedefault“groove”appearanceofanhrbyrenderingthe

Part2:HTMLElementsandGuidance40

twolinesinonecolorinsteadoftwo.UseCSSinstead,suchashr{border:1pxsolid#999;},where#999representsthecolor.

n size:ObsoleteinHTML5.UsetheCSSheightpropertytodictatethesizeinstead.

n width:ObsoleteinHTML5.UsetheCSSwidthpropertytodictatethewidthinstead.

HTML5andthehrElementHTML5givesthehrmorecontextbyredeiningitas“aparagraph-levelthematicbreak,e.g.ascenechangeinastory,oratransitiontoanothertopicwithinasectionofareferencebook.”

htmlDocumentrootelement

Syntax <html></html>Attributes I18n,HTML5Only:Global,manifest

DescriptionThehtmlelementistherootelementofeveryHTMLdocument;allotherelementsarecontainedwithinit.TheopeninghtmltagshouldbeprecededbyavalidDOCTYPE.

Example(typicalHTML4Strictdocument):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"

"http://www.w3.org/TR/html4/strict.dtd">

Part2:HTMLElementsandGuidance Chapter2:PrimaryStructureandSections 41

<html lang="en">

<head>

. . .

</head>

<body>

. . .

</body>

</html>

Thelangattributesetsthebaselanguagefortheentiredocument.ThestructureremainsthesameastheexampleforotherversionsofHTML,exceptfortheDOCTYPEand,insomecases,theattributesonhtml.PleaseseeChapter1formoreinformationaboutlang,thehtmlelement’sotherattributes,andDOCTYPEoptions.

DeprecatedAttributesn version:ObsoleteinHTML5.Donotusethisattributesinceitprovides

redundantinformationastheDOCTYPEregardingtherequiredDTDversion.

HTML5andthehtmlElementIfthepreviousexamplehadbeenanHTML5document,everythingwouldbethesameexcepttheDOCTYPEwouldbe<!DOCTYPEhtml>.

AttributesinDetailn manifest=”URL”:Thisoptionalattributecontainsavalidnon-

emptyURLthatpointstothedocument’sapplicationcachemani-fest.HTML5providesthemeanstorunofflineWebapplications

(continuesonnextpage)

Part2:HTMLElementsandGuidance42

HTML5andthehtmlElement(continued)

(applicationcanmeanarobustapplicationorjustahandfulofHTMLpages;itdoesn’tmatter).Theapplicationcachemanifestliststheilesanapplicationneedstooperatewhendisconnectedfromthenetwork.Thebrowsersavesacopyoftheileswhenyouaccessthesiteonline.DetailsaboutofflineWebapplicationsarebeyondthescopeofthisbook,butyouspecifytheattributelikethis:<html manifest=”myapplication.manifest”>

Pleasenotethatabaseelementhasnoeffectonresolvingarela-tiveURLinthemanifestattributesincemanifestisprocessedbeforebaseappears.

AnHTMLdocument’sheadelementcontainsimportantinformationaboutthepage,linkstoexternalresourcessuchasstylesheets,andembeddedstyles,whennecessary.Plus,whatyouincludeinyourpage’sheadimpactssearchengineoptimization(SEO).

Eachoftheelementsdescribedinthischaptermayappearonlyinthehead,exceptstyle,whichhasanexceptioninHTML5.

note Thescriptelementmayalsoappearinthehead;however,it’sbesttoincludeitattheendofyourpagejustbeforethe</body>endtag

wheneverpossible.

DocumentHead

3

Part2:HTMLElementsandGuidance44

baseDocument’sbaseURI

Syntax <head> <basehref="">or<basehref=""/></head>

Attributes href,target,HTML5Only:Global

DescriptionThebaseelementdeinesthepage’sabsoluteURIfromwhichrelativepathstoexternalresourcesareresolved.(Externalresourcesincludeassetssuchasimages,JavaScriptiles,andstylesheets,aswellaslinkstootherpagesandpathstoserver-sidescriptsthatprocessforms.)basemustbedeinedinthedocumentheadbeforeanyelementthatcallsuponanexternalresource,andtherecanbeonlyonebaseelementperpage.Ifbaseisnotdeined,thepage’sbaseURIdefaultstothecurrentpage.MostpagesontheWebdon’tdeinebasebecausethedefaultbehavioriswhatisdesired.

AttributesinDetailn href="uri":Deinesthedocument’sbaseabsoluteURI.n target:Usedtosetthebasetargetforlinksandformactionsindocu-

mentswithframeoriframeelements.PleaseseetheframeentryinChapter10formoreinformation.

It’simportanttonotethatbaseimpactstheURIsonlyforthepageinwhichitappears.Forinstance,ifyoudeinebackground-image: url(../img/arrow.png)inanexternalstylesheetthatisloadedbyapagewithbasedeined,thepathtotheimageisunaffected.Similarly,

Part2:HTMLElementsandGuidance Chapter3:DocumentHead 45

baseinaparentdocumentdoesnotaffectthepathswithinaniframe’sdocument.Lastly,theobjectelement’scodebaseattributetakesprece-denceoverbase.

Theeasiestwaytounderstandhowbaseworksistoseeexamplesbothwithandwithoutit.Let’ssayyou’vecreatedthefollowingpageathttp://www.myvacationpics.com/2009/.

Example1(withoutbasedefined):

<head>

. . .

<link rel="stylesheet" href=”../css/global.css”

type="text/css" />

</head>

<body>

. . .

<p>

<img src=”image/kauai/thumbnail_volcano_01.jpg”

width=”400” height=”300” alt=”Kauai volcano” />

<a href=”volcanoes/kauai.html”>Kauai Volcano Pics</a>

</p>

. . .

</body>

Example1isyourtypicalHTMLpage—thepathstotheexternalassetsareexactlyhowtheyappearinthecode.Thatis,thepathstothestylesheet,thevolcanoimage,andthepagetoviewmorepicturesarerelativetotheHTMLpage’slocation,whichisinthe/2009/directory.

Now,let’sapplyabasevaluewhileleavingtherestofthecodeexactlyasitwasinExample1.Remember,youaren’tmovingthepagetoadifferentfolder,justaddingbasetothepage.

Part2:HTMLElementsandGuidance46

Example2(withbasedefined):

<head>

. . .

<base href=”http://www.myvacationpics.com/2010/” />

<link rel="stylesheet" href=”../css/global.css”

type="text/css" />

</head>

<body>

. . .

<p>

<img src=”image/kauai/thumbnail_volcano_01.jpg”

width=”400” height=”300” alt=”Kauai volcano” />

<a href=”volcanoes/kauai.html”>Kauai Volcano Pics</a>

</p>

. . .

</body>

WiththebasedeinedinExample2,allURIsinthepagearenowrelativetothebasehrefvalue,meaningthepagetreatsthemasifit’sinthe/2010/directoryeventhoughitstilllivesin/2009/.Herearethepathsastheyappearinthecodeandwherethepagelooksforthemnowthattheyresolvetonewlocations:n ../css/global.cssresolvestohttp://www.myvacationpics.com/css/

global.css(thisdidn’tchangebecauseofthepath).n image/kauai/thumbnail_volcano_01.jpgnowresolvestohttp://

www.myvacationpics.com/2010/image/kauai/thumbnail_volcano_01.jpg(insteadofhttp://www.myvacationpics.com/2009/image/kauai/thumbnail_volcano_01.jpg,asinExample1).

n volcanoes/kauai.htmlresolvestohttp://www.myvacationpics.com/2010/volcanoes/kauai.html(insteadofhttp://www.myvacationpics.com/2009/volcanoes/kauai.html,asinExample1).

Part2:HTMLElementsandGuidance Chapter3:DocumentHead 47

headInformationaboutdocument

Syntax <head> ... </head>

Attributes I18n,profile*,HTML5Only:Global

DescriptionTheheadelementisrequiredineachHTMLdocument.Ithousesahand-fulofotherelementsthatprovideinformationaboutthepage,suchasthecharacterencoding,title,linkstostylesheets,andmetadataforsearchengines.Itdoesnotcontainpagecontent(asthebodyelementdoes)thatuseragentsgenerallyrender,thoughtheymaysurfacetheinformationinotherways(suchaswithtitleonthetitlebar).

Theelementsthatheadmaycontainarebase,link,meta,script,style,andtitle.Allaredeinedinthischapterexceptscript,whichiscoveredinChapter9.Also,alloftheseexceptscript(andstyleinHTML5)mayappearonlyinthehead.

TheheadimmediatelyfollowstheDOCTYPEandthehtmlelement,asshownintheexample.

Example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"

lang="en">

<head>

(continuesonnextpage)

Part2:HTMLElementsandGuidance48

<title>Sunny renewable green energy services - Solar

Panels Galore</title>

<meta http-equiv="Content-Type" content="text/html;

charset=utf-8" />

. . . [other meta elements] . . .

<link rel="stylesheet" type="text/css"

href="/common/css/base.css" />

</head>

<body>

. . .

AttributesinDetailn profile="uri":*ObsoleteinHTML5.AsImentioninthischapter’sentry

forthemetaelement,youmaycreateyourownmetaelementssimplybyincludingtheminyourpage.Youmayalsocreateametadataproile,whichisdocumentationofametadatastandard,andpointtoitwiththeprofileattributeonthehead.It’sawayofinforminguseragentsthatsomeofyourmetaelementsarederivedfromthatproile.Includingtheprofileattributedoesnotchangethebehaviorofthemetaelements,however.Afulldiscussionofproilesisbeyondthescopeofthisbook,butyoucanreadmoreathttp://www.w3.org/TR/html401/struct/global.html#profiles.Also,twosuchproilesareDublinCore(http://dublincore.org/documents/dces/andhttp://dublincore.org/resources/faq/)andXFN(http://gmpg.org/xfn/11andhttp://microformats.org/wiki/xfn).

Part2:HTMLElementsandGuidance Chapter3:DocumentHead 49

HTML5andtheheadElementHTML5declarestheprofileattributeobsoleteandinitsplacerequestsyouregisterextensionstothepredeinedsetofmetadatanames(application-name,author,description,andgenerator,asdiscussedinthemetaentryinthischapter).Youmayregisterexten-sionsathttp://wiki.whatwg.org/wiki/MetaExtensions.

linkLinktoarelatedresource

Syntax <linkrel=""href="">or<linkrel=""href=""/>

Attributes Core,I18n,Events,charset*,href,hreflang,media,rel,rev*,target*,type,HTML5Only:Global,sizes

DescriptionThelinkelementdeinesalinkbetweenthecurrentdocumentandanotherresource,butinamuchdifferentwaythantheaelement.Likea,linkusesthehrefattributetodeinethelocationoftheresource,butlinkdoesn’tdisplayactionabletextinyourpagecontent.Instead,itprovidesinformationforuseragentstoactupon.Apagemayhavemulti-plelinkelements,andtheymustalwaysappearintheheadelement.

Therearetwocasesforusinglink:n Tolinktoaresourcethataffectsthecurrentview,suchasastylesheet

orfavicon.PleaseseeExamples1–4.n Tolinktoaresourcethatdoesn’taffectthepagebutthatisrelated

toit,suchasaversioninanalternateformat(RSSorAtomfeed,PDF,

Part2:HTMLElementsandGuidance50

andsoon)orlanguage,ortolinktoaresourcethatispartofthesameseriesofdocuments,suchaschapterssplitintomultipleHTMLiles.Again,theselinksarenotdisplayedinyourpagecontent,butasearchenginemayindextherelateddocuments,andinthecaseofafeed,anRSSreaderdisplaysthelinkedXMLcontent.PleaseseeExamples5–7.

Thebestwaytogetafeelforlinkistolookatsomeexamples.

LinkingtoStyleSheetsoraFaviconThemostcommonuseforlinkbyfaristoloadastylesheet.

Example1(loadastylesheet):

<head>

. . .

<link rel="stylesheet" href="/common/css/base.css"

type="text/css" media="screen, print" />

. . .

</head>

tip

Youmayhaveseenstylesheetsloadedwith@import,too.However,usinglinkisabestpractice,primarilybecausestylesheetsloadas

fastasorfasterthan@importinarangeofscenarios.

Itdoesn’tmatterinwhatordertheattributesappear,butthesequenceinExample1isprettystandard.Also,it’scustomarytoincludethetypeattributeasshownwheneveryouloadastylesheet,andrelwillalwaysbeeither“stylesheet”or“alternatestylesheet”(seeExample3).Thehrefandmediaattributeswillvary,however.hrefprovidestheURI(anabsolutepath,inthiscase)tothestylesheet,andmediadeinesinwhatmediathestylesheetshouldbeappliedtothepage(screenlayoutandwhenprinting,intheexample).Pleasesee“AttributesinDetail”formoreoptions.

Part2:HTMLElementsandGuidance Chapter3:DocumentHead 51

Nowlet’sloadtwostylesheets.

Example2(loadtwoormorestylesheets):

<link rel="stylesheet" href="/common/css/base.css"

type="text/css" media="screen" />

<link rel="stylesheet" href="/common/css/print.css"

type="text/css" media="print" />

Usetwoormorelinkelementsifyouhaveseparatestylesheetsfordisplayingyourpageon-screenandprinting(orotherpurposesasdeinedbymedia).Thisisprettycommon,sincethereareoftenelementsyouwantto“turnoff”forprinting,suchasnavigationandads.

Theinalstylesheetexampleshowshowtoloadanalternatestylesheet,whichyouusetoprovideadifferentpresentationthanyourdefaultlayout.Itcouldbeforadifferenttheme(lightondarkversusdarkonlight),changingthedimensions,andsoon.

Example3(loadanalternatestylesheet):

<link rel="stylesheet" href="/common/css/base.css"

type="text/css" media="screen" title="Default" />

<link rel="stylesheet" href="/common/css/print.css"

type="text/css" media="print" />

<link rel="alternate stylesheet" href="/common/css/theme-

➥ light-on-dark.css" type="text/css" media="screen"

title="Light on Dark" />

Yourpagemayhaveseveralalternatestylesheets.Analternatestylesheetdoesn’taffectyourpagebydefault.Somebrowsersallowyoutoselectitfromamenuaslistedperitstitleattribute.Forinstance,inFirefox’sView>PageStylemenu,you’dseetheDefaultandLightonDarkthemestochoosefromforExample3.Sincenotallbrowsersprovidea

Part2:HTMLElementsandGuidance52

meanstoselectanalternatestylesheet,developersoftenimplementaJavaScriptstyleswitcher(searchonlineformoredetails).

Nowit’stimetomoveontothesecondmostfrequentuseoflink:displayingafavicon.

Example4(displayafavicon):

<link rel="shortcut icon" href="/img/favicon.ico"

type="image/x-icon" />

Afaviconisthesmallsite-speciiciconyou’lloftenseeinabrowser’saddressbarbeforetheURL,nexttoabookmark/favorite,onatab(dependingonthebrowser),oronadesktopshortcut(dependingontheOS).Iffavicon.icolivesatyoursiteroot,youtypicallydon’tneedtouselink,thoughyoumayprefertojustbeexplicit.Notethatifyouuserel="icon"insteadofrel="shortcuticon",InternetExplorerwon’tloadit.(Evenso,olderversionsofIEexhibitsomeinconsistentfaviconbehavior.Youmayneedtobookmarkthepagebeforethefaviconwillshow.)

LinkingtoRelatedDocumentsTheremainingexamplesdemonstrateusinglinktopointtorelateddocumentsthatdon’timpactthepage’slayout.

Example5(pointtoRSSorAtomfeed):

<link rel="alternate" type="application/rss+xml" href=

➥ "topstories.xml" title="Top Stories -- YourDomain.com" />

ThelinkformatinExample5tellsanRSSreaderwheretolocateyourfeed.Notethevaluesfortherelandtypeattributes.Youmayhavemorethanonefeedperdocument,suchasonelinkfornationaltopstoriesandanotherforregionalnews.ForanAtomfeed,specifytype="application/atom+xml"instead.

Part2:HTMLElementsandGuidance Chapter3:DocumentHead 53

Example6(pointtoalternatelanguage):

<link rel="alternate" type="text/html" hreflang="es"

href="spanish.html" title="Article in Spanish" />

Ifyouprovidealinktoanalternatelanguageversionofthedocument,asinExample6,asearchenginemayindexit.Notetheuseofthehreflangattribute.typeissettotext/htmltorelectthatthehrefpointstoadocumentwiththatcontenttype.

Example7(pointtodocumentsinaseries,andprefetching)

<link rel="start" href="step-one.html" />

<link rel="prev" href="step-four.html" />

<link rel="next" href="step-six.html" />

Let’ssayyou’vewrittenaseriesofpagescalled“TheSevenStepstoCreatingYourOwnLuck.”Ifstep-five.htmlwerethecurrentdocument,itcouldincludethelinkelementsshowninExample7,whichinformsearchenginesabouttheseries.rel=”start”referstotheirstdocu-mentintheseries.

Furthermore,Firefoxprefetchesarel=”next”href.ThismeansthatinExample7,theassetsforstep-six.htmlareloadedbehindthescenesasyou’rebrowsingthecurrentpage.Youdon’thavetoprefetchanentirepage,though.Thehrefattributecouldjustaseasilypointtoanimageorastylesheet.Theformerwouldbehandyifthecurrentpageisoneofseveralwithinaphotogallery,forexample.

note Firefox3.0+alsosupportsrel=”prefetch”,whichistheHTML5waytospecifyaresourceforprefetching(HTML5supportsnext,too).Other

browsersmayfollowsuit.

tip Learnmoreaboutprefetchingathttps://developer.mozilla.org/en/Link_prefetching_FAQ.

Part2:HTMLElementsandGuidance54

AttributesinDetail(Seethe“HTML5andthelinkElement”boxforadditionaldetails.)n charset:*ObsoleteinHTML5.Thisspeciiesthecharacterencodingof

thelinkdestination.Pleasesee“CharacterEncoding”inChapter1formoredetails.

n href="uri":Thisdeinesthelinkresourcelocation.PleaseseetheaelementinChapter5foradescriptionofvariousURIpathsthatareavailabletoyou.

n hreflang="langcode":Notoftenused,thisindicatesthebaselanguageofthehref’sdestination,muchinthewaythelangattributespeciiesthelanguageofotherHTMLelements.Hence,youmayusehreflangonlywhenhrefispresent.SeeExample6.

n media:Whenrelissettostylesheet,thiscomma-separatedlistindi-catesthemediaforwhichthestylesheetapplies(seeExamples1–3).Ifyouleaveoutmedia,thevaluetypicallydefaultstoallinbrowsers,eventhoughHTML4declaresitshouldbescreen.Thefollowinglistincludesthepossiblemediavalues.screenandprintenjoywidesupportand,withall,areusedthemostbyaverylargemargin.Supportfortheothersvaries.Pleasealsoseethe“HTML5andthelinkElement”box.– all:Foralldevices.– aural:Forspeechsynthesizers.– braille:ForBrailleassistivedevices.– handheld:Forhandhelddevices,butfewsupportit.Typically,you’ll

usescreeninsteadwhendesigningformobile.

Part2:HTMLElementsandGuidance Chapter3:DocumentHead 55

– print:Forprintingandprintpreview.– projection:Forprojectorsandsimilarviews.Opera’sprojection

mode,OperaShow,supportsit.– screen:Fortypicalcomputerscreensandmodernmobilebrowsers.

ThisisthevaluethattellsaWebbrowsertorenderastylesheet.– tty:Formediausingaixed-pitchcharactergrid,suchasteletypes.– tv:Fortelevision-typedevices.

n rel="link-types"andrev="link-types":*revisobsoleteinHTML5.relandrevhaveoppositemeaningsandareusedinconjunctionwithhref.Therelattributeindicatestherelationshipfromthecurrentdocumenttothelinkedresource(seeExamples1–7).rev(“reverse”)indicatestherelationshipfromthelinkedresourcetothecurrentdocument.(PleaseseetheaelementinChapter5forafulldescriptionofthedifference.)

n target:*NotvalidwithStrictHTML4andXHTML1DOCTYPEs.ObsoleteinHTML5.targetspeciiesthenameoftheframeforwhichthelinkapplies.HTMLprovidesfourspecialtargetnameswithspeciicbehav-ior:_blank,_self,_parent,and_top.PleaseseeChapter10formoredetails.

n type=”content-type”:Tellstheuseragentthecontenttypeofthecontentatthelink’sdestination.Itisonlyadvisory.

Part2:HTMLElementsandGuidance56

HTML5andthelinkElementHTML5requireslinktohavearelattribute,anitempropattribute,orboth.Pleasesee“Attributes”inChapter1concerningitemprop,anHTML5globalattribute.

HTML5alsoallowslinkinsideanoscriptelementthat’sinthehead.

AttributesinDetail

HTML5expandsthevaluesformediaandincludesthesizesattribute.n media:Thisattribute’slistofvaluesisthesameasinX/HTML

exceptthatitincludesmediaqueries.InHTML5,media’svaluemustbeavalidmediaquerylistfromtheMediaQueriesspecii-cation(http://www.w3.org/TR/2009/CR-css3-mediaqueries-20090915/#syntax).mediaisallowedonlyifhrefispresent.

n sizes:Thisdeinesthesize(s)ofalinkedicon(s).sizes="all"meanstheiconisscalable,suchasanSVGimage.Otherwise,provideaspace-delimitedlistofsizes(ifmorethanone)inWIDTHxHEIGHTformat,whereeachvalueisanon-negativeinteger.

Examples:

<link rel="icon" href="some-icon.svg" sizes="any"

type="image/svg+xml">

<link rel="icon" href="favicon.png" sizes="16x16"

type="image/png">

<link rel="icon" href="icon-set.icns" sizes="16x16 128x128

➥ 256x256">

Part2:HTMLElementsandGuidance Chapter3:DocumentHead 57

metaDocumentmetadata

Syntax <head> <meta>or<meta /></head>

Attributes I18n,content,http-equiv,name,scheme*,HTML5Only:Global,charset

DescriptionViewsourceonvirtuallyanyWebpage,andyou’reboundtoseeahand-fulofmetaelements—typicallycalledmetatags—intheheadelement.metaspeciiesinformationaboutthecurrentHTMLdocumentinaname-valuepairformat,primarilyforthebeneitofbrowsers,searchenginespiders,andotheruseragents.Metadatadoesnotappearinyourpage’scontent.There’snolimittothenumberofmetaelementsyoucanincludeinyourpageaslongasallofthemareinthehead.

Example1showsarguablythemostimportantmetaelement.

Example1(declaringthecontenttype):

<head>

<title>. . .</title>

<meta http-equiv="Content-Type" content="text/html;

➥ charset=utf-8" />

. . .

</head>

Thenameinthename-valuepairinthisexampleisthehttp-equivattribute,whilecontent,asalways,isthevalue.Includethismeta

Part2:HTMLElementsandGuidance58

elementineachofyourpagestodeineyourdocument’scharacterencoding(UTF-8,inthiscase).It’sstandardpracticetomakeitoneoftheirstelementsinsidethehead,eitherjustbeforeorjustafterthetitle.(HTML5changesthesyntaxforthisusageofmeta.Pleaseseethecharsetattributeinthe“HTML5andthemetaElement”box.)

tip

It’simportanttoaddaContent-Typemetaelementtoyourdocumentssouseragentscandetectthedocument’scharacterencoding.Ifyou

excludeit,youruntheriskofyourusersseeingunreadabletext,particularlyonamultilingualsite.Formoreinformation,seehttp://www.w3.org/International/tutorials/tutorial-char-enc/.

Typically,metaelementsaregroupedtogether,thoughtheydon’thavetobe.Andthere’snosetlistofmetaelementname-valuepropertiesfromwhichtochoose.You’reallowedtocreateyourownsimplybyinclud-ingtheminyourpage(oryoucancreatethemmoreformally;seetheheadelement’sprofileattributeinthischapter).But,thefollowingareamongthemostcommonones,andtheydeineinformationthatsearchenginesusetovaryingdegrees.

Example2(commonmetaelements):

<head>

<title>Sunny renewable green energy services - Solar

Panels Galore</title>

<meta http-equiv="Content-Type" content="text/html;

➥ charset=utf-8" />

<meta name="description" content="Solar Panels Galore

provides consulting and installation services for

industrial, commercial and residential active and

passive solar panel systems." /> (continuesonnextpage)

Part2:HTMLElementsandGuidance Chapter3:DocumentHead 59

<meta name="keywords" content="solar panels, active solar,

passive solar, renewable energy, green energy, solar

panel installation, solar panel consultation,

industrial, commercial, residential" />

<meta name="author" content="Tanya Brown" />

. . .

</head>

ThemostusefulofthethreehighlightedmetaelementsinExample2isname="description".Asearchenginemaydisplaythisvalueasasnip-petoftextinitssearchresults.So,Ihighlyrecommendyouincludeasuccinct,informativedescriptionineachpage.Searchenginesdon’talldisplaythesamenumberofcharacters,though,solimityoursto150–160.

Theimpactofname="keywords"metadata(seeExample2)onsearchenginerankinghasdiminisheddramaticallyovertheyears,tothepointthatGoogledeclaredthatitcompletelyignoresname="keywords"forWebsearch.Somesearchenginesstillusethem(thoughnotheavily),socontinuetoincludethem,aslongastheyarerelevanttoyourcontent.Theyfelloutoffavorbecausemanyunscrupuloussiteownerstriedtotricksearchenginesbyincludingpopularkeywordsthatwereunrelatedtotheirsite’scontent.Searchenginesgotwisetothisandputmoreemphasisonasite’sbodycontentandfarlessonmetakeywords.

Thename="author"metadataissimilarinthatasearchenginespiderorotheruseragentmaychoosetouseit.

tip Usethefollowingmetaelementtotellasearchenginetoneitherindexthepagecontentnorfollowanyofthelinksonit.Youmayalso

specifynoindexornofollowindividually.<meta name="robots" content="noindex, nofollow" />

Part2:HTMLElementsandGuidance60

tip

MicrosoftintroducedtheX-UA-CompatibleheaderinIE8toallowyoutodictatetheIEversionyourpageshouldrenderas.Forexample,this

tellsittobehavelikeIE7’sstandardsmode:<meta http-equiv="X-UA-Compatible" content="IE=7" />

Ofcourse,it’sbesttomakeyourpageworkinthelatestversionofIEinsteadofforcingittobehavelikeIE7,buttheremaybetimeswhenthismetaelementisnecessary.Learnmoreaboutthemodesathttp://www.htmlfiver.com/extras/meta/.

AttributesinDetailn content:Thisisthe“value”inthename-valuepairofametaelement.n http-equiv:Alsocalledapragmadirective,thisbehaveslikeanHTTP

headersentbytheserver.Alongwiththenameattribute,http-equivisoneofthe“names”inthename-valuepairofametaelement.Itmustbepairedwithcontent.SeeExample1.

n name:Asyouwouldexpect,thisrepresentsa“name”inthename-valuepairofametaelement.Itmustbepairedwithcontent.

n scheme:*ObsoleteinHTML5.Youmaypopulateschemewithtextofyourchoosingthatclariiesameta’scontent.Forinstance,<metaname="date"content="11-05-2010"scheme="DD-MM-YYYY"/>explainsthedatereferstoMay11,notNovember5.

Part2:HTMLElementsandGuidance Chapter3:DocumentHead 61

HTML5andthemetaElementEachmetaelementmustincludethecharset,http-equiv,itemprop,ornameattribute,butnotmorethanone,andthecontentattributeisrequiredintandemwithallbutcharset.

AttributesinDetailn charset:ExclusivetoHTML5onmeta,charsetspeciiesthedocu-

ment’scharacterencoding.Youmaydeineitonlyonceinapage.TheContent-TypemetasyntaxinExample1technicallyisstillallowedinHTML5,butthepreferredformatishighlightednext,whichIrecommendyouuse.Furthermore,HTML5requiresittoappearwithintheirst512bytes(thatis,characters)ofyourcode.You’llalwaysbesafeifyouputitbeforethetitle.

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset="utf-8"/> <!-- use instead of Example

1 format -->

<title>. . .</title>

. . . [other meta elements] . . .

. . .

</head>

. . .

n name:HTML5deinesasetoffourmetadatanames,thoughyoustillmayuseothers.Thehttp://wiki.whatwg.org/wiki/MetaExtensionspagedocumentsextensionstothispredeinedset,andyoucanregisteryourownbyaddingthemtothewiki.Twoofthepredeinednamesareauthoranddescription,whichyouusejustasIshowedinExample2.Theothertwoareasfollows:– application-name:DeinesashortWebapplicationname,but

useitonlyifyourpagerepresentsaWebapplication;here’san(continuesonnextpage)

Part2:HTMLElementsandGuidance62

HTML5andthemetaElement(continued)

example:<metaname="application-name"content="InventoryManager">.Thisattributemayappearonlyonceinapage.

– generator:Speciiesthenameofthetool,ifany,usedtogener-atethedocument;here’sanexample:<metaname="generator"content="Dreamweaver">.Donotincludeitifyouhand-codeapage.

n http-equiv:HTML5formallydeinesfourstandardvalues:– content-language:HTML5discouragesyoufromusingthisand

recommendsthelangattributeonthehtmlelementinstead.– content-type:Thisdeinesthedocument’scontenttype,as

showninExample1,butusethecharsetattributeinsteadforHTML5.

– default-style:Thissetsthenameofthedefaultalternatestylesheet.

– refresh:Thisinstructsapagetorefreshafteraspeciiedperiodoftime.Yourpagemayincludeonlyoneinstance.Ametarefreshtakesoneoftwoforms:anumberofsecondsoranum-berofsecondsandaURL.Forexample,ifyourpagewereasportsscoreboard,youwoulddirectittorefreshevery90secondswith<metahttp-equiv= "refresh"content="90">.IncludeaURLifyouwanttorefreshtoadifferentpageafterthespeciiednumberofseconds.Ausecaseforthisisaphotogallerythatautocyclesevery10seconds:<metahttp-equiv="refresh"content="10;url=photo-06.html">.However,avoidusingthisifyou’vemovedcontentfromonelocationtoanotherandwanttoredirectuserscomingintotheoldlocationviaasearchengineorbookmark.Usea301Redirectinstead(pleasesearchonlineformoreinformation.)

Part2:HTMLElementsandGuidance Chapter3:DocumentHead 63

styleAnembeddedstylesheet

Syntax <head> <styletype=”text/css”> ... </style></head>

Attributes I18n,media,title,type,HTML5Only:Global,scoped

DescriptionInmostcases,it’sbesttoputyourCSSinanexternalstylesheetandlinktoit,becauseit’seasiertomanageandtakesadvantageofcachingtospeedupyourpages.ThestyleelementisforthoseoccasionswhenyouwanttoembedCSSinyourpage.Yourpagemayincludemultiplestyleelements,buttheymayappearonlyintheheadelement,exceptinHTML5(seethe“HTML5andthestyleElement”box).

IfyouweretodeinethesameCSSselectorineachofthethreestylesheetsintheexamplethatfollows,theorderinwhichtheyappeardeter-mineswhichdeinitionisappliedtothepage.Forinstance,ifthelinkedbase.cssintheexamplespeciiesp{font-size:1em;color:#333;},thentheruleinthestyleblockoverwritesthefont-sizevalue.Inturn,subpage.cssoverwritesanyconlictingp{...}propertyvaluesinbothbase.cssandthestyleblockbecauseit’slast.Theexceptionisifthemediaattributediffersonanyofthethree.Ifthestyleblockhadmedia="print"instead,itsruleswouldnotimpactbase.css,andsubpage.csswouldonlyimpactbase.css.

Part2:HTMLElementsandGuidance64

Example:

<head>

. . .

<link rel="stylesheet" href="base.css" type="text/css"

media="screen" />

<!-- overwrites conflicting rules in base.css -->

<style type="text/css" media="screen">

p {

font-size: 1.2em;

}

. . .

</style>

<!-- overwrites conflicting rules in base.css and style

element -->

<link rel="stylesheet" href="subpage.css" type="text/css"

media="screen" />

</head>

AttributesinDetail(Pleaseseethe“HTML5andthestyleElement”boxformoreattributeinformation.)n media:Thisoptionalcomma-separatedlistindicatesthemediafor

whichthestylesheetapplies.Ifyouleaveoutmedia,thevaluetypicallydefaultstoallinbrowsers,eventhoughHTML4declaresitshouldbescreen.Pleaseseethelinkelemententryinthischapterformoredetails,includinganexplanationofpossiblemediavalues.

n title="text":Thetitleattributeissupposedtobeadvisoryinthiscontext,butitdoesimpactbehaviorinsomebrowsers.Namely,ifa

Part2:HTMLElementsandGuidance Chapter3:DocumentHead 65

titleisspeciied,someversionsofChrome,Firefox,andSafaritreatthestyleblocklikeanalternatestylesheetanddon’trenderthestylesunlesstheuserselectsthealternatestylesheet.OnlyFirefoxmakesiteasytochooseit(View>PageStyle).Seethe“HTML5andthestyleElement”boxformore.So,usetitleonlyifyouintendtoimplementaJavaScriptstyleswitcher(searchonlineformoredetails).

n type:"Required."Thisattributewithavalueoftext/cssmustappearoneachstyleelement.

tip Pleaseseethelinkelementinthischapterregardingloadinganexternalstylesheet.

HTML5andthestyleElementHTML5alsoallowsstyleinsideanoscriptelementintheheadaswellasmostelementswiththescopedattributeinthedocument’sbody.

AttributesinDetail

HTML5hasanadditionalattribute,scoped,andgivestitlespecialmeaningonstyle.n scoped:UnlikeX/HTML,HTML5allowsoneormorestyleelements

inthebodyelementaslongasthisBooleanattributeispresent.Andifitispresent,itmeansthestyleelementappliestoitsparentelementandtheparent’schildnodesonly.Inthefollowingexam-ple,onlythesecondarticleelementanditschildrenreceivetherulesdeinedinthescopedstyleelement.However,mixingCSSandHTMLisnotagoodpracticeandpresentsmaintenancehead-aches,soIrecommendyouuseascopedstyleelementonlyifyouhaveaspecialcasethatcan’tbesolvedbyanexternalstylesheet.

(continuesonnextpage)

Part2:HTMLElementsandGuidance66

HTML5andthestyleElement(continued)

Example:<body>

. . .

<article><!-- this doesn’t receive padding -->

<h1>This is not affected</h1>

<p>This is not affected.</p>

</article>

<article><!-- this receives padding -->

<style type="text/css" scoped>

article { padding: 25px; }

h1 { color: blue; }

p { color: red; }

</style>

<h1>This is blue.</h1>

<p>This is red.</p>

</article>

. . .

</body>

n title:Ifatitleispresent,itdeinesthestyleelementasanalternatestylesheet.

Part2:HTMLElementsandGuidance Chapter3:DocumentHead 67

titleThedocument’stitle

Syntax <head> <title></title></head>

Attributes I18n,HTML5Only:Global

DescriptionThetitleelementdeinesadocument’stitleandmaycontainbothplaintextandcharacterentitiesbutnotmarkup.ItisrequiredforeachHTMLdocument(exceptHTML5emails)andmustbedeinedwithinadocument’sheadelement,andonlyonce.ThetitlevaluedisplaysatthetopofthebrowserwindowratherthanintheWebpage.

Thetitletextalsoservesasthebookmarktitlewhenyoubookmarkapage,unlessyouedititmanually.Asabestpractice,choosetitletextthatbrielysummarizesadocument’scontent.Thisbeneitsbothscreenreaderusersandyoursearchenginerankings(pleaseseethe“ThetitleElementandSEO”box).Secondarily,indicateyoursite’snameinthetitle.

Irecommendyougetyourtitle’scoremessageintotheirst60characters,includingspaces,becausesearchenginesoftencutthemoffintheirresultsataroundthatnumber(asabaseline).Browsersdisplayavaryingnumberofcharacters,butmorethan60,inthetitlebarbeforecuttingoffthetext.

Example:<head>

<title>Photos of the Kauai Volcano | MyVacationPics.com

➥ </title>

. . .

</head>

Part2:HTMLElementsandGuidance68

note Thetitleelementshouldnotbeconfusedwiththetitleattribute(pleasesee“Attributes”inChapter1).

ThetitleElementandSEOManydevelopers—evenwell-intentioned,fairlyexperiencedones—oftengivelittleconsiderationtothetitleelement.They’llsimplyputthenameoftheirsiteandthencopyitacrossallHTMLpages(orevenworse,leavethetitletexttheircodeeditorinsertsbydefault).However,ifoneofyourgoalsistodrivetrafictoyoursite,you’dbedoingyourselfandyourpotentialreadersahugedisservicebyfol-lowingsuit.

Searchengineshavedifferentalgorithmsthatdetermineapage’srankandhowitscontentisindexed;universally,though,titleplaysakeyrole.First,mostsearchengineslooktothetitleelementforanindicationofwhatapageisaboutandindexapage’scontentinsearchofrelatedtext.Aneffectivetitlefocusesonahandfulofkey-wordsthatarecentraltoapage’scontent.

Second,searchenginesusethetitleelementasthelinkedtitlethatappearsintheirsearchresultslistings.Ifyou’relikeme,andIsuspectthemajorityofusers,youscanthetitlesinthelistofsearchresultsirstwhenyou’retryingtodeterminewhichpageseemstomatchwhatyou’reseeking.Themoretargetedyourtitletext,themorelikelyitistoshowupintheresultsandbechosenbyauser.

SEOisadeeptopic,andIhighlyencourageyoutodomoreresearchonyourown.But,IhopethisgivesyoubothaglimpseintooneofSEO’skeycomponentsandtheincentivetocraftstrategictitleele-ments,ifyouaren’tdoingsoalready.

HTMLaffordsyouthreelisttypes:deinitionlist(dl),orderedlist(ol),andunorderedlist(ul).Iexplaineachindepthintheirrespectiveentriesinthischapter.

ListsareoneofthemostcommonlyusedsemanticelementsacrosstheWeb.Thisisparticularlytrueofunorderedlists,whichareubiquitousasthechoiceformarkingupnavigationandmanyothergroupsoflinks.

BeforeIexplaineachlist-relatedelement,I’lldiscussacapabilitythatiscommontoalllists:nesting.

Lists

4

Part2:HTMLElementsandGuidance70

NestedListsListscanbenestedwithinotherlists,asshowninthefollowingexamplethatdetailsasequencedplantorelocate.Inthiscase,it’sanorderedlistinsideanotherone,thoughyoucannestanytypeoflistwithinanyothertype(seethedlentryinthischapterforarelatednote).

<ol>

<li>Take an Italian Berlitz course.</li>

<li>Move to Italy.

<!-- Start nested list -->

<ol>

<li>Have a yard sale.</li>

<li>Pack what’s left.</li>

<li>Ship boxes.</li>

<li>Jump on plane.</li>

</ol>

<!-- end nested list -->

</li><!-- close list item containing nested list -->

<li>Say &ldquo;Ciao!&rdquo; upon landing.</li>

</ol>

Thisdisplaysbydefaultinmostuseragentsasshownhere:

1. Take an Italian Berlitz course.

2. Move to Italy.

1. Have a yard sale.

2. Pack what’s left.

3. Ship boxes.

4. Jump on plane.

3. Say “Ciao!” upon landing.

Part2:HTMLElementsandGuidance Chapter4:Lists 71

There’sonesimplebutimportantruletofollowwhennestinglists:Youmustinsertthenestedlistinsideanlielement(orddelementinthecaseofadeinitionlist)oftheparentlist.Thatis,puttingthelistalongsideaparentliorddisinvalid.

Also,althoughthisexampleshowsonlyonelevelofnesting,youcanalsonestalistinsideanestedlist(andanotherinsidethatone,adinfinitum).Forexample,Icouldnestanunorderedlist(aul,asyou’llrecall)inthe“Packwhat’sleft”litolistallitemstopack,irrespectiveofpackingorder.

dd

Adeinitiondescription

Syntax <dd></dd>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsetheddelementtodescribeacorrespondingterm(dt)inadefinitionlist(dl).Theddfollowsthedtandmaycontainblock-levelcontent,suchasparagraphs(p),orderedlists(ol),unorderedlists(ul),anotherdeini-tionlist,andmore.

note Ifyourddcontentislongerthanoneparagraph,nestpsintheddratherthansplittingthetextamongmultipleddswithoutps.

Part2:HTMLElementsandGuidance72

Example:

<h2>1936 Summer Olympics 100m Men’s Results</h2>

<dl>

<dt>Gold medal winner</dt>

<dd>Jesse Owens (USA)</dd>

<dt>Silver medal winner</dt>

<dd>Ralph Metcalfe (USA)</dd>

<dt>Bronze medal winner</dt>

<dd>Tinus Osendarp (NED)</dd>

</dl>

Thesimplestarrangementwithinadlisonedtgroupedwithonedd,asshowninthepreviousexample.(I’veseparatedeachgroupwithablanklineforclarity;itdoesn’timpacttherendering.)Thedlentryinthischapterelaboratesontheseandotherconigurations,deinitionlistsingeneral,andtheroleofdd.

Useragentstypicallyrenderadeinitionlistbydefaultlikeso(althoughyoucanchangeitwithCSS):

Gold medal winner

Jesse Owens (USA)

Silver medal winner

Ralph Metcalfe (USA)

Bronze medal winner

Tinus Osendarp (NED)

Part2:HTMLElementsandGuidance Chapter4:Lists 73

dl

Adeinitionlist

Syntax <dl> <dt></dt>

<dd></dd>

. . .

</dl>

Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsethedefinitionlist(dl)todeineaterm(representedbyoneormoredtelements)anditsdescription(representedbyoneormoreddelements).Thedtmaycontaininlinecontentonly,whileaddmaycontainblock-levelcontent.

Thoughit’sanaturalitfordeiningwordslikeinadictionary,thedlisnotconstrainedtosuchnarrowusage.Asyouwillsee,thereissomelevityconcerningwhatconstitutesatermandadescription,aswellasdifferingopinionsaboutwhatis“legal.”

note Avoidusinga

dltomarkupdialogue(seethe“WhenCanYouUseaDefinitionList?HTML4MurkinessandHTML5Clarification”boxfor

moreinformation).

Thefollowingareseveralexamplesofhowtouseadeinitionlist.

Part2:HTMLElementsandGuidance

74

Example1:

<dl>

<dt>Boris Karloff</dt>

<dd>Best known for his role in <cite>Frankenstein</cite>

and related horror i lms, this scaremaster’s real name

was William Henry Pratt.</dd>

. . .

</dl>

note Adefinitionlistneednothavemorethanonedtandddgrouptoconstitutealist.

Example1isabasicdl.Allofthefollowingarrangementsarevalidforagroupofdtandddelementswithinadl:n Asingledtgroupedwithasingledd,asinthepreviousExample1

andasDirectorinthefollowingExample2.Thisisthemostcommonoccurrence.

n Asingledtgroupedwithmultipledds.SeeWritersinExample2.n Multipledtsgroupedwithasingledd.SeeExample3.n

Multipledtsgroupedwithmultipledds.SeethenotethatfollowsExample3.

Example2showstheirsttwoofthesebywayofalistofcreditsforthemovieAmélie(forallyouFrenchmoviefanatics).Italsodemonstrateshowtouseanesteddeinitionlist.

Part2:HTMLElementsandGuidance Chapter4:Lists 75

Example2:

<h3>Credits for <cite>Am&eacute;lie</cite></h3>

<dl>

<dt>Director</dt> <!-- Single dt with single dd -->

<dd>Jean-Pierre Jeunet</dd>

<dt>Writers</dt> <!-- Single dt with multiple dds -->

<dd>Guillaume Laurant (story, screenplay)</dd>

<dd>Jean-Pierre Jeunet (story)</dd>

<dt>Cast</dt>

<dd>

<!-- Start nested list -->

<dl>

<dt>Audrey Tautou</dt> <!-- Actor/Actress -->

<dd>Am&eacute;lie Poulain</dd> <!-- Character -->

<dt>Mathieu Kassovitz</dt>

<dd>Nino Quincampoix</dd>

. . .

</dl>

<!-- end nested list -->

</dd>

. . .

</dl>

note Iincludedtheblanklinebetweeneachgroupof

dtandddelementssoyoucouldseethegroupingsmoreexplicitly.It’snotrequiredinadefi-

nitionlistanddoesn’timpactitsrenderinginauseragent,soit’sentirelyuptoyouasanHTMLauthorwhethertoincludeit.

Part2:HTMLElementsandGuidance76

Useragentstypicallyrenderadeinitionlistbydefaultasshownnext(butyoucanalteritwithCSS).Notehowtheddtextinthenestedlistisindentedanotherstep.

Director

Jean-Pierre Jeunet

Writers

Guillaume Laurant (story, screenplay)

Jean-Pierre Jeunet (story)

Cast

Audrey Tautou

Amélie Poulain

Mathieu Kassovitz

Nino Quincampoix

Nowlet’slookatanotherexample.Althoughyoushouldn’trepeatthesamedtvalueinadl(forexample,Writersappearsonlyonceinthepreviousexample),youmayhavemultipledtsgroupedwithasingledd,asImentionedearlier.

Example3:

<h2>Deining words with multiple spellings</h2>

<dl>

<dt><dfn>bogeyman</dfn>, n.</dt> <!-- Multiple dts with

single dd -->

<dt><dfn>boogeyman</dfn>, n.</dt>

<dd>A mythical creature that lurks under the beds of small

children.</dd>

Part2:HTMLElementsandGuidance Chapter4:Lists 77

<dt><dfn lang=”en-gb”>aluminium</dfn>, n.</dt>

<dt><dfn>aluminum</dfn>, n.</dt>

. . .

</dl>

tip

NoticethatIusedthelangattributeheretodenotethataluminiumisintheBritishversionofEnglish.

Thisexampleusesadeinitionlisttodeinetermslikeinadictionary(themosttraditionaluseforadl).You’llnoticeIwrappedthetermsinadfnelement.Youmightthinkthisisredundant,butitcanbeappropriateifit’sconsistentwiththeproperusageofdfn.(PleaseseethedfnentryinChapter5formoredetails.)ThisapproachisencouragedbyHTML5asawaytodistinguishadlusedtodeinewordsindictionaryorglossaryformatfromadlusedforotherappropriatemeanslikeourmoviecredits.Althoughyou’reunlikelytoindreferencestothisapproachelsewhereforHTML4,too,Ithinkit’sappropriate.

note Anexampleofmultiple

dtsgroupedwithmultipleddswouldbeifinExample3bogeyman/boogeymanhadaseconddefinition.Seethedt

entryinthischapterforarelatedexample.

DeprecatedAttributesn compact:ObsoleteinHTML5.Thisattributeispresentationalinnature

sowasdeprecatedinfavorofusingCSS.Pleaseseetheolentryinthischapterformoreinformation.

Part2:HTMLElementsandGuidance78

WhenCanYouUseaDeinitionList?HTML4MurkinessandHTML5Clariication

HTML4hasbeencriticized,andrightfullyso,forbeingalittleunclearinitsdeinitionofthedeinitionlist.Ironic,yes.Asaresult,thedl’susehasbeenopentointerpretation.

Puristsarguethatitshouldbeusedonlyfordeiningtermslikeinadictionaryorglossary.However,HTML4doesnotdeinethedlsostrictly.Itopensthedoortootherusesbyreferringtotheddasa“description”ratherthana“deinition”andbypresentinganalterna-tiveusageformarkingupdialogue,thoughmostagreethatapplica-tionisill-advised.(Idon’trecommendit,andHTML5doesn’tallowit;pleasealsoseethe“HTML5,thedlElement,andDialogue”box).

Others—whatseemslikethemajority—thinktheconceptoftheterm–descriptionrelationshipisnotintendedtobequitesorigidandisanappropriatesemanticchoiceformarkingupothercontentifincontext,suchastheearliermoviecreditsexample.

NoHTMLspeciicationwillbeabletoaccountforeveryusecaseforstructuringcontent,atleastnottoeveryone’ssatisfaction.Forthemostpart,thewaysinwhichdevelopershaveusedthedeinitionlistbeyonddictionary-likedeinitionsarosefromadesiretouseseman-ticmarkupincaseswhereabetteralternativewaslacking.HTML5recognizesthisaswell,providingahandfulofexampleusagesthatrangefromglossarydeinitionstoauthor–editorlistingstometainformationandmore.

So,howfardoyougowithadeinitionlist?Myadviceistoalwaysconsidertheintentofadl—deiningcontentthathasaterm–descriptionrelationship.Useyourbestjudgmenttodeterminewhetheryourcontentitsthismodel.

Part2:HTMLElementsandGuidance Chapter4:Lists 79

note Unliketheotherlisttypes,the lielementmaynotbepartofadefini-tionlistunlessitispartofanorderedorunorderedlistnestedinadd.

HTML5,thedlElement,andDialogueAsnotedinthepreviousbox,HTML4declaresthatadlmayalsobeusedtomarkupdialogue,suchasfromaplay.DespitetheW3C'sendorsement,thisusagehasnotgainedwidespreadapprovalfromthedevelopmentcommunity,becausemanythinkitdeviatestoofarfromtheintentofadeinitionlist.Indeed,HTML5acknowledgesthisbyexplicitlydeclaringthat“Thedlelementisinappropriateformarkingupdialogue.”

Still,thereisn’taperfectsolutionfordialogueineitherHTML4orHTML5.TherecommendationinHTML5involvingbandspanisquestionableandhasalreadyreceivedpushbackfromsomeinthecommunity.Thoseconcernsandaproposedalternative(withitsownissues)arediscussedathttp://24ways.org/2009/incite-a-riot.

dt

Adeinitionlistterm

Syntax <dt></dt>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsethedtelementtodenoteaterminadeinitionlist(dl).Thetermisdescribedbyatleastonecorrespondingddelementthatfollowsthedt.Pleasenotethatadtmaycontaininlinecontentonly.

Part2:HTMLElementsandGuidance80

Thesimplestarrangementwithinadlisonedt(term)groupedwithonedd(description).Anotherpossibilityisshowninthefollowingexample,withonedtassociatedwithmultipleddssincedirectorcanbedeinedinmanyways.Thedlentryinthischapterelaboratesontheseandotherconigurations,deinitionlistsingeneral,andtheroleofdt.

Example:

<dl>

<dt><dfn>director</dfn></dt>

<dd>One who directs</dd>

<dd>One who oversees a group or an organization</dd>

<dd>One who leads all aspects of the creation of a i lm</

➥ dd>

. . .

</dl>

Mostuseragentstypicallyrenderadeinitionlistbydefaultasshownhere,exceptfortheitalicsondirector,whichisbecauseofthedfnelement:

director

One who directs

One who oversees a group or an organization

One who leads all aspects of the creation of a fi lm

tip

Youmightbewonderingwhydirectoriswrappedinadfnelement.Isn’tthedtsufficienttoindicateit’saterm?Itdependsonthecontext.

Yes,adtdoesdenoteaterm,butadfnhasamorespecificmeaning,andinthecontextofadt,dfnindicatesthelistisdefiningtermslikeadictionaryorglos-sarydoes.PleaseseethedlentryinthischapterandthedfnentryinChapter5formoreinformationandexamples.

Part2:HTMLElementsandGuidance Chapter4:Lists 81

liAlistitem

Syntax <li></li>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsethelielementtospecifyeachlistiteminbothorderedandunor-deredlists.Itcannotbeusedonitsownorinanelementbesidesanolorul(ormenuinHTML5).Anlimaycontainbothblock-levelandinlinecontent,includingdiv,span,a,p,allotherlisttypes,andmore.

Examples:

<h4>Sequence of Events before Heading out Tonight</h4>

<ol>

<li>Stretch</li>

<li>Run ive miles</li>

<li>Shower and dress for dinner</li>

</ol>

<h4>Items to Buy for First Grade</h4>

<ul>

<li>Notebooks</li>

<li>Pencils</li>

<li>Eraser</li>

</ul>

Pleaseseetheolandulentriesinthischapterformoreinformationaboutliforeachlisttype.

Part2:HTMLElementsandGuidance82

DeprecatedAttributesThefollowingattributesaredeprecatedinX/HTML:n type:ObsoleteinHTML5.Thisattributeispresentationalinnatureso

wasdeprecatedinfavorofusingCSS.Pleaseseetheolentryinthischapterformore.

n value:ThereisnoequivalentreplacementinX/HTML.Pleaseseethe“HTML5andtheliElement”boxformoreinformationregardingHTML5.

HTML5andtheliElementHTML5reintroducesthevalueattributeandincludesanewelement,menu,thatusesli.

AttributesinDetailn value="number":Thevalueattribute,whichisdeprecatedin

HTML4,isavalidattributeinHTML5aslongastheliisachildofanol.Inthiscontext,valuespeciiestheordinalvalueofitslistitemandadjuststhevalueofeachsubsequentitemaccordingly.Itsvaluemustbeavalidinteger.Forinstance,imaginealistofresultsinwhichthereisatieforthirdplace.Example:

<h3>Class President Voting Results</h3>

<ol>

<li>Hannah Carson (64)</li>

<li>Stefan Rios (51)</li>

<li>Kyla Wong (47)</li> (continuesonnextpage)

Part2:HTMLElementsandGuidance Chapter4:Lists 83

HTML5andtheliElement(continued)

<li value=”3”>Delores Cardinal (47)</li>

<li>Michael McMurtry (44)</li>

</ol>

Thislistrendersasfollows:1. Hannah Carson (64)

2. Stefan Rios (51)

3. Kyla Wong (47)

3. Delores Cardinal (47)

4. Michael McMurtry (44)

Noticethatboththethirdandfourthitemsarenumbered“3.”andtheifthitemisnumbered“4.”Thesameprincipleappliesifyoudeineyourlistmarkersasnon-numericvalueswithCSS.Forexample,withlist-style-type: upper-roman;set,ourexamplewouldshow“iii.”twice,followedby“iv.”

ThemenuElement

liisanoptionalchildofthenewmenuelementandisnotwrappedineitheranoloranulinthiscontext.PleaseseethemenuentryinChapter15formoreinformation.

Part2:HTMLElementsandGuidance84

olAnorderedlist

Syntax <ol> <li></li>

. . .

</ol>

Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUseanorderedlist(ol)todeinealistofitemsforwhichthesequenceisimportanttothelist’smeaning.Forexample,youmightwanttolistarankingofyourfavoritesongs,detailthestepsinarecipe,orprovidedrivingdirectionsfromonepointtoanother.Eachlistitemisrepresentedbyalielement,whichcancontaineitherblock-levelorinlinecontent.

Example:

<h2>Directions to Birthday Party from Town Hall</h2>

<ol>

<li>Head north on Hill Street for a quarter mile.</li>

<li>Bear right at the fork onto Elm Street and continue

for a mile.</li>

<li>Turn left onto Glass Drive; it’s the last house on the

left.</li>

</ol>

Part2:HTMLElementsandGuidance Chapter4:Lists 85

Typically,mostuseragentsrenderanumberasthedefaultmarkerbeforeeachlistitem,likeso:

1. Head north on Hill Street for a quarter mile.

2. Bear right at the fork onto Elm Street and continue for a mile.

3. Turn left onto Glass Drive; it’s the last house on the left.

Youcancontrolwhattypeofmarkerappearswiththelist-style-typeCSSproperty(don’tusethedeprecatedHTMLtypeattribute).Optionsincludeletters,Romannumerals,bullets(yes,evenonanorderedlist,thoughitisn’trecommended),images,nomarkeratall,andmore.Ifyou’recuriousabouttheoptions,theCSS2.1Speciicationdetailsthemathttp://www.w3.org/TR/CSS21/generate.html#lists.

Aswithdeinitionlists(dl)andunorderedlists(ul),youmaynestalltypesoflistsinsideanorderedlist,andviceversa.Pleaseseethe”NestedLists”sectionearlierinthischapterformoreinformationaboutnestingandanexampleusingorderedlists.

Mostimportant,remembertouseanolonlyifit’sappropriatetodescribethesemanticsofyourcontent,notjustbecauseyouwantnumbersoranothersequencedmarkerbeforeyourcontent(thoughthetwotypicallygohandinhand).

tip

Ifoundthishandytiponline.Agoodwaytodeterminewhetheranorderedlistoranunorderedlististhecorrectsemanticchoiceistoask

yourselfwhetherthemeaningofyourlistwouldchangeifyoushuffledtheitemsaround.Iftheanswerisyes,useanol.Pleaseseethedlandulentriesinthischapterforinformationaboutotherlisttypes.

Part2:HTMLElementsandGuidance86

RecommendedUsesAsidefromsomeoftheobvioususesI’venoted,anorderedlististheproperchoiceformarkingupbothbreadcrumbandpaginationnavigation.

Breadcrumbnavigation.Breadcrumbnavigationistheseriesoflinksyou’lloftenseeabovethecontenton,say,ane-commercesitetoindicatethenavigationpathtothepageyou’reviewing.Abreadcrumbisoftendisplayedlikethisexample,withthepageyou’reondisplayedbutnotlinked:

Home > Products > Outdoors > The Garden Weasel

Anorderedlistmakessenseforthisbecauseabreadcrumbrepresentsadistinctsequenceoflinks.

Paginationnavigation.Paginationnavigationisthehorizontallistofmostlynumericlinksyou’reprobablyusedtoseeingone-commerceandnewssites,allowingyoutopaginatethroughlistsofproductsortoaddi-tionalpageswithinanarticle.

tip YoucanturnoffthemarkersinyourCSSwiththis:ol {

list-style-type: none;

}

DeprecatedAttributesThefollowingattributesaredeprecatedinX/HTML.Whereapplicable,I’vedescribedthemethodthathasreplacedtheattributeandthatrepli-catesitspurpose.n compact:ObsoleteinHTML5.Sincethisattributeispresentationalin

nature(andnevergainedwidesupportanyway),usetheCSSmargin, padding,andline-heightCSSpropertiesinsteadtoadjustthespac-ingbetweenlistitemsandmakethelistmorecompact.

Part2:HTMLElementsandGuidance Chapter4:Lists 87

n start:Pleaseseethe“HTML5andtheolElement”boxformoreinformation.

n type:ObsoleteinHTML5.Asnotedearlierinthechapter,usetheCSSlist-style-typepropertyinsteadofthetypeattributetocontroleachlistitem’smarkerstyling.Forinstance,thefollowingruledictatesthatallorderedlistsdisplayanuppercaseRomannumeralbeforeeachlistitem:ol {

list-style-type: upper-roman;

}

HTML5andtheolElementHTML5deinestwoadditionalattributesfororderedlists:startandreversed.

AttributesinDetailn start="number":Thestartattribute,whichisdeprecatedinHTML

4,isavalidattributeinHTML5.startspeciiesthatanorderedlistbeginsatanumber(ornon-numericcharacterdependingonyourstylesheet)otherthanthedefault,whichis“1.”Itsvaluemustbeavalidinteger,evenifthemarkertypeyou’vespeciiedinyourCSSisnotnumeric,likeupper-roman,shownearlier.Forexample,start=”4”woulddisplayas“IV.”Example:

<ol start=”5”>

<li>Preheat oven to 350 degrees</li>

<li>Grease pan</li>

<li>Mix ingredients in a large bowl</li>

</ol>

(continuesonnextpage)

Part2:HTMLElementsandGuidance88

HTML5andtheolElement(continued)Thisrendersasfollows:

5. Preheat oven to 350 degrees

6. Grease pan

7. Mix ingredients in a large bowl

Ifyouhadspeciiedyourmarkeraslower-roman,thenitwouldbeginwith“v.”instead.

n reversed:HTML5introducesthenewreversedBooleanattribute,whichyouusetoindicateadescendinglist.(See“Attributes”inChapter1formoreaboutBooleanattributes.)Example:<h2>Countdown of the World’s Three Coldest Locations</h2>

<ol reversed=”reversed”>

<li>Oymyakon, Russia</li>

<li>Plateau Station, Antarctica</li>

<li>Vostok, Antarctica</li>

</ol>

<p><cite>http://www.aneki.com/coldest.html</cite></p>

Thislistrendersasfollows:3. Oymyakon, Russia

2. Plateau Station, Antarctica

1. Vostok, Antarctica

TheXHTML5syntaxis<ol reversed=”reversed”>.YoumayuseitinHTML5documentsaswellifyoupreferitoverHTML5’s<olreversed>shortenedformat.Pleasealsoseethelientryinthischapterforadiscussionoftherelatedvalueattribute.

Part2:HTMLElementsandGuidance Chapter4:Lists 89

ulAnunorderedlist

Syntax <ul> <li></li>

. . .

</ul>

Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUseanunorderedlist(ul)todeineagenericlistforwhichthesequenceofitemsisnotimportant.Eachlistitemisrepresentedbyalielement,whichcancontaineitherblock-levelorinlinecontent.

TheulisontheshortlistofthemostcommonlyusedelementsontheWebbecauseitissemanticallyappropriateforawidevarietyofcontent(see“RecommendedUses”).

Let’stakealookatasimpleexampleintheformofashoppinglist.

Example:

<ul>

<li>A bag of lour</li>

<li>Carrots</li>

<li>Fresh fruit</li>

</ul>

Typically,mostuseragentsrenderabulletbeforeeachlistitembydefault,likeso:

Part2:HTMLElementsandGuidance90

•Abagofflour

•Carrots

•Freshfruit

However,thefactthatalistmayhavebulletsisn’timportant;it’swhetheryourcontentcallsforanunorderedlistsemantically.CSSprovidesyoufullcontrolovertheformatting,allowingdifferenttypesofbullets,images,nomarkeratall,andmore.

tip Youcanmakesequentialnumbersappearaslistitemmarkerswiththis:ul {

list-style: decimal;

}

Usethisonlyifyourcontentisappropriateforanunorderedlistandnotanorderedlist.Forexample,youmightpostalistwiththeheading“TenTofuDishesICan’tLiveWithout(innoparticularorder),”andyouwanttoshowdeci-malstoreinforcethatthelistdoes,infact,includetenitems.

tip

Ifoundthishandytiponline.Todeterminewhetheranorderedlistoranunorderedlististhebestsemanticchoice,askyourselfwhetherthe

meaningofyourlistwouldchangeifyoushuffledtheitemsaround.Iftheanswerisno,useaul;otherwise,useanol.

RecommendedUsesHerearejustafewofthemanywaysinwhichunorderedlistsareutilized:

Navigation.Whetherit’sforglobalnavigation,agroupoffooterlinks,oranywhereinbetween,theulisthedefactostandardformarkingupsitenavigation.(Pleaseseetheolentryforacoupleexceptions.)

Tabs.Thisformofnavigationtypicallyappearsacrossthetopofamodule.

Productgridsandcarousels.Thesearetypicallydisplayedhorizontally.

Part2:HTMLElementsandGuidance Chapter4:Lists 91

Articleheadlinelists.Theseoftenappearonahomepagetosurfacelinkstorecentarticlesoronanarticlesubpageasrelatedlinks.Viewsourceonyourfavoritenewssites,andyou’relikelytoseegroupsoflinkstoarticlesformattedinaul.

Relatedvideolists.Thesetypicallyhaveathumbnailimageandatitleanddescription.

DeprecatedAttributesn compactandtype:ObsoleteinHTML5.Theseattributearepresenta-

tionalinnaturesoweredeprecatedinfavorofusingCSS.Pleaseseetheolentryinthischapterformoreinformation.

OntheWeb,contentisking,andinmostcasesyourcontentistext.

Thischapterfocusesontheelementsusedtomarkupyourcarefullycraftedprose,links,codesamples,references,andmoreinordertoenrichthesemanticsofyourcontent.That,inturn,pleasesbothscreenreadersandsearchengines,anditaffordsyoupresentationalcontroloveryourcontentviaCSS.

Asyou’llsee,therearealotofelementscoveredinthischapter.You’lllikelyuseonlyahandfulregularly—suchasa,p,em,andstrong—butIreallyencourageyoutobecomefamiliarwiththeothers.Youmayindtherearesomeelementsyoushouldhavebeenusingallalong.citeisjustoneexampleofahiddengem.Andifyou’reworkingonanHTML5site,besuretocheckoutthischapter’scompanion,Chapter12,whichfocusesontextelementsuniquetoHTML5.

Text

5

Part2:HTMLElementsandGuidance94

aAnanchor

Syntax <a></a>Attributes Core,I18n,Events,accesskey,charset*,coords*,href,hreflang,name*,rel,rev*,shape*,tabindex,target*,type,HTML5Only:Global

DescriptionThea(“anchor”)elementisessentialtotheWeb,providingthemeanstocreateahyperlinktoanotherpageorserveasananchorwithinapagetowhichahyperlinkpoints.Youmaywrapanaelementaroundtextoranimagebutnotaroundablocklevelelement,suchasapordiv(thisisallowedinHTML5,though;seethe“HTML5andtheaelement”box).

Youmaylinktoavarietyofresources:anotherpage(.html,.php,andsoon),ananchorwithinapage,adocumentsuchasaPDF,animage,ane-mailaddress,andmore.Thehrefattributeprovidesthelinkpathandtakesonmanyforms.

Example1(simplelinktoanotherresource):

<!-- link within the same folder -->

<p>Africa has numerous inspiring areas to <a href=”parks-and-

➥ reserves.html”>experience animals in the wild</a>.</p>

<!-- link to another site -->

<p>. . . <a href=”http://en.wikipedia.org/wiki/Norway”

title=”History, geography, culture and more”>Norway on

Wikipedia</a> . . .</p>

Part2:HTMLElementsandGuidance Chapter5:Text 95

Theoptionaltitleattributetypicallydisplaysasatooltipandmaybereadbyascreenreader.Asyounodoubtknow,browsersunderlineanddisplaylinksinadifferentcolorthanstatictextbydefault,likeso:

Africa has numerous inspiring areas to experience animals in the wild.

Forsimplicity’ssake,I’llshowonlytheaelementinmostoftheremain-ingexamples,butinpractice,besureeachoneiswrappedinablock-levelelement,suchasap.

Drilldownfromthecurrentpagelocationtoasubfolderbyincludingtheproperpath.Example2drillsdowntoproductsandthentoshoes.

Example2(linktosubpage):

. . . <a href=”products/shoes/basketball.html”>basketball

shoes</a> . . .

Conversely,use../tolinktoaresourceonefolderlevelupfromthecurrentpage.Ifyouuse../../,thelinkpointstwolevelsup,andsoon.

Example3(linkupalevelortwo):

. . . <a href=”../ozzie.html”>Pictures of Ozzie</a> . . .

<!-- Up two levels and down one -->

. . . <a href=”../../organic/salads.html”><img src=”salad.jpg”

width=”200” height=”200” alt=”organic salad” /></a> . . .

Eachofthoseexamples(excepttheonelinkingtoWikipedia)hasarela-tivepath,meaningtheyarerelativetothelocationofthelinkingdocu-ment.Althoughyoucanlinkthroughoutyoursitewiththosemethods,anabsolutepathisoftenyourbestchoice.Itbeginswith/,whichpointstothesite’sroot,andthenyoudrilldownfromthere.Consequently,itdoesn’tmatterwherethelinkingdocumentlivesinthedirectoryhierar-chy,becausethelinkwillalwayswork.

Part2:HTMLElementsandGuidance96

Forinstance,thepagecontainingthelinkinExample4couldbeoneleveldeeporadozen,butthelinkwouldbethesame.

Example4(linkwithabsolutepath):

. . . <a href=”/products/shoes/basketball.html”>basketball

shoes</a> . . .

Linkingtoane-mailaddressisequallysimple.Justpreixthee-mailaddresswithmailto:.Thelinkwillopentheuser’se-mailclientifheorshehasoneinstalledandpopulatetheTo:ieldwiththeaddress.

Example5(linktoe-mailaddress):

. . . <a href=”mailto:slee@yourdomain.com”>contact Sean Lee

➥ </a> . . .

Ifyoudeineananchororelementwithid=”cheetahs”,youmaylinkdirectlytothatportionofthepagebyassigning#plustheidtothehref,asinExample6.(Tolinktoananchoronanotherpage,includetheile-name,asinhref=”big-cats.html#cheetahs”.)

Example6(linktoanchor):

<!-- links from here -->

<p>Visit Africa to <a href=”#cheetahs”>experience cheetahs in

the wild</a>.</p>

<!-- to here in the current document (Approach #1) -->

. . .

<h2><a href=”#cheetahs” id=”cheetahs”></a>Experience Cheetahs

➥ </h2>

. . .

Part2:HTMLElementsandGuidance Chapter5:Text 97

Thisisanalternativeapproach:

<!-- to here in the current document (Approach #2) -->

. . .

<h2 id=”cheetahs”>Experience Cheetahs</h2>

. . .

Bothapproachesworkacrossbrowsers—thepagejumpstothatpoint—butneitherisperfectfromausabilitystandpoint.Inthesecondone,ifyounavigatewiththeTabkeyinInternetExplorerafternavigatingtotheh2,itjumpsyoutotheirstlinkonthepageratherthantheirstlinkaftertheh2.

Theirstapproach,althoughalittlecumbersome,ensuresInternetExplorer’stabbingordercontinuesfromtheanchorasmostuserswouldexpect.But,itaddsalinkthatdoesnothing.(Noteyoucouldalsowrapthelinkaround“ExperienceCheetahs.”)

Meanwhile,Chrome’stabbingmisbehavesregardless,dependingonyourpointofview.Itignoresyourcurrentpositioninthepage,sopressingTabtakesyoutotheirstlinkafterthelastoneyouactivated,notaftertheidanchortowhichyou’vejumped.

AttributesinDetailAlllavorsofHTMLsharethefollowingaattributesunlessotherwisenoted.(Pleaseseethe“HTML5andtheaElement”boxforadditionalattributesspeciictoHTML5.)n accesskey:Pleasesee“Attributes”inChapter1fordetails.n charset:*ObsoleteinHTML5.Thisspeciiesthecharacterencodingof

thelinkdestination.Pleasesee“CharacterEncoding”inChapter1formoredetails.Thisistypicallyomitted.

Part2:HTMLElementsandGuidance98

n coordsandshape:*ObsoleteinHTML5.Thesetwoattributesdeineaclient-sideimagemapthatusestheobjectelement.However,browsersupportofobjectclient-sideimagemapsisextremelypoor(FirefoxandOpera9.2andneweronly),sousethemapelementinstead(pleaseseemapinChapter6).

n href=”uri”:ThemostpowerfulattributeontheWeb,hrefdeinesthelinkdestination.Pleaseseethepreviousexamples.

n hreflang=”langcode”:Thisindicatesthebaselanguageofthehref’sdestination,muchinthewaythelangattributespeciiesthelanguageofotherHTMLelements.Hence,youmayusehreflangonlywhenhrefispresent.

n name="cdata":*DeprecatedinXHTMLbutvalidates.*ObsoleteinHTML5.Thisprovidestheanchorwithauniquenamesoyoucanlinktoitfromanothera.Itmustbeuniquewithinapage,anditsharesanamespacewithid.ThenameattributeisavestigeofearlierversionsofHTML,andidhasreplaceditastheattributetouse(seeExample6).

n rel="link-types"andrev="link-types":*revisobsoleteinHTML5.relandrevhaveoppositemeaningsandareusedinconjunctionwithhref.Therelattributeindicatestherelationshipfromthecurrentdocumenttothelinkedresource.rev(“reverse”)indicatestherelation-shipfromthelinkedresourcetothecurrentdocument;historically,it’sbeenmisunderstoodandrarelyused,whichiswhyit’snotincludedinHTML5.Thefollowingexamplesillustratetheirdifferences:<!-- rel specifies that 04-giraffes.html is a chapter of

the book of which the current document is a part -->

<p>Learn that and more in <a href="04-giraffes.html"

rel="chapter">Giraffes</a>.</p>

<!-- rev specifies that the current page is an appendix,

NOT that chapter-14.html is -->

Part2:HTMLElementsandGuidance Chapter5:Text 99

<p>As stated earlier, <a href="chapter-14.html"

rev="appendix">tofu is delicious</a>.</p>

Eachrelandrevvaluemustbeaspace-separatedlist.Forinstance,inthepreviousexample,rel="chaptersection"wouldindicatethehrefpointstoasectionwithinachapter.Pleasesee“LinkTypes”inChapter1forthelistofdeinedvalues.Youdonothavetoincluderelorrevoneachanchor(includingoneorbothisfarlesscommonthannot),becauseifeitherisundeined,isleftblank,orcontainsavaluetheuseragentdoesn’trecognize,norelationshipisdeined.Thelinkstillfunctions,though.

n tabindex:Pleasesee“Attributes”inChapter1fordetails.n target:*NotvalidwithStrictX/HTMLDOCTYPEs.targetspeciiesthe

nameoftheframeoriframeinwhichthelinkshouldopen.Ifthenamedoesn’texist,thelinkopensinawindow.HTMLprovidesfourspecialtargetnameswithspeciicbehavior:_blank(linkopensinanew,unnamedwindow),_self,_parent,and_top.PleaseseetheframesetelementinChapter10formoredetails.targetisnotdepre-catedinHTML5,butitmaynotreferenceaframeelementsinceframesdon'texistinHTML5.BeginningauthorsoftenwonderhowtoopenalinkinanewwindowwhileusingaStrictDOCTYPE,sincetargetisn’tallowed.Letmepref-acethisbysayingthatit’sbestnottoopenalinkinanewwindow,becauseyouwanttoleavethatdecisionuptotheuser.Butforthosetimeswhenyoumust,youcanimplementitwithJavaScript.Oneapproachusesrel=”external”ontheaasahookforthescript.YoucanindJavaScriptforitbysearchingonline.Nomatteryourmethod,Irecommendyouaddtitle=”Opensexternalsiteinnewwindow”orasimilarmessagetoeachrelevantlinkasacuetousers.Additionally,

Part2:HTMLElementsandGuidance100

useCSStoplaceaniconnexttoeachlinksousersknowataglancethelinkbehavesdifferently.

n type=”content-type”:Tellstheuseragentthecontenttypeofthecontentatthelink’sdestination.Itisonlyadvisory.

HTML5andtheaelementHTML5introducesafewchangestotheaelement.

aasPlaceholder

Ifadoesn’thavethehrefattribute,itrepresentsalinkplaceholder.Forexample,youcouldpopulatetheadynamicallywithJavaScriptbasedonuserbehavior.

WrapaAroundNearlyAnyElement

InabigandextremelyusefuldeparturefrompreviousversionsofHTML,HTML5allowswrappinganaaroundmostelements,includ-ingparagraphs,lists,andmore.Forexample,thefollowingisvalidHTML5,makingboththeh1andh2textanactivelink:

<a href=”giraffe-escapes.html”>

<hgroup>

<h1>Giraffe Escapes from Zoo</h1>

<h2>Animals worldwide rejoice</h2>

</hgroup>

</a>

Theonlylimitationisthatacannotcontainelementsclassiiedasinteractivecontent,suchasotherlinks,theaudio,video,details,form,iframeelements,andmore(they’remostlycommonsense).Thevalidatorwilltellyouwhenyou'vegoneastray.

(continuesonnextpage)

Part2:HTMLElementsandGuidance Chapter5:Text 101

HTML5andtheaelement(continued)

AttributesinDetail

HTML5includestheseadditionalattributes:n media:Thisattributedescribesthemediaforwhichthehrefdes-

tinationresourcewasdesigned(justlikethemediaattributewhenusinglinktoloadastylesheet).Itisonlyadvisory.Thevalueis“all”ifmediaisomitted;otherwise,itmustbeavalidmediaquerylistfromtheMediaQueriesspeciication(http://www.w3.org/TR/2009/CR-css3-mediaqueries-20090915/#syntax).mediaisallowedonlyifhrefispresent.

n ping:pingfacilitatestrackinguserbehaviortogatheranalytics.Itspeciiesaspace-separatedlistofURLs(oneisine,too)thattheuseragentshouldnotifyiftheuserfollowsahyperlink.Typically,thiswouldbeaserver-sidescriptthatlogstheuser’saction.pingisallowedonlyifhrefispresent.Historically,developershaveusedothertrackingmethods,butthey’retypicallyhiddenfromtheuser.Useragentssupportingpingallowonetodisableit,puttingtrackingincontroloftheuserwhereitbelongs(ifyou’reamarketer,youmightdisagree!).Andpingimprovesperformancebyeliminatingtheadditionalover-headofothermethods(somerequiremoretripstotheserverand/orloadextraJavaScript).

Part2:HTMLElementsandGuidance102

abbrAnabbreviation

Syntax <abbr></abbr>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsetheabbrelementtomarkupanabbreviation,suchasJr.forJunior,UKforUnitedKingdom,andB.S.forBachelorofScience.abbrisoftenconfusedwiththeacronymelement,whichisalsofeaturedinthischap-ter.Pleaseseehttp://www.htmlfiver.com/extras/abbr-acronym/formorediscussionofthedifferencebetweenthetwo.

Example1:

<p>They wake up at 7 <abbr>a.m.</abbr> and go to bed at 9

<abbr>p.m.</abbr> every day.</p>

<p>They listen to games via the online <abbr title="Major

League Baseball">MLB</abbr> Gameday Audio service.</p>

Notetheuseoftheoptionaltitleattributetoprovidetheexpansionoftheabbreviation.titleimprovesaccessibility,sinceausercanconigureascreenreadertoannouncethetext,anditalsoappearsasatooltipwhenthemousepointerisontheabbr.

Alternatively,ifyouwanttomaketheexpansionevenmoreaccessibleandexplicit,aswellassupportprintingitinallbrowsers,youcanplaceitinparenthesesinsteadofinthetitle,asshowninExample2.

Example2:

<p>They listen to games via the online <abbr>MLB</abbr>

(Major League Baseball) Gameday Audio service.</p>

Part2:HTMLElementsandGuidance Chapter5:Text 103

RenderingofabbrandacronymUseragentstypicallydon’tdisplayabbroracronymtextdifferentlythanothertextbydefault,thoughsomesuchasFirefoxandOperadoshowadottedbottomborder(underline)ifyoudeineatitle.Thisactsasavisualcuetosightedusersthatatooltipisavailable.YoumayreplicatethiseffectinothermodernbrowserswiththisbitofCSS:

/* show underline when a title is provided */

abbr[title], acronym[title] {

border-bottom-style: dotted;

border-bottom-width: 1px;

}

note Ifyoudon’tseethedottedbottomborderonyourabbroracronyminInternetExplorer,tryadjustingtheparentelement’sline-height

propertyinCSS.

note InternetExplorer6rendersabbrtext,butitdoesn’trecognizeabbrasanelement(unlessyouexecutedocument.createElement('abbr')

first),soyoucan’tstyleitwithCSS,andthetitletooltipwon’tdisplay.

HTML5andtheabbrElementHTML5eliminatestheconfusionbetweenabbreviationsandacro-nymsbydeclaringtheacronymelementobsoleteandadvisingauthorstouseabbrinallinstances.

Italsospeciiesthatifanabbreviationisinpluralformwithintheelement,thetitletext,ifpresent,shouldbepluralaswell.

Part2:HTMLElementsandGuidance104

acronymAnacronym

Syntax <acronym></acronym>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionTheacronymelementdeinesanacronym.Itisoftenconfusedwiththeabbrelement,whichisforabbreviations.(Anacronymisalsoanabbre-viationbutonethatspellsaword,suchaslaser,radar,andscuba.)Pleaseseehttp://www.htmlfiver.com/extras/abbr-acronym/formorediscussionofthedifferencebetweenthetwo.

Example:

<p>After the <acronym>radar</acronym> detected movement under

the ship, she threw on her <acronym title="self-contained

underwater breathing apparatus">scuba</acronym> gear to go

check it out.</p>

Asshown,theoptionaltitleattributedeinestheexpandedformoftheacronym.Pleaseseetheabbrentryformoreaboutthevalueoftitleandanalternativeapproach,aswellashowtitleimpactsacronymrenderinginsomebrowsers.

HTML5andtheacronymElementHTML5eliminatestheconfusionbetweenabbreviationsandacro-nymsbydeclaringtheacronymelementobsoleteandadvisingauthorstouseabbrinallinstances.

Part2:HTMLElementsandGuidance Chapter5:Text 105

bBoldtext

Syntax <b></b>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionInX/HTML,thebelementispurelypresentational;itrenderstextasboldbutprovidesnomeaning.Youcanthinkofitasaspanelementthatisboldbydefault.Becauseit’ssolelypresentational,bfelloutoffavorseveralyearsagoliketheielementandisallbutdeprecatedintheeyesofmany.Developersareadvisedtousethestrongelementinsteadwheneverappropriate,sinceithassemanticvalueanddoesn’tspeaktohowtheenclosedtextshouldlook.

Example:

<!-- Uses strong instead of b -->

<p>That intersection is <strong>extremely dangerous

➥ </strong>.</p>

Useragentsrenderbothstrongandbthesamewaybydefault(andbothcanbealteredwithCSS):

That intersection is extremely dangerous.

However,don’tusestrongforcontent,suchasaheading,justbecauseyouwantittobebold.Instead,useh1—h6,ortheappropriatesemanticelementandstyleitaccordinglywithCSS.

Part2:HTMLElementsandGuidance106

bvs.strong,HTML5,andMoreHTML5redeinesbsoitsuseisrootedintypographicalconventions,insteadofsolelymakingtextbold.Pleaseseetheielemententryinthischapterformorebackgroundconcerningbvs.strong,aswellasb’sroleinHTML5.

bdoBidirectionaltextoverride

Syntax <bdodir=””></bdo>

Attributes Core(dirisrequired),HTML5Only:Global

DescriptionUsethebdo(“bidirectionaloverride”)elementanditsrequireddirattri-butetochangethedirectionalityoftheenclosedtext.dirspeciiesthedesireddisplaydirectionandtakesavalueofeitherltr(“lefttoright”)orrtl(“righttoleft”).

Example1:<p>This text appears left-to-right by default, while

<bdo dir="rtl">this appears right-to-left</bdo>.</p>

Useragentsrenderthisasfollows:

This text appears left-to-right by default, while tfel-ot-thgir sraeppa

siht.

That’sacrudeexamplejusttoshowthebasicconcept,buthere’ssomeofthe“why”and“when”ofbdo.

Part2:HTMLElementsandGuidance Chapter5:Text 107

EachUnicodecharacterhasadirectionalityassociatedwithit—eitherlefttoright(likeLatincharactersinmostlanguages)orrighttoleft(likecharactersinArabicorHebrew).Unicode’sbidirectional(“bidi”)algo-rithmdetermineshowtodisplaycontentthatincludesamixtureofbothleft-to-rightandright-to-leftcharacters.bdocomesintoplaywhenthealgorithmdoesn’tdisplaythecontentasintendedandyouneedtoover-rideit.Pleaseseehttp://www.htmlfiver.com/extras/bdo/formoredetails.Additionally,theW3C'sarticle“CreatingHTMLPagesinArabic,HebrewandOtherRight-to-leftScripts”(http://www.w3.org/International/tutorials/bidi-xhtml/)discussestheissuesatlength.

bigLargertext

Syntax <big></big>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionTextcontainedinabigelementrendersinanindeterminatelargersize(anditmayvaryinuseragents).Likethesmallelement,bigisn’tofi-ciallydeprecatedinX/HTML,butpracticallyspeakingitis,anddevelop-ersareadvisednevertouseit.Instead,useCSStocontrolyourfontsizeinconjunctionwithapropersemanticelement.Theemand,especially,strongelementsareidealsubstitutesforcasesinwhichyoumighthavebeeninclinedtousebig.(Avoidusingspansinceithasnosemanticmeaninganddoesn’tenhanceaccessibility.)Example1showsstronginplaceofbig.

Part2:HTMLElementsandGuidance108

Example:

<p>This is the sale <strong>you CAN’T miss!</strong></p>

Thestrongtextwon’tbelargerthanitssurroundingtextbydefault,butyoucanstyleitasyoupleasewithCSS:larger,anormalweightinsteadofthedefaultbold,andsoon.

HTML5andthebigelementThebigelementisobsoleteinHTML5.

blockquoteAlongquotation

Syntax <blockquote></blockquote>Attributes Core,I18n,Events,cite,HTML5Only:Global

DescriptionUsetheblockquoteelementtodenotealong(block-level)quotation.Itisthecounterparttotheqelement,whichisappropriateforashort(inline)quotation.Theoptionalciteattributeallowsyoutospecifythesource’sURI.

Example:

<p>In <cite>The Brothers Karamazov</cite>, Dostoevsky wrote:

➥ </p>

<blockquote cite=”http://www.dostoevskybooks.com/the-brothers-

➥ karamazov/”>

Part2:HTMLElementsandGuidance Chapter5:Text 109

<p>The stupider one is, the closer one is to reality. The

stupider one is, the clearer one is. Stupidity is brief

and artless, while intelligence wriggles and hides

itself. Intelligence is a knave, but stupidity is honest

and straightforward.</p>

</blockquote>

Browserstypicallyindentblockquotecontentbydefault(youcanchangethiswithCSS):

In The Brothers Karamazov, Dostoevsky wrote:

The stupider one is, the closer one is to reality. The stupider

one is, the clearer one is. Stupidity is brief and artless, while

intelligence wriggles and hides itself. Intelligence is a knave,

but stupidity is honest and straightforward.

note Besuretouseblockquoteonlyifyourcontentisquotedfromasource,notjustbecauseyouwanttoindentit.Youmayindentother

HTMLelementsbysettingthemargin-leftpropertyinCSS.

AttributesinDetailn cite:UsethisoptionalattributetoincludeaURIthatpointstothe

quotation’ssource.ThepreviousexamplereferstoDostoevsky’sbookonasite(ictitious,inthiscase).Pleaseseethedfnelemententryinthischapterformoredetailsaboutciteaccessibilityandpresentationissues.(Note:Theciteattributeisdifferentfromtheciteelement,whichisalsousedintheexampleanddescribedinfullinthischapter.)

note ForapagewithaStrictDOCTYPE,blockquotecontentmustbemarkedupwiththeappropriateelements(likepintheexample)

ratherthanwrappeddirectly.However,Istronglyencourageyoutomarkitupevenifyou’reusingaTransitionalDOCTYPE.It’sbetterforaccessibilityandcontrollingpresentationwithCSS,andit’llmakeyourtransitiontoStricteasier.

Part2:HTMLElementsandGuidance110

HTML5andtheblockquoteElementHTML5saystheblockquoteandciteelementsareinvalidforrepre-sentingaconversation.

brAlinebreak

Syntax <br>or<br />

Attributes Core,I18n,Events,HTML5Only:Global

DescriptionThebrelementforcesalinebreakinarunoftext,suchasinapoemorstreetaddress.Asarule,usebrsparinglysinceitmixespresentation(thedomainofCSS)withyourHTML.Donotuseittocreateabreakbetweenparagraphs;wrapthecontentinthepelementinstead,anddeinethespacebetweenparagraphswiththeCSSmarginproperty.

Example:

<p>

125 Center Street<br />

Moose Jaw, Saskatchewan<br />

Canada S6H 3J9

</p>

DeprecatedAttributesn clear:UsetheCSSclearpropertyinsteadtodictatethelowof

contentthatfollowsabr.

Part2:HTMLElementsandGuidance Chapter5:Text 111

citeAreferencetoasource

Syntax <cite></cite>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsetheciteelementforacitationorreferencetoasource.Examplesincludethetitleofaplay,ascript,abook,asong,amovie,aphoto,asculpture,aconcertormusicaltour,aspeciication,anewspaper,alegalpaper,aperson,andmore.

Forinstancesinwhichyouarequotingfromthecitedsource,useqorblockquote,asappropriate,tomarkupthequotedtext(pleaseseetheirentriesinthischapter).Tobeclear,citeisonlyforthesource,notwhatyouarequotingfromit.citemayalsobeusedwithoutarelatedquotation.

Examples:

<p>Two of the books on her summer reading list are <cite>A

Separate Peace</cite> and <cite>The Odyssey</cite>.</p>

<p>Which character in <cite>This is Spinal Tap</cite> said,

<q>It's such a fine line between stupid, and clever</q>?</p>

<p>When he went to The Louvre, he learned that <cite>Mona

Lisa</cite> is also known as <cite>La Gioconda</cite>.</p>

Useragentstypicallyitalicizecitetextbydefault,likethis(youcanalteritwithCSS):

Part2:HTMLElementsandGuidance112

Which character in This Is Spinal Tap said, “It’s such a fine line

between stupid and clever”?

HTML4,HTML5,andtheciteElementDustupHTML4isdifferentfromHTML5inthatitalsoallowsusingciteonaperson’sname,suchaswhenquotingtheperson.HTML4providesthisexample(I’vechangedtheelementnamesfromuppercasetolowercase):

As <cite>Harry S. Truman</cite> said,

<q lang="en-us">The buck stops here.</q>

Inadditiontoinstanceslikethat,developersoftenuseciteforthenameofblogandarticlecommenters(thedefaultWordPressthemedoes,too).

Amidsomedisagreementinthedevelopmentcommunity,HTML5explicitlydeclaresthatusingciteforaperson’snameisnotappro-priate.Instead,itdeinesciteassolelyforthe“titleofawork,”likeatitleofaplay,ascript,andtheotherones(exceptaperson)listedinthepreviousdescription.ManydevelopershavemadeitcleartheyintendtocontinuetouseciteonnamesbecauseHTML5doesn’tprovideanalternativetheydeemacceptable(namely,thespanandbelements).

Part2:HTMLElementsandGuidance Chapter5:Text 113

codeAcodefragment

Syntax <code></code>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsethecodeelementtomarkupafragmentofcomputercode.Forinstance,you’lloftenseecodeusedonWebtutorials.Typically,it’snestedinporpre,asappropriate,thoughotherelementsmaybeacceptable,too.

Example:<p>The <code>showPhoto(id)</code> function displays the

full-size photo of the thumbnail in our <code>&lt;

➥ ul id=&quot;thumbnails&quot;&gt;</code> carousel list.</p>

Useragentstypicallyrendercodeinamonospacefontbydefault,likeso:

The showPhoto(id) function displays the full-size photo of the

thumbnail in our <ul id="thumbnails"> carousel list.

Ifyou’dliketorenderablockofcode,wrapitinapreelementtopreserveitsformatting.Pleaseseethepreentryinthischapterforanexampleandmoreinformation.

tip Pleaseseethekbd,samp,andvarelemententriesinthischapterforothercomputer-andprogramming-relatedsemantics.

Part2:HTMLElementsandGuidance114

HTML5andthecodeElementHTML5sayscodeisalsoappropriateforailename.HTML4isquiteshortondetailsaboutcode,butinmyjudgment,thisisappropriateforX/HTMLusage,too.

delDeletedcontent

Syntax <del></del>Attributes Core,I18n,Events,cite,datetime,HTML5Only:Global

DescriptionThedelelementindicatescontentthathasbeendeletedfromapreviousversionofthedocument.It’susefulwhenyou’dliketoexplicitlyshowwhathaschangedasapageevolves.Itscounterpartistheinselement,whichindicatescontentthat’sbeeninsertedsinceapreviousversion.Youarenotrequiredtousethemintandem,however.

Forboth,thinkofatechnicalspeciicationorlegaldocumentthatgoesthroughmultipleiterationsbeforebecominginal,agiftregistrylistthatisupdatedasitemsarepurchased,oraWebtutorialyouupdateafterareaderprovidesvaluablefeedbackinthecommentssection.Ineachcase,youmaywanttoinformthereaderofthecontent’sevolutionwithdeland/orins.

Part2:HTMLElementsandGuidance Chapter5:Text 115

Example1(asinlineelement):

<h3>Tomorrow's Showtimes</h3>

<ol>

<li><ins>2 <abbr>p.m.</abbr> (Another show just added!)

➥ </ins></li>

<li><del datetime=”2010-03-03T10:16:15-05:00”>5 <abbr>p.m.

➥ </abbr></del> <ins>SOLD OUT</ins></li>

<li><del cite=”http://www.hot-ticket-plays.com/show-

➥ sells-quickly/” datetime=”2010-03-02T10:10:14-05:00”>8:30

<abbr>p.m.</abbr></del> <ins>SOLD OUT</ins></li>

</ol>

Bydefault,useragentstypicallyrenderastrikethroughondelcontentandunderlineinscontent(youcanalterthiswithCSS).Example1wouldappearlikethis:

1. 2 p.m. (Another show just added!)

2. 5 p.m. SOLD OUT

3. 8:30 p.m. SOLD OUT

AsImentioned,delandinsareoftenusedtogetherbutdon’thavetobe.Forexample,Iinsertedcontentintheirstlistitembutdidn’tdeleteany.Conversely,theremaybetimesyoudocumentadeletionwithoutinsert-ingareplacement.

AttributesinDetailTheseattributeshavethesamepurposeforbothdelandins:n cite="url":UsethisoptionalattributetoincludeaURItoasource

thatexplainswhythechangewasmade.Forinstance,inthelastliinExample1,citemightpointtoastoryabouttheshowsellingout

Part2:HTMLElementsandGuidance116

intenminutes.Alternatively,youcouldprovideabriefmessageinthetitleattribute,whichdisplaysasatooltip.(Note:Theciteattributeisdifferentfromtheciteelement,whichisalsodescribedinthischapter.)

n datetime:Usethisoptionalattributetospecifythedateandtimeofthechange,asshowninExample1.TherequiredformatisYYYY-MM-DDThh:mm:ssTZD.Pleaseseehttp://www.w3.org/TR/html4/types.html#type-datetimeforafullexplanation.

note

citeanddatetimearecuriousinthattheyaddvaluetoyourcontent,butbrowsersdon'treadilyexposetheinformationtousers.Pleasesee

http://www.htmlfiver.com/extras/del-ins/forfurtherdiscussionofthisaccessi-bilityissueandsomesolutions.

AsInlineorBlock-LevelElementdelandinsarerareinthattheycanbeeitherinlineorblock-levelelements.Theyareinlinewhensurroundingcontentwithinablock-levelelement,suchasaparagraphortheliinExample1.Theyareblock-levelwhentheycontainoneormoreblock-levelelements,asinExample2.Aninstanceofdelorinscannotbebothatthesametime,however;youcannotnestblock-levelcontentinsidedelorinswheneitherisusedinline.

Thisexampleshowsinsasablock-levelelement;theapproachisthesamefordel.

Example2(asblock-levelelement):

<ins>

<p><strong>Update:</strong> Since initial publication of

this story, we learned that Mr. Johnson’s bike ride

across the United States will commence on July 7th.</p>

</ins>

Part2:HTMLElementsandGuidance Chapter5:Text 117

note Browsersrendercontentinablock-leveldelandinsinconsistentlybydefault.Mostdisplayastrikethroughfordelandanunderlineforins

onallnestedcontentasexpected,butattheleast,Firefox3.5andolderdonot.YoucanrectifythiswiththefollowingexplicitCSSrule(the*meanseveryelementinsidedelandinsgetsthetreatment):del * {

text-decoration: line-through;}

ins * {

text-decoration: underline;}

dfn

Deininginstanceofterm

Syntax <dfn></dfn>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionThedfnelementindicatesthedeininginstanceofaterm.Wrapdfnonlyaroundthetermyou’redeining,notthedeinitionitself.

Example1:

<p>The contestant was asked to spell &ldquo;pleonasm.&rdquo;

She asked for the definition and was told that <dfn>pleonasm

➥ </dfn> means <q>a redundant word or expression</q> (Ref:

<cite><a href="http://dictionary.reference.com/browse/

➥ pleonasm">dictionary.com</a></cite>).</p>

Useragentstypicallyitalicizedfntextbydefault:

Part2:HTMLElementsandGuidance118

The contestant was asked to spell “pleonasm.” She asked for the

definition and was told that pleonasm means a redundant word or

expression (Ref: dictionary.com).

Notethatalthoughpleonasmappearstwiceinourexample,dfnmarksthesecondoneonly,becausethat’swhenIdeinedtheterm(thatis,it’sthedeininginstance).Similarly,ifIweretousepleonasmsubsequentlyinthedocument,Iwouldn’twrapitindfnbecauseI’vealreadydeinedit.However,Icouldaddanidtothedfnandlinktoitfromotherpointsinthedocumentorsite.Pleasealsonotethatyoudon’tneedtousetheciteelementeachtimeyouusedfn,justwhenyoureferenceasource.

dfnmayalsoencloseanotherinlineelementlikeabbr,whenappropriate.

Example2:

<p>A <dfn><abbr title=”Junior”>Jr.</abbr></dfn> is a son who

has the same full name as his father.</p>

tip dfnisalsoappropriateinadefinitionlist.PleaseseethedlanddtelementsinChapter4formoredetails.

HTML5andthedfnElementHTML5says,“Theparagraph,descriptionlistgroup,orsectionthatisthenearestancestorofthedfnelementmustalsocontainthedeinition(s)forthetermgivenbythedfnelement.”Thepreviousparagraphexamplesreflectthis.

HTML5alsostipulatesthatifyouusetheoptionaltitleattribute,itshouldbethesameasthedfnterm.However,if,asinExample2,younestasingleabbrindfnandthedfndoesnothaveatextnodeofitsown,theoptionaltitleshouldbeontheabbronly.

Part2:HTMLElementsandGuidance Chapter5:Text 119

emEmphasizetext

Syntax <em></em>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsetheemelementtoconveyemphasis.Itscounterpartisthestrongelement,whichconveysgreateremphasis.(Pleaseseethe“HTML5andtheemElement”boxconcerningdifferencesinHTML5.)

Althoughbothemandtheielementrendertextinitalicsbydefault,alwaysuseemwhenemphasizingcontentsinceithassemanticmean-ingandidoesn’tinX/HTML.Pleaseseetheientryinthischapterforadetaileddiscussionaboutivs.em.

Example:

<p>Your Ford Pinto is <em>really</em> cool.</p>

Thistypicallydisplaysbydefaultasfollows:

Your Ford Pinto is really cool.

YoucanchangethedisplaywithCSS,ofcourse,evenmakingitboldifyou’dlike.

note It’snotappropriatetouseemsimplyasameanstoitalicizetext.Asalways,choosethepropersemanticelementforyourcontentandthen

styleit.Forinstance,theremaybetimeswhentheciteelementistherightchoiceinsteadofem.

Part2:HTMLElementsandGuidance120

HTML5andtheemElementInHTML4,emisforemphasis,andthestrongelementisforgreateremphasis.HTML5redeinesthemabit,soemaccountsforalldegreesofemphasisandstrongconveysimportance.It’sasubtleshift.

InHTML5,emrepresentsdifferentlevelsofemphasisbywhetherit’snestedinanotherem;eachnestedlevelisemphasizedmorethanitsparent.HereI’veadjustedthepreviousexampletodemonstrate:

<p>Your Ford Pinto is <em><em>really</em> cool</em>.</p>

Now,I’memphasizingbothreallyandcool,butreallyisstrongerbecauseit’scontainedinthenestedem.

HTML5alsoremindsusthatemchangesthemeaningofasentencebywhereitappears.Forinstance,thenextexampleconveysthat“your”Pintoisreallycool,whilesomeoneelse’sisn’t.

<p><em>Your</em> Ford Pinto is really cool.</p>

Asanotherexample,ifyouwereexcitedbeyondbeliefbythePinto,youcouldconveyitbyplacingtheentiresentenceinanemandadd-inganoptionalexclamationmarktoleavenodoubt:

<p><em>Your Ford Pinto is really cool!</em></p>

Part2:HTMLElementsandGuidance Chapter5:Text 121

iItalicizedtext

Syntax <i></i>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionInX/HTML,theielementispurelypresentational;itrenderstextinital-icsbutprovidesnomeaning.Youcanthinkofitasaspanelementthatisitalicizedbydefault.Becauseit’ssolelypresentational,ifelloutoffavorseveralyearsagolikethebelement.Usetheemelementinsteadtoemphasizetext,sinceithassemanticvalueanddoesn’tspeaktohowtheenclosedtextshouldlook.

Example:

<!-- Uses em instead of i -->

<p>He had a great final kick, but <em>just</em> missed

catching the race leader.</p>

Useragentsrenderbothemandithesameway(andbothcanbealteredwithCSS):

He had a great final kick, but just missed catching the race leader.

Part2:HTMLElementsandGuidance122

bandivs.strongandem,aLittleBackground,andHTML5

Thebandielementswerethesubjectofmuchopinionateddiscus-sionintheearlierdaysofHTML5’sevolution.Somecalledfortheirdeprecationorremoval,whileothersthoughttheyhadtoremain.Thoughadecisionhasbeenmade,thesentimentshaven’tchanged.

Youcouldspendhoursreadingallanglesoftheargumentsbothforandagainstbandi,buttheyboildowntoacouplekeyposi-tions:Thoseagainstthemthinkit’swrongtouseanelementstrictlyintendedforpresentationandthatconveysnosemanticmeaning;thoseforthemthinkbandiaretooentrenchedintheWeb(manymillionsofpagesusethem)andbelieveemandstrongarenotappro-priatesemanticsforeverycase.

Tothelatter,thereareestablishedtypographicconventionsintradi-tionalpublishingthatfallbetweenthecracksoftheavailableHTMLsemantics.Amongthemareitalicizingcertainscientiicnames(forexample,“TheUlmusamericanaistheMassachusettsstatetree.”),foreignphrases(forexample,“Thecoupleexhibitedajoiedevivrethatwasinfectious.”),andnamedvehicles(forexample,“TheOrientExpressbeganservicein1883.”).Theseitalicizedtermsaren’tempha-sized,juststylizedperconvention.Therearefewercasesforbold,butHTML5citeskeywordsinadocumentabstractandaproductnameinareviewasexamples.

Ratherthancreateseveralnewsemanticelements(andfurthermuddythewaters)toaddresscaseslikethese,HTML5takesapracti-calstancebytryingtomakedowithwhatwehave:emforalllevelsofemphasis,strongforimportance,andbandiforthebetween-the-crackscasesto“stylisticallyoffset[thetext]fromthenormalprose.”Thenotionisthatalthoughbandidon’tcarryexplicitsemanticmeaning,thereaderwillrecognizeadifferenceisimplied.Andyou’restillfreetochangetheirappearancefromboldanditalicswithCSS.

(continuesonnextpage)

Part2:HTMLElementsandGuidance Chapter5:Text 123

bandivs.strongandem,aLittleBackground,andHTML5(continued)

Makenomistake,though,HTML5doesemphasizethatyouusebandionlyasalastresortwhenanotherelement(suchasstrong,em,cite,andothers)won'tdo.

HTML5’sapproachisunderstandable,allthingsconsidered.Thatbeingsaid,theideaofalwaysusingemandstronginsteadofiandb,respectively,issowovenintothefabricofstandards-focuseddevel-opersthatthemajorityareunlikelytodeviate.Manyofthemstillthinkitisbettertoaddsomemeaningtoanelement(suchaswithem),evenifitisn’tquiteonpoint,thanitistousewhattheyperceivetobeasolelypresentationalelement.

insInsertedcontent

Syntax <ins></ins>Attributes Core,I18n,Events,cite,datetime,HTML5Only:Global

DescriptionUsetheinselementtodenotecontentyou’veaddedtoanHTMLdocu-mentsinceapreviousversionincaseswhentrackingthehistoryaddsvalue.insisoftenusedinconjunctionwiththedelelement,whichdenotesdeletedcontent.Assuch,bothelementsandtheirattributesaredescribedingreaterdetailinthedelentryinthischapter.

Part2:HTMLElementsandGuidance124

kbdTextforusertoenter

Syntax <kbd></kbd>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsethekbdelementtomarkuptexttheusershouldenter.Itappliestobothletterstypedandkeyspressed.

Example:

<p>To log into the demo:</p>

<ol>

<li>Type <kbd>tryDemo</kbd> in the User Name field</li>

<li><kbd>TAB</kbd> to the Password field and type

<kbd>demoPass</kbd></li>

<li>Hit <kbd>RETURN</kbd> or <kbd>ENTER</kbd></li>

</ol>

Useragentstypicallydisplayamonospacefontforkbdbydefault.Ourexample(sanstheparagraph)wouldrenderlikethis:

1. Type tryDemo in the User Name field

2. TAB to the Password field and type demoPass

3. Hit RETURN or ENTER

tip Pleaseseethecode,samp,andvarelementsforothercomputer-andprogramming-relatedsemantics.

Part2:HTMLElementsandGuidance Chapter5:Text 125

pAparagraph

Syntax <p></p>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionThepisoneofthemost-usedelementsontheWeb,whichshouldcomeasnosurprisesinceitspurposeistodeineaparagraph.

Youmayuseponitsown(seeExample1)orinconjunctionwithnestedinlineelements.Forinstance,youmayseeanimgelementinaparagraph,alongwithelementsthatenrichthesemanticsofthecontent,suchasciteinExample2.

Examples:

<p>Centuries-old sisters, Marge and Priscilla, were the

creation of the children’s fertile imaginations.</p>

<p><img src=”movie_poster.jpg” width=”300” height=”175”

alt=”Monty Python and the Holy Grail poster” /><cite>Monty

Python and the Holy Grail</cite> was released in 1975.</p>

Asshownhere,browsersrendereachparagraphonitsownlinebydefault:

Centuries-old sisters, Marge and Priscilla, were the creation of the

children’s fertile imaginations.

. . . next paragraph . . .

Part2:HTMLElementsandGuidance126

DeprecatedAttributesn align:UsetheCSStext-alignpropertywithavalueofcenter,

justify,left,orrightinstead.

note Nestingablock-levelelementinaparagraphisnotallowed.

prePreformattedtext

Syntax <pre></pre>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsethepreelementtorenderpreformattedtext.Themostcommonusecaseistopresentablockofcode,butyoumayalsouseprefortextandASCIIart.

Example1(code):

<pre>

<code>

var band = {

bass: "Geddy",

guitar: "Alex",

drums: "Neil",

showsPlayed: "2112"

};

</code>

</pre>

Part2:HTMLElementsandGuidance Chapter5:Text 127

Browserstypicallyrenderthisasshown(sanstheoutline)andinamono-spacefont:

Asyousee,prepreservestheindentation,sothecodeblockdisplaysinfromtheleftedge.Withoutpre,thecodedisplayslikeasentence,makingithardertoreadevenforoursimpleexample:

var band = { bass: "Geddy", guitar: "Alex", drums:

"Neil", showsPlayed: "2112" };

Hereisanexamplewithtext.

Example2(text):

<pre>

This is flush left.

This begins fourteen spaces from the left side.

This begins six spaces from the left side and two lines

➥ down.

</pre>

Asexpected,itdisplaysjustasitappearsinthecode(andasthecontentdescribes).

You’llnoticethattheparagraphsaren’twrappedinpelements.Thisisdeliberate,becauseit’sinvalidtonestmanyHTMLelementsinsidepre,

Part2:HTMLElementsandGuidance128

includingp,sub,sup,andmore.Besuretovalidateyourpagestocheckwhetheryou’veaccidentallyincludedaninvalidelementinapre.

PresentationConsiderationswithpreBeawarethatuseragentstypicallydisableautomaticwordwrappingofcontentinsideapre,soifit’stoowide,itmightaffectyourlayoutorforceahorizontalscrollbar.ThefollowingCSSruleenableswrappingwithinpreinmanybrowsers,butnotInternetExplorerexceptversion8wheninIE8mode.

pre {

white-space: pre-wrap;

}

Onarelatednote,inmostcasesIdon’trecommendyouusewhite-space:pre;onanelementsuchasdivasasubstituteforpre,becauseiftheuseragentdoesn’tsupportCSS,theformattingwillbelost.Furthermore,thewhitespacecanbecrucialtothesemanticsoftheenclosedcontent,especiallycode,andonlyprealwayspreservesit.

DeprecatedAttributesn width:UsetheCSSwidthpropertyinstead.

note preisn’tashortcutforavoidingmarkingupyourcontentwithpropersemanticsandstylingitspresentationwithCSS.Forinstance,ifyou

wanttopostanewsarticleyouwroteinawordprocessor,don’tsimplycopyandpasteitintoapreifyoulikethespacing.Instead,wrapyourcontentinpelementsandwriteCSSasdesired.

tip Pleaseseethecode,kbd,samp,andvarelementsinhischapterforothercomputer-andprogramming-relatedsemantics.

Part2:HTMLElementsandGuidance Chapter5:Text 129

qAshortquotation

Syntax <q></q>Attributes Core,I18n,Events,cite,HTML5Only:Global

Usetheqelementtoencloseashort(inline)quotationthatdoesn’trequireaparagraphbreak.Thequotationmaybeaphrasesomeonesaidorareferencefromadocument,movie,song,andsoon.qisthecounter-parttotheblockquoteelement,whichisforlong(block-level)quotations.

Example1:

<p>Kathy is fond of quoting her favorite movie,

<cite>Phantasm</cite>, by exclaiming, <q cite=”http://

➥ www.phantasmscreenplay.com”>You play a good game, boy, but

the game is finished!</q> every chance she gets.</p>

qcanstandonitsownorbepairedwiththeciteelement(inotherwords,<cite>Phantasm</cite>),asinExample1.

Authorsshouldnotincludequotationmarkswhentheyuseq.MostuseragentsautomaticallyrenderthemasrequiredbyHTML4andHTML5.However,InternetExplorer7andolderfailtodoso.Hereisthecorrectrendering:

Kathy is fond of quoting her favorite movie, Phantasm, by exclaiming,

“You play a good game, boy, but the game is finished!” every chance

she gets.

Besureyoudon’tuseqsimplybecauseyouwantquotationmarksaroundawordorphrase,though.Forinstance,<p>Helikestheword<q>morsel.</q></p>,isimproperbecausemorselisn’taquotationfrom

Part2:HTMLElementsandGuidance130

asource.Inthatcase,usecharacterentities,suchas<p>Helikestheword&ldquo;morsel.&rdquo;</p>(or&quot;oneachsideforstraightquotationmarks).

AttributesinDetailn cite:UsethisoptionalattributetoincludeaURItothesourceyouare

quoting.Forinstance,Example1pointstothePhantasmscreenplayonasite(ictitious,inthiscase).Pleaseseethedelelemententryinthischapterformoredetailsaboutciteaccessibilityandpresenta-tionissues.(Notethattheciteattributeisdifferentfromtheciteelement,whichisalsousedinExample1anddescribedinfullelse-whereinthischapter.)

NestedQuotationsYoumayalsonestaqinsideanotherone.

Example2:

<p>The short story began, <q>When she was a child, she would

say, <q>Hello!</q> to everyone she passed.</q></p>

Sinceouterandinnerquotationsaretreateddifferentlyinlanguages,addthelangattributetoqasneeded.UseragentsaresupposedtorenderExample2withsinglequotationsaroundthenestedportion,likethis:

The short story began, "When she was a child, she would say, ‘Hello!’

to everyone she passed."

However,supportisinconsistent(evenwithlangexplicitlydeclared),includingamongmodernbrowsers,surprisingly.Firefoxhandlesitcorrectly,whilethelikesofChromeandSafarirenderdoublequotationsinallcases.

Part2:HTMLElementsandGuidance Chapter5:Text 131

tip

Ahandfulofonlinetutorialsdiscusssolutionsforshowingquotationmarksforqacrossbrowsersconsistently.Twoexamplesarehttp://

monc.se/kitchen/129/rendering-quotes-with-cssandhttp://juicystudio.com/article/fixing-ie-quotes.php. Becauseofthecross-browserissues,youmaysurroundaquotationwithacharacterentitysuchas&ldquo;(leftquotation)and&rdquo;(rightquotation)or&quot;(straightquotationoneachside)insteadofusingq.Similarly,&lsquo;and&rsquo;renderleftandrightsinglequotations,respectively.Youdolosesomeofthesemanticswiththisapproach,though.

sampSampleoutputtext

Syntax <samp></samp>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionThesampelementrepresentssampleoutputtextfromaprogramorscript.

Example:

<p>Once the payment went through, the site returned a message

reading, <samp>Thanks for your order!</samp></p>

Useragentstypicallydisplaysampcontentinamonospacefontbydefault,likethis:

Once the payment went through, the site returned a message reading,

Thanks for your order!

tip Pleaseseethecode,kbd,andvarelementsforothercomputer-andprogramming-relatedsemantics.

Part2:HTMLElementsandGuidance132

smallSmallertext

Syntax <small></small>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionTextcontainedinasmallelementrendersinanindeterminatesmallersize(anditmayvaryinuseragents).Likethebigelement,smallisn’toficiallydeprecatedinX/HTML,butpracticallyspeakingitis,anddevel-opersareadvisednevertouseit(seethe“HTML5andthesmallElement”boxforanexception).Instead,controlyourfontsizewithCSSinconjunc-tionwithapropersemanticelement.Theemelementisoftenagoodsubstitute,asshownhere.

Example:

<p>His handwriting was <em>very, very tiny</em>, so he was

able to fit a term’s worth of notes on a single page.</p>

His handwriting was very, very tiny, so he was able to fit a term’s

worth of notes on a single page.

Theemtextwon’tbesmallerthanitssurroundingtextbydefault,butyoucanstyleitwithCSSasyouplease.Usespanincaseswhenemoranotherelementdoesn’tfeelappropriateforyourcontentandyoujustneedacontainertofacilitatemakingitsmallerwithCSS.

Part2:HTMLElementsandGuidance Chapter5:Text 133

HTML5andthesmallElementHTML5hasredeinedthesmallelementtoputittouseinsteadofmakingitobsoletelikethebigelement.

AccordingtoHTML5,usesmallforsidecommentssuchasineprint,which“typicallyfeaturesdisclaimers,caveats,legalrestrictions,orcopyrights.Smallprintisalsosometimesusedforattribution,orforsatisfyinglicensingrequirements.”

smallisintendedforbriefportionsofinlinetext,notspanningmul-tipleparagraphsorotherelements.

Example:

<p>Order now and you'll receive free shipping. <small>

(Some restrictions may apply.)</small></p>

smallshouldnotbeconfusedwiththeHTML5-onlyasideelement,whichmaycontainlargeblocksofcontent(someofwhichmayincludesmallelements).PleaseseetheasideentryinChapter11formoredetails.

Lastly,ifyouusesmallwithemandstrong,itdoesn’tdiminishtheweightofthemeaningofthoseelements.

Part2:HTMLElementsandGuidance134

strongStrongertextemphasis

Syntax <strong></strong>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsethestrongelementtoconveystrongeremphasisthanitscounter-part,theemelement.(Note:ThemeaninghaschangedinHTML5.Pleaseseethe“HTML5andthestrongElement”box.)

Althoughbothstrongandthebelementrenderinboldbydefault,alwaysusestronginsteadwhenconveyingstrongeremphasissincebispurelypresentationalandhasnosemanticmeaninginX/HTML.Pleaseseetheielemententryinthischapterforadetaileddiscussionaboutbandivs.strongandeminHTML5.

Examples:

<p>They've been married for <strong>44 years</strong>!</p>

<p><strong>Warning:</strong> Pan will be hot.</p>

strongtypicallyrendersbydefaultlikethis:

They’ve been married for 44 years!

YoucanchangeitwithCSS,ofcourse,evenmakingititalicizedifyou’dlike.

note It’snotappropriatetousestrongsimplyasameanstoboldtext.Asalways,choosethepropersemanticsforyourcontentandthenstyleit.

Forinstance,ifyou’retemptedtousestrongtocreateaheading,usetheappro-priateheadinglevel(h1–h6)instead.

Part2:HTMLElementsandGuidance Chapter5:Text 135

HTML5andthestrongElementInX/HTML,emisforemphasis,andthestrongelementisforgreateremphasis.HTML5redeinesthemabit,soemaccountsforalldegreesofemphasisandstrongconveysimportance.It’sasubtleshift.Theirstexampleshownearlier(thatis<p>They’vebeenmarried...</p>)woulduseeminHTML5insteadofstrong.

Additionally,inHTML5,strongindicatesagreaterlevelofimpor-tanceeachtimeit’snestedinanotherstrong.Let’ssupposewewraptheentiresecondexampleinstrong:

<p><strong><strong>Warning:</strong> Pan will be hot.

➥ </strong></p>

Theinnerstrong,inotherwords,<strong>Warning:</strong>,con-veysgreaterimportancethantheparentstrong.

subAsubscript

Syntax <sub></sub>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsethesubelementtomarkupcontentsuitableforsubscriptnotation(inotherwords,notjustbecauseyouwantcontenttoappearbelowthelineoftext).

Example:

<p>The chemist asked for a glass of H<sub>2</sub>O.</p>

Part2:HTMLElementsandGuidance136

Asyouwouldexpect,useragentsrendersubtextbelowothertextonthesamelinebydefault,likeso:

The chemist asked for a glass of H2O.

LineSpacing,subandsupIfyouhaveaparagraphthathasmorethanonelineandcontainsoneormoresuborsupelements,thespacingbetweenthelinesmayvary,dependingonthebrowserandyourpage’sfontandline-heightsettings.YoucansolvethiswithCSS.Solutionsareavail-ableonlineifyousearchforlinespacingwithsupandsub.However,donotheedanyadvicesuggestingyouuseanelementotherthansuborsuptocircumventthislayoutissue.

supAsuperscript

Syntax <sup></sup>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsethesupelementtomarkupcontentsuitableforsuperscriptnotation(inotherwords,notjustbecauseyouwantcontenttoappearabovethelineoftext).

Example:

<p>The mathematician wrote 4<sup>3</sup> for his age.</p>

Part2:HTMLElementsandGuidance Chapter5:Text 137

Asyouwouldexpect,useragentsrendersuptextaboveothertextonthesamelinebydefault,likeso:

The mathematician wrote 43 for his age.

tip Pleaseseethe“LineSpacing,subandsup”boxinthischapter.

tt

Teletypeormonospacetext

Syntax <tt></tt>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionThettelementispurelypresentational;ittypicallyrendersintheuseragent’smonospacefontbydefaultbutconveysnomeaning.ttisn’tofi-ciallydeprecated,butpracticallyspeakingitis,andyoushouldnotuseit.

Instead,usetheelementthatmostaccuratelydescribesthemeaningofthecontent,andthenstyleitwithCSSasdesired.Thecode,kbd,andsampelements(alldescribedelsewhereinthischapter)aregoodseman-ticcandidatesformostinstanceswhereyoumighthavebeentemptedtousett.

HTML5andthettElementThettelementisobsoleteinHTML5.

Part2:HTMLElementsandGuidance138

varAvariable

Syntax <var></var>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionUsethevarelementtomarkupavariableorcomputerprogramargument.

Examples:

<p>If <var>x</var> is the number of marathons Heather has

run, she has run 419.2 total miles in the races, and each

one is 26.2 miles, what is the value of <var>x</var>?</p>

<p>Einstein is best known for <var>E</var>=<var>m</var>

<var>c</var><sup>2</sup>.</p>

Useragentstypicallyrendervarinitalicsinthesamefontasothertextbydefault,likeso:

If x is the number of marathons Heather has run, she has run 419.2

total miles in the races, and each one is 26.2 miles, what is the value

of x?

Einstein is best known for E=mc2.

varandthecodeElementTherearevaryingopinionsaboutwhetheroneshouldusevartomarkupvariablesinsidethecodeelement.HTML4isn’tmuchhelp,because

Part2:HTMLElementsandGuidance Chapter5:Text 139

itsimplysaysvar“indicatesaninstanceofavariableorprogramargu-ment”andprovidesnoexamples.

Generalconsensusisit’sprimarilyintendedforinstancessuchasthoseinourexamplesandothersrepresentingaplaceholdervariable.(IfyouweremarkingupaMadLibssheet,youwouldput<var>adjective</var>,<var>verb</var>,andsoon.)Isuggestthatifyouaremarkingupcode,varisnotrequired,thoughmaybeusedifyouneedtodifferentiatethevariablesfromtheothercode(assumingyouaren’temphasizingavari-able,inwhichcaseemwouldbemoreappropriate).

tip Seethecode,kbd,andsampelementsforothercomputer-andprogramming-relatedsemantics.

Embeddedcontentistypicallysomeformofmedia:animage,amovie,aFlashapplication,andsoon.Ineachcase,it’sanexternalresourcethat’sloadedintoyourpage.Thischapterfocusesontheelementsthatfacili-tatethat.

Ifyou’reworkingonanHTML5site,besuretocheckoutthischapter’scompanion,Chapter13,whichfocusesonembeddedcontentelementsuniquetoHTML5,includingaudio,video,canvas,andmore.

note Lookingfortheembedelement?PleaseseeChapter13.Thoughinwidespreaduseforyears,itwasn’tpartoftheX/HTMLspecs.

However,HTML5makesitofficial.

EmbeddedContent(ImagesandObjects)

6

Part2:HTMLElementsandGuidance142

areaAregionwithinamap

Syntax <map> <area>or<area /></map>

Attributes Core,I18n,Events,accesskey,alt,coords,href,nohref*,shape,target*,onblur,onfocus,HTML5Only:Global,hreflang,media,ping,rel,type

DescriptionTheareaelementdeinesaregionwithinaclient-sideimagemapandmaybeusedonlyinconjunctionwiththemapelement.Pleaseseethemapentryinthischapterforafullexplanation.

AttributesinDetailPleaseseethemapentryinthischapterformoreinformationaboutthealt,href,andshapeattributes.n accesskey:Pleasesee“Attributes”inChapter1.n nohref:*ObsoleteinHTML5.Whenpresent,thisBooleanattribute

speciiesthattheareadoesn’thavealink.n onblur=”script”:Thiseventireswhenanarealosesfocus,whichisto

saywhenuserstabawayfromorclickoutsidethedeinedregion.It’stheoppositeofonfocus.AswithallJavaScriptevents,itisbesttoadditunobtrusivelyratherthaninlineintheareaelement’sHTML.(SearchonlineforunobtrusiveJavaScripttolearnmore.)

Part2:HTMLElementsandGuidance Chapter6:EmbeddedContent(ImagesandObjects) 143

n onfocus=”script”:Thiseventireswhenanareagainsfocus,whichistosaywhenuserstabtothedeinedregion(orastheyarepressingthemousebuttononthelinkinbrowserslikeIEandOpera).It’stheoppositeofonblur.AswithallJavaScriptevents,itisbesttoadditunobtrusivelyratherthaninlineintheareaelement’sHTML.(SearchonlineforunobtrusiveJavaScripttolearnmore.)

n target=”framename”:*NotallowedwithStrictDOCTYPEs.Thisdeinestheframeoriframeinwhichtoopenthehref.PleaseseeChapter10formoredetails.Useitonlyifhrefispresent.

HTML5andtheareaElementSincethenohrefattributedoesn’texistinHTML5,simplydon’tincludehreftomakeanareanotlinked.

AttributesinDetail

Framesdon’texistinHTML5,soyoucanusethetargetattributeonlytopointanhreftoaniframe.

areahastheseadditionalattributesinHTML5:n hreflang=”langcode”:Thisindicatesthebaselanguageofthe

href’sdestination,muchlikethewaythelangattributespeciiesthelanguageofotherHTMLelements.Hence,youmayusehreflangonlywhenhrefispresent.

n mediaandping:Pleaseseethe“HTML5andtheaelement”boxintheaentryofChapter5formoredetails.

n rel:PleaseseetheaentryofChapter5formoredetails.n type=”content-type”:Thistellstheuseragentthecontenttypeof

thecontentatthelink’sdestination.Itisonlyadvisory.

Part2:HTMLElementsandGuidance144

imgAnembeddedimage

Syntax <imgsrc="">or<imgsrc=""/>

Attributes Core,I18n,Events,alt,height,ismap,longdesc*,name*,src,usemap,width,HTML5Only:Global

DescriptionTheimgelementembedsanimageinthedocument.ImagesaretypicallyaGIF,JPEG,orPNG.

imguseisprettystraightforward.Inmostcases,you’llusejustthealt,height,src,andwidthattributes.

Example:

<p>

<img src=”dave_roberts_steal.jpg” width=”320” height=”240”

alt=”Dave Roberts slides in safely to second.” />

. . .

</p>

Althoughyoucansetthewidthandheighttoothervalues,it’sbesttousetheimage’sintrinsicdimensions.Ifyoumakeanimagelarger,itwillappeardistorted.Ifyoumakeitsmaller,you’reusingmorebandwidththanisnecessarytodisplaythedesiredimagesize.Instead,cutoutasmallerversionoftheimage,andembedthatoneinyourpage.

Thealtattributeiscriticalforaccessibility,becauseitprovidesabriefdescriptionoftheimageasalternatetextforscreenreaders.Thetextalsodisplaysinmostbrowsersiftheimagefailstoloadorifimagesare

Part2:HTMLElementsandGuidance Chapter6:EmbeddedContent(ImagesandObjects) 145

turnedoff.Ifanimagedoesn’twarrantalttext,putalt=””(screenread-erstypicallyignoretheseemptyaltvalues,butwithoutthemthey’lloftenreadaloudtheimgsrcvalue).

AttributesinDetailn alt=”text”:Includeanaltattributeforeveryimagetoenhanceacces-

sibility.Pleaseseethedescriptionjustbefore“AttributesinDetail.”n height=”percentageorpixels”:Thisspeciiestheimage’sheight,typi-

callyinpixels.Theimagestretchesorshrinksaccordingly.Whensettoapercentage,it’srelativetoitsparentcontainer’sheight.

n ismap:Whenpresent,thisBooleanattributeindicatesthattheimageispartofaserver-sideimagemap.Thistypeofimagemapisrarelyusedanymore,butwhenitis,theimgmustbeinanaelementwhosehrefpointstotheserver-sidescript.Seethemapentryinthischapterforanexampleofaclient-sideimagemap,thepreferredapproach.

n longdesc=”uri”:*ObsoleteinHTML5.Thispointstoaresource(thatis,atextile,HTMLpage,andsoon)withalongerdescriptiontosupple-ment(notreplace)altwhenitsbriefdescriptionisn’tsuficient.Whentheimgisassociatedwithanimagemap,describetheimagemap’scontents.

n name=”cdata”:*DeprecatedinXHTML.ObsoleteinHTML5.Eventhoughnameisn’tdeprecatedinHTML4,alwaysuseidinsteadtoidentifyanimageforthepurposesofscriptingorstylingwithCSS.

n src=”uri”:Thisspeciiestheimage’slocation.n usemap=”#name”:Thisassociatestheimagewithamapelement.It

mustbe#followedbythemap’snameattribute.Pleaseseethemapentryinthischapterforanexample.Notethatwhentheusemap

Part2:HTMLElementsandGuidance146

attributeispresent,theimagecannotbecontainedinsideeitheranaorabuttonelement.

n width=”percentageorpixels”:Thisistheimage’swidth,typicallyinpixels.Whensettoapercentage,it’srelativetoitsparentcontainer’swidth.

DeprecatedAttributesUsetheCSSpropertieslistedinparenthesesinsteadofthesedeprecatedattributes:align(floatandvertical-align),border(border),hspace(margin-leftandmargin-right),andvspace(margin-topandmargin-bottom).AlloftheseattributesareobsoleteinHTML5.

mapImagemapcontainer

Syntax <mapname=””> <area>or<area/></map>

Attributes Core,I18n,Events,name,HTML5Only:Global

DescriptionAnimagemapspeciiesoneormoreregionswithinasingleimage,typi-callyforthepurposesoflinkingittoanotherpageorresource.Themapelementcontainstheareaelementsthatdeinethelinkedregions.

Considerthefollowingexample,whichtakesaphotoofitemsinagarageandcreateslinkstoindividualpagesaboutthewashingmachine,tire,andtricycle(what,youdon’tblogaboutyourgarage?).

Part2:HTMLElementsandGuidance Chapter6:EmbeddedContent(ImagesandObjects) 147

Example:

<div><!-- it can be inside other elements, such as a p -->

<img src=”things_in_the_garage.jpg” width=”400”

height=”300” alt=”Things in the garage, including a

tire, tricycle and washing machine.” usemap=”#garage” />

<map name=”garage”>

<area shape="rect" coords="16,21,132,152"

href="washing-machine.html" alt="Learn about the

washing machine" />

<area shape="circle" coords="194,159,45"

href="tire.html" alt="Learn about the tire" />

<area shape="poly" coords="288,88,381,194,251,195"

href="tricycle.html" alt="Learn about the tricycle" />

</map>

</div>

Theimgelement’susemapattributeassociatestheimagewiththemap;itmustbe#followedbythemap’snameattribute.Amapcanbeassociatedwithmorethanoneimginapage.(TheHTMLValidatormayincorrectlytellyounameisdeprecatedforStrictDOCTYPEs.)

Eachareaelementdeinesaregionwithintheimage,andhrefdeinestheregion’slinkdestinationURI.Therearefourshapevaluesfromwhichtochoose:circle,poly,rect,anddefault.Declareashapewiththeshapeattribute,anddeineitscoordinateswithcoords(they’rerelativetothetop-leftcorneroftheimage).

Herearetherules:n Whenshape=”circle”,thecoordsattributetakesthreenumbers:the

x,ycoordinatesofthecircle’scenter(forexample,194,159)andthecircle’sradius(forexample,45).

Part2:HTMLElementsandGuidance148

n

Whenshape=”poly”,thecoordsattributetakesthreeormorepairsofx,ycoordinatestodeineapolygon.Intheexample,thethreepointsare288,88and381,194and251,195.

n

Whenshape=”rect”,coordstakestwopairsofnumberstodeinearectangle.Theirsttworepresentthex,ycoordinatesofthetop-leftcorner(forexample,16,21),andthesecondtwoarethebottom-rightcorner(forexample,132,152).

n Whenshape=”default”,itspeciiestheentireimage(coordsisnotrequired).

n

Whenshapeisn’tincluded,theregionshapedefaultstorect.

Thealtattributeonareaismuchdifferentthanitisonanimg.Itshouldreadlikelinktextregardingthehrefdestination(seetheexample),notdescribethatregionoftheimage.altisavailabletoscreenreaderuserssothey’llknowwhytofollowalink.InternetExplorerdisplaysitasatooltip.Usethetitleattributetodisplayatooltipforallbrowsers,butalwaysincludealtregardlessunlessyouhaven’tdeinedhref.

tip Inreality,mostpeopleuseatooltodrawtheregionsandgeneratethemapand area coderatherthanfiguringoutallthecoordinatesby

hand.ManyHTMLeditorshavesuchatoolbuiltin,butifyoursdoesn’t,searchforimagemapeditoronline.

note Technically,mapcanbeassociatedwithanobjectorinputelement,too,butyou’llrarelyseethisinpractice.

AttributesinDetailn name=”text”:Deinesthenameofyourimagemapinordertoassoci-

ateitwithanimageviatheimgelement’susemapattribute.Pleaseseetheexample.

Part2:HTMLElementsandGuidance Chapter6:EmbeddedContent(ImagesandObjects) 149

objectAgenericembeddedobject

Syntax <object></object>Attributes Core,I18n,Events,archive*,classid*,codebase*,code-type*,data,declare*,height,name,standby*,tabindex,type,usemap,width,HTML5Only:Global,form

DescriptionTheobjectelementaddsanexternalresource,typicallymediacontentsuchasFlashapplications(games,video,audio,andsoon)butalsoimages,video(QuickTime,andsoon),documents(PDF,Word,andsoon),andJavaapplets(prettyrarenowadays).object’sbrowsersupportvariesbythetypeofcontent,sobesuretotestitaccordingly.ByfaritsmostprevalentuseisforloadingFlashapplications.

Theobject’sinnercontentisfallbackcontentforsearchenginesandbrowsersthatdon’tsupportwhattheobjectwouldotherwiseload.Makesurethealternativecontentrelectstheintendedcontentorisamessageinformingusershowtheycanaccessit,suchaswheretodown-loadaplug-in.

Example1showsanobjectthatloadsaSWF,alongwithitsalternativecontent.Note:Thisismerelytodemonstrateasimpleobject.Idon’trecom-mendyouusethiscodetoembedFlashbecauseitwon’tstreamamovieinIE.YoucanuseSWFObject2,discussedinamoment,forabetterapproach.

Example1:

<object type="application/x-shockwave-flash"

data="how_to_change_tire.swf" width="512" height="384">

(continuesonnextpage)

Part2:HTMLElementsandGuidance150

<param name="movie" value="how_to_change_tire.swf" /> <!--

➥ for IE -->

<!-- Alternative content -->

<h2>How to Change a Tire</h2>

<ol>

<li>Remove spare tire and jack from trunk</li>

. . . remaining steps . . .

</ol>

</object>

Youcanalsonestobjects.Ifthebrowsercan’thandletheirstone,itlookstothesecond,andsoon,downtothealternativecontent.Thebare-bonesstructure(inotherwords,withoutactuallyspecifyingobjectdatatoload)lookslikeExample2.

Example2(nestedobjects):

<object><!-- Can I load this? Yes, then load it and stop. -->

<object><!-- No, then try this (and so on for other

objects). -->

<p>Alternative content</p><!-- Show only if no object

loaded -->

</object>

</object>

ProbablythemostubiquitousexampleofnestedobjectsisSWFObject2,averypopularmethodforembeddingFlashinavalid,cross-browsermanner.Somebrowsershandlenestedobjectsbetterthanothers(pleaseseehttp://www.alistapart.com/articles/lashembedcagematch/),soSWFObject2usesIE’sconditionalcommentstoprovideIEwithonesetofobjectcodeandotherbrowserswithanother.Pleasesee“Step1”athttp://code.google.com/p/swfobject/wiki/documentationforanexample.

Part2:HTMLElementsandGuidance Chapter6:EmbeddedContent(ImagesandObjects) 151

Objectvs.EmbedYoumightbesayingtoyourself,“Wait,doesn’ttheembedelementembedapplicationslikeFlash,too?”Yes,itdoes,butithasneverbeenanoficialpartofHTMLuntilHTML5(seeChapter13).Althoughit’snowafewyearsold,thisarticlesummarizesthetwoelementsnicely(notjustintermsofFlashembedding),describingprosandconsforeach:http://www.alistapart.com/articles/lashembedcagematch/.IgnoreitsmentionofSWFFixattheend,though;SWFObject2hasreplacedthatmethod.

AttributesinDetailn archive=”URIslist”:*ObsoleteinHTML5.Thisspace-separatedlistof

URIsspeciiesthelocationofoneormorearchives(JARiles,forexam-ple)tospeedupthedownloadoftheobject’sresources,whichmayincludethosespeciiedbyclassidanddata.RelativeURIsarerelativetothecodebaseattributeifit’sset.

n classid=”URI”:*ObsoleteinHTML5.Thisspeciiesthelocationofanobject’simplementation.Forinstance,classid=”clsid:D27CDB6E-AE6D-11cf-96B8-444553540000”tellsInternetExplorertoloadtheFlashActiveXcontrol.classid’svaluemaybeinternal,likethepreced-ingvalue,orpointtoalocationontheWeb.

n codebase:*ObsoleteinHTML5.ThissetsthebasepathforresolvingrelativeURIsintheclassid,data,andarchivevalues.Ittakesprece-denceoverabaseattributeinthedocumenthead.Omitittousethedocument’sbaseURI.

n codetype=”content-type”:*ObsoleteinHTML5.Thisindicatesthecontenttypeoftheclassiddatasotheuseragentcandeterminewhetheritsupportsthecontentbeforedownloadingit.Itdefaultstothetypevalueifcodetypeisomitted.

n data=”URI”:Thispointstothedata(resource)tobeembeddedintheobject.Forexample,foraPNG,itcouldbedata=”rowboat.png”.

Part2:HTMLElementsandGuidance152

n declare:*ObsoleteinHTML5.Whenincluded,thisBooleanattributespeciiesthattheobjectshouldnotbeinstantiatedwhenthepageloadsbut,instead,whenanotherelementreferstoit.Anobjectwithdeclaremusthaveanidsoitcanbereferenced,andtheobjectmustappearinthesourcebeforeanyelementthatreferstoit.Onewaytoinstantiateadeclaredobjectiswithalink,asin<p><ahref=”#idOfObject”>Watchthemovie.</a></p>.

n name=”cdata”:Thisspeciiestheobjectnamewhenit’ssubmittedinaform.

n standby=”text”:*ObsoleteinHTML5.Thisspeciiesamessagetodisplaywhiletheobject’simplementationanddataareloaded.

n tabindex:Pleasesee“Attributes”inChapter1.n type=”content-type”:Thisindicatesthecontenttypeofthedata,

helpingauseragentdeterminewhethertoloadit(inotherwords,ifit’ssupported).TheHTTPcontenttypereturnedbytheservertakesprecedence.

n usemap:Thisassociatesamapelementwiththeobjectwhensettothemap’snameattributevalue.Pleaseseethemapelementinthischapterforanexampleofusemapwithimg;thesameprincipleapplieswithobject.

n width=”percentageorpixels”andheight=”percentageorpixels”:Thesespecifytheobject’sdimensionsinpixelsorasapercentageofitsparentelement’ssize.Thoughthey’retechnicallyoptional,somebrowsersrequirethem.

DeprecatedAttributesUsetheCSSpropertieslistedinparenthesesinsteadofthesedeprecatedattributes:align(floatandvertical-align),border(border),hspace

Part2:HTMLElementsandGuidance Chapter6:EmbeddedContent(ImagesandObjects) 153

(margin-leftandmargin-right),andvspace(margin-topandmargin-bottom).AlloftheseattributesareobsoleteinHTML5.

HTML5andtheobjectElementThearchive,classid,code,codebase,codetype,declare,andstandbyattributesareallobsoleteinHTML5.Forallofthese,withtheexcep-tionofdeclareandstandby,youcanuseaparamelementwithanameequaltotheattributename(thatis,<paramname="archive"value="..."/>)ifyouneedtopassthatdatatotheembeddedobject.Pleaseseeparaminthischapterformoreinformation.

AttributesinDetail

HTML5requiresatleastthedataortypeattributetobepresent.n form=”formelementID”:Whensettoaformelement’sid,theform

attributeassociatestheobjectwiththatformelement.

paramObjectresourceparameter

Syntax <paramname=""value="">or<paramname=""value=""/>

Attributes Core,I18n,Events,name,type*,value,valuetype*,HTML5Only:Global

DescriptionTheparamelementpassesaparameternameandvaluetotheexternalresourceloadedbyanobjectelementforittouseatruntime.Each

Part2:HTMLElementsandGuidance154

objectmayhavemultipleparams.Therearen’tasetofparamnamesdeinedintheHTMLspecs;it’sunderstoodthattheembeddedresourcewillknowwhattodowiththosepassedtoit.

objectisusedtoembedFlashmorethananytypeofcontent.TwocommonparamstopassaSWFareflashvarsandwmode.Theirstpassesastringofvariables(eachseparatedwith&amp;)intothemovie,andthesecondallowsyoutopositionHTMLontopofaSWFwiththeCSSz-indexproperty(itmayimpactperformance,though,sokeepaneyeoutforthat).

Example:

<object . . .>

. . .

<param name=”flashvars” value=”content=info.xml&amp;page=3

/>”

<param name="wmode" value="opaque" />

. . .

</object>

PleasealsoseeExample1intheobjectentryinthischapter.

AttributesinDetailn name=”cdata”:Theparametername.n type=”content-type”:*ObsoleteinHTML5.Speciiesthecontenttypeof

value’sdesignatedresourcewhenvaluetype=”ref”.n value=”cdata”:Theparametervalue.n valuetype=”data|object|ref”:*ObsoleteinHTML5.Speciiesthe

contenttypeofthevalueattribute.

Part2:HTMLElementsandGuidance Chapter6:EmbeddedContent(ImagesandObjects) 155

– Whenvaluetype=”data”,whichisthedefault,itindicatesthatvalue’svalueispassedasastring.

– Youcanpassinaresourcefromanotherobjectwhenvaluetype=”object”andvalueisahashnameoftheotherobject’sid.Examplesare<objectid=”idOfObject"data=”wheelbarrow.gif”type=”image/gif”></object>and<paramname=”image”valuetype=”object”value=”#idOfObject”/>inthesecondobject.

– Whenvaluetype=”ref”,valuemustbeaURIwhereruntimevalues(suchasanimageorasoundile)arestored.

Formsdrivedatagatheringandsearching,whetherit’sforWebapplica-tions,solicitinguser-generatedcontent,sellingproducts,orconductingpolls.

Thischaptercoverstheform-relatedelementscommontoalllavorsofHTML,plusincludestheirnewattributesinHTML5,whichhelpmaketheWebaricherapplicationmedium.

Ifyou’relookingforanoverviewofforms,theformentryprovidesanexampleofacompleteformalongwithitsbehaviorandadescriptionofitscomponents.

Forms

7

Part2:HTMLElementsandGuidance158

buttonAformbutton

Syntax <button></button>Attributes Core,I18n,Events,accesskey,disabled,name,tabindex,type,value,onblur,onfocus,HTML5Only:Global,autofocus,form,formaction,formenctype,formmethod,formnovalidate,formtarget

DescriptionThebuttonelementcanbeasubmitbutton,aresetbutton,orastaticbutton.Inthisregard,itisthesameastheinputelementsoftype=”submit”ortype=”image”(bothofwhichsubmitaform),type=”reset”,andtype=”button”(astaticbutton).

However,buttonisdifferentinthatyoumayplaceHTML(text,images,andmostelements)insideitandstyleitwithCSS.(Youmaystyleinputbuttons,too,buttheydon’tacceptcontentlikebutton.)

Example:<button type=”submit” name=”submitbtn”><strong>Finalize

Order</strong></button>

Theexampleshowsasubmitbuttonandassumesit’scontainedinaformelement.Settype=”reset”foraresetbutton(whichrestoresallformcontrolstotheirinitialvalues),andsettype=”button”forastaticonethatrequiresaddingbehaviorwithJavaScript.DisplayanimagebuttonbyusingeitheranimgasthecontentoraCSSbackground-imagetechnique.

However,buttonhasonemaingotcha:unusualInternetExplorerbehav-ior,particularlyinIE6.(Yes,althoughIE6isold,itremainsarequirementformanyifnotthemajorityofsites.)

Part2:HTMLElementsandGuidance Chapter7:Forms 159

IE6and7,aswellasIE8incompatibilitymode,alldon’tsubmitabutton’svalue;theysubmititscontents—yes,theHTMLthatisbetween<button>and</button>(technically,knownasitsinnerText).Thisisparticularlyoff-puttingwithaformofmethod=”get”becausethatHTMLendsupinyourquerystring.NotethatIE8instandardsmodecorrectlysubmitsthebutton’svalue,asdoallothercommonuseragents.

IE6exhibitsalargerproblemwhenyourformhasmultiplebuttons.Itsubmitsthenameofallthebuttons,notjusttheonetheuserselected,soyoucan’tprocesstheformaccordingly.Forexample,didtheuserselectUpdateShoppingCartorPlaceMyOrder?

Ifyourformhasonlyonebuttonandyou’reusingmethod=”post”(orifthemuddiedquerystringdoesn’tpresentproblems),you’reOK.Otherwise,yoursafestbetisusinginputbuttons,notbuttonelements.inputwithtype=”image”oftenprovidesplentyofcreativecontrol.

AttributesinDetailn accesskeyandtabindex:Pleaseseethe“Attributes”sectionof

Chapter1.n disabled:Pleasesee“AttributesinDetail”fortheinputelementin

thischapter.n name=”cdata”:Thisspeciiesthebutton’snameforthepurposesof

processingtheform.PleaseseethedescriptionfortheprobleminIE6.n onblur=”script”andonfocus=”script”:Pleasesee“AttributesinDetail”

fortheinputelementinthischapter.n type=”button|reset|submit”:Pleaseseethedescriptionfordetails

ofthethreetypes.Iftypeisunspeciied,mostbrowsersdefaulttosubmit,butIE6and7,aswellasIE8incompatibilitymode,alldefaulttobutton,sotheywon’tsubmittheformunlessthetype=”submit”.

n value=”cdata”:Thissetsthebutton’svalue,whichispairedwithitsname.

Part2:HTMLElementsandGuidance160

fieldsetAsetofrelatedcontrols

Syntax <fieldset> <legend></legend>

. . . [form controls] . . .

</fieldset>

Attributes Core,I18n,Events,HTML5Only:Global,disabled,form,name

DescriptionThefieldsetelementgroupstogetheroneormorerelatedformcontrols.Theoptionallegendelementidentiiesthegroup,displaysinthepage,andisreadbyscreenreaders.Pleaseseetheexampleanddiscussionintheformelemententryinthischapter.

HTML5andthefieldsetElementThefieldsetelementsupportstheseadditionalattributesinHTML5.

AttributesinDetailn disabled:Pleasesee“AttributesinDetail”fortheinputelementin

thischapter.n form=”formid”:Pleaseseethe“HTML5andtheinputElement”

boxinthischapter.n name=”cdata”:Thisspeciiesthefieldsetelement’sname.

Part2:HTMLElementsandGuidance Chapter7:Forms 161

formAninteractiveform

Syntax <formaction=””>. . . [your form] . . .

</form>

Attributes Core,I18n,Events,accept*,accept-charset,action,enctype,method,name,onreset,onsubmit,HTML5Only:Global,autocomplete,novalidate,target

DescriptionUsetheformelementanditscontrolstocollectdatafromusers.Usesincludeenablingregisteringonasite,submittingshippingandcreditcardinformation,conductingapoll,gatheringusercommentsonablogornewssite,andsoon.(Pleasenotethatyoumaynotnestaformelementinsideanotherone.)

Aformcontainsoneormorecontrols(button,input,select,andtextarea)withwhichtheusercanengage,aswellasotherelements(fieldset,label,andlegend)thataddsemanticandstructuralmeaning.

Theupcomingcodeexampleresultsinthisformdefaultrendering:

Part2:HTMLElementsandGuidance162

note Elementslookdifferentdependingonthebrowserandplatform.YoucandictatetheappearancewithCSStovaryingdegrees.

Thecodethatfollowscontainsallbuttwooftheavailableformchildelementssoyoucanseehowtheyworktogether(buttonandoptgrouparetheonlyonesnotshown,butthey’redescribedintheirrespectiveentriesinthischapter).I’vebrokenthecodeintotwopartstomakeiteasiertodiscussandhavehighlightedatleastoneinstanceofeachform-relatedelementandattributetheexampleuses.

Example(part1):

<h1>Public Radio Station Listener Survey</h1>

<form action="process-form.php" method="post">

<div> <!-- text input -->

<label for="fullname">Full Name:</label>

<input type="text" id="fullname" name="fullname"

maxlength="100" />

</div>

<fieldset> <!-- radio buttons -->

<legend>Gender</legend>

<input type="radio" id="female" name="gender"

value="female" /> <label for="female">Female</label>

<input type="radio" id="male" name="gender"

value="male" /> <label for="male">Male</label>

</fieldset>

. . . [code from Example (part 2)] . . .

note Iuseadivintheexampletocontainmostformelements.Someprefertouseafieldsetforeachorliswithinalist.Therearenosetrules

aboutthisaslongasyoudon’tuseatable.

Part2:HTMLElementsandGuidance Chapter7:Forms 163

Thispartoftheexampleincludestheform,fieldset,legend,label,andtextinputtypeelementsandradiobuttoninputtypeelements.

Theformelement’sstarttagbeginseachform.Intheexample,theaction=”process-form.php”valuespeciiestheserver-sidelocationthatissenttheformdataforprocessingoncetheusersubmitsitviatheSubmitMyInformationbuttonattheendofpart2oftheexample.Pleasesee“AttributesinDetail”concerningmethod=”post”.

Eachformcontrolhasanameattribute,whichispairedwithitsvalueattribute.Thevalueistypicallydictatedbywhattheuserentersorselects.Whenaformissubmitted,eachcontrolnamewithavalueispassedtotheprocessingscript.Thenamemustbeuniquethroughoutaform,withtheexceptionofarelatedsetofradiobuttonsorcheckboxes.Forinstance,inpart1oftheexample,there’saradiobuttoninputeachforfemaleandmale,butbothhavename=”gender”.Theirvalueattri-butesaredifferent,though;theformsubmitsthevalueof“female”iftheuserselectsthatoptionand“male”fortheother.

Thelabelelement’stextdescribesaformield(forexample,<labelfor="fullname">FullName:</label>).Eachlabelelementisexplicitlyassociatedwithacontrolwhenitsforattributevalueisthesameasacontrol’sid.Forinstance,inpart1ofexample,becausetheirstlabelhasfor=”fullname”,it’sassociatedwiththiscontrol:<inputtype="text"id="fullname"name="fullname"maxlength="100"/>(acontrol’snameandidvaluesareoftenthesamebutdon’thavetobe).

note Donotuseaspecific

name(forexample,name=”email”)ononeelementandthesameidvalue(forexample,id=”email”)onadiffer-

entelement,oryou’reboundtorunintoproblemsinInternetExplorerifyoutrytoaccesstheelementswithJavaScript.

Thefieldsetelementgroupstogetheroneormorerelatedformcontrols.Theoptionallegendelementidentiiesthegroupanddisplaysinthe

Part2:HTMLElementsandGuidance164

page.Forexample,afieldsetcontainsourgender-relatedradiobuttons,and<legend>Gender</legend>describesthegroup.legendiscrucialforscreenreaderusersbecauseitprovidescontexttothefieldset’scontrols.

Thatcoversthehighlightsoftheirstpartofourform.Nowlet’slookatthesecondpart.Again,I’vehighlightedportionsthatI’lldiscussafterthecode.

Example(part2):

. . . [code from Example (part 1)] . . .

<div> <!-- select box -->

<label for="country">Country:</label>

<select id="country" name="country">

<option value="AF">Afghanistan</option>

<option value="AL">Albania</option>

. . . [more country options] . . .

</select>

</div>

<div> <!-- textarea -->

<label for="comments">Comments:</label>

<textarea id="comments" name=”comments” rows="3"

cols="40"></textarea>

</div>

<div> <!-- checkbox -->

<input type="checkbox" id="subscribed"

name="subscribed" checked="checked" /> <label

for="subscribed">Yes, I'm a current subscriber</label>

</div>

<div> <!-- submit -->

<input type="submit" value="Submit My Information" />

</div>

</form>

Part2:HTMLElementsandGuidance Chapter7:Forms 165

Part2oftheexampleincludestheselect,option,textarea,checkboxinputtype,andsubmitbuttoninputtypeelements.

Aselectboxincludesoneormoreoptionelementsthatrepresentthechoicesausermaymake.Forinstance,inthecaseof<optionvalue="AF">Afghanistan</option>,Afghanistanappearson-screen.Iftheuserselectsit,theAFvalueispassedtotheserveruponsubmission.

Atextareaisdifferentfromatextinput(seepart1oftheexample)becauseitcanbeseverallinestall,asdeinedbytherowsattributeandbecauseyoucan’tsetamaxlengthinX/HTML(youcancontrolitwithJavaScript,however).Thecolsattributespeciiesthenumberofcharac-tersallowedonaline,effectivelydeiningitswidth.You’llnoticedifferentrenderingsizesacrossbrowsers;usetheCSSheightandwidthpropertiestonormalizethedimensions.

Nextupisaninputwithatypeofcheckbox.You’llnoticethechecked=”checked”attributeinpart2oftheexamplecode.Thisprese-lectsthecheckbox.(Note:checked=”checked”istheXHTMLsyntax;usesimplycheckedforHTML4,thougheitherformatisacceptableinHTML5.)

Theexample’s<inputtype="submit"value="SubmitMyInformation"/>codedisplaysabuttonthatreadsSubmitMyInformation—orwhateveryouspecifyasthevalue.Becausetheinputissettotype=”submit”,theformissubmittedwhentheuserengagesthebutton.

Thisshouldgiveyouasenseofhowaformworks.Pleaseseetheotherentriesinthischapterforadditionaldetailsabouttheform-relatedelementsandtheirattributes.

AttributesinDetailn accept=”content-typelist”:*ObsoleteinHTML5.Pleasesee“Attributes

inDetail”fortheinputelementinthischapter.

Part2:HTMLElementsandGuidance166

n accept-charset=”charsetlist”:Thisspace-and/orcomma-delimitedlistindicatesthecharacterencodingsforinputdatathattheserverprocessingtheformaccepts.Typically,it’sleftout,sincethedefaultvalueisthereservedstring,“UNKNOWN,”whichbrowsersmayinterpretasthecharacterencoding(suchasutf-8)ofthepagethatcontainstheform.

n action=”uri”:RequiredinX/HTML.Thisattributepointstotheserverlocationthatwillprocesstheformwhenitissubmitted(pleaseseetheexample).Ifomitted,theformwillsubmittothecurrentpage.

n enctype=”content-type”:Whenmethod=”post”,thisattributecanbeusedtospecifytheencodingoftheformdatasenttotheserver.Typically,it’sleftout(thedefaultvalueisapplication/x-www-form-urlencoded);however,youshouldincludeitasenctype=”multipart/form-data”ifyourformincludesaninputwithtype=”file”.Thethirdpossiblevalueistext/plain(dataislargelyunencodedwhensubmitted),butitisusedrarely.

n method=”get|post|plusdelete|putforHTML5”:Themethod="post"declarationmeansthatuponsubmission,theformvaluesaresenttotheserverwithoutbeingexposedtotheuser.Itisthemoresecuremethod.Generallyspeaking,it’sthemethodofchoicewheneveryouwanttopostinformationtotheservertosave,update,orremovedatainadatabase.Anexampleisashippingaddressandcreditcardinfor-mationformonane-commercesite.Whenmethod="get",thevaluesareappendedtotheactionvalue’sURIfollowedbyaquestionmark.Generallyspeaking,usemethod="get"wheneveryouwanttogetinformationfromtheserveraftertheformissubmitted.Anexampleisasearchformthatreturnsresults.Ifaction=”search-results.php”andthesearchinputtextieldhasaname=”searchphrase”attribute,thenthetailendofthe

Part2:HTMLElementsandGuidance Chapter7:Forms 167

URIwouldbesearch-results.php?searchphrase=Kermit+and+YodaaftersearchingforKermitandYoda.HTML5includestwomoremethodvalues,deleteandput,whichmaptotheHTTPDELETEandHTTPPUTmethods,respectively.

n name=”cdata”:Thisattributewasincludedforbackwardcompatibilitywithmucholderuseragents,butyoushoulduseidinsteadtoapplyauniqueidentiier(forexample,<formid=”signup”...>)forstylingorscriptingpurposes.

n onreset=”script”:Thiseventireswhentheuseractivatesaninputbuttonwithtype=”reset”.AttachthiseventunobtrusivelyinsteadofasanattributeintheHTML.

n onsubmit=”script”:Thiseventireswhentheformissubmitted,allow-ingyoutoexecuteJavaScript,suchasafunctionthatsubmitstheformviaAjaxinsteadofapagerefreshincaseswherescriptingisenabled.AttachthiseventunobtrusivelyinsteadofasanattributeintheHTML.

HTML5andtheformElementTheformelementhasthreeadditionalattributesinHTML5.

AttributesinDetailn autocomplete:Pleaseseethe“HTML5andtheinputElement”box

inthischapter.n novalidate:Whenpresent,thisBooleanattributeindicatesthat

theform’sdatashouldnotbevalidatedwhenit’ssubmitted.n target=”name”:Thissetsthetargetoftheformsubmissionand

canhaveavalueof_blank,_parent,_self,or_top,oravalueyouspecifythatcouldmatchthenameofaniframe.

Part2:HTMLElementsandGuidance168

inputAninputcontrol

Syntax <inputtype=””/>or<inputtype=””/>

Attributes Core,I18n,Events,accept,accesskey,alt,checked,disabled,ismap,maxlength,name,onblur,onchange,onfocus,onselect,readonly,size,src,tabindex,type,usemap,value,HTML5Only:Global,autocomplete,autofocus,disabled,form,formaction,formenctype,formmethod,formnovalidate,formtarget,height,list,max,min,multiple,pattern,placeholder,required,step,width

DescriptionTheinputelementisthemostdiverseoftheformcontrols,sinceitcanbeacheckbox,aradiobutton,asingle-linetextentryield,hiddenfromtheuser,ameanstouploadaile,animagebuttonforsubmittingaform,andmore.Thetypeattributedictateswhichoftheseshapesaninputtakes.

Examplesofeachtype:

<input type=”button” name=”calculate” value=”Calculate” />

<input type=”checkbox” name=”newsletter” value=”technology” />

<input type=”file” name=”uploadedvideo” />

<input type=”hidden” name=”productids” value=”19382, 10375” />

<input type=”image” name=”submit” src=”btn_submit.png”

alt=”Submit Form” />

<input type=”password” name=”password” maxlength=”25” />

<input type=”radio” name=”color” value=”blue” />

<input type=”reset” name=”reset” value=”Reset Form” />

<input type=”submit” name=”submit” value=”Place Order” />

<input type=”text” name=”firstname” maxlength=”50” />

Part2:HTMLElementsandGuidance Chapter7:Forms 169

note Pleaseseethe

formentryinthischapterforanexampleregardinginputsoftype=”checkbox”,type=”radio”,type=”submit”,and

type=”text”,includingascreenshotofhowtheyrenderbydefault.

Aninputoftype=”button”rendersabuttonthatdoesnotsubmittheformwhentheuseractivatesit.Thevalueattributeprovidesthetextthatappearsonthebutton.YoumayuseJavaScripttoapplybehaviortoit.

Aninputoftype=”checkbox”islikeanon/offswitch.Itsvalueissubmit-tedonlywhentheboxisselected(“on”).Likeradiobuttons,asetofrelatedcheckboxesmayhavethesamenameattribute;however,insuchacase,theirvalueattributesshouldbedifferent.Forinstance,youmightofferseverale-mailnewslettersforwhichuserscansignup.Yourcheckboxescouldbe<inputtype=”checkbox”name=”newsletter”value=”design”/>and<inputtype=”checkbox”name=”newsletter”value=”technology”/>.Ausermayselectmultiplecheckboxes.

Aninputoftype=”file”allowsuserstobrowseontheircomputerornetworkforailetoupload.

Aninputoftype=”hidden”doesn’tdisplay,andtheusercannotchangeitsvalue.Ahiddeninputallowsyoutopassdatafrompagetopage.

Aninputoftype=”image”displaysasubmitbuttonthatisrepresentedbythesrcattribute.Whentheformissubmitted,thepasseddataisname.x=x-valueandname.y=y-value.Thenameistheelement’snameattributevalue.x-valueandy-valuearethexandypixelcoordinates—measuredfromthetopleftcorneroftheimage—ofwheretheuserclickedwithintheimage(ifamouseorsimilarpointingdevicewasused).

Useaninputoftype=”password”whenrequestingauser’spassword.Itrenderslikeatextinputexceptthatforprivacy,dots,orasimilarcharac-terdisplayinsteadofthecharacterstheuserenters.

Part2:HTMLElementsandGuidance170

Aninputoftype=”radio”displaysaradiobutton.Radiobuttonstypi-callycomeinsetsofatleasttwo(otherwiseuseacheckbox).Unlikeacheckbox,ausermayselectonlyoneradiobuttonfromasetofthemsharingthesamenameattribute.However,likewithacheckbox,makesureeachrelatedradiobuttonhasadifferentvalue.Pleaseseethegenderexampleanddescriptionintheformentryinthischapter.

Aninputoftype=”reset”displaysabuttonthatresetsallcontrolstotheirinitialvalues(thatis,priortouserinvolvement).ThetextonthebuttonreadsResetunlessyouoverrideitwiththevalueattribute.

Aninputoftype=”submit”displaysabuttonthatsubmitstheformwhentheuseractivatesit.ThetextonthebuttonreadsSubmitunlessyouoverrideitwiththevalueattribute.

Aninputoftype=”text”providesasingle-linetextboxwithanoptionalmaxlengthattributethatlimitsthenumberofcharactersacceptedbythebox.Ifvalueisset,itstextappearsinthetextinputbydefault.Usethetextareaelement(alsointhischapter)toallowforalonger,multilinetextentry.

AttributesinDetailn accept="content-typelist":*ObsoleteinHTML5.Thisattributespeciies

acomma-separatedlistofmediatypesauseragentmayusetoverifythatilessubmittedbyaformviaaninputtype=”file”isacceptable.However,browsersupportispoor,soyoushouldn’trelyonit.Besureyourserver-sideform-processingscriptperformsallrequiredvalidationofuploadediles.

n accesskey:Pleaseseethe“Attributes”sectionofChapter1.n alt=”text”:Thisbehaveslikealtontheimgelement—providingalter-

natetextwhentheimagedoesn’tdisplay—exceptinthiscaseit’sforaninputoftype=”image”.

Part2:HTMLElementsandGuidance Chapter7:Forms 171

n checked:Whenpresent,thisBooleanattributepreselectsinputsoftype=”checkbox”andtype=”radio”.AswithotherBooleanattributes,ittakesadifferentformdependingonthemarkuplanguageversion(asspeciiedbytheDOCTYPE).checked="checked"istheXHTMLsyntax;usesimplycheckedforHTML4,thougheitherformatisaccept-ableinHTML5.

n disabled:Whenpresent,thisBooleanattributedisablestheelementsotheusercan’tinteractwithit.Furthermore,adisabledcontroldoesn’treceivefocus,itisskippedintabbingnavigation,anditsvalueisnotsubmittedwiththeform.

n ismap:Whenpresent,thisBooleanattributespeciiesthataninputoftype=”image”isaserver-sideimagemap.You’llrarely,ifever,seethisusedthesedays.

n maxlength=”number”:Thisspeciiesthemaximumnumberofcharac-tersallowedinatype=”text”ield.

n name=”cdata”:Thisassignsanametotheinput,whichispairedwithitsvaluewhenprocessingtheform.

n onblur="script"andonfocus="script":Theseeventsareopposites.onblurireswhenfocusleavestheelement,suchaswhentheusertabsawayfromitorclicksoutsideit,whileonfocusireswhenfocusisrestored.Aswithotherevents,addthemunobtrusivelywithJavaScriptratherthanhard-codingthemintheHTML.

n onchange="script":Thiseventireswhentheuserchangesthecontent.n onselect="script":Thiseventireswhentheuserselectscontentinan

inputoftype=”text”.n readonly:Whenpresent,thisBooleanattributeprohibitstheuser

fromalteringtheelement’scontents.Theelementstillmayreceivefocus,betabbedtowiththekeyboard,andsubmitswiththeform.

Part2:HTMLElementsandGuidance172

n size="number":Thissetsthenumberofcharactersthatarevisibleforaninputoftype=”text”.Renderingvariesacrossbrowsers,sousetheCSSwidthpropertyforinercontrolandmoreconsistency.

n src=”uri”:Thisspeciiesthelocationoftheimageforaninputoftype=”image”.

n tabindex:Pleaseseethe“Attributes”sectionofChapter1.n type=”text|password|checkbox|radio|submit|reset|file|hidden|

image|button”:Pleaseseethedescriptionsofeachtypeinthisentry.n usemap:Whenpresent,thisBooleanattributespeciiesthataninput

oftype=”image”isaclient-sideimagemap.PleaseseetheentryforthemapelementinChapter6formoredetails.

n value:Thisisthevalueoftheinputthatisassociatedwithitsname,bothofwhicharepassedtotheprocessingscriptwhentheformissubmitted.

HTML5andtheinputElementOneofHTML5’sprimarygoalsistoprovidenativeelementsthatenablecreatingWebapplicationsmoreeasily.Inthatvein,itmakesbigadvancesintheformdepartment,especiallyasitpertainstoinputtypesandotherattributes.

AttributesinDetailn autocomplete=”on|off”:Manybrowsersstorevaluesyou’ve

enteredinatextield(withaparticularname)forsubsequentusewhenillingoutanotherform.Forinstance,nodoubtyou’vefoundyourselftypingyourcityore-mailaddressinatextield,onlytoseeitappearinasmallmenufromwhichtochoose.It’shandywhenyou’reusingtheform,butit’sdangerousifsomeoneelseusesyourbrowserlater.Theymaybeexposedtosensitive

Part2:HTMLElementsandGuidance Chapter7:Forms 173

information(suchasacreditcardnumber)you’veentered.Whenyousetautocomplete=”off”,theuseragentwon’tdothis.Thedefaultvalueisthatoftheautocompletesettingfortheinput’sformowner--whichisthenearestformelementthatcontainstheinput--orthatisassociatedwiththeieldviatheinput’sformattri-bute.Aformelement’sautocompletedefaultstoon,sobesuretosetautocomplete=”off”forallsensitiveinputields.

n autofocus:Whenpresent,thisBooleanattributetellsthebrowsertosetfocusontheieldassoonasthepageisloaded.Thisallowsuserstousethecontrolwithouthavingtotabtoitorclickitirst.

n form=”formid”:Bydefault,eachformcontrolisassociatedwithitsnearestancestorformelement(thatis,theformthatcontainsit).Setthisattributetotheidofadifferentforminthepagetooverridethisbehavior.

n formaction,formenctype,formmethod,formnovalidate,andformtarget:Thesearethesameastheformelement’saction,enctype,method,novalidate,andtargetattributes,respectively,exceptyoumayassignthemtoasubmitbutton.Iftheyaren’tpresent,theydefaulttotherelatedattributevaluesoftheinput’sformowner(seetheautocompleteattribute).

n height=”numberofpixels”andwidth=”numberofpixels”:Thesespecifytheheightandwidth,respectively,ofaninputoftype=”image”.

n list=”datalistid”:Thisidentiiesanelementthatlistspredeinedoptionssuggestedtotheuserinadatalistelement(seeChapter14).Itsvalueshouldmatchtheidoftherelevantdatalistinthesamedocument.

n maxandmin:Theseindicatetherangeofacceptablevaluesforinputsthatareoftypedate,datetime,datetime-local,month,number,range,time,andweek. (continuesonnextpage)

HTML5andtheinputElement(continued)

Part2:HTMLElementsandGuidance174

n multiple:Whenpresent,thisBooleanattributespeciiestheuserisallowedtoentermorethanonevalueintheinputield.Itappliesonlytoinputsoftype=”email”andtype=”file”.

n pattern=”regularexpression”:Thisspeciiesaregularexpres-sion—thesamekindyouuseinJavaScriptperECMAScript—againstwhichthebrowsershouldchecktheinput'svaluewhenaformissubmitted(butbeforeit’ssenttotheserver).Pleaseseethe“Patterns”sectionoftheECMAScriptspec:http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf.Forexample,youwouldcheckforaive-digitnumericpatternwith<inputpattern="[0-9]{5}"name="zipcode"title="Azipcoderequiresfivenumbers."/>.Youshouldincludeatitleattributethatdescribestherequiredpattern;useragentsdisplayittousersasahint.patternisawelcomeadditiontoHTML5sinceitallevi-atestheneedtowriteJavaScriptforclient-sideformvalidation(ofcourse,youshouldalwaysdoserver-sidevalidationregardless).

n placeholder=”text”:Thisdeinesawordorbriefphrasethatdisplaysintheelementasahinttowhattheusershouldenterintheield.Whentheusertabstotheield,clicksit,orhasprevi-ouslyenteredtextinit,theplaceholdervaluedoesn’tshow.Itappliesonlytoaninputoftype=”text”andatextareaelement.Itshouldn’tbeusedasareplacementforthelabelelement.

n required:Whenpresent,thisBooleanattributerequirestheusertoengagetheinput(thatis,makeaselectionorentertext,asthecasemaybe)beforesubmittingtheform.Useragentsmayalertuserswhenthey’vefailedtocompletetheield(tryitinOpera10.5toseeitinaction!).

n step:AccordingtoHTML5,this“indicatesthegranularitythatisexpected(andrequired)ofthecontrol’svalue,bylimitingtheallowedvalues.”Itappliestoinputsthatareoftypedate,datetime,datetime-local,month,number,range,time,andweek.

HTML5andtheinputElement(continued)

Part2:HTMLElementsandGuidance Chapter7:Forms 175

n type=”color|date|datetime|datetime-local|email|month|number |range|search|tel|time|url|week”:TheseadditionalinputtypesareoneofHTML5’sbiggestfeatures.Wheresupported,validationoccursnativelyinthebrowser.Theemail,search,tel,andurltypesarespeciictypesoftextields.Theothersprovidenewkindsofcontrols,suchasacolorpickerforcolorandthosedescribedin“ExamplesofNewinputTypes.”

ExamplesofNewinputTypes

Hereareafewexamplesofthenewinputtypes.Operahasthebestsupportatthetimeofthiswriting.Nonsupportingbrows-erstypicallyfallbacktoaninputoftype="text".Pleaseseehttp://www.htmlfiver.com/extras/inputs/formoreinformationaboutthenewtypes(andmoreexamples).

Thedatetypeprovidesacalendar.Inthisexample,theusermustselectadateonorafterJune11,2010.(datetime,datetime-local,month,andweekalsoprovideacalendar,thoughtheirallowedvaluesdiffer.datetimeanddatetime-localalsoshowatimecontrollikethekindtype=”time”displays.)

<input type="date" name="eventdate" min="2010-06-11" />

Thenumbertypeshowsatextieldandspinnercontrol.Inthisexam-ple,theuserisrequiredtoselectanumber,anditmustbebetween10and25:

<input type="number" name="quantity" min="10" max="25"

required=”required” />

Therangetypeshowsaslidercontrol.Inthisexample,thevalueisbetween100and500inincrementsof10.:

<input type="range" name="pick" min="100" max="500"

step="10" />

HTML5andtheinputElement(continued)

Part2:HTMLElementsandGuidance176

labelAformcontrollabel

Syntax <labelfor=””></label>

Attributes Core,I18n,Events,accesskey,for,onblur,onfocus,HTML5Only:Global,form

DescriptionUsethelabelelementtoassociateatextlabelwithaformcontrol.Setitsforattributetothecontrol’sidtomaketheassociation;thisiscrucialforaccessibility.Manybrowsersputthecursorfocusinsidetheinput(orselectthechoiceinthecaseofaradiobuttonorcheckbox)iftheuserclicksthelabeltext.

Example:

<label for=”address”>Street Address:</label> <input

type=”text” id=”address” name=”address” />

Pleasealsoseetheexampleanddiscussionintheformelemententryinthischapter.

note Youareallowedtowraplabelaroundcontrols,suchasacheckboxinput.However,somescreenreadersmayfailtoannouncethecontrol

containedinthelabel,sobesuretotestyourform.Whenindoubt,stickwiththemodelshownintheexample.

AttributesinDetailn accesskey:Pleaseseethe“Attributes”sectionofChapter1.n for=”controlid”:Associatesthelabelwithacontrolwhensettothe

control’sid.

Part2:HTMLElementsandGuidance Chapter7:Forms 177

n onblur=”script”andonfocus=”script”:Theseeventsareopposites.onblurireswhenfocusleavesthelabel,whileonfocusireswhenitisrestored.

HTML5andthelabelElementThelabelelementhasoneadditionalattributeinHTML5.

AttributesinDetailn form=”formid”:Pleaseseethe“HTML5andtheinputElement”

boxinthischapter.

legendAieldsetcaption

Syntax <fieldset> <legend></legend>

. . . [form controls] . . .

</fieldset>

Attributes Core,I18n,Events,accesskey,HTML5Only:Global

DescriptionTheoptionallegendelementidentiiesthegroupofcontrolscontainedwithinafieldset.Thelegenddisplaysinthepageandisreadbyscreenreaders,providingvisuallyimpaireduserscontextfortherelatedformcontrols.Pleaseseetheexampleanddiscussionintheformelemententryinthischapter.

Part2:HTMLElementsandGuidance178

AttributesinDetailn accesskey:Pleaseseethe“Attributes”sectionofChapter1.

DeprecatedAttributesThealignattributeisdeprecated.

optgroupAgroupofselectchoices

Syntax <optgrouplabel=””><option></option>

. . .

</optgroup>

Attributes Core,I18n,Events,disabled,label,HTML5Only:Global

DescriptionUsetheoptgroupelementtoorganizeoneormoregroupsofrelatedoptionelementsinaselectelement.Eachoptgroupmustcontainatleastoneoption.

Example:

. . .

<select name="computers">

<optgroup label="Desktops">

<option value="xyz2000">The XYZ 2000</option>

. . . [more Desktop options] . . .

</optgroup>

<optgroup label="Laptops">

Part2:HTMLElementsandGuidance Chapter7:Forms 179

. . . [Laptop options] . . .

</optgroup>

</select>

. . .

Typically,optgrouprendersbydefaultlikethis:

AttributesinDetailn disabled:Pleasesee“AttributesinDetail”fortheinputelementin

thischapter.BothInternetExplorer6and7ignoreitonoptgroup.n label="cdata":Required.Thisprovidesthegroup’slabelthatdisplays

intheselectboxabovetheoptgroup’soptions.

optionAselectelementchoice

Syntax <option></option>Attributes Core,I18n,Events,disabled,label,selected,value,HTML5Only:Global

DescriptionTheoptionelementprovidesachoicewithinaselectelement.

Pleaseseetheformandoptgroupelemententriesinthischapterforexamplesandmoreinformation.

Part2:HTMLElementsandGuidance180

AttributesinDetailn disabled:Pleasesee“AttributesinDetail”fortheinputelementin

thischapter.BothInternetExplorer6and7ignoreitonoption.n label="cdata":Iflabeltextisspeciied,useragentsaresupposedto

renderitinsteadofthetextinsidetheoption.OnlyChrome,Opera,andSafarisupportitamongpopularbrowsers.

n selected:Whenpresent,thisBooleanattributepreselectstheoption.Morethanoneoptionmaybepreselectedifthemultipleattributeissetontheselectelement.

n value=”cdata”:Thisisthevaluesubmittedwiththeformiftheuserchoosestheoption.Ifthevalueattributeisn’tspeciied,theoption’sinsidetext,forinstance,<option>GroundShipping</option>,isitsvalue.

HTML5andtheoptionElementHTML5’sdatalistelementmaycontainoneormoreoptionele-ments.PleaseseeChapter14fordetails.

selectAmenuofchoices

Syntax <selectname=””><option></option>

</select>

Attributes Core,I18n,Events,disabled,name,multiple,size,HTML5Only:Global,autofocus,form

Part2:HTMLElementsandGuidance Chapter7:Forms 181

DescriptionUsetheselectelementtoprovideoneormorechoicesinasingle“menu.”Eachchoiceisrepresentedbyanoptionelement,whichmayeitherexistonitsownorexistaspartofanoptgroup.Pleaseseetheexamplesintheformandoptgroupelemententriesinthischapter.

AttributesinDetailn disabled:Pleasesee“AttributesinDetail”fortheinputelementin

thischapter.n name=”cdata”:Thisspeciiestheselectelement’snamesotheform-

processingscriptcanassociatetheselectedoptionswiththeselect.n multiple:Whenpresent,thisBooleanattributeallowsformorethan

onechoicefromtheselectbox.n size=”number”:Bydefault,aselectdisplaysonlyoneoptionwhen

theuserhasn’texpandedthelist.Setthesizeattribute(forexample,size=”3”)tothenumberofoptionsyouwanttoshowinstead.(Note:ChromeandSafarimayshowmoreoptionsthandesiredwhensizeislessthan5.)Typically,whensizeisset,aselectrendersasalistboxwithascrollbarontheright.

HTML5andtheselectElementTheselectelementsupportstheautofocusandformattributesinHTML5.Pleaseseethe“HTML5andtheinputElement”boxinthischapter.

Part2:HTMLElementsandGuidance182

textareaMultilineieldfortext

Syntax <textarea></textarea>Attributes Core,I18n,Events,accesskey,cols,disabled,name,onblur,onchange,onfocus,onselect,readonly,rows,tabindex,HTML5Only:Global,autofocus,form,maxlength,placeholder,required,wrap

DescriptionAtextareaelementisamultilinetextcontrol.Itisusefulincaseswhenyouwouldliketoprovidemorespaceforcontentthananinputoftype=”text”comfortablyallows,forexample,whensolicitingreaderfeedbackonablogentryoraproductpage.Youcanprepopu-lateatextareawithcontentbyplacingitbetween<textarea>and</textarea>.Pleaseseetheexampleanddiscussionintheformelemententryinthischapter.

AttributesinDetailn accesskey:Pleaseseethe“Attributes”sectionofChapter1.n cols=”number”:RequiredinX/HTML.Thissetsthemaximumnumber

ofcharactersperline,effectivelysettingthetextarea’swidthunlessyouoverwriteitwiththeCSSwidthproperty.

n disabled:Pleasesee“AttributesinDetail”fortheinputelementinthischapter.

n name=”cdata”:Thisspeciiesthetextarea’snameforthepurposesofprocessingtheformandthiselement’svalue.

n onblur=”script”andonfocus=”script”:Pleasesee“AttributesinDetail”fortheinputelementinthischapter.

Part2:HTMLElementsandGuidance Chapter7:Forms 183

n onchange=”script”:Thiseventireswhentheuserchangesthecontent.Sincetextareadoesn’thaveamaxlengthattributeinX/HTML(itdoesinHTML5,althoughmostbrowsersdon’thonorityet),youcanwriteJavaScriptthatwillcheckforthelengthofthecontenteachtimeitchangesandpreventtheuserfromtypingmoreifitexceedsthelimityoudetermine.

n onselect=”script”:Thiseventireswhentheuserselectscontentinthetextarea.

n readonly:Whenpresent,thisBooleanattributesprohibitstheuserfromalteringthetextarea’scontents.Theelementstillmayreceivefocus,betabbedtowiththekeyboard,andsubmitswiththeform.Onecommonuseisonatextareathatcontainstermsofusecopy,followedbyacheckboxinputaskingtheusertoselectittoagreetotheterms.

n rows=”number”:RequiredinX/HTML.Thissetsthenumberofrowsoftext,effectivelysettingthetextarea’sheightunlessyouoverwriteitwiththeCSSheightproperty.

n tabindex:Pleaseseethe“Attributes”sectionofChapter1.

HTML5andthetextareaElementThetextareaelementsupportstheseadditionalattributesinHTML5.

AttributesinDetailn autofocus:Pleaseseethe“HTML5andtheinputElement”boxin

thischapter.n form=”formid”:Pleaseseethe“HTML5andtheinputElement”

boxinthischapter. (continuesonnextpage)

Part2:HTMLElementsandGuidance184

HTML5andthetextareaElement(continued)

n maxlength=”number”:Thissetsthemaximumnumberofcharac-tersallowedinthetextarea.

n placeholder=”text”:Pleaseseethe“HTML5andtheinputElement”boxinthischapter.

n required:Whenpresent,thisBooleanattributerequirestheusertoentertextbeforesubmittingtheform.

n wrap=”hard|soft”:Thisspeciiesthetypeoftextwrappingintheield.Setwrap=”hard”toensurenolinehasmorecharactersthanisspeciiedbythecolsattribute,whichisrequiredinthisinstance.Ifwrapisnotset,itdefaultstosoft(theuseragentig-uresoutwrappingonitsown).

Tabulardatacantakemanyformssuchasinancialorsurveydata,acalendarofevents,abusschedule,oratelevisionprogrammingschedule.Whateverthecasemaybe,thiskindofinformationisusuallypresentedwithoneormorecolumnorrowheadingsalongwiththedata.

Thetableelementisyourelementofchoiceintheseinstances.It—alongwithitschildelements—aredescribedinthischapter.Ifyou’relookingforacodeexampleandsummaryofthemajorityofatable’selementsandfeatures,pleaseheadtothetableentry.

Notethattablesarenotintendedtocontrolpagelayout,sincethat’sthedomainofCSS(butyoualreadyknewthat,right?).

TabularData

8

Part2:HTMLElementsandGuidance186

captionAtablecaption

Syntax <caption></caption>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionTheoptionalcaptionelementprovidesabriefdescriptionofatable.Itmayappeardirectlyonlyafterthe<table>starttag.Useragentstypi-callydisplaythecaptioncenteredabovethetablebydefault.Pleaseseethetableentryinthischapterforanexample.

DeprecatedAttributesn align:UsetheCSScaption-sideproperty(withavalueoftopor

bottom)insteadtodictatewhetherthecaptionshouldappearaboveorbelowthetable.Firefoxalsosupportsadditionalvaluesofleftandrightforcaption-side,thoughthey’renolongerstandard.PleasenotethatInternetExplorer7andpreviousversionsdon’tsupportcaption-side.UsetheCSStext-alignproperty(withavalueofleft,center,orright)tocontrolacaption’shorizontalalignment.

colAtablecolumnforstyling

Syntax <col>or<col/>

Attributes Core,I18n,Events,align*,char*,charoff*,span,valign*,width*,HTML5Only:Global

Part2:HTMLElementsandGuidance Chapter8:TabularData 187

DescriptionThecolelementallowsyoutoapplystyletooneormoretablecolumns.Itdoesn’timpactthetable’sstructure.Allcolsmustgoaftercaptionorbeforetheadifeitherofthoseelementsispresent.InX/HTML,theymayexistontheirownorbecontainedwithinoneormorecolgroupelements.However,ifatleastonecolgroupispresent,allcolsmustbeinoneormorecolgroups.HTML5requiresallcolelementstobeexplic-itlycontainedinsideoneormorecolgroups.

Pleaseseethecolgroupentryinthischapterforexamplesandfurtherdiscussion,andseethe“AttributesinDetail”sectionsincebothelementshavethesameattributes.

colgroupAgroupoftablecolumns

Syntax <colgroup></colgroup>Attributes Core,I18n,Events,align*,char*,charoff*,span,valign*,width*,HTML5Only:Global

DescriptionThecolgroupelementallowsyoutogrouponeormoretablecolumnsforstylingpurposes.Itdoesn’timpactthetable’sstructure.colgroupmayexistonitsown(seeExample2)orcontainoneormorecolelements(seeExample1),whichallowmoregranularstylingcontrolwithinacolgroup.Allcolgroupsmustgoaftercaptionandbeforetheadifeitherofthoseelementsispresent.

Let’saddcolgroupandcolelementstotheexamplefromthetableelemententryinthischapter.I’veabbreviatedportionsofthecodesurroundingthecolgroups.

Part2:HTMLElementsandGuidance188

Example1(colgroupswithcols):

<table summary=" . . . ">

<caption> . . . </caption>

<colgroup class="quarter">

<col />

</colgroup>

<colgroup class="years">

<col span="3" />

</colgroup>

<!-- thead is here -->

<!-- the rest of the table code -->

</table>

Thespanattributemaybeusedoneithercolgrouporcol,andineithercase,itindicatesthenumberofcolumnstheelementspansforstyling.(spandoesn’timpactthetable’sstructure,unlikethecolspanattributethatmayappearonathortd.)Theclassattribute(oryoucoulduseidifit’suniquetothepage)allowsyoutotargetCSStoacolgroup.Forexample,ifyouapply.yearscol{background:#ccc;width:60px;}totheExample1code,eachthandtdinthesecond,third,andfourthcolumnswillbe60pixelswidewithagraybackground(theirstcolumnisdictatedbytheirstcolgroup).

There’sactuallymorecodeinExample1thanisnecessarysinceeachofthecolgroupshasonlyonecol.So,youcanrewritethecolgroupportionlikeinExample2.Inthiscase,thecolelementsareimplied.

Example2( justcolgroups):

. . . [table start tag and caption] . . .

<colgroup class="quarter"></colgroup>

<colgroup class="years" span="3"></colgroup>

. . . [rest of table] . . .

Part2:HTMLElementsandGuidance Chapter8:TabularData 189

And,inX/HTMLthere’syetathirdwaytowriteit.

Example3( justcols):

. . . [table start tag and caption] . . .

<col class="quarter" />

<col class="years" span="3" />

. . . [rest of table] . . .

Inshort,whetheryouusecolgroupand/orcolisuptoyoudependingonwhatmakesthecodethelightesttoaccommodateyourstylingneeds.However,youmaynotuseacombinationofExamples2and3;ifyouuseatleastonecolgroup,allcolsmustappearinoneormorecolgroups.

tip Use.years{background:#ccc;width:60px;}toapplythesamestylingtoExamples2and3asinExample1.

note BrowsersvaryinwhatCSSstylestheyapply(andhowyoumustapplythem)tocolgroupandcol.Forinstance,InternetExplorertendsto

supportmoretextstylingoptions(suchasbold,italics,andalignment)viacolgroupandcolthanotherbrowsers.

AttributesinDetailForalign,char,charoff,andvalign(allofwhichareobsoleteinHTML5),pleasesee“AttributesinDetail”forthetbodyelementinthischapter.n span=”numberofcolumns”:Setspantothenumberofcolumnsthe

elementshouldrepresentforstyling.Ifspanisomitted,itdefaultsto1.Pleaseseetheexamplesinthisentry.

n width=”numberofpixels,apercentagevalue,or0*”:*ObsoleteinHTML5.Thisattributeisn’tdeprecatedinX/HTML,butusetheCSSwidthpropertyinsteadtosetanumberofpixelsorapercentage(seetheexplanationforExample1inthisentry).widthtakesathirdvalue,

Part2:HTMLElementsandGuidance190

too.Whenitissetto0*(zeroasterisk),eachcolumnshoulddisplayattheminimumwidthnecessarytocontainitscontents.Browsersupportforthisvalueisinconsistent,though.

tableTabulardataparentelement

Syntax <table></table>Attributes Core,I18n,Events,border*,cellpadding*,cellspacing*,frame*,rules*,summary,width*,HTML5Only:Global

DescriptionUsethetableelementtopresenttabulardata,suchasdatainaspread-sheet.Forinstance,itcouldbeinancialorsurveydata,acalendarofevents,oratelevisionprogrammingschedule.Atthemostfundamentallevel,atableiscomprisedofrowsofcells.Eachrow(tr)containsheading(th)and/ordata(td)cells.SeveralotherHTMLelementsandattributesareparticulartoconstructingtables,asyouwillseeinexampleshereandelsewhereinthischapter.

note Althoughnottechnicallyillegal,donotusetablestocontrolthelayoutofyourpages,sinceit’sconsideredaverybadanddatedpractice.

Instead,usethepropersemanticsforyourcontentandcontrolyourlayoutwithCSS.Thetableelementismeanttostructuretabulardata.(HTMLe-mailsaretheoneunfortunateexception,butthat’sonlybecausenotalle-mailclientsandproviderssupport,orallow,theCSSrequiredtoachievecertainlayoutsconsistently.)

Someofthetable-relatedelementsandattributesaregearedtowardmakingatablemoreaccessible.Sightedusersmaytakeforgrantedhoweasilytheycangleaninformationpresentedinatablejustbyglancing

Part2:HTMLElementsandGuidance Chapter8:TabularData 191

atit.However,imagineyouareusingascreenreader(orotherassistivedevice),andthetableinformationisreadtoyou.Itcanbedisorientingunlessthetableincludesinformationthatdeclarescolumnandrowheadingsandassociatesthemwithdatacells,forinstance,sothedatacanbeannouncedincontext.

Let’stakealookatthesampletableI’llexplainbeforegettingintothecode.Alltheformattingshownisthetypicaldefaultbrowserrendering,thoughaswithotherelements,youcanstyletablesmuchdifferentlywithCSS.

I’vesplitthetablecodeintotwopartstomakeiteasiertodiscuss.I’vealsohighlightedatleastoneinstanceofeachtable-relatedelementandattri-butethattheexampleuses.

Example(part1—thetableheaderandfooter):

<table summary=”Company financials from 1962-64 in which each

year is a column heading and the quarter within each year is

a row heading.”>

<caption>Company Financials for 1962-1964 in

Thousands</caption>

<thead> <!-- table head -->

<tr>

<th scope=”col”>Quarter</th>

<th scope=”col”>1962</th>

<th scope=”col”>1963</th>

<th scope=”col”>1964</th>

</tr>

</thead> (continuesonnextpage)

Part2:HTMLElementsandGuidance192

<tfoot> <!-- table foot -->

<tr>

<th scope=”row”>TOTAL</th>

<td>$595</td>

<td>$648</td>

<td>$664</td>

</tr>

</tfoot>

<!-- Example 1 (part 2) code picks up from here -->

Let’sdiscussafewofthecomponentsshowninthisirstpart.Notsurprisingly,eachtablebeginswiththe<table>starttag.Unlikethesummaryattribute,theoptionalcaptionelementdoesdisplayinthepage(see“AttributesinDetail”regardingsummary).Ifyouincludeacaption,itmustimmediatelyfollowthestarttagforthetable.

Thetheadelementexplicitlymarksaroworrowsofheadingsasthetablehead.Eachrowisencapsulatedinatrelement,andeachofitsheadingsismarkedupwithathelement,asshownwith<thscope=”col”>Quarter</th>,<thscope=”col”>1962</th>,andsoon.thelementstypicallydisplayinboldandcenter-alignedbydefault.Thescopeattributedoesnotaffectpresentation,butithelpsmakeatableaccessible.Itinformsascreenreaderorotherassistivedevicethattheheadingisforeachtdinarow(whenscope=”row”)oracolumn(whenscope=”col”)orisforagroupofrows(whenscope=”rowgroup”)oragroupofcolumns(whenscope=”colgroup”)inamorecomplextable.

Thetfootelementexplicitlymarksaroworrowsasthetablefoot.Sampleusesincludecolumncalculations,suchasintheexample,orarepeatofthetheadheadingsforalongtable,suchasatrainschedule.Eventhoughitseemscounterintuitive,tfootmustcomebeforetbodyinthecode(showninpart2oftheexample)eventhoughitdisplaysafterit.(Note:HTML5allowstfootaftertbodyaslongasthere’sonlyonetfoot

Part2:HTMLElementsandGuidance Chapter8:TabularData 193

inthetable.)Pleasesee“ThetheadandtbodyElements”boxformoreinformation.

note You’llnoticeinpart1oftheexamplethatonlythefirst

tfootchildelementisath,whichisincontrasttothetheadthathasfourths.It’s

becauseonlyoneofthecellsisaheading,inthiscasefortherow,asdenotedwith<thscope="row">TOTAL</th>.

Allright,nowontothesecondpartoftheexample,whichincludesthetable’sdata.

Example(part2—thetablebodydata):

. . . [tfoot] . . .

<!-- Example 1 (part 1) code precedes this -->

<tbody> <!-- table body -->

<tr>

<td scope="row">Q1</td>

<td>$145</td>

<td>$167</td>

<td>$161</td>

</tr>

. . . [similarly structured tr and tds for Q2-Q4 rows]

. . .

</tbody>

</table>

Thetbodyelementsurroundsallthedatarows,whicharespeciiedbytrelementsjustlikeinthetheadandtfoot.Eachdatacellisatd,andtbodyisrequiredwheneveryouincludeatheadortfoot.

ThekeenobservermighthavespottedthattheirstelementintheQ1throughQ4rowsisatdwithscope=”row”,insteadofath.Iused<tdscope="row">Q1</td>becauseeachofthe“Q1”through“Q4”cells

Part2:HTMLElementsandGuidance194

intheirstcolumnisdataunderneaththe“Quarter”columnheading(<thscope="col">Quarter</th>)inthethead.Whenyouplacethescopeattributeonatd,itbehaveslikeaheadingfromtheperspectiveofanassistivedevice.(scopeonatdisobsoleteinHTML5;useathwithscopeinstead.)

ResourcestoLearnMoreTablescanbeverycomplexdependingonthedatayouneedtorepresent.I’vecollectedsomelinkstoresourcesthatprovideavarietyoftablediscussionsandexamples,withanemphasisonmakingtablesacces-sible.Thelinksareavailableathttp://www.htmlfiver.com/extras/tables/.

AttributesinDetailn border,frameandrules:*AllareobsoleteinHTML5.Thesearepresen-

tationalattributesthatwerecreatedbeforeCSShadameanstoprovidesimilarcontrol.So,althoughtheyaren’tdeprecatedinX/HTML,usetheCSSborderpropertyonthevarioustableelementsinstead.

n cellpadding=”numberofpixelsorpercentagevalue”:*ObsoleteinHTML5.Thisattributesetstheamountofspacearoundthecontentwithineachcell.UsetheCSSpaddingpropertyonthetdandthelementsinstead.

n cellspacing=”numberofpixelsorpercentagevalue”:*ObsoleteinHTML5.Thisattributesetstheamountofspacebetweeneachcell.ThereisaCSSalternative,border-spacing,butInternetExplorer8andolderdon’tsupportit.Ifyourgoalistoremoveallspacingbetweencells,there’sawayaroundthis;usetable{border-collapse:collapse;}inyourCSSinsteadof<tablecellspacing=”0”>inyourHTML.However,ifyou’dliketosetthespacingtoavalueotherthanzero(3,forexample)andyouwantIEtodisplaythesamespacingasotherbrowsers,you’llhavetoresortto<tablecellspacing=”3”>insteadofusingtheCSSborder-spacingproperty.

Part2:HTMLElementsandGuidance Chapter8:TabularData 195

n summary=”text”:Thisoptionalattributeprovidesanoverviewofthetablestructureandcontenttoscreenreadersandotherassistivedevices.Itdoesnottypicallydisplayinthepage.Reservesummaryforinstanceswhensomeexplanatorytextwouldbeusefultothevisuallyimpaired.Pleaseseetheexampleinthisentry.

n width=”numberofpixelsorpercentagevalue”:*ObsoleteinHTML5.Thisattributeisn’tdeprecatedinX/HTML,butusetheCSSwidthpropertytodictatethetablewidthinstead.Forexample,usetable{width:90%;}.Whensetasapercentage,thetablewidthisrelativetothewidthoftheelementinwhichit’scontained.Browserstypicallydetermineatable’swidthbasedonitscontentifwidthisn’tspeciiedandusuallywon’tletitexceedthecontainer’swidth(unlessthere’salargeimageinit).

DeprecatedAttributesn align:UsetheCSSfloatormarginpropertiesinstead.n bgcolor:UsetheCSSbackground-colorpropertyinstead.

ThetheadandtfootElementsThoughnotrequired,Irecommendyouincludeatheadineachtablethathasatleastonerowofcolumnheadings,andusetfootasappropriate.

theadandtfootallowbrowserstodifferentiateatable’sheadandfootfromitsbodydata(intbody)sothetbodycanscrollindepen-dentlyofthem.Also,somebrowsersmayprintthetfootandtheadelementsoneachpageifatablespansmultiplepages.Furthermore,usersofassistivedevicesmaybeneitfromtheheadingsbeingexplicitlydeclared,andyoucangaingreaterCSScontrol.

Part2:HTMLElementsandGuidance196

tip Youmaynestatableinsideanotherone,thoughthecasesfordoingsoarenotcommon.Nestingmustbedonewithinatd.

tbodyAtable’sbodyofdatacells

Syntax <tbody></tbody>Attributes Core,I18n,Events,align*,char*,charoff*,valign*,HTML5Only:Global

DescriptionThetbodyelementcontainstherows(trelements)ofdatacells(tdelements)thatrepresentatable’sbodyofdata.Itisrequiredwheneveratableincludesatheadortfootelement.Atablemayhavemorethanonetbody.Pleaseseethetableelemententryinthischapterforanexampleandfurtherdiscussion.

AttributesinDetailThecolgroup,tbody,td,tfoot,th,thead,andtrelementssharetheseattributes,noneofwhichenjoyswidespreaduse.n align=”left|center|right|justify|char”:*ObsoleteinHTML5.

Thoughalignisn’tdeprecatedinX/HTML,usetheCSStext-alignpropertyontbodyinstead.YoumayalsowanttousetheCSSmargin-left:autoand/ormargin-right:autodeclarationsonatbody’schildelements.Setalign=”char”whenalsospecifyingthecharattribute.

n char=”character”:*ObsoleteinHTML5.Theintentofcharistoallowyoutospecifyasingletextcharacterthatservesastheaxisfor

Part2:HTMLElementsandGuidance Chapter8:TabularData 197

horizontalalignmentwithincells.Thedefaultisthedecimalpointcharacterfortheelement’slanguage(forexample,aperiodinEnglishandacommainFrench).However,browsersupportforcharisvirtuallynonexistent.

n charoff=”number”:*ObsoleteinHTML5.Usedintandemwithalign=”char”andthecharattribute,charoffisintendedtoallowyoutospecifyapositiveornegativenumericoffsettotheirstoccurrenceofthealignmentcharacteroneachline.However,browsersupportforcharoffisvirtuallynonexistent.

n valign=”top|middle|bottom|baseline”:*ObsoleteinHTML5.Thoughvalignisn’tdeprecatedinX/HTML,usetheCSSvertical-alignprop-ertyontbodyinstead.

tdAcelloftabledata

Syntax <td></td>Attributes Core,I18n,Events,abbr*,align*,axis*,char*,charoff*,colspan,headers,rowspan,scope*,valign*,HTML5Only:Global

DescriptionUsethetdelementtospecifyatabledatacell.Typically,atdcontainsnumericortextdatawithoutHTMLelements,butitisvalidtoplacebothinlineandblock-levelcontentinadatacell.

Thisexampleshowsabrieftableforthepurposesofdemonstratingtheeffectofcolspanandrowspan,whichcanalsobeappliedtothelements.Pleaseseethetableelemententryinthischapterforalonger,propertableexampleandfurtherdiscussion.

Part2:HTMLElementsandGuidance198

Example(withcolspanandrowspan):

<table border="1">

<tbody>

<tr>

<td rowspan="3">1</td>

<td colspan="2">2</td>

</tr>

<tr>

<td>3</td>

<td>4</td>

</tr>

<tr>

<td>5</td>

<td>6</td>

</tr>

</tbody>

</table>

tip Iincludedborder=”1”soyoucouldseethecellboundariesquicklywithoutwritingCSS.Thisapproachcanbehandyasyou’rebuildinga

table.Whenyou’redone,removetheborderfromtheHTMLandsetitinyourCSSifdesiredwhenstylingyourtable.

Theexampletypicallyrenderslikethis:

Part2:HTMLElementsandGuidance Chapter8:TabularData 199

AttributesinDetailForalign,char,charoff,andvalign(allofwhichareobsoleteinHTML5),pleasesee“AttributesinDetail”forthetbodyelementinthischapter.n abbr=”text”:*ObsoleteinHTML5.Useabbrtospecifyanabbreviated

versionofthetd’scontent.Ascreenreadermightreadtheabbrvalueinsteadofthetdvalue.

n axis=”cdata”:*ObsoleteinHTML5.Browsersupportforthisattributeisvirtuallynonexistent.Intheory,itallowsyoutospecifyaspace-separatedlistofnamesofyourchoosingasawayofcategorizingacell.Pleaseseehttp://www.w3.org/TR/html4/struct/tables.html#multi-dimensionformoreinformation.

n colspan=”number”:Thisspeciiesthenumberofcolumnsthecellspansacross.Pleaseseetheexample.

n headers=”listofids”:Thisattributeperformsasimilartaskasscope—associatingtdswiththeirheadingsforthebeneitofassis-tivedeviceusers—exceptinamoreexplicitmanner.Supposeyouhaveacalendartablewithtwoheadingsabovethesamecell,suchas<thid=”month”colspan=”7”>June</th>inonerowand<thid=”weekday”>Fri</th>inthenext.YouexplicitlyassociateacellwiththesebylistingtheirIDs(separatedbyaspace)astheheadersvalue:<tdheaders=”monthweekday”>11:Bakesale</td>.UseheadersinsteadofscopeinHTML5pages.

n rowspan=”number”:Thisspeciiesthenumberofrowsthecellspans.Pleaseseetheexample.

n scope=”col|colgroup|row|rowspan”:*ObsoleteinHTML5onatdbutvalidonath;useonathinstead.Thisbeneitsscreenreadersbyspeci-fyingthattheelementisaheadingforeitherarow(scope=”row”),acolumn(scope=”col”),agroupofrows(scope=”rowgroup”),ora

Part2:HTMLElementsandGuidance200

groupofcolumns(scope=”colgroup”).Pleaseseeanexampleofscopeinthetableentryinthischapter.

DeprecatedAttributesn bgcolor:UsetheCSSbackground-colorpropertyinstead.n height:UsetheCSSheightpropertyinstead.n nowrap:UsetheCSSwhite-space:nowrapdeclarationinstead.n width:UsetheCSSwidthpropertyinstead.

tip Unlikemostotheruseragents,InternetExplorerdoesn’tdisplaytheborderonanemptytd,evenifyoutypeaspaceinit,like<td></td>.

However,itwillrendertheborderifthecontentisanonbreakingspaceentity,asin<td>&nbsp;</td>.IEshowsatd’sbackgroundcolorregardlessofcontent.

tfootAtablefoot

Syntax <tfoot></tfoot>Attributes Core,I18n,Events,align*,char*,charoff*,valign*,HTML5Only:Global

DescriptionThetfootelementexplicitlymarksaroworrows(eachasatrelement)asthetablefoot.Pleaseseethetableelemententryinthischapterforanexampleandfurtherdiscussion,including“ThetheadandtfootElements”box.Pleasealsosee“AttributesinDetail”inthetbodyentryinthischapter,sincethetwoelementshavethesameattributes.

Part2:HTMLElementsandGuidance Chapter8:TabularData 201

thAtablecolumnorrowheading

Syntax <th></th>Attributes Core,I18n,Events,abbr*,align*,axis*,char*,charoff*,colspan,headers,rowspan,scope,valign*,HTML5Only:Global

DescriptionThethelementspeciiestheheadingofatablecolumnorrow.Pleaseseethetableelemententryinthischapterforanexampleandfurtherdiscus-sion.Pleasealsosee“AttributesinDetail”and“DeprecatedAttributes”inthetdentryinthischapter,sincethetwoelementsarethesameregard-ingattributeswithoneexception:scopeisvalidonathinHTML5.

theadAtablehead

Syntax <thead></thead>Attributes Core,I18n,Events,align*,char*,charoff*,valign*,HTML5Only:Global

DescriptionThetheadelementexplicitlymarksaroworrows(eachasatrelement)ofheadingsasthetablehead.Theheadingsprovidecontexttothetable’scolumnsofdata.

Pleaseseethetableelemententryinthischapterforanexampleandfurtherdiscussion,including“ThetheadandtfootElements”box.Also

Part2:HTMLElementsandGuidance202

see“AttributesinDetail”inthetbodyentryinthischapter,sincethetwoelementshavethesameattributes.

trAtablerow

Syntax <tr></tr>Attributes Core,I18n,Events,align*,char*,charoff*,valign*,HTML5Only:Global

DescriptionThetrelementdesignatesatablerowandmaycontaintdand/orthelements,asisappropriate.Pleaseseethetableelemententryinthischapterforanexampleandfurtherdiscussion.Pleasealsosee“AttributesinDetail”inthetbodyentryinthischapter,sincethetwoelementshavethesameattributes.

DeprecatedAttributesn bgcolor:UsetheCSSbackground-colorpropertyinstead.

Ontoday’sWeb,client-sidescripting—namely,JavaScript—makestheworldgo’round.Orfadeinandout.Orcompleteyoursearchtermasyou’retypingit.Ordriveaninteractivenewsmodule.Orcontrolavideoplayer.Or...yougettheidea.

Alas,showingyouhowtowriteJavaScriptoranyotherscriptinglanguageisbeyondthescopeofthisbook,butIwillshowyoutheeasypart,whichisgettingyourscriptsintoapage.

Pleasealsosee“Attributes”inChapter1foralistoftheeventsyoucanapplyandcapturewithJavaScript.

Scripting

9

Part2:HTMLElementsandGuidance204

ScriptingandPerformanceBestPractices

Afulldiscussionofbestpracticespertainingtoscriptsandpageperformanceisbeyondthescopeofthisbook,butI’lltouchonafewpointsthatarehighimpact.

First,ithelpstounderstandhowabrowserhandlesscripts.Asapageloads,thebrowserdownloads(ifit’sexternal),parses,andexecuteseachscriptintheorderinwhichitappearsinyourHTML.(Seethedeferattributeinthescriptelemententryforrelatedinformation.)Asit’sprocessingit,thebrowserneitherdownloadsnorrendersanyothercontentthatappearsafterthescriptelement—noteventext.Thisisknownasblockingbehavior.

Thisistrueforbothembeddedandloadedscripts,andasyoucanimagine,itcanreallyimpacttherenderingspeedofyourpagedependingonthesizeofyourscriptand/orwhatactionsitperforms.

MostbrowsersdothisbecauseyourJavaScriptmayincludecodeonwhichanotherscriptrelies,mayincludecodethatgeneratescontent(suchaswithdocument.appendChild()),ormayincludecodethatotherwisealtersyourpage.Browsersneedtotakeallofthatintoaccountbeforeinishingrendering.

So,howdoyouavoidthis?TheeasiesttechniquetomakeyourJavaScriptnonblockingistoputallscriptelementsattheendofyourHTML,rightbeforethe</body>endtag.Ifyou’vespentevenjustalittletimeviewingsourceonothers’sites,nodoubtyou’veseenscriptsloadedintheheadelement.Outsideoftheoccasionalinstancewherethatmaybenecessary,it’sconsideredadatedprac-ticethatyoushouldavoidwheneverpossible. (continuesonnextpage)

Part2:HTMLElementsandGuidance Chapter9:Scripting 205

ScriptingandPerformanceBestPractices(continued)

AnothersimplewaytospeedupyourscriptloadingistocombineyourJavaScriptintoasingleile(orasfewaspossible)andminifythecodeusingatoolsuchasthefollowing:n GoogleClosureCompiler:

http://code.google.com/closure/compiler/(downloadanddocumentation),http://closure-compiler.appspot.com(onlineversionoftool)

n YUICompressor:http://developer.yahoo.com/yui/compressor/(downloadanddocumentation),http://refresh-sf.com/yui/(unoficialonlineversionoftool)

Eachwillreduceyourilesize,butresultswillvaryfromscripttoscript.

Thosearetwocommonandpowerfulmethods,buttheyonlyscratchthesurfaceofwhat’spossible.Forin-depthdiscussionsofscript-loadingmethodsandoptimization,IhighlyrecommendEvenFasterWebSites(O’Reilly)bySteveSoudersandhissite,http://www.stevesouders.com.

Part2:HTMLElementsandGuidance206

noscriptScriptalternative

Syntax <noscript></noscript>Attributes Core,I18n,Events,HTML5Only:Global

DescriptionContentcontainedinanoscriptelementdisplaysonlywhentheuseragentdoesn’thavescriptingenabledordoesn’tsupportthetypeofscriptspeciied.Itcancontainbothinlineandblock-levelcontent.Youmaynotnestanoscriptinsideanotherone.

Example:

<script src=”widget.js” type=”text/javascript” />

<noscript>

<p>This content only displays if JavaScript is disabled or

not supported by the browser.</p>

</noscript>

AlthoughnoscriptisdesignedasafallbacktoJavaScript,it’sbesttoavoidusingitwheneverpossible.Instead,yourpage’sdefaultexperience(thatis,withoutJavaScript)shouldmakecontentavailabletoallusers,whilebrowserswithJavaScriptenableddisplayanenhancedexperience.Thisapproachisknownasprogressiveenhancement.

Forexample,imagineyouhaveacarouselofadozenimagethumbnails,andifyouselectone,thefull-sizeversionofthatthumbnaildisplays.Saythedefaultexperience(withCSS)isthatallthethumbnailsdisplayinagrid(builtasanunorderedlist).Selectingathumbnailreloadsthepageanddisplaysthefull-sizeimageabovethegrid.However,iftheuser

Part2:HTMLElementsandGuidance Chapter9:Scripting 207

agenthasJavaScriptenabled,theprogressivelyenhancedversionrecon-iguresthethumbnailgridintoahorizontalcarouselthatdisplaysfourthumbnailsatatime.Userscanuseleftandrightarrowstonavigatethroughthecarousel,andiftheyselectathumbnail,thefull-sizeimagedisplaysabovethecarouselwithoutapagerefresh.

HTML5andthenoscriptElementHTML5notesthatnoscriptshouldbeusedonlywhenyouareservinganHTML5document,notanXHTML5document.

Italsoallowsfornoscriptinadocumenthead,thoughitscontentmaybethelink,meta,andstyleelementsonly.ThisisnotvalidinX/HTML.

scriptEmbedorloadascript

Syntax <script></script>Attributes charset,defer,type,src,HTML5Only:Global

DescriptionUsethescriptelementtoimportorembedaclient-sidescriptinadocu-ment.Thoughscriptsupportsotherlanguages,JavaScriptisundeniablythescriptinglanguageofchoice.scriptmayappearinboththeheadandbodyelementsandmultipletimeswithinadocument.However,asInoteatthebeginningofthechapter,it’sbesttocombineyourJavaScriptintooneileandloaditattheendofyourpagewheneverpossible.

Part2:HTMLElementsandGuidance208

note YoucannotplaceHTMLelementswithina

scriptblock(youcancreateHTMLwithJavaScript,however).

YoucanaddJavaScripttoyourpageinthreeways:byputtingitinanexternalile,byembeddingthecodeasthecontentsofthescriptelement,orbyapplyingitinlinewithaneventattribute.I’llcovertheirsttwoways(thethirdisn’tadvised).

Inmostcases,you’llwanttohouseadistinctpieceofJavaScriptinanexternalilebothsomultiplepagescanloaditandbecauseit’seasiertomaintainyourcodeinoneileratherthaninthescriptblocksofseveralHTMLiles.Additionally,auseragentwillcachetheileafterit’sloadedtheirsttime,speedingupthepageloadofsubsequentpagesonthesamesitethatusethescript.

Example1(importexternalfile):

. . .

<body>

. . .

<!-- Load JavaScript for product carousel -->

<script src=”js/carousel.js” type=”text/javascript”>

➥ </script>

</body>

</html>

Alternatively,youcanembedtheJavaScriptinyourpage;however,asnoted,theirstapproachisusuallypreferred.

Example2(embeddedcode):

. . .

<body>

. . .

Part2:HTMLElementsandGuidance Chapter9:Scripting 209

<script type=”text/javascript”>

var Foo = window.Foo || {};

Foo.bar = {

. . . // rest of code

};

</script>

</body>

</html>

Thetypeattributeisrequiredinbothcases,butsrcappliesonlytotheirst.

AsImentioned,youcanhaveseveralscriptelementsinapage,andtheycanappearinboththeheadandthebody.

Variablesandfunctionsbothembeddedinadocumentanddeinedinanexternalilecanbeavailabletoeachother.Inotherwords,eachscriptelementisnotmutuallyexclusive.Forexample,it’scommontoseeaJavaScriptlibraryloadedbyonescriptelement,followedbyanotherscriptelementthatimportsorembedscodeleveragingthatlibrary.

However,youmaynotcombineanexternalscriptcallandanembeddedscriptinthesamescriptelement.Theembeddedportionisignored.Forinstance,onlycarousel.jsexecutesinthisexample:

<script src=”js/carousel.js” type=”text/javascript”>

var Foo = window.Foo || {};

Foo.bar = {

. . . // rest of code

};

</script>

Part2:HTMLElementsandGuidance210

AttributesinDetailn charset:Thisspeciiesthecharacterencodingofascriptloadedvia

thesrcattribute.Itdoesnotapplytoanembeddedscriptblock(suchasExample2).Pleasesee“CharacterEncoding”inChapter1.

n defer(IE6–8,FF3.1–3.6):Pleasesee“ThescriptElementandPerformanceBestPractices”boxearlierinthischapterforanexplana-tionofhowuseragentshandlescriptsbydefault.TheBooleandeferattributeallowsyoutotellthebrowserthatitmaychoosetoloadandexecuteascriptaftertherestofthepagehasbeenparsedandrendered.Inessence,youareindicatingthatyourJavaScriptdoesn’tincludeanycodethatotherscriptsinthepagedependonorthatgeneratesHTMLcontent.Ifyoudeferascriptthatdoeseitherofthese,yourpageisnotlikelytorenderproperly.Example:<script type="text/javascript" src="photo-gallery.js"

defer="defer"></script>

Pleasenotedefer’slimitedbrowsersupport,listedearlier.n src=”uri”:ThesrcvaluerequiresavalidURIthatpointstoyourexternal

script.Theexternalscript’slanguagemustmatchwhatyouspecifyinthetypeattribute.Also,ifascriptelementhasbothasrcattribute(likeExample1)andembeddedcode(likeExample2),thelatterisignored.

n type=”content-type”:Usetypeinsteadofthedeprecatedlanguageattributetospecifyascript’sMIMEtype.Forinstance,setittotext/javascriptwheneitherembeddingorloadingJavaScript.Thisattributeisrequired.

Part2:HTMLElementsandGuidance Chapter9:Scripting 211

DeprecatedAttributesn language=”cdata”:Usetypeinsteadoflanguage.

tip Pleasesee“ScriptingandPerformanceBestPractices”earlierinthischapter.

HTML5andthescriptElementHTML5introducesanewattributetoscriptcalledasync.asyncisaBooleanattributethatinstructsascripttobeexecutedasynchronouslyassoonasitisavailable.Itmaybeusedonlyonascriptelementwithasrcattribute.Example:<script type="text/javascript" src="module-slider.js"

async="async"></script>

Youmayassignbothasyncanddeferforthepurposesofolderbrowsersthatsupportdeferonly.However,asynctakesprecedenceifabrowsersupportsbothattributes.Pleaseseehttp://www.htmlfiver.com/html5-browser-support/forthelatestsupportinformation.

FrameswerefarmoreprevalentintheearlydaysoftheWeb,inpartbecausebandwidthwassopoorthatdeveloperssawabeneitinsplit-tingthescreenupintopiecesthatloadedindependentlyofoneanother.Butwithframescameusability,accessibility,andSEOshortcomings.

Nowadays,framesareconsideredarelicoftheearlydaysoftheWeb—somuchsothatHTML5doesnotincludethematall.Becauseofthis,cover-agehereofframe,frameset,andnoframesisverylight.

Themainfocusofthischapteristheiframeelement,whichisverymuchpartofHTML5,completewithsomenewattributes.

Frames

10

Part2:HTMLElementsandGuidance214

frameAframewithinaframeset

Syntax <framesrc="">or<framesrc=""/>

Attributes Core,frameborder,longdesc,marginheight,marginwidth,name,noresize,scrolling,src

Description

note TheframeelementisobsoleteinHTML5.

Theframeelementrepresentsaframewithinaframesetelement.Pleaseseetheframesetentryinthischapterformoreinformation.

AttributesinDetailWhenpresent,theBooleannoresizeattributedisallowstheuserfromresizingtheframe.Pleaseseetheiframeelementinthischapterfordetailsabouttheotherattributes.

framesetAsetofframes

Syntax <frameset></frameset>Attributes Core,cols,onload,onunload,rows

Descriptionnote TheframesetelementisobsoleteinHTML5.Youcancreateasimilar

visualeffectwiththeCSSposition:fixeddeclaration.

Part2:HTMLElementsandGuidance Chapter10:Frames 215

Theframesetelementsplitsthewindowintooneormoreframeelements.EachframeloadsitsownHTMLdocument,andnavigationtakesplacewithineachframeunlessalink’stargetattributepointstothenameattributeofanotherframe,iframe,orwindow.

targetalsohasfourpredeinedvalues:_blank(opensthelinkinanewwindow;canbeusedinnormal,nonframespages,too),_parent(opensthelinkintheparentframeset),_self(thedefaultsetting;opensthelinkinthesameframecontainingthelink),and_top(opensthelinkinthefullbrowserwindow,notconstrainedtoaframe).

Framesetsmaybeconiguredinawidevarietyofways.Pleaseseehttp://www.w3.org/TR/html4/present/frames.htmlforexamples.

AttributesinDetailn colsandrows:Eachoftheseisacomma-separatedlistofthenumber

ofpixels,percentagevalues,andrelativelengths(whichuseanaster-isk).colsdeinesthelayoutofverticalframes,whilerowsdeineshori-zontalones.Thedefaultforeachis100%,whichmeansonecolumnandonerow(thatis,theentirescreen).Anexamplewithrelativelengthsiscols="*,475px,3*".Themiddlecolumnis475pixelswide,andtheirstandthirdcolumnsare25percentand75percentoftheremainingwidthspace,respectively.

n onload="script":Thiseventireswhenallframeelementshaveloaded.n onunload="script":Thiseventireswhenallframeelementshavebeen

removedfromthewindow,suchaswhenalinkwithtarget="_top"isselected.

Part2:HTMLElementsandGuidance216

iframeAnembeddedframe

Syntax <iframe></iframe>Attributes Core,frameborder*,height,longdesc*,marginheight*,marginwidth*,name,scrolling*,src,width,HTML5Only:Global,sandbox,seamless,srcdoc

DescriptionTheiframeelementallowsyoutoembedoneHTMLdocumentinsideanotherone.Thedocumentloadedintheiframeisitsownentity;forexample,itisn’timpactedbyCSSintheparentpage(seeHTML5’sseamlessattributeforanexception).Whenyouactivatealinkinaniframe,itloadsintheiframeunlessithasatargetattributethatpointselsewhere.Pleaseseetheframesetelementinthischapterformoreabouttarget.

Example:

<iframe name=”embeddedpage” width=”300” height=”400”

src=”embedded-page.html”><p>This content shows if the user’s

browser doesn’t support iframes.</p></iframe>

AttributesinDetailn frameborder="1|0":*ObsoleteinHTML5.Thedefaultvalueofthis

attributeis1,whichinformstheuseragenttorenderaborderontheiframe.Avalueof0turnsitoff.Sinceframeborderispresentationalinnature,usetheCSSborderpropertyinsteadinbothX/HTMLandHTML5documents.

Part2:HTMLElementsandGuidance Chapter10:Frames 217

n height="numberofpixelsorapercentagevalue"andwidth="numberofpixelsorapercentagevalue":Thisspeciiesthedimensions.Ifeachissettoapercentagesuchas33%,itwilloccupyathirdofitsparentelement’savailablespace.

n longdesc="uri":*ObsoleteinHTML5.Thisprovidesalinktoalongdescription(tosupplementthetitleattribute,ifpresent)oftheiframefornonvisualuseragentssuchasascreenreader.Itisusedrarely.

n marginheight="numberofpixels"andmarginwidth="numberofpixels":*BothareobsoleteinHTML5.marginheightspeciiestheamountofspacebetweenthetopandbottomedgesoftheiframeanditscontents.marginwidthdoesthesameexceptfortheleftandrightsides.Althoughthesearen’tdeprecatedinX/HTML,theyarepresentationaleffects,souseCSSinstead.

n name="cdata":Thisnamestheiframesootherelementsmaytargetitviatheirtargetattribute.

n scrolling="auto|no|yes":*ObsoleteinHTML5.Avalueofauto,whichisthedefaultstate,informstheuseragenttoprovidescrollbarswhennecessary.nomeanstonevershowscrollbars,andyesmeansalwaysshowthem.Althoughthisisn’tdeprecatedinX/HTML,usetheCSSoverflow(withavalueofauto,hidden,orscroll)propertyinstead.

n src="uri":Thisisthelocationofthedocumentorresourceloadedintotheiframe.

DeprecatedAttributesn align:UsetheCSSfloatpropertyinstead.

Part2:HTMLElementsandGuidance218

HTML5andtheiframeElementInHTML5,theiframeelementdoesnothavefallbackcontentinbetweenthestartandendiframetags.

HTML5addsthreeattributestoiframe.

AttributesinDetailn sandbox:Thesandboxattributeallowsyoutosetrestrictions

onaniframe’scontent.Thevalueforthisoptionalattributeisaspace-separatedlistthatincludesoneormoreofthesevalues:allow-same-origin,allow-top-navigation,allow-forms,andallow-scripts.Whensandboxisset,theiframe’sformsandscriptsaredisabled,itslinksarepreventedfromtargetingareasoutsidetheiframe,anditsplug-insaredisabled.However,settingsand-boxtoallow-formsandallow-scriptsreenablestheappropriateelements.Scriptscannevercreatepop-upwindows,though.Theallow-same-originvaluetreatsthecontentoftheiframeasifitwerefromthesameoriginastheparentpage(thatis,thepagethatcontainstheiframe).Pleaseseehttp://www.w3.org/TR/html5/text-level-semantics.html#attr-iframe-sandboxformoredetails,particularlyregardingwarningsforcertainvaluecombinations.

n seamless:Whenpresent,thisBooleanattributemakestheiframe’slinksopenintheparentpageinsteadoftheiframeandmakestheparent’sCSSapplytotheiframe’scontents.

n srcdoc:YoumayassignsrcdoctoastringofHTMLthatrepresentswhatthecontentsoftheiframeshouldbe.Ifbothsrcandsrcdocarespeciied,srcdoctakespriority.Thisallowsalegacybrowsertoloadthesrcandasupportingbrowsertousethesrcdocvalue.

Part2:HTMLElementsandGuidance Chapter10:Frames 219

noframesFramesfallbackcontent

Syntax <noframes></noframes>Attributes Core,I18n,Events

Description

note ThenoframeselementisobsoleteinHTML5.

Thenoframeselementprovidesfallbackcontentforauseragentthatdoesn’tsupportframes.Pleaseseehttp://www.w3.org/TR/html4/present/frames.htmlforexamples.

Part3

ThispartofthebookcoversallelementsthatareuniquetoHTML5.ItcombineswithPart2todetailthefullsetofelementsavailabletoyouforHTML5development.

Pleasealsosee“AnHTML5Overview”inChapter1ifyou’renewtoHTML5.

HTML5isstillunderdevelopmentatthetimeofthiswriting,andalthoughit’sonstablefooting,it’sstillsubjecttochange.(Towit,someelementswereaddedandremovedwhilewritingthisbook.)Forthemostpart,I’veleftoutbrowsersupportinformationsinceitoftenchangesasvendorsaddmorefeaturesorreinetheirimplementations.Pleaseseehttp://www.htmlfiver.com/html5-browser-support/forup-to-dateinformation.

HTML5ElementsandGuidance

Chapter11: PrimaryStructureandSections. . . . . . . . . . . . . . . . . 223Chapter12: Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245Chapter13: EmbeddedContent

(Images,Media,andMore) . . . . . . . . . . . . . . . . . . . . . . 263Chapter14: Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277Chapter15: InteractiveElements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285

Part3Contents

ThischapterisacounterparttoChapter2becauseitdescribesrelatedelementsuniquetoHTML5.Ifyou’rewritingX/HTMLdocuments,thenthischapterisn’trelevant.But,ifyou’rewritingHTML5,thenitcombineswithChapter2todetailalltheprimarystructuralandsectionalelementsatyourdisposal.

InX/HTML,thedivelementisyourmaindevicetocontainchunksofcontent.Asyouknow,div,althoughgreatasacontainer,hasabsolutelynosemanticmeaning.Thesevenelementsinthischapterarecontainersthatdohavemeaning.divdoesn’tgoawayinHTML5;youjustwon’tuseitasoften.

PrimaryStructureandSections

11

Part3:HTML5ElementsandGuidance224

Furthermore,afewoftheseelementsdirectlyimpactadocument’soutlineandchangethewayyouuseh1–h6headingsinHTML5.Iexplainthatnextandthengetintotheentriesfortheindividualelements.

HTML5’sDocumentOutlineEachHTMLdocumenthasanunderlyingoutline,whichislikeatableofcontents.Now,theoutlineisn’tsomethingthatdisplaysinyourpageexplicitly,butaswithallsemantics,it’smeaningfultothelikesofsearchenginesandscreenreaders,whichusetheoutlinetogleanthestructureofyourpageandprovidetheinformationtousers.

InX/HTML,theh1–h6headingelementsareallyouhavetostructuretheoutline.HTML5,ontheotherhand,includesfoursectioningcontentelements—article,aside,nav,andsection—thatdemarcatedistinctsectionswithinadocumentanddeinethescopeoftheh1–h6(andfooter)elementswithinthem.

Thismeanseachsectioningelementhasitsownh1-h6hierarchy,whichisabigshiftfromX/HTML.Also,notonlyismorethanh1inapageOK,butit’srecommended.

Allthisimpactstheoutline.Let’scomparetwoequivalentoutlinestoseehowthisworks.Theirst,whichistypicalinX/HTML,usesheadingelementsonly.

Version1:

<body>

<h1>Product User Guide</h1>

<h2>Setting it up</h2>

<h2>Basic Features</h2>

Part3:HTML5ElementsandGuidance Chapter11:PrimaryStructureandSections 225

<h3>Video Playback</h3>

<h2>Advanced Features</h2>

</body>

Now,thesecondversion,whichusesbothheadingandsectionelements,includingonenestedsection.(Note:Thecodeindentationisunimportantanddoesn’taffecttheoutline.)

Version2:

<body>

<h1>Product User Guide</h1>

<section>

<h1>Setting it up</h1>

</section>

<section>

<h1>Basic Features</h1>

<section>

<h1>Video Playback</h1>

</section>

</section>

<section>

<h1>Advanced Features</h1>

</section>

</body>

TheHTML5Outliner(http://gsnedders.html5.org/outliner/)isafantastictoolthatpresentsavisualrepresentationofyourdocument’soutline.UsingittogenerateoutlinesforVersions1and2showsthateventhoughtheirh1–h6headinglevelsaredifferent,bothresultinthisoutline:

Part3:HTML5ElementsandGuidance226

1.ProductUserGuide1.Settingitup2.BasicFeatures

1.VideoPlayback3.AdvancedFeatures

Asyoucansee,eachsectionelementinVersion2becomesasubsectionofitsnearesth1–h6orsectioningcontentancestor(alsosection,inthiscase).Thesamebehavioristrueofallfoursectioningcontentelements(article,aside,nav,andsection)evenwhenthey’remixedtogether.

note Bycomparison,ifVersion2hadnosections,itsoutlinewouldbethis:1.ProductUserGuide2.Settingitup3.BasicFeatures4.VideoPlayback5.AdvancedFeatures

BothVersions1and2arevalidHTML5,butthesecondispreferablebecausethesectionelementsaremoreexplicitsemantically.Infact,inpracticeIrecommendyouwrapanarticleelementaroundVersion2’scontent,sincethat’sevenmoreappropriateinthiscontext(thoughtheresultingoutlineisslightlydifferent).Here’sanexample:

<body>

<article>

<h1>Product User Guide</h1>

<section>

<h1>Setting it up</h1>

</section>

. . . [other sections] . . .

</article>

</body>

Part3:HTML5ElementsandGuidance Chapter11:PrimaryStructureandSections 227

tip Pleaseseethesectionelemententryinthischapterforamorecompleteversion.

IhighlyrecommendyoucreateavarietyoftestpagesandcomparetheresultsintheHTML5Outlinertogetabetterfeelforhowtheoutlinealgorithmworks.UsetheOutlinerduringyourprojectwork,too,toensureyourstructureisasintended.First,besureyouvalidateyourHTML5pagesathttp://html5.validator.nu/.

ThistakessomegettingusedtofordeveloperswellversedinX/HTMLbutnewtoHTML5,becauseyou’reconditionedtothinkthatonlyoneh1isappropriateonapageexceptinrarecircumstances.But,itmakesalotofsenseifyouthinkaboutitintermsofheadingsandsectionswithinanormal(thatis,non-HTML)document,likethekindyoumightwritewithawordprocessor.

Nowlet’sdiveintothischapter’selements.

article

Aself-containedcomposition

Syntax <article></article>Attributes HTML5Only:Global

DescriptionThearticleelementsigniiesaself-containedcompositionthatisintendedtobedistributableorreusable,suchas(thoughnotnecessarily)insyndication.Forexample,itcouldbeanewsarticle,amusicreview,ablogentry,acasestudy,acompany’shistoryonanAboutUspage,aprod-uctdescription,auser-submittedcomment,oraninteractivewidgetorgadget.Inshort,articleisanyindependentitemofcontent.

Part3:HTML5ElementsandGuidance228

Naturally,apagemaycontainseveralarticleelements.Forexample,ablog’shomepagetypicallyincludesafewofthemostrecentpostings;eachwouldbeitsownarticle.

Youmaynestanarticleinsideanotheraslongastheinnerarticleisrelatedtothearticleonthewhole(pleaseseeExample2).(Notethatyoumaynotnestanarticleinsideanaddresselement.)

Allright,you’vereadaboutarticle;nowlet’sseeit.

Example1(basicarticle):

<article>

<h1>The Diversity of Papua New Guinea</h1>

<p>Papua New Guinea is home to more than 800 tribes and

languages . . .</p>

. . . [rest of story content] . . .

<footer> <!-- the article’s footer, not the page’s -->

<p>Leandra Allen is a freelance journalist who earned

her degree in Anthropology from the University of

Copenhagen./p>

<address>

You may reach her at <a href=”mailto:leandra@

➥ therunningwriter.com">leandra@therunningwriter.com</

a>.

</address>

</footer>

</article>

Notetheuseofthefooterandaddresselements(seetheirentriesinthischapterandChapter2,respectively).Here,addressappliesonlytoitsparentarticle(theoneshown),nottothepageoranyarticlesnestedwithinthatarticle,suchasthereadercommentsinExample2.

Part3:HTML5ElementsandGuidance Chapter11:PrimaryStructureandSections 229

Example2demonstratesnestedarticleelementsintheformofuser-submittedcommentstotheparentarticle.

Example2(nestedarticles):

<article>

<h1>The Diversity of Papua New Guinea</h1>

. . . [parent article content] . . .

<footer>

. . . [parent article footer] . . .

</footer>

<section>

<h1>Reader Comments</h1>

<article>

<footer>bloose wrote on <time datetime=”2010-08-20”

pubdate>August 20, 2010</time>:</footer>

<p>Great article! I’ve always been curious about

Papua New Guinea.</p>

</article>

<article>

. . . [next reader comment] . . .

</article>

</section>

</article>

tip Pleaseseetheotherelementsinthischapterforadditionalexamplesthatincludearticle.

Part3:HTML5ElementsandGuidance230

asideTangentialcontent

Syntax <aside></aside>Attributes HTML5Only:Global

DescriptionTheasideelementindicatesasectionofcontentthatistangentiallyrelatedtothemaincontentonthepagebutthatcouldstandonitsown.Itmaybeaboxwithinthemaincontentitself,inthesamecolumnbutnotnestedinthemaincontent,orin(oras)asecondarycolumn.Examplesincludeapullquote,asidebar,aboxoflinkstorelatedarticlesonanewssiteorotherblogentries,advertising,groupsofnavelements,andalistofrelatedproductsonacommercesite.

Example1showsanasideusedforaninsetsidebar.

Example1(nestedinmaincontent):

<article>

<h1>The Diversity of Papua New Guinea </h1>

. . . [article content] . . .

<aside>

<h1>Papua New Guinea Quick Facts</h1>

<ul>

<li>The country has 38 of the 43 known birds of

paradise.</li>

<li>Though quite tropical in some regions, others

occasionally experience snowfall.</li>

. . .

</aside>

Part3:HTML5ElementsandGuidance Chapter11:PrimaryStructureandSections 231

. . . [more article content] . . .

</article>

Thatsamearticlemightincludea“RelatedStories”asidecontainingalistoflinkstootheressaysaboutthecountryorsurroundingregion(Indonesia,Australia,andsoon).Alternatively,thatasidecouldbeinadifferentpagecolumninsteadofnestedinthearticle.

Now,let’sconsideranexampleofadesignportfolioorcasestudies,inwhicheachpagefocusesonasingleprojectandyouprovidelinkstotheotheronesinanadjacentcolumn(ascontrolledbyCSS,notsimplybyvirtueofarrangingthecodeasshowninExample2).

Example2(notnestedinmaincontent):

<article> <!-- main content on the page -->

<h1>. . . [name of project] . . .</h1>

<figure>. . . [project photo] . . .</figure>

<p>. . . [project write-up] . . .</p>

</article>

<!-- this aside is not nested in the article -->

<aside>

<h1>Other Projects</h1>

<nav>

<ul>

<li><a href=”habitat-for-humanity.html”>Habitat for

Humanity brochure</a></li>

<li><a href=”royal-philharmonic.html”>Royal

Philharmonic Orchestra site</a></li>

. . .

</ul>

</nav>

</aside>

Part3:HTML5ElementsandGuidance232

Itwouldbeperfectlyinetonestthisparticularasideintheprojectarticle,too,sincetheyarerelated.

Onthatsubject,anasidenestedinthepage’smaincontenttypicallyrequiresacloserrelationshipthanwhenit’soutside.Forexample,ifthemaincontentisablogentryarticleelement,youcouldmarkupyourblogrollinanon-nestedaside.Itwouldbeinappropriatetonestitinthearticle,becauseitisn’trelatedtothatspeciicentry—unless,ofcourse,yourblogpostis“MyFavoriteBlogs”!Notethatoneotherplaceyoumaynotnestanasideisinsideanaddresselement.

note Usethe figureelement,notaside,tomarkupfiguresthatarepartofanarticle,suchasachartorgraph.PleaseseeChapter12formore

information.

footer

Footerofsegmentorpage

Syntax <footer></footer>Attributes HTML5Only:Global

DescriptionUsethefooterelementtorepresentafooterforthenearestarticle,aside,blockquote,body,details,fieldset,figure,nav,section,ortdelementinwhichitisnested.Itsigniiesthefooterforthewholepageonlywhenitsnearestancestoramongtheseisthebody(seeExample1).Andifafooterwrapsallthecontentinitssection(suchasanarticle,forexample),itrepresentsthelikesofanappendix,index,longcolophon,orlonglicenseagreement,dependingonitscontent.

Part3:HTML5ElementsandGuidance Chapter11:PrimaryStructureandSections 233

Afootertypicallyincludesinformationaboutitssection,suchaslinkstorelateddocuments(seeExample1),copyrightinformation(seeExample1),itsauthor(seeExample2),andsimilaritems.Afooterdoesnotneedtobeattheendofitscontainingelement,thoughusuallyitis.Also,youmaynotnestaheaderelementoranotherfooterwithinafooter,normayyounestafooterwithinaheaderoraddresselement.

Evenifyou’veneverwrittenalineofHTML5,you’renodoubtfamiliarwiththenotionofapagefooter.That’sonesuchuseforthefooterelement,asshowninExample1.

tip Pleaseseetheentryfortheheaderelementinthischapterforanexampleofhowthepageheaderandcontentareacouldbe

structured.

Example1(aspagefooter):

<body>

. . . [page header and content] . . .

<!-- this is a page footer because body is its nearest

ancestor -->

<footer>

<p><small>&copy; Copyright 2011 The Corporation, Inc.</

➥ small></p>

<ul>

<li><a href=”terms-of-use.html”>Terms of Use</a></li>

<li><a href=”privacy-policy.html”>Privacy Policy</a>

➥ </li>

</ul>

</footer>

</body>

Part3:HTML5ElementsandGuidance234

Pleaseseethenavelemententryinthischapterforanexplanationofwhythelinksulisn’twrappedinanav.

ThefollowingborrowsfromExample1inthearticleelemententryinthischapter.Itdemonstratesafooterinthecontextofapagesection.Pleaseseethatentryforanexplanationoftheaddresselement’sscopehere.

Example2(asapagesectionfooter):

<body>

. . .

<article>

<h1>. . . [article header] . . .</h1>

<p>. . . [article content] . . .</p>

<footer> <!-- the article footer -->

<p>Leandra Allen is a freelance journalist who

earned her degree in Anthropology from the

University of Copenhagen.</p>

<address>

You may reach her at <a href=”mailto:leandra@the

➥ runningwriter.com”>leandra@therunningwriter.com

➥ </a>.

</address>

</footer>

</article>

<footer id=”footer”> <!-- the page footer -->

. . . [copyright, terms of use, privacy policy] . . .

</footer>

</body>

Theid=”footer”(callitanythingyoulike)onthepagefooterisoptionalandisjusttodifferentiateitfromtheotherfooterforstylingcontrol.

Part3:HTML5ElementsandGuidance Chapter11:PrimaryStructureandSections 235

header

Groupedintroductorycontent

Syntax <header></header>Attributes HTML5Only:Global

DescriptionUsetheheaderelementtomarkupagroupofintroductoryornavi-gationalcontent.Itusuallyincludesthesection’sheading(anh1–h6orhgroup),butthisisn’tmandatory.Someotherheaderusesincluderepre-sentingtheheaderforthewholepageorcontainingasearchform,rele-vantlogos,orasection’stableofcontents(seeExample2).SeeExample1regardingtheirstthree.Youmaynotnestafooteroranotherheaderwithinaheader,normayyounestaheaderwithinafooteroraddresselement.

note Don’tuseheaderunnecessarily.Ifallyouhaveisanh1–h6oranhgroupandnocompanioncontentworthyofgroupingwithit,there’s

noneedtowrapitinaheaderinmostcases.

Whenyouthinkofaheader,nodoubtapage’smastheadcomestomind,asinthiscommonstructureinX/HTMLpages:

<body>

<div id=”header”>

. . . [site logo, global navigation, etc.] . . .

</div>

. . . [page content and footer] . . .

</body>

Part3:HTML5ElementsandGuidance236

HTML5’sheaderelementistherightchoiceforreplacingthatdiv,butaheadermayalsoappearelsewhereinyourpages,asshowninExample2.But,irst,let’sreplacethatpageheaderdiv.

Example1(aspageheader):

<body>

<header><!-- add an id like “header” or “masthead” if

desired -->

<!-- site logo could go here -->

<!-- a search box form could go here -->

<!-- site’s global navigation -->

<nav>

<ul> . . . </ul>

</nav>

</header>

<article>

. . . [page content] . . .

</article>

<footer>

. . . [copyright, terms of use, privacy policy, etc.]

. . .

</footer>

</body>

tip Pleaseseetheentryforthefooterelementinthischapterforanexampleofhowtostructureapagefooter.

AsImentioned,headerisn’tlimitedtocontainingyourpage’smasthead.InExample2I’veaddedaheaderthatwrapsboththeheadingandques-tionlinksatthetopofaFAQ.Thecommonthemeoftheexamplesisthat

Part3:HTML5ElementsandGuidance Chapter11:PrimaryStructureandSections 237

theheadercontainsagroupofintroductorycontentornavigationthatleadsintothenextsection.

Example2(inpagecontent):

<body>

<header>

. . . [site logo, navigation, etc.] . . .

</header>

<article>

<header>

<h1>Frequently Asked Questions</h1>

<nav>

<ul>

<li><a href=”#answer1”>What is your return

policy?</a></li>

<li><a href=”#answer2”>How do I find a

location?</a></li>

. . .

</ul>

</nav>

</header>

<!-- the header links point to these -->

<article id=”answer1”>

<h1>What is your return policy?</h1>

<p> . . . [answer] . . . </p>

</article>

<article id=”answer2”>

<h1>How do I find a location?</h1>

<p> . . . [answer] . . . </p>

</article> (continuesonnextpage)

Part3:HTML5ElementsandGuidance238

. . .

</article> <!-- end parent article -->

. . .

</body>

tip ThenavelementisappropriatearoundthelistofFAQquestionlinkssinceit’samajornavigationgroupwithinthepage,asdiscussedinthe

naventryinthischapter.

hgroupGroupofmultipleheadings

Syntax <hgroup>[twoormoreheadings]</hgroup>

Attributes HTML5Only:Global

DescriptionThehgroupelementrepresentsasectionheaderandmaycontainonlytwoormoreh1–h6headings.It’sfortimeswhenyourheadinghasmulti-plelevels,suchassubheadings,alternativetitles,ortaglines,orifyoudon’twantthosesubheadingsoralternatetitletoaffectthedocumentoutline.Groupingtheminanhgroupindicatestheyarerelated.

Forinstance,considerthenewsstoryshownintheexample.

Example:

<article>

<hgroup>

<h1>Giraffe Escapes from Zoo</h1>

<h2>Animals Worldwide Rejoice</h2>

Part3:HTML5ElementsandGuidance Chapter11:PrimaryStructureandSections 239

</hgroup>

<p>. . . [article content] . . .</p>

</article>

Onlytheirstinstanceofthehighest-rankedheadinginanhgroupappearsinthedocumentoutline—“GiraffeEscapesfromZoo”intheexample.Similarly,ifanotherh1appearedafterit,itwouldbeomittedfromtheoutlinejustliketheh2.Pleasesee“HTML5’sDocumentOutline”earlierinthischapter.

navSectionofmajornavigation

Syntax <nav></nav>Attributes HTML5Only:Global

DescriptionX/HTMLdoesn’thaveanelementthatexplicitlyrepresentsasectionofmajornavigationlinks,butHTML5does:thenavelement.Linksinanavmaypointeitherwithinthepage,tootherresources,orboth.However,useitonlyforyourdocument’smostimportantgroupsoflinks,notallofthem.

navdoesn’treplacetheneedtostructureyourlinksinanulandolelement,asappropriate.Continuetousethoseelements,andsimplywrapanavaroundthem.

HTML5recommendsnotwrappingancillarypagefooterlinkslike“TermsofUse”and“PrivacyPolicy”inanav,whichmakessense.Sometimes,though,yourpagefooterreiteratesthetop-levelglobalnavigationor

Part3:HTML5ElementsandGuidance240

includesotherimportantlinkslike“StoreLocator.”Inmostcases,Irecom-mendputtingthosetypesoffooterlinksinanav.

Thefollowingsamplenewspageincludesfourlistsoflinks,onlytwoofwhichareconsideredmajorenoughtowarrantbeingwrappedinanav:

Example:

<body>

<header>

<!-- site logo could go here -->

<!-- site global navigation -->

<nav>

<ul> . . . </ul>

</nav>

</header>

<div id=”main”>

<h1>Arts &amp; Entertainment</h1>

<article>

<h1>Gallery Opening Features the Inspired,

Inspiring</h1>

<p>. . . [story content] . . . </p>

<aside>

<h1>Other Stories</h1>

<!-- not wrapped in nav -->

<ul> . . . [story links] . . . </ul>

</aside>

</article>

</div>

<aside id=”sidebar”>

<nav><!-- secondary navigation -->

Part3:HTML5ElementsandGuidance Chapter11:PrimaryStructureandSections 241

<ul>

<li><a href=”/arts/movies/”>Movies</a></li>

<li><a href=”/arts/music/”>Music</a></li>

. . .

</ul>

</nav>

</aside>

<footer>

<!-- Ancillary links not wrapped in nav. See

Example 1 of footer entry in this chapter. -->

<ul> . . .</ul>

</footer>

</body>

ThesecondarynavigationintheasideallowstheusertonavigatetootherpagesintheArts&Entertainmentdirectory,soitconstitutesamajornavigationalsection.

Notethatyoushouldn’tnestanavwithinanaddresselement.

tip Example2intheheaderelemententryinthischapterincludesanexampleofanavsurroundingagroupoflinksthatpointwithin

thepage.

So,howdoyoudecidewhenagroupoflinksdeservesanav?Ultimately,it’sajudgmentcallbasedonyourcontentorganizationandaccessibility.Althoughthisfeaturedidn’texistatthetimeofthiswriting,auseragentsuchasascreenreadermaychoosetoprioritizelinkscontainedinanavoverothers.Forinstance,itcouldallowuserstojumpeasilyfromonenavblocktoanotherwithakeyboardcommand.Orauseragentmaypresentthenavelementsandsuppressotherlinksinitiallytoassistcertainusers(note:thisisn’tdefaultbrowserbehavior).

Part3:HTML5ElementsandGuidance242

sectionThematiccontentgrouping

Syntax <section></section>Attributes HTML5Only:Global

DescriptionThesectionelementindicatesathematicgroupingofcontent,typicallywithaheading.Examplesincludecompositionsections(andsubsections,ifnested;seetheexample),chapters,oreachtabwithinatabbedmodule.

note Keepinmindthatsectionisnotagenericcontainerlikediv,becausesectionconveysmeaning.Generallyspeaking,usesectioninsteadof

divifitscontentshouldappearinthepage’soutline(see“HTML5’sDocumentOutline”earlierinthischapter).

Thedistinctionbetweenarticleandsectionisalittlesubtle.HTML5recommendsusingarticleinsteadifthecontentcouldbesyndicated.Pleaseseetheexamplesthroughoutthischaptertogetasenseofhowtousearticle.

Thefollowingexample,likeExample2inthischapter’sarticleelemententry,showsarticleandsectionworkingtogether.

Example:

<article>

<h1>Product User Guide</h1>

. . . [introductory content] . . .

<section>

<h1>Setting it up</h1>

Part3:HTML5ElementsandGuidance Chapter11:PrimaryStructureandSections 243

. . . [instructions] . . .

</section>

<section> <!-- this contains two subsections -->

<h1>Basic Features</h1>

<section> <!-- nested, so it’s a subsection -->

<h1>Video Playback</h1>

. . . [instructions] . . .

</section>

<section> <!-- another subsection -->

<h1>Jumping to Chapters</h1>

. . . [instructions] . . .

</section>

</section>

. . .

</article>

Notethatyoushouldn’tnestasectionwithinanaddresselement.

Thischapterfeaturestext-levelsemanticsthatareuniquetoHTML5.

Ofthese,youwillprobablyindyourselfusingthenewfigureandfigcaptionthemost,sincetheyaddressacommoncontentconvention(aigurewithacaption,surprise!)forwhichX/HTMLlacksdedicatedelements.

Thischapter’scounterpartisChapter5;togethertheydetailallthetext-levelelementsavailabletoyouwhendevelopingHTML5documentsandapplications.

Text

12

Part3:HTML5ElementsandGuidance246

figcaptionCaptionforaigure

Syntax <figure> <figcaption></figcaption></figure>

Attributes HTML5Only:Global

DescriptionThefigcaptionelementrepresentsthecaptionorlegendforafigureelement’scontents.Itmightbeabriefphotodescriptionorreferencesthatbeginwith“ExhibitD”andthelike.Youcannotusefigcaptionunlessit’sinafigureelementandfigurehasothercontent.Andalthoughfigcaptionisoptional,afiguremayincludeonlyone,anditmustbeeithertheirstorlastchildelementofthefigure.

Pleaseseethefigureelementinthischapterformoredetailsandcodeexamples.

figureAigure

Syntax <figure></figure>Attributes HTML5Only:Global

DescriptionUsethefigureelementtomarkupaself-containedpieceofcontent(withanoptionalcaption)thatisreferredtobythemaincontentofyour

Part3:HTML5ElementsandGuidance Chapter12:Text 247

document.Typically,figureispartofthecontentthatreferstoit,butthefigurecouldalsoliveelsewhereonthepageoronanotherpage,suchasinanappendix.

Afigureelementmayincludeachart,agraph,aphoto,anillustration,acodesegment,andsoon.Thinkofhowyouseeiguresinmagazineornewspaperarticles,stories,andreports,andyou’llhaveagoodsenseofwhentousefigure.

Theoptionalfigcaptionisafigure’scaptionorlegendandmayappeareitheratthebeginningorattheendofafigure’scontent.(Seethefigcaptionentryinthischapterformoredetails.)

ConsiderExample1,anexcerptfromanannualreport,whichincludesapiecharttosupplementtheprimarycontent.

Example1:

<article>

<h1>2011 Revenue by Industry</h1>

. . . [report content] . . .

<figure>

<figcaption>Figure 3: 2011 Revenue by Industry

➥ </figcaption>

<img src=”chart_revenue.png” width=”260” height=”260”

alt=”Revenue chart: Clothing 42%, Toys 36%,

Food 22%” />

</figure>

<p>As Figure 3 illustrates, . . . </p>

. . . [more report content] . . .

</article>

Part3:HTML5ElementsandGuidance248

tip

Notetheuseoftheimage’saltattributeinExample1toconveythechart’scontentstoscreenreadersorintheeventabrowser’simages

areturnedoff.

Anotherpartofthereportcouldincludealetterfromthepresidentofaboardoftrustees,accompaniedbyherphotoandacaption.

Example2:

<article>

. . .

<figure>

<img src=”photo_president.jpg” width=”200” height=”300”

alt=”Gwen Chapman” />

<figcaption>Gwen Chapman, President of the Board

➥ </figcaption>

</figure>

. . .

</article>

Or,insteadofaphoto,itcouldbeavideointroduction(pleaseseethevideoelementinChapter13).figuremayalsoincludemultiplepiecesofcontent.Forinstance,Example1couldincludetwocharts:oneforrevenueandanotherforproits.Keepinmind,though,thatwhenusingafigurewithmultiplepiecesofcontent,onlyonefigcaptionelementispermitted.

note Don’tusefiguresimplyasameanstoembedallinstancesofself-containedcontentwithinabodyoftext.Oftentimes,theaside

elementmaybeappropriateinstead.PleaseseeitsentryinChapter11.

Part3:HTML5ElementsandGuidance Chapter12:Text 249

markHighlightedtext

Syntax <mark></mark>Attributes HTML5Only:Global

DescriptionThemarkelementislikeasemanticversionofahighlighterpen.Inotherwords,youdon’tuseahighlighterbecauseyouwanttocolorsnippetsofyourtextbookorlegaldocumentyellow;youuseitbecausethetextyouhighlightisespeciallyrelevanttothetaskathand(suchaswhenstudy-ingforanexam,reviewingacontractforkeylanguage,andsoon).Thesameistruewhenyouusemark;styleitstextwithCSSasyouplease(ornotatall,asisthedefaultuseragentbehavior),butuseitonlywhenit’spertinenttodoso.

Nomatterwhenyouusemark,it’stodrawthereader’sattentiontoaparticulartextsegment.Herearesomeusecasesforit:n Highlightingpartofaquotethatwasn’thighlightedinitsoriginal

formbytheauthortocallattentiontoit(seeExample1).n Highlightingasearchtermwhenitappearsinaresultspageoran

article.Supposeyousearchedformegapixelandeachresultingarticleused<mark>megapixel</mark>tohighlightthetermthroughoutitstextforyourbeneit.

n Highlightingacodefragment(seeExample2).

Part3:HTML5ElementsandGuidance250

Example1:

<p>So, I went back and read the instructions myself to see

what I’d done wrong. They said:</p>

<blockquote>

<p>Remove the tray from the box. Pierce the overwrap

several times with a fork and cook on High for <mark>15

minutes</mark>, rotating it half way through.</p>

</blockquote>

<p>I thought she’d told me <em>fifty</em>. No wonder it

exploded in my microwave.</p>

tip markisnotthesameaseitherem(representsemphasis)orstrong(representsimportance).PleaseseetheirentriesinChapter5.

Example2featuresahighlightedpieceofcode.(Again,themarkcodewon’tlookdifferentunlessyoustyleitwithCSS.)

Example2:

<p>Experienced developers know it’s bad practice to use a

class name that describes how it should look, such as with

the highlighted portion below:

<pre>

<code>

<mark>.redText</mark> {

color: #c00;

}

</code>

</pre>

Part3:HTML5ElementsandGuidance Chapter12:Text 251

meterAscalarmeasurement

Syntax <metervalue=””></meter>

Attributes HTML5Only:Global,form,high,low,min,max,optimum,value

DescriptionThemeterelementsigniiesameasurementwithinaknownrangeorafractionalvalue.InplainEnglish,it’sthetypeofgaugeyouusetorepre-sentthelikesofvotingresults(forexample,“30%Smith,37%Garcia,33%Clark”),thenumberofticketssold(forexample,“811outof850”),numericaltestgrades,anddiskusage.Youmayusemeterwithinmostotherelements,thoughnotwithinanothermeter.

Althoughit’snotrequired,asabestpracticeyoushouldincludetextinsidemeterthatrelectsthecurrentmeasurementsoolderuseragentsmaypresentit.

Examples:

<p>Project completion status: <meter value=”0.80”>80%

completed</meter></p>

<p>Car brake pad wear: <meter low=”0.25” high=”0.75”

optimum=”0” value=”0.21”>21% worn</meter></p>

meterisnotformarkingupgeneralmeasurementssuchasheight,weight,distance,orcircumferencethathavenoknownrange.Forexam-ple,youcannotdothis:<p>Iwalked<metervalue=”3”>3</meter>milesyesterday.</p>.However,youcandothefollowing:

Part3:HTML5ElementsandGuidance252

Example(withtitle):

<p>Miles walked during half-marathon: <meter min=”0”

max=”13.1” value=”2.5” title=”Miles”>2.5</meter></p>

meterdoesn’thavedeinedunitsofmeasure,butyoucanusethetitleattributetospecifytextofyourchoosing,asinthepreviousexample.Useragentsmightdisplaythetitleasatooltiporotherwiseleverageitwhenrenderingthemeter.

note HTML5suggestsuseragentsmightrenderameterlikeahorizontalbarwiththemeasuredvaluecoloreddifferentlythanthemaximumvalue

(unlessthey’rethesame,ofcourse).Thinkofathermometeronitsside.Nobrowserssupportthisatthetimeofthiswriting.Inthemeantime,youcanstylemetertosomeextentwithCSSorenhanceitfurtherwithJavaScript.

AttributesinDetailEachoftheseattributesisoptionalexceptvalue.Andallthoseindicat-inganattributevalueofnumbershouldbesettoavalidloating-pointnumber.Negativenumbersareallowed.n form="formelementID":Associatesthemeterwiththeformelement

whoseidequalsthevalueofthisattribute.Thisoverridesthedefaultbehavior,whichisifmeterisnestedinsideaformelement,it’sassoci-atedwiththatelement.

n high="number",low="number",optimum="number":Worktogethertosplittherangeintolow,medium,andhighsegments.optimumindicatestheoptimumpositionwithintherange,suchas“0brakepadwear”inoneoftheexamples.Setoptimumlowerthanlowtoindi-catethatlowvaluesarebetter,dotheoppositeforhigh,andsetitinbetweenifneitheralowvaluenorahighvalueisoptimal.

Part3:HTML5ElementsandGuidance Chapter12:Text 253

n min="number":Speciiesthelowerboundoftherange.Itequals0ifit’sunspeciied.

n max="number":Speciiestheupperboundoftherange.Itequals1.0ifit’sunspeciied.

n value="number":Required.Speciiesthevalueforthemetertoindi-cateasthevaluemeasurement.Ifit’slessthantheminvalue,useragentstreatitthesameasmin,andifit’smorethanmax,itistreatedthesameasmax.

Furthermore,thefollowingmustbetruewhenyouapplytheseattributevalues(LTEmeans“islessthanorequalto”):n minLTEvalueLTEmax.n minLTElowLTEmax(iflowisspeciied).n minLTEhighLTEmax(ifhighisspeciied).n minLTEoptimumLTEmax(ifoptimumisspeciied).n lowLTEhigh(ifbothlowandhigharespeciied).

Andifaminimumormaximumisn’tspeciied,thenthevalueattributemustbebetweentherangeof0and1.

note Usetheprogresselement(seeitsentryinthischapter)insteadofmetertoindicateatask’sprogress,suchaswithaprogressbar.

Part3:HTML5ElementsandGuidance254

progressTaskprogressindicator

Syntax <progress></progress>Attributes HTML5Only:Global,form,max,value

DescriptionUsetheprogresselementtodisplaythecompletionprogressofatask(likeaprogressbar).

Forinstance,aWebapplicationcouldindicatetheprogressasit’ssavingalargeamountofdata.Althoughit’snotrequired,asabestpracticeyoushouldincludetext(forexample,“0%saved,”asshownintheexam-ple)insideprogressthatrelectsthecurrentvalueandmaxforolderuseragents.

Example:

<p>Please wait as we save your data. Current progress:

<progress id=”progressBar” max=”100”>0% saved</progress></p>

Thoughafulldiscussionisbeyondthescopeofthisbook,typicallyyouwouldupdateboththeprogressvalueandtheinnertext(forexample,makeit“20%saved,”andsoon)dynamicallywithJavaScript.var bar = document.getElementById(‘progressBar’);givesyouaccesstotheelementfromtheexample,andthenyoucangetorsetbar.value.

Part3:HTML5ElementsandGuidance Chapter12:Text 255

AttributesinDetailThoseindicatinganattributevalueofnumbershouldbesettoavalidloating-pointnumber.n form="formelementID":Associatestheprogresswiththeform

elementwhoseidequalsthevalueofthisattribute.Thisoverridesthedefaultbehavior,whichisifprogressisnestedinsideaformelement,it’sassociatedwiththatelement.

n max="number":Speciiesthenumberthevalueattributemustreachtosignalthetaskiscomplete.Itmustbegreaterthan0,andifit’sunspeciied,itequals1.0.

n value="number":Speciiesthecurrentprogressasanumber.Itisoptional,butifit’sspeciied,itmustbeequaltoorgreaterthan0andlessthanorequaltothemaxattribute.

note Youmaynotnestoneprogressinsideanotherone.

note Therearetwotypesofprogresselements:determinateandindeter-minate.Adeterminateprogresshasavalue,soitsprogresscanbe

determinedbytherelationofthevaluetothemaxattribute.Anindeterminateprogressdoesnothaveaspecifiedvalue,soalthoughprogressmaybeoccur-ring,itslevelcan’tbedetermined(thetaskmaybewaitingforfeedback). HTML5suggestsuseragentsdisplaydeterminateandindeterminateprogresselementsdifferentlybutisshortonspecificsotherthantosaythatdeterminateonesshouldshowthevalueofvaluerelativetothevalueofmax.Nobrowserssupportthisatthetimeofthiswriting.Inthemeantime,youcanstyleprog-resstosomeextentwithCSSorenhanceitfurtherwithJavaScript.

Part3:HTML5ElementsandGuidance256

rpForrubyfallbackparentheses

Syntax <rp>(</rp>and<rp>)</rp>

Attributes HTML5Only:Global

DescriptionUsetherpelementtodisplayparenthesesaroundrubytext(thertelement)inuseragentsthatdon’tsupportrubyannotations.Useragentsthatdosupportrubyignoretherp,sotheydon’tdisplaytheparentheses.

Pleaseseetherubyelementinthischapterforanexample.

rtRubytextcomponent

Syntax <ruby> <rt></rt></ruby>

Attributes HTML5Only:Global

DescriptionThertelementcontainstherubytextusedinarubyannotation.Thecontentofanrtrepresentstheannotationoftherubyelementcontentthatimmediatelyprecedesit(notincludinganrpelement).

Pleaseseetherubyelementinthischapterforanexample.

Part3:HTML5ElementsandGuidance Chapter12:Text 257

rubyArubyannotation

Syntax <ruby> <rp>(</rp><rt></rt><rp>)</rp></ruby>

Attributes HTML5Only:Global

DescriptionArubyannotationisaconventioninEastAsianlanguages,suchasChineseandJapanese,typicallyusedtoshowthepronunciationoflesser-knowncharacters.Thesesmallannotativecharactersappeareitheraboveortotherightofthecharacterstheyannotate.Theyareoftencalledsimplyrubyorrubi,andtheJapaneserubycharactersareknownasfurigana.

Therubyelement,aswellasitsrtandrpchildelements,isHTML5’smechanismforaddingthemtoyourcontent.rtspeciiestherubychar-actersthatannotatethebasecharacters.Theoptionalrpallowsyoutodisplayparenthesesaroundtherubytextinuseragentsthatdon’tsupportruby.ThisexampledemonstratesthisstructurewithEnglishplaceholdercopy.Theareaforrubytextishighlighted.

Example:

<ruby>

base <rp>(</rp><rt>ruby chars</rt><rp>)</rp>

base <rp>(</rp><rt>ruby chars</rt><rp>)</rp>

</ruby>

Part3:HTML5ElementsandGuidance258

Auseragentthatsupportsrubymaydisplayitlikethis(orontheside):

IftheexampleincludedthebaseChinesecharactersforBeijing(whichrequirestwocharacters)andtheiraccompanyingrubycharacters,auseragentthatsupportsrubymaydisplayitlikethis(orontheside):

Asyoucansee,itignorestherpparenthesesandjustpresentsthertcontent.However,auseragentthatdoesn’tsupportrubydisplaysitlikethis:

Youcanseehowimportanttheparenthesesare;withoutthem,thebaseandrubytextwouldruntogether,cloudingthemessage.

note Atthetimeofthiswriting,onlyInternetExplorerandGoogleChromesupportrubyannotations(allthemorereasontouserpinyour

markup).TheHTMLRubyFirefoxadd-on(https://addons.mozilla.org/en-US/firefox/addon/6812)providessupportinthemeantime.

tip Youmaylearnmoreaboutrubycharactersathttp://en.wikipedia.org/wiki/Ruby_character.

Part3:HTML5ElementsandGuidance Chapter12:Text 259

timeDateand/ortime

Syntax <time></time>Attributes HTML5Only:Global,datetime,pubdate

DescriptionUsethetimeelementtorepresentaprecisetimeorGregoriancalendardate.Thetimeisbasedona24-hourclockwithanoptionaltime-zoneoffset.Youmaynotnestatimeelementinsideanotherone.

Thedatetimeattributeprovidesthedateand/ortimeinamachine-read-ableformat.Thissampledemonstratesthedatetimeformat:

2011-03-25T17:19:10-02:00

Thismeans“March25,2011,at10secondsafter5:19p.m.”Tseparatesthedate(YYYY-MM-DD)andtime(hh:mm:ss),andthetime-zoneoffsetisprecededby-(minus)or+(plus).Youaren’trequiredtoprovidedatetime,andifyoudo,itdoesn’tneedtobethefullcomplementofinformation(seeExample1).

Theoptionaltextcontentinsidetime(thatis,<time>text</time>)appearsonthescreenasahuman-readableversionofthedatetimevalue.

Thefollowingexamplesdemonstratevarioustimeconigurations.

Part3:HTML5ElementsandGuidance260

Example1(variations):

<p>The volunteers arrive at <time>03:30</time>.</p>

<p>We began our hike through Zion National Park on <time

datetime=”2003-07-03T10:30:00”>July 3, 2003 at 10:30 am

➥ </time>.</p>

<p>They made their dinner reservation for <time datetime=

➥ ”2010-11-02T19:15:00”>tonight at 7:15</time>.</p>

<p>The record release party is on <time datetime=”2010-11-02”>

➥ </time>.</p>

You’llnoticethatthelastonedoesn’thaveanytextcontent.Insuchcases,useragentsaresupposedtorenderthedatetimevalueastextinahuman-friendlymanner,butasofthiswriting,noneyetdoso.You’llhavetowaituntilafewbrowserssupportthisrenderingfeatureoftimetoseetheexactresults.

Usethepubdateattributetoindicatethattimerepresentsapublishingdate(see“AttributesinDetail”formorespeciics.)

Example2(withpubdate):

<article>

<header>

<h1>Popularity of Mountain Hiking Sees Steady

Increase</h1>

<p><time datetime=”2006-06-15” pubdate>June 15, 2006

➥ </time></p>

</header>

. . . [article content] . . .

</article>

Part3:HTML5ElementsandGuidance Chapter12:Text 261

Ifthearticlehadreader-submittedcomments,thosecouldbetime-stampedwithtime,datetime,andpubdate,too.

AttributesinDetailn datetime:Thisprovidesthedateortimebeingspeciied.Ifyoudon’t

includeit,thedateortimeisrepresentedbythetimeelement’stextcontent.Itsmachine-readableformat(describedearlierinthisentry)allowsforsyncingdatesandtimesbetweenWebapplications.

n pubdate:ThisBooleanattributespeciiesthatthetimeelementrepresentsthepublicationdateandtimeofthenearestarticleelementthatcontainsthetimeelement.Ifthereisn’tanarticleancestor,thepublicationdateappliestothewholepage.Ifpubdateisincluded,eitherdatetimeorthetimeelement’stextcontentasavaliddatestring(suchas“June15,2006”inExample2)withanoptionaltimeisrequired.pubdatemaybespeciiedaseitherpubdateorpubdate=”pubdate”.ThelatterisrequiredforXHTML5.

note Donotusetimetomarkupimprecisedatesortimes,suchas“themid-1900s,”“justaftermidnight,”“thelatterpartoftheRenaissance,”

or“earlylastweek.”

note BecausedatesinthetimeelementarebasedontheGregoriancalen-dar,HTML5recommendsyoudon’tuseitforpre-Gregoriandates.

Therehasbeenalotofdiscussionaboutthislimitation,butit’sacomplicatedissue.Readhttp://www.quirksmode.org/blog/archives/2009/04/making_time_saf.htmlforanextensiveexplanationofsomeoftheissues.

Part3:HTML5ElementsandGuidance262

wbrAlinebreakopportunity

Syntax <wbr>or<wbr/>

Attributes HTML5Only:Global

DescriptionBrowserswraptextcontentautomatically,butsometimesawordorcontinuousphraseistoolongtoitintheavailablespace.Insuchacase,usethewbrelementinbetweenwordsorletterstoindicatewherecontentmaywrapifnecessarytomaintainlegibility.Toclarify,wbrdoesnotforcealinebreaklikethebrelement;itinformsthebrowserofanopportunitytoinsertalinebreak.

Inthisexample,thewordsruntogetherwithoutspacestomimicbeingsaidveryquickly,andthewbrsspecifypointsforwrapping.

Example:

<p>They liked to say, &quot;Friendly<wbr>Fleas<wbr>and<wbr>

Fire<wbr>Flies<wbr> Friendly<wbr>Fleas<wbr>and<wbr>Fire<wbr>

Flies<wbr>&quot; as fast as they could over and over.</p>

OneofHTML5’sgoalsistoeliminatetheneedforbrowserplug-instoprovidemediacontentandrich,interactiveexperiences.Thethoughtisthatopenstandardsshouldprovideallyouneedsoyouaren’tboundtoproprietarytechnologiessuchasAdobeFlashandMicrosoftSilverlight.

Tothatend,mediamakesahugeleapinHTML5withbothnativeaudioandvideosupport.ThelatterisoneofHTML5’shot-ticketitems.It’salsohotlydebatedamongthebrowservendors,asyou’lllearninthischap-ter.Regardless,thelikesofYouTubeandVimeohavealreadyjumpedonboard,anditsmomentumpromisestokeepgrowingwiththereleaseoftheAppleiPadandotherdevicesthataresansplug-ins.

EmbeddedContent(Images,Media,andMore)

13

Part3:HTML5ElementsandGuidance264

And,howaboutrich,interactiveexperiences?Thecanvaselementmakeshugewavesinthatdepartment.Thischapterdoesn’thaveroomforanin-depthexplorationofcanvas,butitdoesprovideanoverviewandseveralresourcessoyoucandigintoitfurtheronyourown.

audioEmbeddedaudiostream

Syntax <audio></audio>Attributes HTML5Only:Global,autoplay,controls,loop,preload,src

DescriptionUsetheaudioelementtoembedanaudiostream.

Example:

<audio src=”ocean.oga" controls=”controls”>

<!-- The HTML in here is for non-supporting user agents -->

<p>Sorry, your browser doesn’t support HTML5 audio

with the Ogg Vorbis format. You may <a href=”ocean.oga”>

➥ download the file</a> instead.</p>

</audio>

Thetextinsidetheaudioelementisfallbackcontentthatdisplaysonlyifthebrowserdoesn’tsupportaudio.YoucanincludeamessagelikeinExample1,oryoucanincludecodethatembedsanothertypeofaudioplayer,suchasFlash.

note Thefallbackcontentareashouldn’tbeusedforaccessibility-focusedcontent,suchasanaudiotranscript.

Part3:HTML5ElementsandGuidance Chapter13:EmbeddedContent(Images,Media,andMore) 265

Asisthecasewiththevideoelement,themajorbrowsershavenotagreedonabaselineaudioformattosupportwiththeaudioelement,andHTML5doesnotdictateoneasaresult.Asofthetimeofthiswriting,thesupportwassplitamongafewformats:n AAC(M4A):Safari4+n MPEG(MP3):Chrome3+,Safari4+n MPEG-4(MP4):Chrome3+,Safari4+n OggVorbis:Chrome3+,Firefox3.5+,Opera10.5+n

WAV:Firefox3.5+,Safari4+,Opera10.5+

Additionally,MicrosofthassaidthatIE9willsupportHTML5audiowithMP3andAAC(M4A).Youmaytrackthelatestaudiosupportondesk-topandmobilebrowsersathttp://www.htmlfiver.com/html5-browser-support/.

Thismeansyou’llneedtoprovidemultiplesourceilestosupportallbrowsers.Thesourceelementallowsyoutodoexactlythat.Pleaseseeitsentryinthischapterforanexamplewithaudio.

note Eventhoughthesebrowserssupportaudio,youmayexperienceanoccasionalbug.It’saprettynewfeatureforallofthem,butitshould

improveovertime.

AttributesinDetailPleaseseethedescriptionsfortheautoplay,controls,loop,preload,andsrcattributesinthevideoentryinthischapter,sincetheybehavethesameforaudio.

Part3:HTML5ElementsandGuidance266

canvasBitmapdrawingsurface

Syntax <canvas></canvas>Attributes HTML5Only:Global,height,width

DescriptionThecanvaselementisoneoftheheadline-grabbingfeaturesofHTML5.ThinkofitlikeanentirelyblankimgelementthatyoucandrawonwithJavaScript.Itis—truetoitsname—adigitalcanvas.Youcancreategames,graphs,animations,andotherdynamicbitmapimages.

Example:

<canvas id=”piechart” width=”400” height=”430”>

<!-- fallback content for browsers that don’t support

canvas -->

</canvas>

Youshouldalwaysprovidefallbackcontentinsidethatdisplaysifthebrowserdoesn’tsupportcanvasorJavaScriptisturnedoff.Thiscontentshouldbesimilarinspirittothebitmapcanvas.Forinstance,iftheexam-plecanvaswereapiechart,yourfallbackcontentcouldbethis:

<p>45% chose blue as their favorite color, 30% chose green,

and 25% chose red.</p>

note Oneshortcomingofcanvasisitisn’taccessible.Sure,thefallbackcontentis,butanythingyoudrawoncanvasisn’t.Someproposalsto

remedythisarebeingdiscussedatthetimeofthiswriting.

Part3:HTML5ElementsandGuidance Chapter13:EmbeddedContent(Images,Media,andMore) 267

Atthetimeofthiswriting,canvasissupportedbyeverymajorbrowser—Chrome,Firefox,Opera,Safari—exceptInternetExplorer.However,therearerumors(thoughnotanannouncementfromMicrosoft)thatIE9mightincludeit.Inthemeantime,developersmustresorttousingExCanvas(http://code.google.com/p/explorercanvas/).

LearnMoreSo,howdoyoudrawoncanvas?Well,youaccessyourcanvaselementthroughitsidandusethebuilt-inJavaScriptAPIfordrawingonitssurface.Unfortunately,apropercanvasdrawingdiscussionisbeyondthescopeofthisbook,becauseitcouldillatleastachapterbyitself.But,thefollowingresourcesareallyou’llneedtogetbothasenseofwhatyoucandowithcanvasandhowtodoit:n Demos:CanvasDemos(http://www.canvasdemos.com/)provides

informationandlinkstoawidevarietyofcanvasapplications.Italsoincludesatutorialssection,plusalinktoacheatsheetifyousearchforthatterm.

n Tutorials:– FromMozilla:https://developer.mozilla.org/en/Canvas_tutorial– FromOpera:http://dev.opera.com/articles/view/html-5-canvas-the-

basics/– FromOpera(advanced):http://dev.opera.com/articles/view/

blob-sallad-canvas-tag-and-javascrip/

AttributesinDetailn heightandwidth=”numberofpixels”:Setthedimensionsofthe

canvasinpixels.Theydefaultto300(width)and150(height)ifundeined.

Part3:HTML5ElementsandGuidance268

embed

Embedplug-incontent

Syntax <embed>or<embed />

Attributes HTML5Only:Global,height,src,type,width

DescriptionTheembedelementaddsexternalcontentthatrequiresaplug-in,suchasaFlashgameormovie.embedisn’tpartoftheX/HTMLspecs,butbrows-ershavesupporteditforyears,soHTML5hasmadeitoficial.

note PleaseseetheobjectelemententryinChapter6fordifferencesbetweenobjectandembed.

Example1:

<embed src=”game.swf” type=”application/x-shockwave-flash”

width=”500” height=”500” />

note

embedisanemptyelement,meaningit’sproperlywrittenas<embed>or<embed />insteadof<embed></embed>and,consequently,doesn’t

haveanyinnercontent.However,youmayneedtousetheinvalid,latterformforbackwardcompatibility.Also,youcan’tassociatefallbackcontentwithembedlikeyoucanfortheaudioandvideoelements,whicharenotemptyelements.

Eventhoughitdoesn’tvalidateinX/HTMLpages,embedisubiquitousnowadayssinceit’spartofthecodeYouTubeandothervideositesprovidetoembedavideoonasite.ForExample2,I’veslightlymodiiedYouTubecode(notincludingtheobjectportion)inordertomakeitvalidHTML5.Namely,Imadeembedanemptyelementandchangedallamper-sandsto&amp;.

Part3:HTML5ElementsandGuidance Chapter13:EmbeddedContent(Images,Media,andMore) 269

Example2:

<embed src="http://www.youtube.com/v/Z3ZAGBL6UBA&amp;hl=en_

➥ US&amp;fs=1&amp;" type="application/x-shockwave-flash"

allowscriptaccess="always" allowfullscreen="true" width="480"

height="385" />

You’llnoticetwoattributes,allowscriptaccessandallowfullscreen,thataren’tamongthefourattributesnativetoembed.ThisisOK,becauseembedallowscustomattributesspeciictoplug-ins.Theseattributesarepassedintoplug-insasparameters.

AttributesinDetailn src=”url”:Thepathtotheresourcen type=”MIMEtype”:TheMIMEtypeoftheresource,suchas

application/x-shockwave-flash

n width=”numberofpixelsorpercentagevalue”andheight=”numberofpixelsorpercentagevalue”:Thewidthandheightinpixelsorpercent-agevalues.Thepercentagesarerelativetothesizeoftheembed’sparentelement.

sourceAmediasource

Syntax <source src=””>or<source src=”” />

Attributes HTML5Only:Global,media,src,type

DescriptionNotalluseragentssupportthesamemediaformatsfortheaudioandvideoelements,asdiscussedintheirentriesinthischapter.Thesource

Part3:HTML5ElementsandGuidance270

elementallowsyoutospecifymultiplemediasourceURLsforaudioandvideo,soiftheuseragentdoesn’tsupporttheirstinthelist,itlookstothesecond,thenthethird,andsoon,untilitindsoneitdoessupport.

Example:

<audio controls="controls" autoplay=”autoplay”>

<!-- UA looks at this first -->

<source src="laughter.oga" type="audio/ogg;

➥ codecs=vorbis" />

<!-- then this, etc. -->

<source src="laughter.spx" type="audio/ogg;

➥ codecs=speex" />

</audio>

Thisistherecommendedpracticesinceyou’llriskshuttingoutusersifyouprovideonlyonesource.Notethatyouarepermittedtousesourceonlyineitheranaudioorvideoelement.Pleaseseeanexampleofsourcewiththevideoelementinthevideoentryinthischapter.

AttributesinDetailn media=”mediaquerylist”:Ifdesired,specifythemediaplatform(s),

suchasscreenorprojection,tohelpthebrowserdeterminewhetherit’llbeusefultoloadtheresourcespeciiedbysrc.Ifyouomitthemediaattribute,whichiscommon,itdefaultstoall.SeethelinkelementinChapter3formoreinformation.

n src=”uri”:Required.Thisisthepathtothemediaresource.n type=”MIMEtype”:Thisspeciiesthetypeofthemediaresource(for

example,audio/mp3,video/ogg,orvideo/mp4)speciiedbysrctohelptheuseragentdeterminewhetheritsupportsit.Theoptionalcodecsparameterservesthesamepurposebutisspeciictothecodec(s)usedtoencodethemedia.Inbothcases,iftheuseragentknowsitdoesn’t

Part3:HTML5ElementsandGuidance Chapter13:EmbeddedContent(Images,Media,andMore) 271

supportit,itlooksatthenextsource,ifany.typemustbeavalidMIMEtype.You’llindseveralexamplesoftypeandcodecsconigura-tionsforbothaudioandvideoathttp://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element.

videoAnembeddedvideo

Syntax <video></video>Attributes HTML5Only:Global,autoplay,controls,height,loop,poster,preload,src,width

DescriptionNativevideoplaybackisoneofHTML5’shighest-proileadditions,andit’simplementedwiththevideoelement.

Example1(basicvideoembed):

<video src=”your-video.ogv” controls=”controls”>

<!-- The HTML in here is for non-supporting user

agents -->

</video>

Addingavideotoyourpageisthateasy—noplug-ins,complicatedembeddingmethods,orJavaScriptrequired.srcisthepathtoyourvideo,andcontrols=”controls”(orsimplycontrols,ifyoupreferthatformat)makesdefaultplay,pause,andotherbuttonsavailabletotheuser.(See“AttributesinDetail”regardingotherattributes.)OryoucancreateyourowncontrolsandaddbehaviorwithJavaScript(seehttps://developer.mozilla.org/En/Using_audio_and_video_in_Firefoxforataste).

Part3:HTML5ElementsandGuidance272

TheHTMLinsidevideoisoptionalthoughhighlyencouraged.Itdisplaysonlyifthebrowserdoesn’tsupportthevideoelement.Typically,you’llwanttoincludeanembedmethodforanothervideoplayerformat,suchasFlash,orperhapsasimplemessagewithalinkdirectlytothevideoileforoflineviewing.PleaseseeExample2andrelatedcontentforthebestwaytoapproachfallbacksolutions.

note Donotusevideo’sinnercontentforaccessibilitymeans,suchastoincludeatranscriptofthevideo.Intheory,thevideoitselfshouldbe

encodedwithcaptionsorrelatedinformation.Atthetimeofthiswriting,therewasn’tastandardcaptioningformatforthevideoelement,butdiscussionswereunderway.

ThevideoFormatDebateAddingvideomaybesimple,butunfortunately,it’sbeendificulttogetthemajorbrowservendorstoagreeuponthebaselinestandardvideoformat.It’sbeenahotlydebatedissue,thedetailsofwhichIwon’tgetintohere,thoughyoucanreadasummaryathttp://lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2009-June/020620.html.Asaresult,HTML5removedaninitialrequirementthatuseragentsmustsupportOggTheoraataminimumandnowdoesn’trequireaspeciicformat.

Currently,thefollowingformatsworkwiththevideoelementonthebrowserslisted:n OggTheora:Universalsupportforanopen,licensing-androyalty-free

formatsuchasOggTheoraistheHolyGrail,buttheissueisn’tquitethatsimple.ThesupportingbrowsersareChrome3.0+,Firefox3.5+,andOpera10.5+.

n H.264:Thepopularformatinwhichvastamounts(forexample,YouTubeetal.)ofvideocontentisalreadyencoded.Thesupport-ingbrowsersareChrome3.0+,Safari3.1+,andInternetExplorerwithGoogleChromeFrameinstalled.InternetExplorer9,stillin

Part3:HTML5ElementsandGuidance Chapter13:EmbeddedContent(Images,Media,andMore) 273

developmentatthetimeofthiswriting,willsupportH.264(withouttheneedforGoogleChromeFrame).

tip Youmaytrackthelatestsupportfor videoondesktopandmobilebrowsersathttp://www.htmlfiver.com/html5-browser-support/.

Asyoucansee,neitherformatissupportedacrosstherangeofbrowsers.Therefore,unlessyouknowyouraudienceprimarilyusesoneofthesesetsofbrowsers—veryunlikely,exceptfornarrowerplatformsliketheiPhoneandiPad—you’llneedtoencodeyourvideoinatleasttwoformats.

That’snotparticularlyconvenient,butsupposeyoudogeneratetwoversions.Howdoyouservethemtousers?Thesourceelementhasyoucovered.

MultipleMediaSourceswiththesourceElementExample2showshowtousethesourceelementtospecifymultiplemediasources.

Example2(providemultiplevideosources):

<video controls="controls">

<!-- option 1: OGG Theora video and Vorbis audio -->

<source src="your-video.ogv" type='video/ogg;

➥ codecs="theora, vorbis"' />

<!-- option 2: H.264 -->

<source src="your-video.mp4" type='video/mp4;

➥ codecs="avc1.42E01E, mp4a.40.2"' />

<!-- The HTML below here is for non-supporting user

agents, for example, you could embed a Flash video

player. -->

. . .

</video>

Part3:HTML5ElementsandGuidance274

Notethatyouspecifythesrconeachsourceelementinsteadofonthevideostarttag.Theuseragentchecksthetypeandcodecsinformationoftheirstsourcetoseewhetheritsupportsit.Ifitknowsitdoesn’t,itmovestothenextone,andsoon.Pleaseseethesourceelementinthischapterformoredetails.

tip VideoforEverybody(http://camendesign.com/code/video_for_everybody)isablockofcode(noJavaScriptrequired)youmayuse

thatleveragesthevideoandsourceelementswithfallbacksforQuickTimeandFlashsoyourvideocanworkonallbrowsers,providedyourvideoisencodedinthevarietyofformats.

AttributesinDetailn autoplay:Ifpresent,thisBooleanattributeinstructstheuseragent

tostartplayingthemediawhenthepageloads,ratherthanwaitingfortheusertoinitiateplayback.Here’sanexampleofusingit:<videosrc=”skywriter.ogg”autoplay=”autoplay”></video>(orsimply,autoplay).

n controls:Ifpresent,thisBooleanattributeinstructstheuseragenttodisplaycontrolssotheusercancontrolplayback.Thesedefaultcontrolsincludeplay,pause,volume,seek,andinsomeinstancesmore(browsersaresupposedtoprovidemore,butnotalldo).Thelookandfeelofthedefaultcontrolsvariesbetweensupportedbrowsers.IfyoucreateyourowncontrolswithJavaScript,thedefaultcontrolsshowifscriptingisdisabled.

n loop:Ifpresent,thisBooleanattributeinstructstheuseragenttoplaythemediaagainwhenitreachestheend.

n poster=”url”:Ifpresent,thisisthepathtoanimagethatisintendedtoberepresentativeofthevideo,suchasoneoftheinitialframes.HTML5recommendsbrowsersshowtheposterframewhenthevideo

Part3:HTML5ElementsandGuidance Chapter13:EmbeddedContent(Images,Media,andMore) 275

isn’tavailable(suchaswhenloading),thoughtheymaychoosetoshownothinginstead.Useragentshavefulldiscretionofwhattoshowwhenthevideoispausedontheirstframe.

n preload=”none|metadata|auto”:Preloadedvideoloadsinpartorfullbeforetheuserinitiatesplayback.Thepreloadattributeisyourmeanstosuggesttotheuseragentwhatyouthinkwillresultinthebestuserexperienceregardingpreloading.It’sjustahint;theuseragentmaychoosetoignoreyoursettingif,forexample,bandwidthisnotaconcern.preloadhasnoeffectifautoplayispresent.Theoptionsareasfollows:– preload=”none”:Thissuggeststhatitisn’tnecessarytopreloadthe

videooranymetadata.Usethisifit’slesslikelytheuserwillplaythevideoorifyouwanttominimizeservertrafic.

– preload=”metadata”:Thisisthesameasnoneexcepttohintthatfetchingvideometadataonly(notthevideoitself),suchasthedimensions,duration,andsoon,isOK.

– preload=”auto”:Thishintstotheuseragentthatservertraficisnotaconcernsoitmaypreloadsomeorallofthevideo.

n src=”url”:Thisisthepathtothevideo.n width=”numberofpixelsorpercentagevalue”andheight=”numberof

pixelsorpercentagevalue”:Thesedeinethewidthandheightofthevideo.Iftheydon’tequalthedimensionsofthevideo’sintrinsicsize,thevideowillshrinkorstretchaccordinglyandmaybeletterboxedorpillarboxed.Notethatthevideowillmaintainitsnativeaspectratioregardlessofwhetherwidthandheightrelectthataspectratio.Ifthewidthandheightareundeined,theplayertypicallyrendersattheintrinsicsizeofthevideo.YoumaydeinethesewithCSSinstead,suchaswithvideo{width:320px;height:240px;}.

FormsmakeabigleapinHTML5aspartofitsfocusonmakingWebapplicationsricherandtheirdevelopmenteasier.

Amongthemostcompellingadditionsaretheinputtypesforcoloranddatepickers,numbers,arangeslider,search,emailandtelephonenumberields,andmore.Plus,thereareattributesformarkingieldsasrequired,orspecifyingaregularexpressionthatperformspatternmatch-ingwithoutJavaScript.Pleaseseethe“HTML5andtheinputElement”boxinChapter7’sinputentryformoreinformation.

HTML5alsoincludesnewform-relatedelements,whichthischaptercovers.

(Note:PleasealsoseethemeterandprogresselementsinChapter12sinceyoumayindthemvaluabletousewithaform.)

Forms

14

Part3:HTML5ElementsandGuidance278

datalistAlistofpredeinedoptions

Syntax <datalist> <option></option> ...</datalist>

Attributes HTML5Only:Global

DescriptionThedatalistelementspeciiesalistofpredeinedoptionelementsforaninputelement.Forinstance,youmayturnatextinputcontrolintoacombobox,meaningtheusermayeithertypeinavalueorchoosefromthedatalist’soptions.Settingtheinput’slistattributetothedatalist’sidhooksthemtogether.

Ifabrowsersupportsdatalist,itdoesn’tdisplayanyofitscontents,exceptthatitmakestheoptionsavailableoncetheuserinteractswiththeinput.Thisallowsyoutoaddfallbackcontentinthedatalistcontentforbrowsersthatdon’tsupportdatalist.(There’sonenotableexception:Asofthiswriting,Chromedoesn’tshowthefallbackcontenteventhoughitdoesn’tsupportdatalist.)

Inthisexample,Ipredeinesomedrinkoptions.UsersmaychoosefromthoseortypesomethinglikeTang,ifthat’stheirpreference.Forthepurposesofbeingreallyexplicittodemonstratetheconcept,Iincluded“fallback”intheattributevaluesofeachelementthatisignoredbyabrowserthatsupportsdatalist.(Note:Theexampleassumesthecodeisinaformelement.)

Part3:HTML5ElementsandGuidance Chapter14:Forms 279

Example:

<label for="drink">Enter your favorite drink:</label>

<input type="text" name="drink" id="drink" list="drinkslist">

<datalist id="drinkslist">

<label for="drinkfallback">Or, select a drink from this

list:</label>

<select name="drinkfallback" id="drinkfallback">

<!-- the options are not ignored, just the select -->

<option value="apple juice">apple juice</option>

<option value="frappe">frappe</option>

<option value="water">water</option>

</select>

</datalist>

Technically,youshouldn’thavetospecifythevalueattributesontheoptions,butOpera9+,theonlybrowsertoprovidereasonable(thoughincomplete)supportfordatalistatthetimeofthiswriting,doesn’tpresentanoption’sinnertext,onlythevalue(andthelabelattributevalueifvalueispresent).Youcan’tleaveouttheinnertext,though,becauseanemptyselectboxwoulddisplayasthefallbackcontent.

Here’showtheexamplelooksinabrowserthatdoesn’tsupportdatalist.(IaddedalittleCSStomakeitwrapandbreatheabit.)

UntilOperaoranotherbrowserhascompletesupportfordatalist,Section2.1ofhttp://docs.google.com/View?id=dch3zh37_0cf8kc8c4illus-trateshowaproperimplementationmightlookandbehave.

Part3:HTML5ElementsandGuidance280

keygenAkeypairgeneratorcontrol

Syntax <keygenname="">or<keygenname=""/>

Attributes HTML5Only:Global,autofocus,challenge,disabled,form,keytype,name

DescriptionThekeygenelementisakeypairgeneratorcontrol.Whentheformissubmitted,“theprivatekeyisstoredinthelocalkeystore,andthepublickeyispackagedandsenttotheserver.”Manybrowsers(butnotInternetExplorer)havesupportedkeygenforalongtimeeventhoughitwasneveranoficialelementinanyHTMLspec.HTML5makesitoficial.

Example:

<form action="processkey.php" method="post"

enctype="multipart/form-data">

<div>

<label for=”key”>Choose a Key Grade:</label>

<keygen name="key" id="key">

<input type=”submit” value="Submit Key">

</div>

</form>

keygenrenderslikeaselectboxinsupportingbrowsers,thoughitsoptionsmaybedifferent.ThisshowshowkeygenrendersinChrome:

Part3:HTML5ElementsandGuidance Chapter14:Forms 281

HTML5doesn’tdictatehowthegeneratedprivatekeyshouldbeused,thoughpresumably,itcouldresultinaclientcertiicatebeinggeneratedbytheserverandofferedtotheuserforthepurposesofSSLandcertii-cateauthenticationservices.

AttributesinDetailn autofocus:Whenpresent,thisBooleanattributetellsthebrowser

tosetfocusonthekeygencontrolassoonasthepageisloaded.Thisallowsuserstousethecontrolwithouthavingtotabtoitorclickitirst.

n challenge="challengestring":Whenpresent,thevalueispackagedwiththesubmittedkey.

n disabled:Whenpresent,thisBooleanattributedisablestheelementsotheusercan’tinteractwithit.Furthermore,adisabledcontroldoesn’treceivefocus,itisskippedintabbingnavigation,anditsvalueisnotsubmittedwiththeform.

n form="formid":Bydefault,eachformcontrolisassociatedwithitsnearestancestorformelement(thatis,theformthatcontainsit).Setthisattributetotheidofadifferentforminthepagetooverridethisbehavior.

n keytype="keyword":rsaisthedefaultkeywordthatsupportingbrowsersunderstand.Firefoxalsosupportsec,andbothFirefoxandSafarisupportdsa.Ifkeytype="rsa",thestateofthekeyisRSA.Useragentsarenotrequiredtosupportthisorothervalues,only“recognizevalueswhosecorrespondingalgorithmstheysupport.”

n name:Thisassignsanametothekeygenforprocessingtheform.

Part3:HTML5ElementsandGuidance282

outputTheresultofacalculation

Syntax <output></output>Attributes HTML5Only:Global,for,form,name

DescriptionTheoutputelementrepresentstheresultsofacalculation.

Example:

<form action=”calculate-it.php” method=”post”>

<input name=”value1” id="value1" type=”number”> x

<input name=”value2” id="value2" type=”number”> =

<output name="total" for="value1 value2"></output>

<input name=”submit” type=”submit”>

</form>

Oneapplicationofoutputcouldbeashoppingcartthatupdatesthetotalpriceastheuserchangesthenumberofproductsortheshippingoption.AsanenhancementforuserswhosebrowserssupportJavaScript,youcouldalsoprocessoutputcalculationsontheclientsidebywiringaJavaScriptfunctiontoupdatetheoutputeverytimeachangeismadetothecart.That’snotareplacementforserver-sideprocessing,though,sinceyoudon’twanttoshutoutuserswithJavaScriptdisabled.

AttributesinDetailn for="controlid(s)":Thisexplicitlyassociatestheoutputwitheach

controlinvolvedinthecalculationwhenitissettoaspace-separatedlistofthecontrolids.Thecontrolsmayexistanywhereinthesamedocument.Pleaseseetheexample.

Part3:HTML5ElementsandGuidance Chapter14:Forms 283

n form="formid":Bydefault,anoutputisassociatedwithitsnearestancestorformelement(thatis,theformthatcontainsit).Setthisattri-butetotheidofadifferentforminthepagetooverridethisbehavior.

n name="outputname":Thisassignsanametotheoutputforthepurposesofprocessingtheform.

HTML5includestwonewinteractiveelements,detailsandmenu,andtheirsupportingelements,summaryandcommand,respectively.TheysupportoneofHTML5’sgoalsofmakingWebapplicationdevelopmenteasier,richer,andmoreaccessiblebybuildingfeaturesintonativeHTMLelements.

Thischapterexplainshowtoleveragethemtocreateapplication-styletoolbarsandcontextualmenus(inthecaseofmenu),aswellasexpand-ableandcollapsibleinformationandformcontrolmodules(inthecaseofdetails).Pleasebeaware,though,thatmuchofthenativefunctionalitythattheseelementspromisedoesn’texistinanymajorbrowseratthetimeofthiswriting.ThatisexpectedtochangeasbrowserscontinuetoincorporatemoreandmoreofHTML5’sfeatures.LiketheotherHTML5

InteractiveElements

15

Part3:HTML5ElementsandGuidance286

chapters,thisonedetailshowtheelementsandattributeshouldbehaveonceimplementedcorrectly.

note Thedeviceelementisnotincluded,sinceit’sconsideredanadditiontoHTMLbeyondHTML5anditsdetailswerestill

beingdefinedatthetimeofthiswriting.Youmaytrackitsprogressathttp://dev.w3.org/html5/html-device/.Inshort,device“representsadeviceselector,toallowtheusertogivethepageaccesstoadevice,forexampleavideocamera”forvideoconferencingfromHTMLapplications.

command

Amenucommand

Syntax <commandlabel="">or<commandlabel=""/>

Attributes HTML5Only:Global,checked,disabled,icon,label,radiogroup,type

DescriptionThecommandelementrepresentsachoicewithinamenuelement.Acommandmaybeoneofthreestates,asspeciiedbyitstypeattribute.Thedefaultisanormalcommand(type="command"ornotype)thatisassociatedwithanaction(seetheexampleinthemenuentryinthischapter).Anotherisatoggle(type="radio"),asshowninthefollow-ingexample.Thethirdstateisachoiceofoneitemfromalistofitems(type="checkbox").

SupposeyouwriteawordprocessingWebapplication,andyouwanttoprovideacontextmenusouserscaneasilytogglethetrackchangesoptionfromwheretheyaretyping,ratherthannavigatingthroughthetoolbaratthetop.

Part3:HTML5ElementsandGuidance Chapter15:InteractiveElements 287

Example(contextmenuwithradiocommands):

<menu type=”context” id="trackChanges">

<h1>Track Changes</h1>

<command type="radio" radiogroup="tracking" label="On" />

<command type="radio" radiogroup="tracking" label="Off" />

</menu>

<article contenteditable="true" contextmenu="trackChanges">

. . . [paragraphs and other content the user may edit] . . .

</article>

Theradiogroupspeciiesanameforthegroupofrelatedradiocommandsthattogglewhenthecommandistoggled(inotherwords,theselectedoneistoggledon,andallothersintheradiogrouparetoggledoff).Thecontextmenuattributeonthearticleelementissettothemenu’sidinordertospecifythemenuasthearticle’scontextmenu;usersmaynotaccessitoutsidethearticle.

Atype="checkbox"commandmaybestructuredsimilarlybutwouldnotincludetheradiogroupattribute.

note Youmayusemenuinotherwaysbesidesacontextmenu.Pleaseseethemenuentryinthischapterforanexplanationofmenutypes,aswell

asanotherexampleandfurtherdiscussionofcommand,includinghowtomakeacommandfunctional.

AttributesinDetailn checked:Ifpresent,thisBooleanattributeindicatesthecommandis

selected.It’spermittedonlyiftypeissettocheckboxorradio.n disabled:Ifpresent,thisBooleanattributemakesthecommand

unavailable,thoughitmaystilldisplay.

Part3:HTML5ElementsandGuidance288

n icon="imageURL":Thisspeciiesthelocationofanimagethatrepre-sentsthecommandandisshowntotheuser.

n label="text":Required.Thisspeciiesthecommandnametextthatisshowntotheuser.

n radiogroup="name":Thisvalueisanameofyourchoosingandmaybeassignedonlyiftype="radio".Pleaseseethedescriptioninthisentry.

n type="checkbox|command|radio":Thisdeinesacommand’sstate.Thecommanddefaultstotype="command"iftypeisomitted.Pleaseseethedescriptioninthisentry.

detailsAnexpandablewidget

Syntax <details></details>Attributes HTML5Only:Global,open

DescriptionThedetailselementexpandsorcollapsestorevealorhideinformationorcontrols.JavaScriptisn’trequiredforthisbehavior,sinceit’sbuiltintotheelement.

Bydefault,adetailselementshouldrenderasclosed,soitscontentdoesn’tdisplayexceptforthesummaryelement(theopenattributesetsittoopeninstead).summaryisthecaptionforthecontentand,dependingontheuseragent,maybethemeansbywhichtheusercanopenorclosethedetails.Ifsummaryisabsent,theuseragentshoulddisplayatermofitschoosing,suchasDetails.

Part3:HTML5ElementsandGuidance Chapter15:InteractiveElements 289

Thesefollowingexamplesshowacouplewaysyoumightusedetails.Theirstisafootball(American-style)gametracker.Thesummaryprovidesasnapshotoftheaction,andtheusercanlearnmorebyopeningthedetailselement.Itcouldevenhaveavideoelementinit.Thesecondexampleisalistofemoticonstheusercouldtoggleopeninachatappli-cationandthencloseafterselectingone.

Examples:

<details>

<summary>Good Guys 20, Bad Guys 17, fourth quarter

➥ </summary>

<!-- Code showing score by quarter and

other statistics would go here. -->

</details>

<details>

<summary>Emoticons</summary>

<ul>

<li><a href=”#”><img src=”icon/super_smiley.png”

width=”20” height=”20” alt=”Super smiley” /></a></li>

<li><a href=”#”><img src=”icon/guffaw.png” width=”20”

height=”20” alt=”Guffaw” /></a></li>

. . . [more emoticons] . . .

</ul>

</details>

Anotherapplicationofdetailscouldbuildonthedrawingtoolexamplefromthemenuentryinthischapter.AloatingpalettelikethoseinPhotoshopcouldincludeaseriesofstackeddetailselementsthatrevealforminputstotypeinshapedimensionsorpickacolor,andsoon.

Part3:HTML5ElementsandGuidance290

note Trytocraftasummarythatreflectsthevaluesofthedetailswheneverpossible.Thefootballexampledemonstratesthis.

AttributesinDetailn open:Whenpresent,thisBooleanattributespeciiesthatthecontent

withindetailsshouldbeshowntotheuser.Useragentsshouldn’tshowitbydefaultexceptthesummary.

menu

Anapplicationmenu

Syntax <menu></menu>Attributes HTML5Only:Global,label,type

DescriptionThemenuelementhashadapreviouslifeinHTML,butit’sdeprecatedinX/HTML.HTML5bothresurrectsandreinesittoaddvalue.

Amenumaybeacontextmenuoratoolbar,asspeciiedbyitstypeattribute(it’sneitheriftypeisundeined,asshownintheexample).Acontextmenuislikethekindthatdisplaysinsoftwarewhenyouright-clickorOption-click(orAlt-clickinsomecases).Atoolbarislikethekindavailablealongthetopofmostsoftware(thoughatoolbarmenuwon’tnecessarilyappearatthetop).Ineachcase,amenuhasoneormorechoices.

note menuisappropriateforWebapplicationmenus,notnavigation.PleaseseethenavelementinChapter11regardingstructuringnavigation.

Part3:HTML5ElementsandGuidance Chapter15:InteractiveElements 291

Thecommandelementisonewaytodeineyourmenu’soptions.(Pleaseseeitsentryinthischapterformoredetails.)

Example(toolbarmenuwithcommands):

<menu type="toolbar">

<li>

<menu label="File">

<command label="New" icon="icon/new.png"

title="Start a new drawing" />

<command label="Open" icon="icon/open.png"

title="Open a drawing" />

<command label="Save" icon="icon/save.png"

title="Save your drawing" disabled="disabled" />

. . . [more commands] . . .

</menu>

</li>

<li>

<menu label="Edit">

. . . [commands for Edit menu] . . .

</menu>

</li>

</menu>

Thisexampleshowsamenuoftype="toolbar"foranimaginarydraw-ingapp(usingthecanvaselement,forinstance).Itassumestheuser’sbrowserhasJavaScriptenabled,sinceyoucan’tapplybehaviortocommandelements(orcanvas,forthatmatter)withoutit.Notethatthetypeisspeciiedonlyontheparentmenusincethenestedmenusarepartofthetoolbar(amenudoesn’trequirenestedmenus,however).Intheexample,eachnestedmenuisrepresentedintheinterfacebyitslabelattribute(althoughasofthiswriting,nopopularuseragentrendersityet).

Part3:HTML5ElementsandGuidance292

note Theuseofliwithoutanolorulelementparentisparticulartomenu.menuallowsnearlyallotherHTMLelements,too,thoughyoucan’t

structuresomeofitwithlielementsandtherestwithsomethingelse.

ThedisabledattributerenderstheSavecommandelementinactive.Presumably,youwouldremovedisabledprogrammaticallytoenablethecommandoncetheuserperformsachange,asiscommoninapplications.Thetitleattributetextmaydisplayasatooltipasthepointerhoversoverthecommand;itisoptional,liketheiconattribute.

Acommandelementdoesn’tperformanactionunlessyouspecifyitsbehaviorviaanonclickevent.Forinstance,selectingtheNewcommandcouldcallaJavaScriptfunctionthatstartsanewdrawing.Istronglyrecommendyouaddtheonclickeventsunobtrusivelyratherthanasinlineonclickattributes.(PleasesearchforunobtrusiveJavaScriptonlinefordetails.)

Previously,Inotedthatcommandisjustonewaytorepresentamenu’schoices.Youmayalsouseelementssuchasa,button,andselect.Ifyouweretousebutton,theexample’sstructurewouldbethesameexceptbuttonelementswouldreplacethecommands.Thisapproachcouldbefriendliertobrowsersthatdon’tsupportcommand,becausetheywouldstillbeabletodisplaythelistofbuttons.

ContextMenusAcontextmenuisstructuredthesameasatoolbarexceptithasatype="context"declaration.Youassociateacontextmenuwithanotherelementbysettingtheelement’scontextmenuattributevaluetothemenu’sid.Pleaseseetheexampleinthecommandentryinthischapter.

note Usethehrelementasaseparatorwithinamenuasneeded.

Part3:HTML5ElementsandGuidance Chapter15:InteractiveElements 293

note HTML5suggestshowamenumayappearbutdoesn’tdefineitoutright,souseragentrenderingsmayvary.

AttributesinDetailn type="context|toolbar":Deinesamenuaseitheracontextmenuora

toolbar.Iftypeisunspeciied,themenuisalistofoptionsthat’sneithertype.Forinstance,thenestedmenuintheexampledoesn’thaveatypesinceit’sasubmenu.

n label="text":Themenu’slabelthatisshowntotheuser.

summaryDetailssummaryorcaption

Syntax <summary></summary>Attributes HTML5Only:Global

DescriptionThesummaryelementprovidesasummary,caption,orlegendfortheothercontentsofadetailselement.Pleaseseethedetailsentryinthischapterformoreinformation.

a,94abbr,102acronym*,104address,28area,142article(HTML5only),227aside(HTML5only),230audio(HTML5only),264b,105base,44bdo,106big*,107

blockquote,108body,30br,110button,158canvas(HTML5only),266caption,186cite,111code,113col,186colgroup,187command(HTML5only),286datalist(HTML5only),278

Appendix:AlphabeticalHTMLElementsPageListing

LEGEND:(HTML5only) HTML4andXHTML1includeallelementsexceptthosemarkedwith

(HTML5only),whichareuniquetoHTML5.* HTML5includesallelementsexceptthosemarkedwithanasterisk(*).

Appendix 295

dd,71del,114details(HTML5only),288dfn,117div,35dl,73dt,79em,119embed,268fieldset,160figcaption(HTML5only),246figure(HTML5only),246footer(HTML5only),232form,161frame*,214frameset*,214h1–h6,36head,47header(HTML5only),235hgroup(HTML5only),238hr,39html,40i,121iframe,216img,144input,168ins,123kbd,124keygen,280label,176legend,177li,81link,49map,146mark(HTML5only),249menu(HTML5only),290meta,57meter(HTML5only),251nav(HTML5only),239noframes*,219

noscript,206object,149ol,84optgroup,178option,179output(HTML5only),282p,125param,153pre,126progress(HTML5only),254q,129rp(HTML5only),256rt(HTML5only),256ruby(HTML5only),257samp,131script,207section(HTML5only),242select,180small,132source(HTML5only),269strong,134style,63sub,135summary(HTML5only),293sup,136table,190tbody,196td,197textarea,182tfoot,200th,201thead,201time(HTML5only),259title,67tr,202tt*,137ul,89var,138video(HTML5only),271wbr(HTML5only),262

Aaelement,94–101attributes,97–100,101examplesofusing,94–97HTML5and,101

abbrelement,102–103abbreviations,102–103aboutthisbook,vii–xabsolutepath,95,96accesskeyattribute,15,18acronymelement,103,104addresselement,28–29anchors,96–101applicationcachemanifest,41–42applicationmenus,290–293areaelement,142–143articleelement,29,227–229,242asideelement,230–232,248

Atomfeedlink,52attributeminimization,10attributesBoolean,10Core,15–16data,20–21deprecated,24Events,17–18Global,18–22howthey’renoted,14–15I18n,16–17newtoHTML5,5obsolete,24

audioelement,264–265audioformatsupport,265authorcontactinfo,28–29

Index

Index 297

Bbelement,105–106,122,123baseelement,44–46bdoelement,106–107bestpracticesHTML,7–8scripting,204–205

bidirectionaltextoverride,106–107bigelement,107–108blockingbehavior,204block-levelelements,13,116,117blockquoteelement,108–110bodyelement,30–34deprecatedattributes,31–32eventattributes,31,32–34HTML5and,32–34

boldtext,105–106,122,123Booleanattributes,10bordersframe,216table,198,200

brelement,110breadcrumbnavigation,86browsers,xscripthandlingby,204supportforHTML5,4,221

buttonelement,158–159

Ccalculationresults,282–283canvaselement,266–267captionelement,186Castro,Elizabeth,24CDATAvalues,22characterencoding,22characterentities,23–24charsetattribute,22citeelement,111–112classattribute,15–16,18codeconventionsusedfor,ix–xHTML5syntaxformat,5–6

codeelement,113–114,138–139colelement,186–187colgroupelement,187–190

attributes,189–190examplesofusing,188–189

commandelement,286–288,291comments,13contenttypes,22–23contenteditableattribute,18–19contextmenus,290,292–293contextmenuattribute,19Coreattributes,15–16Cutts,Matt,38

Ddataattributes,20–21datatypes,22–23datalistelement,278–279date/timeinfo,259–261ddelement,71–72deinitionlists,73–79denotingtermsin,79–80describingtermsin,71–72dialogueand,79examplesof,73–77whentouse,78

delelement,114–117attributes,115–116block-level,116,117

deletedcontent,114–117deprecatedelements/attributes,24detailselement,288–290determinateprogress,255deviceelement,286dfnelement,117–118dirattribute,16,19divelement,35–36,223,242dlelement,73–79deprecatedattribute,77dialoguemarkupand,79examplesofusing,73–77whentouse,78

DOCTYPEs,7,9,11–13documentheadelements,43–68draggableattribute,19drawingsurface,266–267dtelement,79–80

TheHTMLPocketGuide298

Eelementsattributesfor,14–22conventionsusedfor,ix–xdeprecatedorobsolete,24emptyorvoid,10inlinevs.block-level,13newtoHTML5,4–5summarylistof,295–296Seealsospeciicelements

emelement,119–120,122,123embedelement,151,268–269embeddedcontentoverviewofelementsfor,141–155uniqueHTML5elementsfor,

263–275emptyelements,10Eventsattributes,17–18,21–22expandablewidgets,288–290

Ffavicons,52fieldsetelement,160figcaptionelement,246figureelement,246–248footerelement,232–234formelement,157,161–167attributes,165–167examplesofusing,162–165HTML5and,167

form-relatedelementsoverviewof,157–184uniquetoHTML5,277–283

frameelement,214frames,213–219framesetelement,214–215

GGlobalattributes,18–22dataattributes,20–21Eventsattributes,21–22

GoogleClosureCompiler,205

Hh1-h6elements,36–38H.264videoformat,272–273headelement,43,47–49headerelement,235–238headings,36–38,238–239hgroupelement,238–239hiddenattribute,19highlightedtext,249–250horizontalrule,39–40hrelement,39–40,292HTMLattributes,14–22bestpractices,7–8characterentities,23–24comments,13datatypes,22–23deprecatedelements/attributes,24DOCTYPEs,11–13documentstructure,8–9inlinevs.block-levelelements,13obsoleteelements/attributes,24summarylistofelements,295–296versiondifferences,10–11

HTML4DOCTYPEs,11–12HTML5differences,11summarylistofelements,295–296XHTMLdifferences,10

HTML5dataattributes,20–21DOCTYPEs,12documentoutlines,224–227elementstyling,7embeddedcontent,263–275form-relatedelements,277–283Globalattributes,18–22HTML4differences,11interactiveelements,285–293overview,4–7,221structuralelements,223–243summarylistofelements,295–296syntaxformats,5–6textelements,245–262

HTML5Outlinertool,225,227

TheHTMLPocketGuide Index 299

htmlelement,9,40–42HTMLRubyFirefoxadd-on,258

II18nattributes,16–17ielement,121–123idattribute,16,19,22iframeelement,216–218attributes,216–217,218HTML5and,218

imagemaps,146–148images,embedded,144–146imgelement,144–146indeterminateprogress,255inlineelements,13,116inputelement,168–175attributes,170–175HTML5and,172–175typesofinputs,168–170

inselement,123insertedcontent,123interactiveelements,285–293italicizedtext,119,121,122,123itemidattribute,19itempropattribute,19itemrefattribute,19itemscopeattribute,19itemtypeattribute,19

JJavaScript,17,203,204–205,206–209

Kkbdelement,124keygenelement,280–281keywords,59

Llabelelement,176–177langattribute,16–17,19,23languagecodes,23legendelement,177–178lielement,81–83,292linebreaks,110,262

linkelement,49–56attributes,54–55,56casesforusing,49–50faviconsand,52HTML5and,56relateddocumentsand,52–53stylesheetsand,50–52

linktypes,23lists,69–91deinition,73–79itemsin,81–83nested,70–71ordered,84–88unordered,89–91

Mmapelement,146–148markelement,249–250measurements,251–253mediacontent,263–275menucommands,286–288menuelement,83,290–293metaelement,9,57–62attributes,60,61–62commonlyusedformsof,58–59contenttypedeclaration,57–58HTML5and,61–62

metatags,57metadata,57meterelement,251–253attributes,252–253examplesofusing,251–252

MIMEtypes,22–23monospacetext,137

Nnameattribute,22navelement,238,239–241navigationorderedlistsand,86sectionoflinksfor,239–241unorderedlistsand,90

nestingarticles,228,229asides,230–231,232

TheHTMLPocketGuide300

nesting(continued)lists,70–71objects,150quotations,130tables,196

noframeselement,219noscriptelement,206–207

Oobjectelement,149–153attributes,151–152examplesofusing,149–150

obsoleteelements/attributes,24OggTheoravideoformat,272olelement,84–88HTML5and,87–88recommendedusesof,86

onclickattribute,17ondblclickattribute,17onkeydownattribute,18onkeypressattribute,18onkeyupattribute,18onmousedownattribute,17onmousemoveattribute,17onmouseoutattribute,17onmouseoverattribute,17onmouseupattribute,17optgroupelement,178–179optionelement,179–180orderedlists,84–88recommendedusesof,86usingunorderedvs.,85,90

outlines,224–227outputelement,282–283

Ppelement,125–126paginationnavigation,86paragraphs,125–126paramelement,153–155preelement,126–128prefetching,53preformattedtext,126–128preloadedvideo,275progresselement,253,254–255progressiveenhancement,

206–207

Qqelement,129–131quotationslong,108–110nested,130short,129–131

Rrelativepath,95rpelement,256RSSreaderlink,52rtelement,256rubyannotations,257–258rubyelement,257–258

Ssampelement,131scriptelement,43,204,207–211attributes,210–211examplesofusing,208–209HTML5and,211

scripting,203–211bestpracticesfor,204–205elementsandattributes,206–211

searchengineoptimization(SEO),43,68

sectionelement,242–243sectioningcontentelements,224selectelement,180–181semantics,7–8smallelement,132–133Souders,Steve,205sourceelement,269–271,273–274spanelement,35spellcheckattribute,19strongelement,122,123,134–135structural/sectionalelementsgeneraloverviewof,27–42uniquetoHTML5,223–243

styleattribute,16,19styleelement,63–66attributes,64–66HTMLand,65–66

stylesheetsembedded,63–66linkingto,50–52

TheHTMLPocketGuide Index 301

subelement,135–136subscriptnotation,135–136summaryelement,293supelement,136–137superscriptnotation,136–137supportWebsite,ix

Ttabindexattribute,15,20tableelement,185,190–196attributes,194–195examplesofusing,191–194resourcesabout,194

tabulardata,185–202taskprogressindicator,254–255tbodyelement,193,196–197tdelement,197–200teletypetext,137terminologyoverview,xtextbolding,105–106,122,123emphasizing,119–120,122–123,

134–135highlighting,249–250italicizing,119,121,122,123resizing,107–108,132–133

textelementsoverviewof,93–139uniquetoHTML5,245–262

textareaelement,182–184attributes,182–184HTML5and,183–184

tfootelement,192–193,195,200thelement,201theadelement,192,195,201–202thematiccontent,242–243timeelement,259–261time/dateinfo,259–261titleattribute,16,20titleelement,67–68toolbar,290,291trelement,202ttelement,137

Uulelement,89–91unobtrusiveJavaScript,17,292unorderedlists,89–91recommendedusesof,90–91usingorderedvs.,85,90

useragents,x

Vvalidators,8,227varelement,138–139variables,138–139videoelement,271–275attributes,274–275examplesofusing,271–272,

273–274multiplemediasourcesand,

273–274videoformatsand,272–273

VideoforEverybodycode,274

Wwbrelement,262WebresourcesHTML5WorkingDraft,4HTMLPocketGuidesupport,ixscript-loadingmethods,205

Webstandards,7–8widgets,288–290

XXHTMLDOCTYPEs,12–13HTML4differences,10summarylistofelements,

295–296syntaxformat,6

XHTML5,6X/HTML,x,223,239

YYUICompressor,205

top related