HTML & XHTML The Definitive Guide
HTML_XHTML_The_Definitive_Guide
HTML_XHTML_The_Definitive_Guide
User Manual:
Open the PDF directly: View PDF .
Page Count: 994 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- Chapter 1. HTML, XHTML, and the World Wide Web
- Chapter 2. Quick Start
- Chapter 3. Anatomy of an HTML Document
- Chapter 4. Text Basics
- Chapter 5. Rules, Images, and Multimedia
- Chapter 6. Links and Webs
- Chapter 7. Formatted Lists
- Chapter 8. Cascading Style Sheets
- Chapter 9. Forms
- Chapter 10. Tables
- Chapter 11. Frames
- Chapter 12. Executable Content
- Chapter 13. Dynamic Documents
- Chapter 14. Mobile Devices
- Chapter 15. XML
- Chapter 16. XHTML
- Chapter 17. Tips, Tricks, and Hacks
HTML&XHTML:TheDefinitiveGuide,6thEdition
TableofContents
Copyright
Dedication
prefacePreface
Chapter1.HTML,XHTML,andtheWorldWideWeb
Section1.1.TheInternet
Section1.2.TalkingtheInternetTalk
Section1.3.HTMLandXHTML:WhatTheyAre
Section1.4.HTMLandXHTML:WhatTheyAren't
Section1.5.StandardsandExtensions
Section1.6.ToolsfortheWebDesigner
Chapter2.QuickStart
Section2.1.WritingTools
Section2.2.AFirstHTMLDocument
Section2.3.EmbeddedTags
Section2.4.HTMLSkeleton
Section2.5.TheFleshonanHTMLorXHTMLDocument
Section2.6.Text
Section2.7.Hyperlinks
Section2.8.ImagesAreSpecial
Section2.9.Lists,SearchableDocuments,andForms
Section2.10.Tables
Section2.11.Frames
Section2.12.StylesheetsandJavaScript
Section2.13.ForgingAhead
Chapter3.AnatomyofanHTMLDocument
Section3.1.AppearancesCanDeceive
Section3.2.StructureofanHTMLDocument
Section3.3.TagsandAttributes
Section3.4.Well-FormedDocumentsandXHTML
Section3.5.DocumentContent
Section3.6.HTML/XHTMLDocumentElements
Section3.7.TheDocumentHeader
Section3.8.TheDocumentBody
Section3.9.EditorialMarkup
Section3.10.TheTag
Chapter4.TextBasics
Section4.1.DivisionsandParagraphs
Section4.2.Headings
Section4.3.ChangingTextAppearanceandMeaning
Section4.4.Content-BasedStyleTags
Section4.5.PhysicalStyleTags
Section4.6.PreciseSpacingandLayout
Section4.7.BlockQuotes
Section4.8.Addresses
Section4.9.SpecialCharacterEncoding
Section4.10.HTML'sObsoleteExpandedFontHandling
Chapter5.Rules,Images,andMultimedia
Section5.1.HorizontalRules
Section5.2.InsertingImagesinYourDocuments
Section5.3.DocumentColorsandBackgroundImages
Section5.4.BackgroundAudio
Section5.5.AnimatedText
Section5.6.OtherMultimediaContent
Chapter6.LinksandWebs
Section6.1.HypertextBasics
Section6.2.ReferencingDocuments:TheURL
Section6.3.CreatingHyperlinks
Section6.4.CreatingEffectiveLinks
Section6.5.Mouse-SensitiveImages
Section6.6.CreatingSearchableDocuments
Section6.7.Relationships
Section6.8.SupportingDocumentAutomation
Chapter7.FormattedLists
Section7.1.UnorderedLists
Section7.2.OrderedLists
Section7.3.The
Tag
Section7.4.NestingLists
Section7.5.DefinitionLists
Section7.6.AppropriateListUsage
Section7.7.DirectoryLists
Section7.8.MenuLists
Chapter8.CascadingStyleSheets
Section8.1.TheElementsofStyles
Section8.2.StyleSyntax
Section8.3.StyleClasses
Section8.4.StyleProperties
Section8.5.TaglessStyles:TheTag
Section8.6.ApplyingStylestoDocuments
Chapter9.Forms
Section9.1.FormFundamentals
Section9.2.The
Section9.3.ASimpleFormExample
Section9.4.UsingEmailtoCollectFormData
Section9.5.The Tag
Section9.6.The
Tag
Section9.7.MultilineTextAreas
Section9.8.Multiple-ChoiceElements
Section9.9.GeneralForm-ControlAttributes
Section9.10.LabelingandGroupingFormElements
Section9.11.CreatingEffectiveForms
Section9.12.FormsProgramming
Chapter10.Tables
Section10.1.TheStandardTableModel
Section10.2.BasicTableTags
Section10.3.AdvancedTableTags
Section10.4.BeyondOrdinaryTables
Chapter11.Frames
Section11.1.AnOverviewofFrames
Section11.2.FrameTags
Section11.3.FrameLayout
Section11.4.FrameContents
Section11.5.The
Section11.6.InlineFrames
Section11.7.NamedFrameorWindowTargets
Section11.8.XFrames
Chapter12.ExecutableContent
Section12.1.AppletsandObjects
Section12.2.EmbeddedContent
Section12.3.JavaScript
Section12.4.JavaScriptStylesheets(Antiquated)
Chapter13.DynamicDocuments
Section13.1.AnOverviewofDynamicDocuments
Section13.2.Client-PullDocuments
Section13.3.Server-PushDocuments
Chapter14.MobileDevices
Section14.1.TheMobileWeb
Section14.2.DeviceConsiderations
Section14.3.XHTMLBasic
Section14.4.EffectiveMobileWebDesign
Chapter15.XML
Section15.1.LanguagesandMetalanguages
Section15.2.DocumentsandDTDs
Section15.3.UnderstandingXMLDTDs
Section15.4.ElementGrammar
Section15.5.ElementAttributes
Section15.6.ConditionalSections
Section15.7.BuildinganXMLDTD
Section15.8.UsingXML
Chapter16.XHTML
Section16.1.WhyXHTML?
Section16.2.CreatingXHTMLDocuments
Section16.3.HTMLVersusXHTML
Section16.4.XHTML1.1
Section16.5.ShouldYouUseXHTML?
Chapter17.Tips,Tricks,andHacks
Section17.1.TopoftheTips
Section17.2.CleaningUpAfterYourHTMLEditor
Section17.3.TrickswithTables
Section17.4.TrickswithWindowsandFrames
AppendixA.HTMLGrammar
SectionA.1.GrammaticalConventions
SectionA.2.TheGrammar
AppendixB.HTML/XHTMLTagQuickReference
SectionB.1.CoreAttributes
SectionB.2.HTMLQuickReference
AppendixC.CascadingStyleSheetPropertiesQuickReference
AppendixD.TheHTML4.01DTD
AppendixE.TheXHTML1.0DTD
AppendixF.CharacterEntities
AppendixG.ColorNamesandValues
SectionG.1.ColorValues
SectionG.2.ColorNames
SectionG.3.TheStandardColorMap
AppendixH.NetscapeLayoutExtensions
SectionH.1.CreatingWhitespace
SectionH.2.MulticolumnLayout
SectionH.3.Layers
HTML&XHTML:TheDefinitiveGuide,6thEdition
ByBillKennedy,ChuckMusciano
...............................................
Publisher:O'Reilly
PubDate:October2006
PrintISBN-10:0-596-52732-2
PrintISBN-13:978-0-59-652732-7
Pages:678
TableofContents|Index
"...lucid,in-depthdescriptionsofthebehaviorofeveryHTMLtagoneverymajorbrowserandplatform,plus
enoughdryhumortomakethebookapleasuretoread."
--EdwardMendelson,PCMagazine
"Whentheysay'definitive'they'renotkidding."
--LindaRoeder,About.com
PuteverthingyouneedtoknowaboutHTML&XHTMLatyourfingertips.Fornearlyadecade,hundredsof
thousandsofwebdevelopershaveturnedtoHTML&XHTML:TheDefinitiveGuidetomasterstandards-basedweb
development.Trulyadefinitiveguide,thebookcombinesauniquebalanceoftutorialmaterialwithacomprehensive
referencethateventhemostexperiencedwebprofessionalskeepcloseathand.Frombasicsyntaxandsemanticsto
guidelinesaimedathelpingyoudevelopyourowndistinctivestyle,thisclassicisallyouneedtobecomefluentinthe
languageofwebdesign.
ThenewsixtheditionguidesyouthrougheveryelementofHTMLandXHTMLindetail,explaininghoweachelement
worksandhowitinteractswithotherelements.You'llalsofinddetaileddiscussionsofCSS(CascadingStyleSheets),
whichisintricatelyrelatedtowebpagedevelopment.Themostall-inclusive,up-to-datebookontheselanguages
available,thiseditioncoversHTML4.01,XHTML1.0,andCSS2,withapreviewoftheupcomingXHTML2andCSS3.
OthertopicsincludethenewerinitiativesinXHTML(XForms,XFrames,andmodularization)andtheessentialsofXML
foradvancedreaders.You'lllearnhowto:
Usestylesheetstocontrolyourdocument'sappearance
WorkwithprogrammaticallygeneratedHTML
Createtables,bothsimpleandcomplex
Useframestocoordinatesetsofdocuments
Designandbuildinteractiveformsanddynamicdocuments
Insertimages,soundfiles,video,Javaapplets,andJavaScriptprograms
Createdocumentsthatlookgoodonavarietyofbrowsers
Theauthorsapplyanaturallearningapproachthatusesstraightforwardlanguageandplentyofexamples.
Throughoutthebook,theyoffersuggestionsforstyleandcompositiontohelpyoudecidehowtobestuseHTML
andXHTMLtoaccomplishavarietyoftasks.You'lllearnwhatworksandwhatdoesn't,andwhatmakessenseto
thosewhoviewyourwebpagesandwhatmightbeconfusing.Writtenforanyonewhowantstolearnthelanguage
oftheWeb--fromcasualuserstothefull-timedesignprofessionals--thisisthesinglemostimportantbookonHTML
andXHTMLyoucanown.
BillKennedyischieftechnicalofficerofMobileRobots,Inc.WhennothackingnewHTMLpagesorwritingabout
them,"Dr.Bill"(Ph.D.inbiophysicsfromLoyolaUniversityofChicago)isoutpromotingthecompany'slineofmobile,
autonomousrobotsthatcanbeusedforartificialintelligence,fuzzylogicresearch,andeducation.
ChuckMuscianobeganhiscareerasacompilerwriterandcrafteroftoolsatHarrisCorporations'Advanced
TechnologyGroupandisnowamanagerofUnixSystemsinHarris'CorporateDataCenter.
HTML&XHTML:TheDefinitiveGuide,6thEdition
ByBillKennedy,ChuckMusciano
...............................................
Publisher:O'Reilly
PubDate:October2006
PrintISBN-10:0-596-52732-2
PrintISBN-13:978-0-59-652732-7
Pages:678
TableofContents|Index
Copyright
Dedication
prefacePreface
Chapter1.HTML,XHTML,andtheWorldWideWeb
Section1.1.TheInternet
Section1.2.TalkingtheInternetTalk
Section1.3.HTMLandXHTML:WhatTheyAre
Section1.4.HTMLandXHTML:WhatTheyAren't
Section1.5.StandardsandExtensions
Section1.6.ToolsfortheWebDesigner
Chapter2.QuickStart
Section2.1.WritingTools
Section2.2.AFirstHTMLDocument
Section2.3.EmbeddedTags
Section2.4.HTMLSkeleton
Section2.5.TheFleshonanHTMLorXHTMLDocument
Section2.6.Text
Section2.7.Hyperlinks
Section2.8.ImagesAreSpecial
Section2.9.Lists,SearchableDocuments,andForms
Section2.10.Tables
Section2.11.Frames
Section2.12.StylesheetsandJavaScript
Section2.13.ForgingAhead
Chapter3.AnatomyofanHTMLDocument
Section3.1.AppearancesCanDeceive
Section3.2.StructureofanHTMLDocument
Section3.3.TagsandAttributes
Section3.4.Well-FormedDocumentsandXHTML
Section3.5.DocumentContent
Section3.6.HTML/XHTMLDocumentElements
Section3.7.TheDocumentHeader
Section3.8.TheDocumentBody
Section3.9.EditorialMarkup
Section3.10.The<bdo>Tag
Chapter4.TextBasics
Section4.1.DivisionsandParagraphs
Section4.2.Headings
Section4.3.ChangingTextAppearanceandMeaning
Section4.4.Content-BasedStyleTags
Section4.5.PhysicalStyleTags
Section4.6.PreciseSpacingandLayout
Section4.7.BlockQuotes
Section4.8.Addresses
Section4.9.SpecialCharacterEncoding
Section4.10.HTML'sObsoleteExpandedFontHandling
Chapter5.Rules,Images,andMultimedia
Section5.1.HorizontalRules
Section5.2.InsertingImagesinYourDocuments
Section5.3.DocumentColorsandBackgroundImages
Section5.4.BackgroundAudio
Section5.5.AnimatedText
Section5.6.OtherMultimediaContent
Chapter6.LinksandWebs
Section6.1.HypertextBasics
Section6.2.ReferencingDocuments:TheURL
Section6.3.CreatingHyperlinks
Section6.4.CreatingEffectiveLinks
Section6.5.Mouse-SensitiveImages
Section6.6.CreatingSearchableDocuments
Section6.7.Relationships
Section6.8.SupportingDocumentAutomation
Chapter7.FormattedLists
Section7.1.UnorderedLists
Section7.2.OrderedLists
Section7.3.The<li>Tag
Section7.4.NestingLists
Section7.5.DefinitionLists
Section7.6.AppropriateListUsage
Section7.7.DirectoryLists
Section7.8.MenuLists
Chapter8.CascadingStyleSheets
Section8.1.TheElementsofStyles
Section8.2.StyleSyntax
Section8.3.StyleClasses
Section8.4.StyleProperties
Section8.5.TaglessStyles:The<span>Tag
Section8.6.ApplyingStylestoDocuments
Chapter9.Forms
Section9.1.FormFundamentals
Section9.2.The<form>Tag
Section9.3.ASimpleFormExample
Section9.4.UsingEmailtoCollectFormData
Section9.5.The<input>Tag
Section9.6.The<button>Tag
Section9.7.MultilineTextAreas
Section9.8.Multiple-ChoiceElements
Section9.9.GeneralForm-ControlAttributes
Section9.10.LabelingandGroupingFormElements
Section9.11.CreatingEffectiveForms
Section9.12.FormsProgramming
Chapter10.Tables
Section10.1.TheStandardTableModel
Section10.2.BasicTableTags
Section10.3.AdvancedTableTags
Section10.4.BeyondOrdinaryTables
Chapter11.Frames
Section11.1.AnOverviewofFrames
Section11.2.FrameTags
Section11.3.FrameLayout
Section11.4.FrameContents
Section11.5.The<noframes>Tag
Section11.6.InlineFrames
Section11.7.NamedFrameorWindowTargets
Section11.8.XFrames
Chapter12.ExecutableContent
Section12.1.AppletsandObjects
Section12.2.EmbeddedContent
Section12.3.JavaScript
Section12.4.JavaScriptStylesheets(Antiquated)
Chapter13.DynamicDocuments
Section13.1.AnOverviewofDynamicDocuments
Section13.2.Client-PullDocuments
Section13.3.Server-PushDocuments
Chapter14.MobileDevices
Section14.1.TheMobileWeb
Section14.2.DeviceConsiderations
Section14.3.XHTMLBasic
Section14.4.EffectiveMobileWebDesign
Chapter15.XML
Section15.1.LanguagesandMetalanguages
Section15.2.DocumentsandDTDs
Section15.3.UnderstandingXMLDTDs
Section15.4.ElementGrammar
Section15.5.ElementAttributes
Section15.6.ConditionalSections
Section15.7.BuildinganXMLDTD
Section15.8.UsingXML
Chapter16.XHTML
Section16.1.WhyXHTML?
Section16.2.CreatingXHTMLDocuments
Section16.3.HTMLVersusXHTML
Section16.4.XHTML1.1
Section16.5.ShouldYouUseXHTML?
Chapter17.Tips,Tricks,andHacks
Section17.1.TopoftheTips
Section17.2.CleaningUpAfterYourHTMLEditor
Section17.3.TrickswithTables
Section17.4.TrickswithWindowsandFrames
AppendixA.HTMLGrammar
SectionA.1.GrammaticalConventions
SectionA.2.TheGrammar
AppendixB.HTML/XHTMLTagQuickReference
SectionB.1.CoreAttributes
SectionB.2.HTMLQuickReference
AppendixC.CascadingStyleSheetPropertiesQuickReference
AppendixD.TheHTML4.01DTD
AppendixE.TheXHTML1.0DTD
AppendixF.CharacterEntities
AppendixG.ColorNamesandValues
SectionG.1.ColorValues
SectionG.2.ColorNames
SectionG.3.TheStandardColorMap
AppendixH.NetscapeLayoutExtensions
SectionH.1.CreatingWhitespace
SectionH.2.MulticolumnLayout
SectionH.3.Layers
AbouttheAuthors
Colophon
Index
Copyright©2007,2002,2000,1998,1997,1996O'ReillyMedia,Inc.Allrights
reserved.PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighwayNorth,Sebastopol,
CA95472.
O'Reillybooksmaybepurchasedforeducational,business,orsalespromotional
use.Onlineeditionsarealsoavailableformosttitles(safari.oreilly.com).Formore
information,contactourcorporate/institutionalsalesdepartment:(800)998-
9938orcorporate@oreilly.com.
Editor: TatianaApandi
ProductionEditor: ColleenGorman
Copyeditor: AudreyDoyle
Proofreader: ColleenGorman
Indexer: JohnnaVanHooseDinse
CoverDesigner: EdieFreedman
InteriorDesigner: MelanieWang
Illustrators: RobertRomanoandJessamynRead
PrintingHistory:
April1996: FirstEdition.
May1997: SecondEdition.
August1998: ThirdEdition.
August2000: FourthEdition.
August2002: FifthEdition.
October2006: SixthEdition.
NutshellHandbook,theNutshellHandbooklogo,andtheO'Reillylogoare
registeredtrademarksofO'ReillyMedia,Inc.HTML&XHTML:TheDefinitive
Guide,theimageofakoala,andrelatedtradedressaretrademarksofO'Reilly
Media,Inc.
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheir
productsareclaimedastrademarks.Wherethosedesignationsappearinthis
book,andO'ReillyMedia,Inc.wasawareofatrademarkclaim,thedesignations
havebeenprintedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthisbook,the
publisherandauthorsassumenoresponsibilityforerrorsoromissions,orfor
damagesresultingfromtheuseoftheinformationcontainedherein.
ISBN-10:0-596-52732-2
ISBN-13:978-0-596-52732-7
[M]
Dedication
Thisbookisdedicatedtoourwivesandchildren,Cindy,Courtney,
andCole,andJeanne,Eva,andEthan.Withouttheirloveand
patience,weneverwouldhavehadthetimeorstrengthtowrite.
Preface
LearningHypertextMarkupLanguage(HTML)andExtensibleHypertextMarkup
Language(XHTML)islikelearninganynewlanguage,computerorhuman.Most
studentsfirstimmersethemselvesinexamples.Studyingothersisanaturalway
tolearn,makinglearningeasyandfun.Ouradvicetoanyonewantingtolearn
HTMLandXHTMListogetoutthereontheWebwithasuitablebrowserandsee
foryourselfwhatlooksgood,what'seffective,andwhatworksforyou.Examine
others'documentsandponderthepossibilities.Mimicryishowmanyofthe
currentwebmastershavelearnedthelanguage.
Imitationcantakeyouonlysofar,though.Examplescanbebothgoodandbad.
Learningbyexamplehelpsyoutalkthetalk,butnotwalkthewalk.Tobecome
trulyconversant,youmustlearnhowtousethelanguageappropriatelyinmany
differentsituations.Youcouldlearnallthatbyexample,ifyoulivelongenough.
Computer-basedlanguagesaremoreexplicitthanhumanlanguages,thoughthe
markuplanguagesaremuchmoreforgivingthantheprogrammingones.
Nonetheless,youtypicallyhavetogetthecomputerlanguagesyntaxcorrectorit
won'twork.Thereare"standards,"too.Committeesofacademicsandindustry
expertsdefinethepropersyntaxandusageofacomputerlanguagelikeHTML.
Theproblemisthatthebrowsertechnologiesthatyouandyouraudienceuseto
displayyourdocumentsdon'talwayskeepupwiththestandards.Somecan't,like
thelimitedviewersusedintheburgeoningmobile-devicemarket.Andthenthere
arethosethatmakeuptheirownpartstothelanguage;standardsbedamned.
Standardschange,besides.HTMLisundergoingaconversionintoXHTML,making
itanapplicationoftheExtensibleMarkupLanguage(XML).HTMLandXHTMLare
sosimilarthatweoftenrefertothemasasinglelanguage,buttherearekey
differences,whichwediscusslaterinthisPreface.
Tobesafe,thewaytobecomefluentinHTMLandXHTMListhrougha
comprehensive,up-to-datelanguagereferencethatcoversthelanguagesyntax,
semantics,andvariationsindetailtohelpyoudistinguishbetweengoodandbad
usage.
There'sonemorestepleadingtofluencyinalanguage.Tobecomeatruemaster
ofthelanguage,youneedtodevelopyourownstyle.Thatmeansknowingnot
onlywhatisappropriate,butalsowhatiseffective.Layoutmatters.Sodoesthe
orderofpresentationwithinadocument,betweendocuments,andbetween
documentcollections.
OurgoalinwritingthisbookistohelpyoubecomefluentinHTMLandXHTML,
fullyversedintheirsyntax,semantics,andelementsofstyle.Wetakethe
natural-learningapproach,usingexamples(goodones,ofcourse).Wecoverin
detaileveryelementofthecurrentlyacceptedstandardversionsofthelanguages
(HTML4.01andXHTML1.0)aswellasallofthecurrentextensionssupportedby
thepopularbrowsers,explaininghoweachelementworksandhowitinteracts
withalloftheotherelements.
And,withallduerespecttoStrunkandWhite,throughoutthebookwegiveyou
suggestionsforstyleandcompositiontohelpyoudecidehowbesttouseHTML
andXHTMLtoaccomplishavarietyoftasks,fromsimpleonlinedocumentationto
complexmarketingandsalespresentations.Weshowyouwhatworksandwhat
doesn't,whatmakessensetothosewhoviewyourpages,andwhatmightbe
confusing.
Inshort,thisbookisadefinitiveguidetocreatingdocumentsusingHTMLand
XHTML,startingwithbasicsyntaxandsemanticsandfinishingwithbroadstyle
guidelinestohelpyoucreatebeautiful,informative,accessibledocumentsthat
you'llbeproudtodelivertoyourreaders.
OurAudience
Wewrotethisbookforanyoneinterestedinlearningandusingthelanguageof
theWeb,fromthemostcasualusertothefull-timedesignprofessional.Wedon't
expectyoutohaveanyexperienceinHTMLorXHTMLbeforepickingupthisbook.
Infact,wedon'tevenexpectthatyou'veeverbrowsedtheWeb,althoughwe'dbe
very,verysurprisedifyouhaven't.BeingconnectedtotheInternetisnotstrictly
necessarytousethisbook,butifyou'renotconnected,thisbookbecomeslikea
travelguideforthehomebound.
Theonlythingsweaskyoutohaveareacomputer,aneditorthatcancreate
simpletextfiles,andcopiesofthelatestwebbrowsers.Weusedthelatest
InternetExplorer,MozillaFirefox,NetscapeNavigator,andOperaSoftwareASA's
Operafortheexamplesinthisbook.BecauseHTMLandXHTMLdocumentsare
storedinauniversallyacceptedformatplaintextandbecausethelanguagesare
completelyindependentofanyspecificcomputer,wewon'tevenmakean
assumptionaboutthekindofcomputeryou'reusing.However,browsersdovary
byplatformandoperatingsystem,whichmeansthatyourHTMLorXHTML
documentscanlookquitedifferentdependingonthecomputerandbrowser
version.Soweexplainwherewecanhowthevariousbrowsersusecertain
languagefeatures,payingparticularattentiontohowtheyaredifferent.
IfyouarenewtoHTML,theWeb,orhypertextdocumentationingeneral,you
shouldstartbyreadingChapter1.Init,wedescribehowallthesetechnologies
cometogethertocreatewebsitesofinterrelateddocuments.
IfyouarealreadyfamiliarwiththeWeb,butnotwithHTMLorXHTMLspecifically,
startbyreadingChapter2.Thischapterisabriefoverviewofthemostimportant
featuresofthelanguageandservesasaroadmaptohowweapproachthe
languageintheremainderofthebook.
Subsequentchaptersdealwithspecificlanguagefeaturesinaroughlytop-down
approachtoHTMLandXHTML.Readtheminorderforacompletetourthrough
thelanguage,orjumparoundtofindtheexactfeatureyou'reinterestedin.
TextConventions
Throughoutthebook,weuseaconstant-widthtypefacetohighlightanyliteral
elementoftheHTML/XHTMLstandards,tags,andattributes.Wealwaysuse
lowercaselettersfortags.[*]Weuseitalicforfilenamesandtoindicatenew
conceptswhentheyaredefined.Elementsyouneedtosupplywhencreatingyour
owndocuments,suchastagattributesanduser-definedstrings,appearin
constant-widthitalicinthecode.
[*]HTMLiscase-insensitivewithregardtotagandattributenames,butXHTMLiscase-sensitive.AndsomeHTMLitems,
suchassourcefilenames,arecase-sensitive,sobecareful.
Wediscusselementsofthelanguagethroughoutthebook,butyou'llfindeach
onecoveredindepth(somemightsayinnauseatingdetail)inashorthand,quick-
referencedefinitionboxthatlooksliketheonethatfollows(forthe<title>
element).Thefirstlineoftheboxcontainstheelementname,followedbyabrief
descriptionofitsfunction.Next,welistthevariousattributes,ifany,ofthe
element:thosethingsthatyoumayormustspecifyaspartoftheelement.
<title>
Function Definesthedocumenttitle
Attribute dirlang
Endtag </title>;neveromitted
Contains plain_text
Usedin head_content
Theicon identifiestagsandattributesthataren'tintheHTML4.01orXHTML
1.0standards,andthosethatarehandledverydifferentlybetweenthevarious
popularbrowsers.
ThedescriptionalsoincludestheHTMLendingtag,ifany,fortheelement,along
withageneralindicationofwhethertheendtagmaybesafelyomittedingeneral
useinHTML.ForthefewtagsthatrequireendtagsinXHTML,butdonothave
theminHTML,thelanguageletsyouindicatethatbyplacingaforwardslash(/)
beforethetag'sclosingbracket,asin<br/>.Inthesecases,thetagmayalso
containattributes,indicatedwithaninterveningellipsis,suchas<br.../>.
The"Contains"headernamestheruleintheHTMLgrammarthatdefinesthe
elementstobeplacedwithinthistag.Similarly,the"Usedin"headerliststhose
rulesthatallowthistagaspartoftheircontent.Wedefinetheserulesin
AppendixA.
Finally,HTMLandXHTMLarefairlyintertwinedlanguages.Youwilloccasionally
useelementsindifferentwaysdependingoncontext,andmanyelementsshare
identicalattributes.Whereverpossible,weplaceacross-referenceinthetextthat
leadsyoutoarelateddiscussionelsewhereinthebook.Thesecross-references,
liketheoneattheendofthisparagraph,serveasacrudepapermodelof
hypertextdocumentation,onethatwouldbereplacedwithatruehypertextlink
shouldthisbookbedeliveredinanelectronicformat.[TheSyntaxofaTag,3.3.1]
Weencourageyoutofollowthesecross-referenceswheneverpossible.Often,we
coveranattributebrieflyandexpectyoutojumptothecross-referencefora
moredetaileddiscussion.Inothercases,followingthelinktakesyouto
alternativeusesoftheelementunderdiscussionortostyleandusage
suggestionsthatrelatetothecurrentelement.
VersionsandSemantics
ThelatestHTMLstandardisversion4.01,butmostupdatesandchangestothe
languagestandardweremadeinversion4.0.Therefore,throughoutthebook,we
oftenrefertotheHTMLstandardasHTML4,encompassingversions4.0andlater.
Weexplicitlystatethe"dot"versionnumberonlywhenitisrelevant.
TheXHTMLstandardiscurrentlyinitsfirstiteration,1.0.TheWorldWideWeb
Consortium(W3C)hasreleasedaWorkingDraftofasecondversion(XHTML2.0),
butthestandardisyetestablished.Forthemostpart,XHTML1.0isidenticalto
HTML4.01;wedetailtheirdifferencesinChapter16.Throughoutthebook,we
specificallynotecaseswhereXHTMLhandlesafeatureorelementdifferentlythan
theoriginallanguage,HTML.
TheHTMLandXHTMLstandardsmakeveryclearthedistinctionbetween"element
types"ofadocumentandthemarkup"tags"thatdelimitthoseelements.For
example,thestandardreferstotheparagraphelementtype,whichisnotthe
sameasthe<p>tag.Theparagraphelementconsistsoftheacceptedelement-type
namewithinthestartingtag(<p>),interveningcontent,andtheendingparagraph
tag(</p>).The<p>tagisthestartingtagfortheparagraphelement,andits
contents,knownasattributes,ultimatelyaffecttheparagraphelementtype's
contents.
Althoughtheseareimportantdistinctions,we'repragmatists.Itisthemarkuptag
thatauthorsapplyintheirdocumentsandthataffectsanyinterveningcontent.
Accordingly,throughoutthebook,werelaxthedistinctionbetweenelementtypes
andtags,oftentalkingabouttagsandallrelatedcontentsandnotnecessarily
usingthetermelement-typewhenitwouldbetechnicallyappropriatetomakethe
distinction.Forgiveusthetransgression,butwedosoforthesakeofclarity.
HTMLVersusXHTML
It'snotLatin,butHTMLhasreachedoldageinstandardversion4.01.TheW3C
hasnoplanstodevelopanotherversionandhasofficiallysaidso.Rather,HTMLis
beingsubsumedandmodularizedasanExtensibleMarkupLanguage(XML).Its
newnameisXHTML,ExtensibleHyptertextMarkupLanguage.
TheemergenceofXHTMLisjustanotherchapterintheoftentumultuoushistory
ofHTMLandtheWeb,whereconfusionforauthorsisthenorm,nottheexception.
Atitsnadir,theeldersoftheW3Cresponsibleforacceptedandacceptableusesof
thelanguagestandardslostcontrolofthelanguageinthebrowser"wars"between
NetscapeandMicrosoft.TheabortiveHTML+standardnevergotofftheground,
andHTML3.0becamesoboggeddownindebatethattheW3Csimplyshelvedthe
entiredraft.HTML3.0neverhappened,despitewhatsomeopportunistic
marketersclaimedintheirliterature.Instead,bylate1996,thebrowser
manufacturersconvincedtheW3CtoreleaseHTMLstandardversion3.2,which
forallintentsandpurposessimplystandardizedmostofNetscape'sHTML
extensions.
Netscape'sdominanceastheleadingbrowser,andasaleaderinweb
technologies,fadeddramaticallytowardtheendofthemillennium.Bythen,
MicrosofthadeffectivelybundledInternetExplorerintotheWindowsoperating
system,notonlyasaninstalledapplication,butalsoasadominantfeatureofthe
GUIdesktop.Inaddition,InternetExplorerintroducedseveralfeatures(albeit
nonstandardatthetime)thatappealedprincipallytothegrowingInternet
businessandmarketingcommunity.
Fortunatelyforthoseofuswhoappreciateandstronglysupportstandards,the
W3CtookbackitsprimacyrolewithHTML4.0,whichstandstodayasHTML
version4.01,releasedinDecember1999.AbsorbingmanyoftheNetscapeand
InternetExplorerinnovations,thestandardisclearerandcleanerthanany
previousones,establishessolidimplementationmodelsforconsistencyacross
browsersandplatforms,providesstrongsupportandincentivesforthecompanion
CascadingStyleSheets(CSS)standardforHTML-baseddisplays,andmakes
provisionsforalternative(nonvisual)useragents,aswellasformoreuniversal
languagesupports.
Cleanerandcleareraside,theW3CrealizedthatHTMLcouldneverkeepupwith
thedemandsofthewebcommunityformorewaystodistribute,process,and
displaydocuments.HTMLoffersonlyalimitedsetofdocument-creationprimitives
andishopelesslyincapableofhandlingnontraditionalcontentlikechemical
formulae,musicalnotation,andmathematicalexpressions.Norcanitwellsupport
alternativedisplaymedia,suchashandheldcomputersandintelligentcellular
phones.
Toaddressthesedemands,theW3CdevelopedtheXMLstandard.XMLprovidesa
waytocreatenew,standards-basedmarkuplanguagesthatdon'ttakeanactof
theW3Ctoimplement.XML-compliantlanguagesdeliverinformationthatcanbe
parsed,processed,displayed,sliced,anddicedbythemanydifferent
communicationtechnologiesthathaveemergedsincetheWebsparkedthedigital
communicationrevolutionadecadeago.XHTMLisHTMLreformulatedtoadhere
totheXMLstandard.ItisthefoundationlanguageforthefutureoftheWeb.
WhynotjustdropHTMLforXHTML?Formanyreasons.Firstandforemost,XHTML
hasnotexactlytakentheWebbystorm.There'sjusttoomuchcurrent
investmentinHTML-baseddocumentationandexpertiseforthattohappen
anytimesoon.Besides,XHTMLisHTML4.01reformulatedasanapplicationof
XML.KnowHTML4andyou'reallreadyforthefuture.[*]
[*]WeplumbthedepthsofXMLandXHTMLinChapters15and16.
DeprecatedFeatures
Oneoftheunpopularthingsstandardsbearershavetodoismakechoices
betweenpopularandproper.TheauthorsoftheHTMLandXHTMLstandards
exercisethatresponsibilityby"deprecating"thosefeaturesofthelanguagethat
interfereinthegrandschemeofthings.
Forinstance,the<center>tagtellsthebrowsertodisplaytheenclosedtext
centeredinthedisplaywindow.ButtheCSSstandardprovideswaystocenter
text,too.TheW3CchoosestosupporttheCSSwayanddiscouragestheuseof
<center>bydeprecatingthetag.Theplanis,insomelaterstandardversion,to
stopusing<center>andotherdeprecatedelementsandattributesofthelanguage.
Throughoutthebook,wespeciallynoteandcontinuouslyremindyouwhenan
HTMLtagorothercomponentisdeprecatedinthecurrentstandards.Shouldyou
stopusingthemnow?Yesandno.
Yes,becausethereisapreferredandperhapsbetterwaytoaccomplishthesame
thing.Byexercisingthatalternative,youensurethatyourdocumentswillsurvive
formanyyearstocomeontheWeb.And,yes,becausethetoolsyoumayuseto
prepareHTML/XHTMLdocumentsprobablyadheretothepreferredstandard.You
maynothaveachoice,unlessyoudisableyourtools.Inanyevent,unlessyou
hand-composeallyourdocuments,you'llneedtoknowhowthepreferredway
workssothatyoucanidentifythecodeandmodifyit.
Howevercompellingthereasonsfornotusingdeprecatedelementsandattributes
are,theystillarepartofthestandards.Theyremainwellsupportedbymost
browsersandaren'texpectedtodisappearanytimesoon.Infact,sincethereisno
plantochangetheHTMLstandard,the"deprecated"stampisverymisleading.
So,no,youdon'thavetoworryaboutdeprecatedHTMLfeatures.Thereisno
reasontopanic,certainly.Wedo,however,encourageyoutomakeamove
towardthestandardssoon.
ADefinitiveGuide
TheparadoxinallthisisthateventheHTML4.01standardisnotthedefinitive
resource.TherearemanymorefeaturesofHTMLinpopularuseandsupportedby
thepopularbrowsersthanareincludedinthelatestlanguagestandard.Andthere
aremanypartsofthestandardsthatareignored.Wepromiseyou,thingscanget
downrightconfusing.
We'vemanagedtosortthingsoutforyou,though,soyoudon'thavetosweat
overwhatworksanddoesn'tworkwithwhatbrowser.Thisbook,therefore,isthe
definitiveguidetoHTMLandXHTML.Wegivedetailsforalltheelementsofthe
HTML4.01andXHTML1.0standards,plusthevarietyofinterestinganduseful
extensionstothelanguage.WealsoincludedetaileddiscussionsoftheCSS
standard,sinceitissointricatelyrelatedtowebpagedevelopment.
Inaddition,thereareafewthingsthatarecloselyrelatedbutnotdirectlypartof
HTML.Forexample,wetouch,butdonothandle,JavaScript,CommonGateway
Interface(CGI),andJavaprogramming.TheyallworkcloselywithHTML
documentsandrunwithoralongsidebrowsers,buttheyarenotpartofthe
languageitself,sowedon'tdelveintothem.Besides,theyarecomprehensive
topicsthatdeservetheirownbooks,suchasJavaScript:TheDefinitiveGuide,by
DavidFlanagan;CGIProgrammingwithPerl,byScottGuelich,Shishir
Gundavaram,andGuntherBirzneiks;CascadingStyleSheets:TheDefinitive
Guide,byEricMeyer;andLearningJava,byPatNiemeyerandJonathanKnudsen
(allpublishedbyO'Reilly).
ThisisyourdefinitiveguidetoHTMLandXHTMLastheyareandshouldbeused,
includingeveryextensionwecouldfind.Someextensionsaren'tdocumented
anywhere,evenintheplethoraofonlineguides.But,ifwe'vemissedanything,
certainlyletusknowandwe'llputitinthenextedition.
UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,youmayusethecode
inthisbookinyourprogramsanddocumentation.Youdonotneedtocontactus
forpermissionunlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcodefromthisbookdoes
notrequirepermission.SellingordistributingaCD-ROMofexamplesfrom
O'Reillybooksdoesrequirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.Incorporatingasignificant
amountofexamplecodefromthisbookintoyourproduct'sdocumentationdoes
requirepermission.
Weappreciate,butdonotrequire,attribution.Anattributionusuallyincludesthe
title,author,publisher,andISBN.Forexample:"HTML&XHTML:TheDefinitive
Guide,SixthEdition,byChuckMuscianoandBillKennedy.Copyright2007
O'ReillyMedia,Inc.,978-0-596-52732-7."
Safari®Enabled
WhenyouseeaSafari®Enabledicononthecoverofyourfavorite
technologybook,thatmeansthebookisavailableonlinethroughtheO'Reilly
NetworkSafariBookshelf.
Safarioffersasolutionthat'sbetterthane-books.It'savirtuallibrarythatlets
youeasilysearchthousandsoftoptechbooks,cutandpastecodesamples,
downloadchapters,andfindquickanswerswhenyouneedthemostaccurate,
currentinformation.Tryitforfreeathttp://safari.oreilly.com.
CommentsandQuestions
Pleaseaddresscommentsandquestionsconcerningthisbooktothepublisher:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
800-998-9938(intheUnitedStatesorCanada)
707-829-0515(international/local)
707-829-0104(fax)
Thereisawebpageforthisbook,whichlistsanyerrata,examples,oradditional
information.Youcanaccessthispageat:
http://www.oreilly.com/catalog/html6
Tocommentorasktechnicalquestionsaboutthisbook,sendemailto:
bookquestions@oreilly.com
Formoreinformationaboutbooks,conferences,ResourceCenters,andthe
O'ReillyNetwork,seetheO'Reillywebsiteat:
http://www.oreilly.com
Acknowledgments
Wedidnotcompose,andcertainlycouldnothavecomposed,thisoranyother
editionofthebookwithoutgenerouscontributionsfrommanypeople.Ourwives,
JeanneandCindy,andourchildren,Eva,Ethan,Courtney,andCole(they
happenedbeforewestartedwriting),formedthefrontlinesofsupport.Andthere
arenumerousneighbors,friends,andcolleagueswhohelpedbysharingideas,
testingbrowsers,andlettingususetheirequipmenttoexploreHTML.Youknow
whoyouare,andwethankyouall.
Inaddition,wethankourtechnicalreviewers,ChatClussman,PatrickKrekelberg,
SamMarshall,andShlomiFish,forcarefullyscrutinizingourwork.Wetookmost
ofyourkeensuggestions.WeespeciallythankourO'Reillyeditors,especiallyMike
LoukidesandTatianaApandi,fortheirpatienceinkeepingustwomavericks
corralled.AndspecialthankstoTatianaforbringingthissixtheditiontofruition.
Chapter1.HTML,XHTML,andtheWorldWideWeb
Thoughitbeganasamilitaryexperimentandspentitsadolescenceasasandbox
foracademicsandeccentrics,inlessthanadecadejustbeforethenew
millennium,theworldwidenetworkofcomputernetworks(a.k.a.theInternet)
maturedintoahighlydiversified,financiallyimportantcommunityofcomputer
usersandinformationvendors.Fromtheboardroomtoyourlivingroom,youcan
bumpintoInternetusersofnearlyanyandallnationalities,ofanyandall
persuasions,fromserioustofrivolousindividuals,frombusinessestononprofit
organizations,andfromborn-againChristianevangeliststopornographers.
Inmanyways,theWebtheopencommunityofhypertext-enableddocument
serversandreadersontheInternetisresponsibleforthemeteoricriseinthe
network'spopularity.You,too,canbecomeavaluedmemberbycontributing:
writingHTMLandXHTMLdocumentsandthenmakingthemavailabletoweb
surfersworldwide.
Let'sclimbuptheInternetfamilytreetogainsomedeeperinsightintoits
magnificence,notonlyasanexerciseofcuriosity,butalsotohelpusbetter
understandjustwhoandwhatwearedealingwithwhenwegoonline.
1.1.TheInternet
Althoughpopularmediaaccountsareoftenconfusedandconfusing,theconceptof
theInternetreallyisrathersimple:it'saworldwidecollectionofcomputer
networksanetworkofnetworkssharingdigitalinformationviaacommonsetof
networkingandsoftwareprotocols.
Networksarenotnewtocomputers.WhatmakestheInternetuniqueisits
worldwidecollectionofdigitaltelecommunicationlinksthatshareacommonsetof
computer-networktechnologies,protocols,andapplications.Whetheryourun
MicrosoftWindowsXP,Linux,MacOS,oreventhenowancientWindows3.1,
whenconnectedtotheInternet,allcomputersspeakthesamenetworking
languageandusefunctionallyidenticalprograms,soyoucanexchange
informationevenmultimediapicturesandsoundwithsomeonenextdoororacross
theplanet.
Thecommonandnowquitefamiliarprogramspeopleusetocommunicateand
distributetheirworkovertheInternethavealsofoundtheirwayintoprivateand
semiprivatenetworks.Theseso-calledintranetsandextranetsusethesame
software,applications,andnetworkingprotocolsastheInternet.Butunlikethe
Internet,intranetsareprivatenetworks,withaccessrestrictedtomembersofthe
institution.Likewise,extranetsrestrictaccessbutusetheInternettoprovide
servicestomembers.
TheInternet,ontheotherhand,seeminglyhasnorestrictions.Anyonewitha
computerandtherightnetworkingsoftwareandconnectioncan"getontheNet"
andbeginexchangingwords,sounds,andpictureswithothersaroundtheworld,
dayornight:nomembershiprequired.Andthat'spreciselywhatisconfusing
abouttheInternet.
Likeanorientalbazaar,theInternetisnotwellorganized,therearefewcontent
guides,anditcantakealotoftimeandtechnicalexpertisetotapitsfull
potential.That'sbecause....
1.1.1.IntheBeginning
TheInternetbeganinthelate1960sasanexperimentinthedesignofrobust
computernetworks.Thegoalwastoconstructanetworkofcomputersthatcould
withstandthelossofseveralmachineswithoutcompromisingtheabilityofthe
remainingonestocommunicate.FundingcamefromtheU.S.Departmentof
Defense,whichhadavestedinterestinbuildinginformationnetworksthatcould
withstandnuclearattack.
Theresultingnetworkwasamarveloustechnicalsuccess,butitwaslimitedin
sizeandscope.Forthemostpart,onlydefensecontractorsandacademic
institutionscouldgainaccesstowhatwasthenknownastheARPAnet(Advanced
ResearchProjectsAgencyNetworkoftheDepartmentofDefense).
Withtheadventofhigh-speedmodemsfordigitalcommunicationovercommon
phonelines,someindividualsandorganizationsnotdirectlytiedtothemain
digitalpipelinesbeganconnectingtoandtakingadvantageofthenetwork's
advancedandglobalcommunications.Nonetheless,itwasn'tuntilaround1993
thattheInternetreallytookoff.
SeveralcrucialeventsledtothemeteoricriseinpopularityoftheInternet.First,
intheearly1990s,businessesandindividualseagertotakeadvantageofthe
easeandpowerofglobaldigitalcommunicationsfinallypressuredthelargest
computernetworksonthemostlyU.S.government-fundedInternettoopentheir
systemsfornearlyunrestrictedtraffic.(Thenetworkwasn'tdesignedtoroute
informationbasedoncontent,meaningthatcommercialmessageswentthrough
universitycomputersthatatthetimeforbadesuchactivity.)
Truetotheiracademictraditionsoffreeexchangeandsharing,manyofthe
originalInternetmemberscontinuedtomakesubstantialportionsoftheir
electroniccollectionsofdocumentsandsoftwareavailabletothenewcomersfree
forthetaking!Globalcommunications,awealthoffreesoftwareandinformation:
whocouldresist?
Well,frankly,theInternetwasatoughrowtohoebackthen.Gettingconnected
andusingthevarioussoftwaretools,iftheywereevenavailablefortheir
computers,presentedaninsurmountabletechnologybarrierformostpeople.And
mostavailableinformationwasplain-vanillatextaboutacademicsubjects,notthe
neatlypackagedfarethatattractsuserstoservicessuchasAmericaOnline.The
Internetwasjusttoodisorganized,and,outsideofthegovernmentandacademia,
fewpeoplehadtheknowledgeorinteresttolearnhowtousethearcanesoftware
orthetimetospendrummagingthroughdocumentslookingforonesofinterest.
1.1.2.HTMLandtheWeb
IttookanothersparktolighttheInternetrocket.Ataboutthesametimethe
Internetopenedupforbusiness,somephysicistsatCERN,theEuropeanParticle
PhysicsLaboratory,releasedanauthoringlanguageanddistributionsystemthey
developedforcreatingandsharingmultimedia-enabled,integratedelectronic
documentsovertheInternet.AndsowasbornHypertextMarkupLanguage
(HTML),browsersoftware,andtheWeb.Nolongerdidauthorshavetodistribute
theirworkasfragmentedcollectionsofpictures,sounds,andtext.HTMLunified
thoseelements.Moreover,theWeb'ssystemsenabledhypertextlinking,whereby
documentsautomaticallyreferenceotherdocumentslocatedanywherearoundthe
world:lessrummaging,moreproductivetimeonline.
Lift-offhappenedwhensomebrightstudentsandfacultyattheNationalCenter
forSupercomputingApplications(NCSA)attheUniversityofIllinois,Urbana-
ChampaignwroteawebbrowsercalledMosaic.Althoughdesignedprimarilyfor
viewingHTMLdocuments,thesoftwarealsohadbuilt-intoolstoaccessthemuch
moreprolificresourcesontheInternet,suchasFTParchivesofsoftwareand
Gopher-organizedcollectionsofdocuments.
Withversionsbasedoneasy-to-useGUIsfamiliartomostcomputerowners,
Mosaicbecameaninstantsuccess.It,likemostInternetsoftware,wasavailable
ontheNetforfree.Millionsofuserssnatchedupcopiesandbegansurfingthe
Internetfor"coolwebpages."
1.1.3.GoldenThreads
Sincethoseearlydays,theWebhasspawnedanentirelynewmediumfor
worldwideinformationexchangeandcommerce.Forinstance,whenthe
marketeerscaughtontothefactthattheycouldcheaplyproduceanddelivereye-
catching,wow-and-whiz-bangcommercialsandproductcatalogstothosemillions
ofwebsurfersaroundtheworld,therewasnostoppingthestampedeofblue
suedeshoes.EventhekeydevelopersofMosaicandrelatedwebserver
technologiessensedpotentialriches.TheyleftNCSAandmadetheirfortuneswith
NetscapeCommunicationsbyproducingcommercialwebbrowsersandserver
software.Thatwasuntilthesleepinggiant,Microsoft,awoke.Butthat'sanother
story....
BusinessusersandmarketingopportunitieshavehelpedinvigoratetheInternet
andfuelitsphenomenalgrowth.Internet-basedcommercehasbecomeVeryBig
Business,exceeding$150billionannuallyby2005.Traditionalbricks-and-mortar
businesseshaveeitheropenedweb-basedcommercialsitesorfaceextinction.
Forsome,particularlyweInternetold-timers,businessandmarketinghavealso
trashedthemedium.Inmanyways,theWebhasbecomeavaststripmallandan
annoyingadvertisingmedium.Believeitornot,onceuponatime,Internetusers
actuallyfollowedcommonlyheld(butnotformallycodified)rulesofnetiquette
thatprohibitedsuchthingsasspamemail.
Nonetheless,thepowerofHTMLandnetworkdistributionofinformationgoeswell
beyondmarketingandmonetaryrewards:seriousinformationalpursuitsalso
benefit.Publicationscompletewithimagesandothermediasuchasexecutable
softwarecangettotheirintendedaudiencesintheblinkofaneye,insteadofthe
monthstraditionallyrequiredforprintingandmaildelivery.Educationtakesa
greatleapforwardwhenstudentsgainaccesstothegreatlibrariesoftheworld.
Andattimesofleisure,theinteractivecapabilitiesofHTMLlinkscanreinvigorate
ourotherwisetelevision-numbedminds.
1.2.TalkingtheInternetTalk
EverycomputerconnectedtotheInternet(evenabeat-upoldAppleII)hasa
uniqueaddress:anumberwhoseformatisdefinedbytheInternetProtocol(IP),
thestandardthatdefineshowmessagesarepassedfromonemachinetoanother
ontheNet.AnIPaddressismadeupoffournumbers,eachlessthan256,joined
togetherbyperiods,suchas192.12.248.73and131.58.97.254.
Whilecomputersdealonlywithnumbers,peopleprefernames.Forthisreason,
mostcomputersalsohavenamesbestoweduponthem.Bycurrentestimates,
therearehundredsofmillions,ifnotbillions,ofdevicesontheNet,soitwouldbe
verydifficulttocomeupwiththatmanyuniquenames,letalonekeeptrackof
themall.Instead,theInternetisanetworkofnetworks,andisdividedinto
groupsknownasdomains,whicharefurtherdividedintooneormore
subdomains.So,whileyoumightchooseaverycommonnameforyourcomputer,
itbecomesuniquewhenyouappend,likesurnames,allofthemachine'sdomain
namesasaperiod-separatedsuffix,creatingafullyqualifieddomainname.
Thisnamingstuffiseasierthanitsounds.Forexample,thefullyqualifieddomain
namewww.oreilly.comtranslatestoamachinenamed"www"that'spartofthe
domainknownas"oreilly,"which,inturn,ispartofthecommercial(com)branch
oftheInternet.OtherbranchesoftheInternetincludeeducationalinstitutions
(edu),nonprofitorganizations(org),theU.S.government(gov),andInternet
serviceproviders(net).ComputersandnetworksoutsidetheUnitedStatesmay
havetwo-letterabbreviationsattheendoftheirnames:forexample,"ca"for
Canada,"jp"forJapan,and"uk"fortheUnitedKingdom.
Specialcomputers,knownasnameservers,keeptablesofmachinenamesand
associatedIPaddressesandtranslateoneintotheotherforusandforour
machines.Domainnamesmustberegisteredandpaidforthroughanyoneofthe
nowmanyfor-profitregistrars.[*]Onceauniquedomainnameisregistered,its
ownermakesitanditsaddressavailabletootherdomainnameserversaroundthe
world.
[*]Atonetime,asinglenonprofitorganizationknownasInterNIChandledthatfunction.NowICANN.orgcoordinatesU.S.
government-relatednameservers,butotherorganizationsorindividualsmustworkthroughafor-profitcompanyto
registertheiruniquedomainnames.
1.2.1.Clients,Servers,andBrowsers
TheInternetconnectstwokindsofcomputers:servers,whichserveup
documents,andclients,whichretrieveanddisplaydocumentsforushumans.
Thingsthathappenontheservermachinearesaidtobeontheserverside,and
activitiesontheclientmachineoccurontheclientside.
ToaccessanddisplayHTMLdocuments,werunprogramscalledbrowsersonour
clientcomputers.Thesebrowserclientstalktospecialwebserversoverthe
Internettoaccess,retrieve,anddisplayelectronicdocuments.
Avarietyofbrowsersareavailabletoday.InternetExplorercomeswithMicrosoft's
operatingsystemsoftware,forexample,whilemostotherbrowsersarefreefor
downloadontheWeb.Andmostbrowsersrunonclientdevicesthathavehigh-
resolution,high-colorgraphicalviewingscreens.Infact,today'sbrowsersshare
commonHTML-renderingsoftwareunderthehood,sotospeak,anddifferonlyby
extraneous,albeitsomeveryusefulfeatures.Forinstance,whenyouinstall
NetscapeNavigatorversion8,youdecidewhethertousetheNCSAMosaic
renderingsoftware,portionsofwhichalsoareunderMicrosoft'sInternetExplorer,
orMozilla'ssoftware,whichcomesunderthehoodofanotherpopularbrowser,
Firefox.
Thisisverydifferentfromaroundtheturnofthecentury,whenInternetExplorer
savagelycompetedwithNetscapeNavigatorthroughuniqueextensionstothe
HTMLlanguage.InternetExplorerwon.ManyofitsextensionsevenbecameHTML
standards,andotherssuchasNetscape'slayoutextensionsdisappearedandso
gotrelegatedtoappendicesinthisbook.
1.2.2.TheFlowofInformation
Allwebactivitybeginsontheclientside,whenauserstartshisbrowser.The
browserbeginsbyloadingahomepagedocument,eitherfromlocalstorageor
fromaserveroversomenetwork,suchastheInternet,acorporateintranet,ora
townextranet.Whenstartinguponthenetwork,theclientbrowserfirstconsults
adomainnamesystem(DNS)servertotranslatethehomepageserver'sname,
suchaswww.oreilly.com,intoanIPaddress,beforesendingarequesttothat
serverovertheInternet.Thisrequest(andtheserver'sreply)isformatted
accordingtothedictatesoftheHypertextTransferProtocol(HTTP)standard.
Aserverspendsmostofitstimelisteningtothenetwork,waitingfordocument
requestswiththeserver'suniqueaddressstampedonthem.Uponreceiptofa
request,theserververifiesthattherequestingbrowserisallowedtoretrieve
documentsfromtheserverand,ifso,checksfortherequesteddocument.Ifit
findsthedocument,theserversendsittothebrowser.Theserverusuallylogsthe
request,typicallyincludingtheclientcomputer'sIPaddress,thedocument
requested,andthetime.Theservermightalsoissuespecialattachmentsknown
ascookiesthatcontainadditionalinformationabouttherequestingbrowserand
itsowner.
Backonthebrowser,thedocumentarrives.Ifit'saplain-vanillatextfile,most
browsersdisplayitinacommon,plain-vanillaway.Documentdirectories,too,are
treatedlikeplaindocuments,whichmostgraphicalbrowsersdisplayasfolder
iconsthattheusermayselect,therebyrequestingtoviewthecontentsofthe
subdirectory.
Browserscanretrievemanydifferenttypesoffilesfromaserver.Unlessassisted
byahelperprogramorspeciallyenabledbyplug-insoftwareorapplets,which
displayanimageorvideofileorplayanaudiofile,thebrowserusuallystoresthe
filedirectlyonalocaldiskforlateruse.
Forthemostpart,however,thebrowserretrievesaspecialdocumentthat
appearstobeaplaintextfilebutthatcontainsbothtextandspecialmarkup
codescalledtags.ThebrowserprocessestheseHTMLorXHTMLdocuments,
formattingthetextbasedonthetagsanddownloadingspecialaccessoryfiles,
suchasimages.
Theuserreadsthedocument,selectsahyperlinktoanotherdocument,andthe
entireprocessstartsover.
1.2.3.BeneaththeWeb
WeshouldpointoutagainthatbrowsersandHTTPserversneednotbepartofthe
Webtofunction.Infact,youneverneedtobeconnectedtotheInternetortoany
network,forthatmatter,towriteHTML/XHTMLdocumentsandoperateabrowser.
Youcanloadanddisplaylocallystoreddocumentsandaccessoryfilesdirectlyon
yourbrowser.Manyorganizationstakeadvantageofthiscapabilitybydistributing
catalogsandproductmanuals,forinstance,onamuchlessexpensive,butmuch
moreinteractivelyuseful,CD-ROM,ratherthanviatraditionalprintonpaper.
Manygraphical-userapplicationsevendocumenttheirfeaturesthrough
HTML/XHTML-basedHelpmenus.
Isolatingwebdocumentsisgoodfortheauthor,too,sinceitgivesyouthe
opportunitytofinish,intheeditorialsenseoftheword,adocumentcollectionfor
laterdistribution.Diligentauthorsworklocallytowriteandprooftheirdocuments
beforereleasingthemforgeneraldistribution,therebysparingreadersthe
agoniesofbrokenimagefilesandbogushyperlinks.[*]
[*]VigoroustestingofHTMLdocumentsoncetheyaremadeavailableontheWebis,ofcourse,alsohighly
recommendedandnecessarytoridthemofvariouslinkingbugs.
Organizations,too,canbeconnectedtotheInternetbutalsomaintainprivate
websitesanddocumentcollectionsfordistributiontoclientsontheirlocal
networks,orintranets.Infact,privatewebsitesarefastbecomingthetechnology
ofchoiceforthepaperlessofficeswe'veheardsomuchaboutduringtheselast
fewyears.WithHTMLandXHTMLdocumentcollections,businessescanmaintain
personneldatabasescompletewithemployeephotographsandonlinehandbooks,
collectionsofblueprints,parts,assemblymanuals,andsoonallreadilyandeasily
accessedelectronicallybyauthorizedusersanddisplayedonalocalcomputer.
1.2.4.StandardsOrganizations
Likemanypopulartechnologies,HTMLstartedoutasaninformalspecification
usedbyonlyafewpeople.Asmoreandmoreauthorsbegantousethelanguage,
itbecameobviousthatmoreformalmeanswereneededtodefineandmanagei.e.,
tostandardizethelanguage'sfeatures,makingiteasierforeveryonetocreateand
sharedocuments.
1.2.4.1.TheWorldWideWebConsortium
TheWorldWideWebConsortium(W3C)wasformedwiththechartertodefinethe
standardsforHTMLand,later,XHTML.Membersareresponsiblefordrafting,
circulatingforreview,andmodifyingthestandardbasedoncross-Internet
feedbacktobestmeettheneedsofmany.
BeyondHTMLandXHTML,theW3Chasthebroaderresponsibilityofstandardizing
anytechnologyrelatedtotheWeb;theymanagetheHTTP,CascadingStyleSheet
(CSS),andExtensibleMarkupLanguage(XML)standards,aswellasrelated
standardsfordocumentaddressingontheWeb.Theyalsosolicitdraftstandards
forextensionstoexistingwebtechnologies.
IfyouwanttotrackHTML,XML,XHTML,CSS,andotherexcitingweb
developmentandrelatedtechnologies,contacttheW3Cathttp://www.w3.org.
Also,severalInternetnewsgroupsaredevotedtotheWeb,eachapartofthe
comp.infosystems.wwwhierarchy.Theseinclude
comp.infosystems.www.authoring.htmland
comp.infosystems.www.authoring.images.
1.2.4.2.TheInternetEngineeringTaskForce
EvenbroaderinreachthanW3C,theInternetEngineeringTaskForce(IETF)is
responsiblefordefiningandmanagingeveryaspectofInternettechnology.The
WebisjustonesmallareaunderthepurviewoftheIETF.
TheIETFdefinesallofthetechnologyoftheInternetviaofficialdocuments
knownasRequestsforComments,orRFCs.Individuallynumberedforeasy
reference,eachRFCaddressesaspecificInternettechnologyeverythingfromthe
syntaxofdomainnamesandtheallocationofIPaddressestotheformatof
electronicmailmessages.
TolearnmoreabouttheIETFandfollowtheprogressofvariousRFCsastheyare
circulatedforreviewandrevision,visittheIETFhomepage,http://www.ietf.org.
1.3.HTMLandXHTML:WhatTheyAre
HTMLandXHTMLdefinethesyntaxandplacementofspecial,embeddeddirections
thataren'tdisplayedbythebrowserbutadviseithowtodisplaythecontentsof
thedocument,includingtext,images,andothersupportmedia.Thelanguages
alsomakeadocumentinteractivethroughspecialhypertextlinks,whichconnect
yourdocumentwithotherdocumentsoneitheryourcomputerorsomeoneelse'sas
wellaswithotherInternetresources.
You'vecertainlyheardofHTMLand,perhaps,XHTML,butdidyouknowthatthey
arejusttwoofmanyothermarkuplanguages?Indeed,HTMListheblacksheepin
thefamilyofdocumentmarkuplanguages.HTMLwasbasedonSGML,the
StandardGeneralizedMarkupLanguage.ThepowersthatbecreatedSGMLwith
theintentthatitwouldbetheoneandonlymarkupmetalanguagefromwhichall
otherdocumentmarkupelementswouldbecreated.Everythingfrom
hieroglyphicstoHTMLcanbedefinedusingSGML,negatinganyneedforany
othermarkuplanguage.
TheproblemwithSGMListhatitissobroadandall-encompassingthatmere
mortalscannotuseit.UsingSGMLeffectivelyrequiresveryexpensiveand
complextoolsthatarecompletelybeyondthescopeofregularpeoplewhojust
wanttobangoutanHTMLdocumentintheirsparetime.Asaresult,HTML
adherestosome,butnotall,SGMLstandards,[*]eliminatingmanyofthemore
esotericfeaturessothatitisreadilyuseableandused.
[*]TheHTMLDocumentTypeDefinition(DTD)inAppendixDusesasubsetofSGMLtodefinetheHTML4.01standard.
BesidesthefactthatSGMLisunwieldyandnotwellsuitedtodescribingthevery
popularHTMLinausefulway,therewasalsoagrowingneedtodefineother
HTML-likemarkuplanguagestohandledifferentnetworkdocuments.Accordingly,
theW3CdefinedXML.LikeSGML,XMLisaseparateformalmarkupmetalanguage
thatusesselectfeaturesofSGMLtodefinemarkuplanguages.Iteliminatesmany
featuresofSGMLthataren'tapplicabletolanguageslikeHTMLandsimplifies
otherSGMLelementsinordertomakethemeasiertouseandunderstand.
However,HTMLversion4.01isnotXMLcompliant.Hence,theW3CoffersXHTML,
areformulationofHTMLthatiscompliantwithXML.XHTMLattemptstosupport
everylastnitandfeatureofHTML4.01usingthemorerigidrulesofXML.It
generallysucceeds,butithasenoughdifferencestomakelifedifficultforthe
standards-consciousHTMLauthor.
1.4.HTMLandXHTML:WhatTheyAren't
Despitealltheirnew,multimedia-enablingpage-layoutfeatures,andthehot
technologiesthatgivelifetoHTML/XHTMLdocumentsovertheInternet,itisalso
importanttounderstandthelanguages'limitations.Theyarenotwordprocessing
tools,desktoppublishingsolutions,orevenprogramminglanguages.Their
fundamentalpurposeistodefinethestructureofdocumentsanddocument
familiessothattheymaybedeliveredquicklyandeasilytoauseroveranetwork
forrenderingonavarietyofdisplaydevices;jacks-of-all-tradesbutmastersof
none,sotospeak.
1.4.1.ContentVersusAppearance
HTMLanditsprogeny,XHTML,providemanydifferentwaystoletyoudefinethe
appearanceofyourdocuments,buttheirfocusisonstructure,notappearance.Of
course,appearanceisimportant,sinceitcanhaveeitherdetrimentalorbeneficial
effectsonhowusersaccessandusetheinformationinyourdocuments.Andthat
iswhythecompanionCSSstandardisimportant.
Nonetheless,webelievethatcontentisparamount;appearanceissecondary,
particularlysinceitislesspredictable,giventhevarietyofbrowsergraphicsand
text-formattingcapabilities.Infact,HTMLandXHTMLcontainmanywaysfor
structuringyourdocumentcontentwithoutregardtothefinalappearance:
sectionheaders,structuredlists,paragraphs,rules,titles,andembeddedimages
aredefinedbythestandardlanguageswithoutregardforhowtheseelements
mightberenderedbyabrowser.Consider,forexample,abrowserfortheblind,
whereingraphicsonthepagecomewithaudiodescriptionsandalternativerules
fornavigation.TheHTML/XHTMLstandardsdefinesuchathing:contentover
visualpresentation.
IfyoutreatHTMLorXHTMLasadocument-formattingtool,youwillbesorely
disappointed.Thereissimplynotenoughcapabilitybuiltintothelanguagesto
allowyoutocreatethekindsofdocumentsyoumightwhipupwithtoolssuchas
FrameMakerandWord.Attemptstosubvertthesuppliedstructuringelementsto
achievespecificformattingtricksseldomworkacrossallbrowsers.Inshort,don't
wasteyourtimetryingtoforceHTMLandXHTMLtodothingstheywerenever
designedtodo.
Instead,useHTMLandXHTMLinthemannerforwhichtheyweredesigned:
indicatingthestructureofadocumentsothatthebrowsercanthenrenderits
contentappropriately.HTMLandXHTMLarerifewithtagsthatletyouindicatethe
semanticsofyourdocumentcontent,somethingthatismissingfromoroften
badlyimplementedinwordprocessorsandpage-layoutprograms.Createyour
documentsusingthesetagsandyou'llbehappier,yourdocumentswilllookand
workbetter,andyourreaderswillbenefitimmensely.
1.5.StandardsandExtensions
ThebasicsyntaxandsemanticsofHTMLaredefinedintheHTMLstandard,nowin
itsfinalversion,4.01.HTMLmaturedquickly,inbarelyadecade.Atonetime,a
newversionwouldappearbeforeyouhadachancetofinishreadinganearlier
editionofthisbook.Today,HTMLhasstoppedevolving.AsfarastheW3Cis
concerned,XHTMLhastakenover.Nowthewaitisforbrowsermanufacturersto
implementthestandards.
TheXHTMLstandardcurrentlyisversion1.0.Fortunately,XHTMLversion1.0is,
forthemostpart,areconstitutionofHTMLversion4.01.Therearesome
differences,whichweexploreinChapter16.Thepopularbrowserscontinueto
supportHTMLdocuments,sothereisnocausetostampedetoXHTML.Do,
however,startwalkinginthatdirection:anewerXHTMLversion,2.0,isunder
considerationattheW3C,andbrowserdevelopersareslowlybutsurelydropping
nonstandardHTMLfeaturesfromtheirproducts.
Obviously,browserdevelopersrelyuponstandardsandacceptedconventionsto
havetheirsoftwareproperlyformatanddisplaycommonHTMLandXHTML
documents.Authorsusethestandardstomakesuretheyarewritingeffective,
correctdocumentsthatgetdisplayedproperlybythebrowsers.
However,standardsarenotalwaysexplicit;manufacturershavesomeleewayin
howtheirbrowsersmightdisplayanelement.Andtocomplicatematters,
commercialforceshavepusheddeveloperstoaddintotheirbrowsersnonstandard
extensionsmeanttoimprovethelanguage.
Confused?Don'tbe:inthisbook,weexploreindetailthesyntax,semantics,and
idiomsoftheHTMLversion4.01andXHTMLversion1.0languages,alongwiththe
manyimportantextensionsthataresupportedinthelatestversionsofthemost
popularbrowsers.
1.5.1.NonstandardExtensions
Itdoesn'ttakeanadvanceddegreeinTheObvioustoknowthatdistinctiondraws
attention;so,too,withbrowsers.Extrawhiz-bangfeaturescangivetheedgein
theotherwisestandardizedbrowsermarket.Thatcanbeanightmareforauthors.
Alotofpeoplewantyoutousethelatestandgreatestgimmickorevenuseful
HTML/XHTMLextension.Butit'snotpartofthestandard,andnotallbrowsers
supportit.Infact,onoccasion,thepopularbrowserssupportdifferentwaysof
doingthesamething.
1.5.2.Extensions:ProandCon
Everysoftwarevendoradhereslargelytothetechnologicalstandards.It's
embarrassingtobeincompatible,andyourcompetitorswilltakeevery
opportunitytoremindbuyersofyourproduct'sfailuretocomply,nomatterhow
arcaneoruselessthatstandardmightbe.Atthesametime,vendorsseekto
maketheirproductsdifferentfromandbetterthanthecompetition'sofferings.
Netscape'sandInternetExplorer'sextensionstostandardHTMLareperfect
examplesofthesemarketpressures.
Manydocumentauthorsfeelsafeusingtheseextendedbrowsers'nonstandard
extensionsbecauseoftheircombinedandcommandingshareofusers.Forbetter
orworse,extensionstoHTMLinprominentbrowsersbecomepartofthestreet
versionofthelanguage,muchlikeEnglishslangcreepingintothevocabularyof
mostFrenchmen,despitethebesteffortsoftheAcadémieFrançaise.
Fortunately,withHTMLversion4.0,theW3Cstandardscaughtupwiththe
browsermanufacturers.Infact,thetablesturnedsomewhat.Themany
extensionstoHTMLthatoriginallyappearedasextensionsinNetscapeNavigator
andMicrosoftInternetExplorerarenowpartoftheHTML4andXHTML1
standards,andthereareotherpartsofthenewstandardwhicharenotyet
featuresofthepopularbrowsers.
1.5.3.AvoidingExtensions
Ingeneral,weurgeyoutoresistusingextensionsunlessyouhaveacompelling
andoverridingreasontodoso.Byusingthem,particularlyinkeyportionsofyour
documents,youruntheriskoflosingasubstantialportionofyourpotential
readership.Tobefair,mostbrowserseschewextensions,sothepointismootnow.
Weadmitthatitisdisingenuousofustodecrytheuseofextensionswhile
presentingcompletedescriptionsoftheiruse.Inkeepingwiththegeneral
philosophyoftheInternet,we'llerronthesideofhandingoutropeandgunsto
allinterestedpartieswhilehopingyouhaveenoughsmartstokeepfromhanging
yourselforshootingyourselfinthefoot.
Ouradvicestillholds,though:useanextensiononlywhereitisnecessaryorvery
advantageous,anddosowiththeunderstandingthatyouaredisenfranchisinga
portionofyouraudience.Tothatend,youmightevenconsiderproviding
separate,standards-basedversionsofyourdocumentstoaccommodateusersof
otherbrowsers.
1.5.4.ExtensionsThroughModules
XHTMLversion1.1providesamechanismforextendingthelanguageina
standardway:XMLmodules.Infact,XHTML1.1iscomposedofmodulesitself.
XHTMLmodulesdividetheHTMLlanguageintodiscretedocumenttypes,each
definingfeaturesandfunctionsthatarepartsofthelanguage.Thereareseparate
modulesforXHTMLforms,text,scripting,tables,andsoonallthenondeprecated
elementsofXHTML1.0.
Theadvantageofmodulesisextensibility.Inadditiontousingthemarkup
featuresfromtheXHTMLmodulesnormallyincludedinthestandard,thenew
languageletsyoueasilyblendotherXMLmodulesintoyourdocuments,extending
theirfeaturesandcapabilitiesinastandardway.Forinstance,theW3Chas
definedaMathMLmodulethatprovidesexplicitmarkupelementsfor
mathematicalequationsthatyoucoulduseinyournextXHTML-basedmath
thesis.
Modules,letalonetheXHTMLversion1.1language,areexperimentalandarenot
wellsupportedbythepopularbrowsers.Accordingly,wedon'trecommendthat
youuseXHTMLmodulesjustyet.Fornow,thesubjectisbeyondthescopeofthis
book.ConsulttheW3Cwebsiteformoredetails.
1.6.ToolsfortheWebDesigner
WhileyoucanusethebarestofbarebonestexteditorstocreateHTMLandXHTML
documents,mostauthorshaveatoolboxofsoftwareutilitiesthatisabitmore
elaboratethanasimpletexteditor.Atthebarestminimum,youalsoneeda
browser,soyoucantestandrefineyourwork.Beyondtheessentialsaresome
specializedsoftwaretoolsfordevelopingandpreparingHTMLdocumentsand
accessorymultimediafiles.
1.6.1.Essentials
Attheveryleast,you'llneedatexteditor,abrowsertocheckyourwork,and,
ideally,aconnectiontotheInternet.
1.6.1.1.TextprocessororWYSIWYGeditor?
Someauthorsusethewordprocessingcapabilitiesoftheirspecialized
HTML/XHTMLeditingsoftware.SomeuseaWYSIWYG-like(what-you-see-is-what-
you-get,kindof)compositiontoolsuchasthosethatcomewiththelatest
versionsofthepopularwordprocessors.Others,suchasourselves,preferto
composetheirworkonacommontexteditorandlaterinsertthemarkuptagsand
theirattributes.Stillothersincludemarkupastheycompose.
Wethinkthestepwiseapproachcompose,thenmarkupisthebetterway.Wefind
thatoncewe'vedefinedandwrittenthedocument'scontent,it'smucheasierto
makeasecondpasstojudiciouslyandeffectivelyaddtheHTML/XHTMLtagsto
formatthetext.Otherwise,themarkupcanobscurethecontent.Note,too,that
unlessspeciallytrained(iftheycanbe),spellcheckersandthesaurusestypically
chokeonmarkuptagsandtheirvariousparameters.Youcanspendwhatseems
tobealifetimeclickingtheIgnorebuttononallthoseotherwisevalidmarkup
tagswhensyntax-orspellcheckingadocument.
Whenandhowyouembedmarkuptagsintoyourdocumentdictatesthetoolsyou
need.Werecommendthatyouuseagoodwordprocessor,whichcomeswithmore
andbetterwritingtoolsthansimpletexteditorsorthebrowser-basedmarkup-
languageeditors.You'llfind,forinstance,thatanoutliner,spellchecker,and
thesauruswillbesthelpyoucraftthedocument'sflowandcontent,disregarding
forthemomentitslook.Thelatestwordprocessorsencodeyourdocumentswith
HTML,too,butdon'texpectmiracles.Exceptforboilerplatedocuments,youwill
probablyneedtonursethoseautomatedHTMLdocumentstofullhealth.(Notto
mentionputthemonadietwhenyouseehowlongthegeneratedHTMLis.)And
it'llbeawhilebeforeyou'llseeXHTML-specificmarkuptoolsinthepopularword
processors.
Anotherwordofcautionaboutautomatedcompositiontools:theytypicallychange
orinsertcontent(e.g.,replacingrelativehyperlinkswithfullones)andarrange
yourdocumentinwaysthatwillannoyyou.Annoying,inparticular,becausethey
rarelygiveyoutheopportunitytodothingsyourownway.
BecomefluentinnativeHTML/XHTML.Bepreparedtoreversesomeofthethings
acompositiontoolwilldotoyourdocuments.Andmakesureyoucanwrestyour
documentawayfromthetoolsothatyoucanmakeitdoyourbidding.
1.6.1.2.Browsersoftware
Obviously,youshouldviewyournewlycomposeddocumentsandtesttheir
functionalitybeforeyoureleasethemforusebyothers.Forseriousauthors,
particularlythoselookingtopushtheirdocumentsbeyondtheHTML/XHTML
standards,werecommendthatyouhaveseveralbrowsers,perhapswithversions
runningondifferentcomputers,justtobesureone'sdelightfuldisplayisn't
another'snightmare.
Thecurrentlypopularandtherefore,mostimportantbrowsersareMicrosoft
InternetExplorer,MozillaFirefox,Safari(forApple),Opera,andNetscape
Navigator,thoughthelastisrapidlydisappearingfromtheWeblandscape.Most
versionsrunonthevarietyofpopularcomputingplatforms,suchasthevarious
MicrosoftOSes,Linux,MacOS,andsoforth.Differentbrowserversionsoften
varyintheelementsofHTMLandXHTMLthattheysupport.Wemakeeveryeffort
topointoutthosedifferencesthroughoutthisbook.Nevertheless,ithelpsto
downloadnotonlythelatestversionsfromtheirwebsites,butalsoprevious
browserversionsinordertobettertestyourworkforcompatibility.Thisis
particularlyimportantgiventhatseveralmillionsoftheestimatedmorethanone
billionWebusersworldwidestilloperatetheancientInternetExplorerversion5!
1.6.2.AnExtendedToolkit
Ifyou'reseriousaboutcreatingdocuments,you'llsoonfindthatallsortsofnifty
toolsareavailabletomakelifeeasier.Thelistoffreeware,shareware,and
commercialproductsgrowsdaily,soit'snotveryusefultoprovidealisthere.This
is,infact,anothergoodreasontofrequentthevariousnewsgroupsandwebsites
thatkeepupdatedlistsofHTMLandXHTMLresourcesontheWeb.Ifyouare
reallydedicatedtowritinginHTMLandXHTML,youwillvisitthosesites,andyou
willvisitthemregularlytokeepabreastofthelanguage,tools,andtrends.
Chapter2.QuickStart
Wedidn'tspendhoursstudiouslyporingoversomereferencebookbeforewe
wroteourfirstHTMLdocument.Youprobablyshouldn't,either.HTMLissimpleto
readandunderstand,andit'ssimpletowrite.Andonceyou'vewrittenanHTML
document,you'venearlycompletedyourfirstXHTMLone,too.Solet'sgetstarted
withoutfirstlearningalotofarcanerules.
Tohelpyougetthatquick,satisfyingstart,we'veincludedthischapterasabrief
summaryofthemanyelementsofHTMLanditsprogeny,XHTML.Ofcourse,we've
leftoutalotofdetailsandsometricksthatyoushouldknow.Readtheupcoming
chapterstogettheessentialsforbecomingfluentinHTMLandXHTML.
Evenifyouarefamiliarwiththelanguages,werecommendthatyouworkyour
waythroughthischapterbeforetacklingtherestofthebook.Itnotonlygives
youaworkinggraspofbasicHTML/XHTMLandtheirjargon,butyou'llalsobe
moreproductivelater,flushwiththeconfidencethatcomesfromcreating
attractivedocumentsinsuchashorttime.
2.1.WritingTools
UseanytexteditortocreateanHTMLorXHTMLdocument,aslongasitcansave
yourworkonadiskintextfileformat.That'sbecauseeventhoughweb
documentsincludeelaboratetextlayoutandpictures,they'realljustplainold
textdocumentsthemselves.AfancierWYSIWYGeditororatranslatorforyour
favoritewordprocessorisfine,tooalthoughitmaynotsupportallthelanguage
featureswediscussinthisbook.You'llprobablyenduptouchingupthesource
texttheyproduce,inanycase,anddon'texpectlayoutresultslikewhatyou'dget
withapage-layoutapplication.
Whileit'snotneededtocomposedocuments,youshouldhaveatleastone
versionofapopularbrowserinstalledonyourcomputertoviewyourwork.That's
because,unlessyouuseaspecialeditor,thesourcedocumentyoucomposewon't
lookanythinglikewhatgetsdisplayedbyabrowser,eventhoughit'sthesame
document.Makesurewhatyourreadersactuallyseeiswhatyouintendedby
viewingthedocumentyourselfwithabrowser.Besides,thepopularonesarefree
overtheInternet.WecurrentlyrecommendMicrosoftInternetExplorer,Mozilla
Firefox,AppleSafari,NetscapeNavigator,andOperaSoftwareASA.
Alsonotethatyoudon'tneedaconnectiontotheInternetortheWebtowrite
andviewyourHTMLorXHTMLdocuments.Youcancomposeandviewyour
documentsstoredonaharddriveorfloppydiskthat'sattachedtoyourcomputer.
YoucanevennavigateamongyourlocaldocumentswiththeHTML/XHTML's
hyperlinkingcapabilitieswithouteverbeingconnectedtotheInternet,orany
othernetwork,forthatmatter.Infact,werecommendthatyouworklocallyto
developandthoroughlytestyourdocumentsbeforeyousharethemwithothers.
Westronglyrecommend,however,thatyoudogetaconnectiontotheInternetif
youareseriousaboutcomposingyourowndocuments.Youcandownloadand
viewothers'interestingwebpagesandseehowtheyaccomplishedsome
interestingfeaturegoodorbad.Learningbyexampleisfun,too.(Reusingothers'
work,ontheotherhand,isoftenquestionable,ifnotdownrightillegal.)An
Internetconnectionisessentialifyouincludeinyourworkhyperlinkstoother
documentsontheInternet.
2.2.AFirstHTMLDocument
Itseemseveryprogramminglanguagebookeverwrittenstartsoffwithasimple
exampleonhowtodisplaythemessage,"Hello,World!"Well,youwon'tseea
"Hello,World!"exampleinthisbook.Afterall,thisisastyleguideforthenew
millennium.Instead,ourssendsgreetingstotheWorldWideWeb:
<html>
<head>
<title>MyfirstHTMLdocument</title>
</head>
<body>
<h2>MyfirstHTMLdocument</h2>
Hello,<i>WorldWideWeb!</i>
<!No"Hello,World"forus>
<p>
Greetingsfrom<br>
<ahref="http://www.ora.com">O'Reilly</a>
<p>
Composedwithcareby:
<cite>(insertyournamehere)</cite>
<br>©2000andbeyond
</body>
</html>
Goahead:typeintheexampleHTMLsourceonafreshwordprocessingpageand
saveitonyourlocaldiskasmyfirst.html.Makesureyouselecttosaveitinplain
textformat;wordprocessor-specificfileformatslikeMicrosoftWord's.docfiles
savehiddencharactersthatcanconfusethebrowsersoftwareanddisruptyour
HTMLdocument'sdisplay.
Aftersavingmyfirst.html(ormyfirst.htm,ifyouareusingarchaicDOS-or
Windows3.11-basedfile-namingconventions)ontodisk,startupyourbrowser
andlocateandopenthefilefromtheprogram'sFilemenu.Yourscreenshould
looklikeFigure2-1.Thoughlook-and-feelelementssuchasmenusandtoolbars
differbetweenbrowsers,thewindow'scontentsshouldbequitesimilar.
Figure2-1.AverysimpleHTMLdocument
2.3.EmbeddedTags
Youprobablynoticedrightaway,perhapsinsurprise,thatthebrowserdisplays
lessthanhalfoftheexamplesourcetext.Closerinspectionofthesourcereveals
thatwhat'smissingiseverythingthat'sbracketedinsideapairofless-than(<)
andgreater-than(>)characters.[TheSyntaxofaTag,3.3.1]
HTMLandXHTMLareembeddedlanguages:youinserttheirdirections,ortags,
intothesamedocumentthatyouandyourreadersloadintoabrowsertoview.
Thebrowserusestheinformationinsidethosetagstodecidehowtodisplayor
otherwisetreatthesubsequentcontentsofyourdocument.
Forinstance,the<i>tagthatfollowsthewordHellointhesimpleexampletells
thebrowsertodisplaythefollowingtextinitalics.[*][PhysicalStyleTags,4.5]
[*]Italicizedtextisaverysimpleexampleandonethatmostbrowsers,exceptthetext-onlyvariety(e.g.,Lynx),can
handle.Ingeneral,thebrowsertriestodoasitistold,butaswedemonstrateinupcomingchapters,browsersvaryfrom
computertocomputerandfromusertouser,asdothefontsthatareavailableandselectedbytheuserforviewing
HTMLdocuments.AssumethatnotallarecapableoforwillingtodisplayyourHTMLdocumentexactlyasitappearson
yourscreen.
Thefirstwordinatagisitsformalname,whichusuallyisfairlydescriptiveofits
function,too.Anyadditionalwordsinatagarespecialattributes,sometimeswith
anassociatedvalueafteranequalssign(=),whichfurtherdefineormodifythe
tag'sactions.
2.3.1.StartandEndTags
Mosttagsdefineandaffectadiscreteregionofyourdocument.Theregionbegins
wherethetaganditsattributesfirstappearinthesourcedocument(a.k.a.the
starttag)andcontinuesuntilacorrespondingendtag.Anendtagisthetag's
nameprecededbyaforwardslash(/).Forexample,theendtagthatmatchesthe
"startitalicizing"<i>tagis</i>.
Endtagsneverincludeattributes.InHTML,mosttags,butnotall,haveanend
tag.And,tomakelifeabiteasierforHTMLauthors,thebrowsersoftwareoften
infersanendtagfromsurroundingandobviouscontext,soyouneedn'texplicitly
includesomeendtagsinyoursourceHTMLdocument.(Wetellyouwhichare
optionalandwhichareneveromittedwhenwedescribeeachtaginlater
chapters.)Oursimpleexampleismissinganendtagthatissocommonlyinferred
andhencenotincludedinthesourcethatsomeveteranHTMLauthorsdon'teven
knowthatitexists.Whichone?
2.4.HTMLSkeleton
Notice,too,thatoursimpleexampleHTMLdocumentstartsandendswith<html>
and</html>tags.Thesetagstellthebrowserthattheentiredocumentiscomposed
inHTML.[*]TheHTMLandXHTMLstandardsrequirean<html>tagforcompliant
documents,butmostbrowserscandetectandproperlydisplayHTMLencodingina
textdocumentthat'smissingthisoutermoststructuraltag.[<html>,3.6.1]
[*]XHTMLdocumentsalsobeginwiththe<html>tag,buttheycontainadditionalinformationtodifferentiatethemfrom
commonHTMLdocuments.SeeChapter16fordetails.
Likeourexample,exceptforspecialframesetdocuments,allHTMLandXHTML
documentshavetwomainstructures:aheadandabody,eachboundedinthe
sourcebyrespectivelynamedstartandendtags.Youputinformationaboutthe
documentintheheadandthecontentsyouwantdisplayedinthebrowser's
windowinsidethebody.Exceptinrarecases,you'llspendmostofyourtime
workingonyourdocument'sbodycontent.[<head>,3.7.1][<body>,3.8.1]
Thereareseveraldifferentdocumentheadertagsthatyoucanusetodefinehow
aparticulardocumentfitsintoadocumentcollectionandintothelargerscheme
oftheWeb.Somenonstandardheadertagsevenanimateyourdocument.
Formostdocuments,however,theimportantheaderelementisthetitle.
StandardsrequirethateveryHTMLandXHTMLdocumenthaveatitle,even
thoughthecurrentlypopularbrowsersdon'tenforcethatrule.Choosea
meaningfultitle,onethatinstantlytellsthereaderwhatthedocumentisabout.
Encloseyours,aswedoforthetitleofourexample,betweenthe<title>and
</title>tagsinyourdocument'sheader.Thepopularbrowserstypicallydisplaythe
titleatthetopofthedocument'swindow.[<title>,3.7.2]
2.5.TheFleshonanHTMLorXHTMLDocument
Exceptforthe<html>,<head>,<body>,and<title>tags,theHTMLandXHTML
standardshavefewotherrequiredstructuralelements.You'refreetoinclude
prettymuchanythingelseinthecontentsofyourdocument.(Thewebsurfers
amongyouknowthatauthorshavetakenfulladvantageofthatfreedom,too.)
Perhapssurprisingly,though,thereareonlythreemaintypesofHTML/XHTML
content:tags(whichwedescribedpreviously),comments,andtext.
2.5.1.Comments
Arawdocumentwithallitsembeddedtagscanquicklybecomenearly
unreadable,likecomputer-programmingsourcecode.Westronglyrecommend
thatyouusecommentstoguideyourcomposingeye.
Althoughit'spartofyourdocument,nothinginacomment,whichgoesbetween
thespecialstartingtag<!andendingtag>commentdelimiters,getsincludedin
thebrowserdisplayofyourdocument.Youseeacommentinthesource,asinour
simpleHTMLexample,butyoudon'tseeitonthedisplay,asevidencedbyour
comment'sabsenceinFigure2-1.Anyonecandownloadthesourcetextofyour
documentsandreadthecomments,though,sobecarefulwhatyouwrite.
2.5.2.Text
Ifitisn'tatagoracomment,it'stext.Thebulkofcontentinmostofyour
HTML/XHTMLdocumentsthepartreadersseeontheirbrowserdisplaysistext.
Specialtagsgivethetextstructure,suchasheadings,lists,andtables.Others
advisethebrowserhowthecontentshouldbeformattedanddisplayed.
2.5.3.Multimedia
Whataboutimagesandothermultimediaelementsweseeandhearaspartofour
webbrowserdisplays?Aren'ttheypartoftheHTMLdocument?No.Thedatathat
comprisesdigitalimages,movies,sounds,andothermultimediaelementsthat
maybeincludedinthebrowserdisplayisinfilesseparatefromthemain
HTML/XHTMLdocument.Youincludereferencestothosemultimediaelementsvia
specialtags.Thebrowserusesthosereferencestoloadandintegrateothertypes
ofdocumentswithyourtext.
Wedidn'tincludeanyspecialmultimediareferencesinthepreviousexample
simplybecausetheyareseparate,nontextdocumentsthatyoucan'tjusttypeinto
atextprocessor.Wedo,however,talkaboutandgiveexamplesofhowto
integrateimagesandothermultimediainyourdocumentslaterinthischapter,as
wellasinextensivedetailinsubsequentchapters.
2.6.Text
Text-relatedHTML/XHTMLmarkuptagscomprisetherichestsetofallinthe
standardlanguages.That'sbecausetheoriginallanguageHTMLemergedasaway
toenrichthestructureandorganizationoftext.
HTMLcameoutofacademia.Whatwasandstillisimportanttothoseearly
developerswasthecapabilityoftheirmostlyacademic,text-orienteddocuments
tobescannedandreadwithoutsacrificingtheircapabilitytodistributedocuments
overtheInternettoawidediversityofcomputerdisplayplatforms.(Unicodetext
istheonlyuniversalformatontheglobalInternet.)Multimediaintegrationis
somethingofanappendagetoHTMLandXHTML,albeitanimportantone.
Also,pagelayoutissecondarytostructure.Wehumansvisuallyscananddecide
textualrelationshipsandstructurebasedonhowitlooks;machinescanonlyread
encodedmarkings.Becausedocumentshaveencodedtagsthatrelatemeaning,
theylendthemselvesverywelltocomputer-automatedsearchesandtothe
recompilationofcontentfeaturesveryimportanttoresearchers.It'snotsomuch
howsomethingissaidaswhatisbeingsaid.
Accordingly,neitherHTMLnorXHTMLisapage-layoutlanguage.Infact,giventhe
diversityofuser-customizablebrowsers,aswellasthediversityofcomputer
platformsforretrievalanddisplayofelectronicdocuments,allthesemarkup
languagesstrivetoaccomplishistoadvise,notdictate,howthedocumentmight
lookwhenrenderedbythebrowser.Youcannotforcethebrowsertodisplayyour
documentinanycertainway.You'llhurtyourbrainifyouinsistotherwise.
2.6.1.AppearanceofText
Forinstance,youcannotpredictwhatfontandwhatabsolutesize8-or40-point
Helvetica,Geneva,Subway,orwhateverwillbeusedforaparticularuser'stext
display.OK,sothelatestbrowsersnowsupportstandardCascadingStyleSheets
(CSS)andotherdesktoppublishing-likefeaturesthatletyoucontrolthelayout
andappearanceofyourdocuments.Butusersmaychangetheirbrowser'sdisplay
characteristicsandoverrideyourcarefullylaidplansatwill,quiteafewofthe
olderbrowsersouttheredon'tsupportthesenewlayoutfeatures,andsome
browsersaretext-onlywithnonicefontsatall.Whattodo?Concentrateon
content.Coolpagesareaflashinthepan.Deepcontentwillbringpeoplebackfor
moreandmore.
Nonetheless,styledoesmatterforreadability,anditisgoodtoincludeitwhere
youcan,aslongasitdoesn'tinterferewithcontentpresentation.Youcanattach
commonstyleattributestoyourtextwithphysicalstyletags,liketheitalic<i>tag
inoursimpleexample.Moreimportantandtruertothelanguage'soriginal
purpose,HTMLandXHTMLhavecontent-basedstyletagsthatattachmeaningto
varioustextpassages.Andyoucanaltertextdisplaycharacteristics,suchasfont
style,size,color,andsoon,withCSS.
Today'sgraphicalbrowsersrecognizethephysicalandcontent-relatedtextstyle
tagsandchangetheappearanceoftheirrelatedtextpassagestovisuallyconvey
meaningorstructure.Youcan'tpredictexactlywhatthatchangewilllooklike.
TheHTML4standard(andevenmoreso,theXHTML1.0standard)stressesthat
futurebrowserswillnotbesovisuallybound.Textcontentsmaybeheardoreven
felt,forexample,notreadbyviewers.Contextcluessurelyarebetterinthose
casesthanphysicalstyles.
2.6.1.1.Content-basedtextstyles
Content-basedstyletagsindicatetothebrowserthataportionofyour
HTML/XHTMLtexthasaspecificusageormeaning.The<cite>taginoursimple
example,forinstance,meanstheenclosedtextissomesortofcitationthe
document'sauthor,inthiscase.Browserscommonly,althoughnotuniversally,
displaythecitationtextinitalic,notasregulartext.[Content-BasedStyleTags,
4.4]
Whileitmayormaynotbeobvioustothecurrentreaderthatthetextisa
citation,somedaysomeonemightcreateacomputerprogramthatsearchesavast
collectionofdocumentsforembedded<cite>tagsandcompilesaspeciallistof
citationsfromtheenclosedtext.Similarsoftwareagentsalreadyscourthe
Internetforembeddedinformationtocompilelistings,suchastheinfamous
Googledatabaseofwebsites.
Themostcommoncontent-basedstyleusedtodayisthatofemphasis,indicated
withthe<em>tag.Andifyou'refeelingreallyemphatic,youmightusethe<strong>
contentstyle.Othercontent-basedstylesinclude<code>,forsnippetsof
programmingcode;<kbd>,todenotetextenteredbytheuserviaakeyboard;
<samp>,tomarksampletext;<dfn>,fordefinitions;and<var>,todelimitvariable
nameswithinprogrammingcodesamples.Allofthesetagshavecorresponding
endtags.
2.6.1.2.Physicalstyles
Eventhebarestofbarebonestextprocessorsconformtoafewtraditionaltext
styles,suchasitalicandboldcharacters.Whilenotwordprocessingtoolsinthe
traditionalsense,HTMLandXHTMLprovidetagsthatexplicitlytellthebrowserto
display(ifitcan)acharacter,word,orphraseinaparticularphysicalstyle.
Althoughyoushoulduserelatedcontent-basedtags,forthereasonsweargued
earlier,sometimesformismoreimportantthanfunction.Usethe<i>tagto
italicizetextwithoutimposinganyspecificmeaning,the<b>tagtodisplaytextin
boldface,orthe<tt>tagsothatthebrowser,ifitcan,displaysthetextina
teletype-stylemonospacedtypeface.[PhysicalStyleTags,4.5]
It'seasytofallintothetrapofusingphysicalstyleswhenyoushouldreallybe
usingacontent-basedstyleinstead.Disciplineyourselfnowtousethecontent-
basedstylesbecause,aswearguedearlier,theyconveymeaningaswellasstyle,
therebymakingyourdocumentseasiertoautomateandmanage.
2.6.1.3.Specialtextcharacters
Notalltextcharactersavailabletoyoufordisplaybyabrowsercanbetypedfrom
thekeyboard.Andsomecharactershavespecialmeanings,suchasthebrackets
aroundtags,whichifnotsomehowdifferentiatedwhenusedforplaintexttheless-
thansign(<)inamathequation,forexamplewillconfusethebrowserandtrash
yourdocument.HTMLandXHTMLgiveyouawaytoincludeanyofthemany
differentcharactersthatcomprisetheUnicodecharactersetanywhereinyour
textthroughaspecialencodingofitscharacterentity.
Likethecopyrightsymbolinoursimpleexample,acharacterentitystartswithan
ampersand(&),followedbyitsname,andterminatedwithasemicolon(;).
Alternatively,youmayalsousethecharacter'spositionnumberintheUnicode
tableofcharacters,precededbythepoundorsharpsign(#),inlieuofitsnamein
thecharacter-entitysequence.Whenrenderingthedocument,thebrowser
displaysthepropercharacter,ifitexistsintheuser'sfont.[CharacterEntities,
3.5.2]
Forobviousreasons,themostcommonlyusedcharacterentitiesarethegreater-
than(>),less-than(<),andampersand(&)characters.CheckAppendixF
tofindoutwhatsymbolthecharacterentity¦represents.You'llbepleasantly
surprised!
2.6.2.TextStructures
It'snotobviousinoursimpleexample,butthecommoncarriagereturnsweuse
toseparateparagraphsinoursourcedocumenthavenomeaninginHTMLor
XHTML,exceptinspecialcircumstances.Youcouldhavetypedthedocumentonto
asinglelineinyourtexteditor,anditwouldstillappearthesameinFigure2-1.
[*]
[*]Weuseacomputerprogramming-likestyleofindentationsothatoursourceHTML/XHTMLdocumentsaremore
readable.It'snotobligatory,norarethereanyformalstyleguidelinesforsourceHTML/XHTMLdocumenttextformats.
Wedo,however,highlyrecommendthatyouadoptaconsistentstylesothatyouandotherscaneasilyfollowyour
sourcedocuments.
You'dsoondiscover,too,ifyouhadn'treaditherefirst,thatexceptinspecial
cases,browserstypicallyignoreleadingandtrailingspaces,andsometimesmore
thanafewinbetween.(Ifyoulookcloselyatthesourceexample,theline
"Greetingsfrom"lookslikeitshouldbeindentedbyleadingspaces,butitisn'tin
Figure2-1.)
2.6.2.1.Divisions,paragraphs,andlinebreaks
Abrowsertakesthetextinthebodyofyourdocumentand"flows"itontothe
computerscreen,disregardinganycommoncarriage-returnorline-feed
charactersinthesource.Thebrowserfillsasmuchofeachlineofthedisplay
windowaspossible,beginningflushagainsttheleftmargin,beforestoppingafter
therightmostwordandmovingontothenextline.Resizethebrowserwindow,
andthetextreflowstofillthenewspace,indicatingHTML'sinherentflexibility.
Ofcourse,readerswouldrebelifyourtextjustranonandon,soHTMLand
XHTMLprovidebothexplicitandimplicitwaystocontrolthebasicstructureof
yourdocument.Themostrudimentaryandcommonwaysarewiththedivision
(<div>),paragraph(<p>),andline-break(<br>)tags.Allbreakthetextflow,which
consequentlyrestartsonanewline.Thedifferencesarethatthe<div>and<p>tags
defineanelementalregionofthedocumentandtext,respectively,thecontentsof
whichyoumayspeciallyalignwithinthebrowserwindow,applytextstylesto,and
alterwithotherblock-relatedfeatures.
Withoutspecialalignmentattributes,the<div>and<br>tagssimplybreakalineof
textandplacesubsequentcharactersonthenextline.The<p>tagaddsmore
verticalspaceafterthelinebreakthaneitherthe<div>or<br>tag.[<div>,4.1.1]
[<p>,4.1.2][<br>,4.6.1]
Bytheway,theHTMLstandardincludesendtagsfortheparagraphanddivision
tags,butnotfortheline-breaktag.[*]Fewauthorseverincludetheparagraph
endtagintheirdocuments;thebrowserusuallycanfigureoutwhereone
paragraphendsandanotherbegins.[ ]Giveyourselfastarifyouknewthat</p>
evenexists.
[*]WithXHTML,<br>'sstartandendarebetweenthesamebrackets:<br/>.Browserstendtobeveryforgivingand
oftenignoreextraneousthings,suchastheforwardslashinthiscase,soit'sperfectlyOKtogetintothehabitofadding
thatendmark.
[ ]Theparagraphendtagisbeingusedmorecommonlynowthatthepopularbrowserssupporttheparagraph-
alignmentattribute.
2.6.2.2.Headings
Besidesbreakingyourtextintodivisionsandparagraphs,youcanalsoorganize
yourdocumentsintosectionswithheadings.Justastheydoonthisandother
pagesinthisprintedbook,headingsnotonlydivideandentitlediscretepassages
oftext,buttheyalsoconveymeaningvisually.Andheadingsreadilylend
themselvestomachine-automatedprocessingofyourdocuments.
Therearesixheadingtags,<h1>tHRough<h6>,withcorrespondingendtags.
Typically,thebrowserdisplaystheircontentsin,respectively,verylargetovery
smallfontsizes,andusuallyinboldface.Thetextinsidethe<h4>tagtypicallyis
thesamesizeastheregulartext.[HeadingTags,4.2.1]
Theheadingtagsalsobreakthecurrenttextflow,standingaloneonlinesand
separatedfromsurroundingtext,eventhoughtherearen'tanyexplicitparagraph
orline-breaktagsbeforeorafteraheading.
2.6.2.3.Horizontalrules
Besidesheadings,HTMLandXHTMLprovidehorizontalrulelinesthathelp
delineateandseparatethesectionsofyourdocument.
Whenthebrowserencountersan<hr>taginyourdocument,itbreakstheflowof
textanddrawsalineacrossthedisplaywindowonanewline.Theflowoftext
resumesimmediatelybelowtherule.[*][<hr>,5.1.1]
[*]Similarto<br>,withXHTML,theformalhorizontalruleendtagis<hr/>.
2.6.2.4.Preformattedtext
Occasionally,you'llwantthebrowsertodisplayablockoftextasis:forexample,
withindentedlinesandverticallyalignedlettersornumbersthatdon'tchange
eventhoughthebrowserwindowmightgetresized.The<pre>tagrisestothose
occasions.Alltextuptotheclosing</pre>endtagappearsinthebrowserwindow
exactlyasyoutypeit,includingcarriagereturns,linefeeds,andleading,trailing,
andinterveningspaces.Althoughveryusefulfortablesandforms,<pre>textlooks
prettydull;thepopularbrowsersrendertheblockinamonospacetypeface.
[<pre>,4.6.5]
2.7.Hyperlinks
WhiletextmaybethemeatandbonesofanHTMLorXHTMLdocument,theheart
ishypertext.Hypertextgivesuserstheabilitytoretrieveanddisplayadifferent
documentintheirownorsomeoneelse'scollectionsimplybyaclickofthe
keyboardormouseonanassociatedwordorphrase(hyperlink)inthedocument.
Usetheseinteractivehyperlinkstohelpreaderseasilynavigateandfind
informationinyourownorothers'collectionsofotherwiseseparatedocumentsin
avarietyofformats,includingmultimedia,HTML,XHTML,otherXML,andplain
text.HyperlinksliterallybringthewealthofknowledgeonthewholeInternetto
thetipofthemousepointer.
Toincludeahyperlinktosomeotherdocumentinyourowncollectionorona
serverinTimbuktu,allyouneedtoknowisthedocument'suniqueaddressand
howtodropananchorintoyourdocument.
2.7.1.URLs
Whileitishardtobelieve,giventhebillionsofthemoutthere,everydocument
andresourceontheInternethasauniqueaddress,knownasitsuniformresource
locator(URL;commonlypronounced"you-are-ell").AURLconsistsofthe
document'snameprecededbythehierarchyofdirectorynamesinwhichthefile
isstored(pathname),theInternetdomainnameoftheserverthathoststhefile,
andthesoftwareandmannerbywhichthebrowserandthedocument'shost
servercommunicatetoexchangethedocument(protocol):
protocol://server_domain_name/pathname
HerearesomesampleURLs:
http://www.kumquat.com/docs/catalog/price_list.html
price_list.html
../figs/my_photo.png
ftp://ftp.netcom.com/pub
ThefirstexampleisanabsoluteorcompleteURL.Itincludeseverypartofthe
URLformat:protocol,server,andpathnameofthedocument.Whileabsolute
URLsleavenothingtotheimagination,theycanleadtobigheadacheswhenyou
movedocumentstoanotherdirectoryorserver.Fortunately,browsersalsoletyou
userelativeURLsandautomaticallyfillinanymissingportionswithrespective
partsfromthecurrentdocument'sbaseURL.Thesecondexampleisthesimplest
relativeURLofall;withit,thebrowserassumesthattheprice_list.htmldocument
islocatedonthesameserver,inthesamedirectoryasthecurrentdocument,and
usesthesamenetworkprotocol(http).Similarly,examplethreeisarelativeURL
whichlooksupandintothe/figsdirectoryforapicturefile.
Althoughappearancesmaydeceive,thelastFTPexampleURLactuallyis
absolute;itpointsdirectlyatthecontentsofthe/pubdirectory.Moreover,theftp
protocolspecificationintheexampleaccessesdifferentsoftwareontheserver
thanthehttpprotocolintheotherexamples.
2.7.2.Anchors
Theanchor(<a>)tagistheHTML/XHTMLfeaturefordefiningboththesourceand
thedestinationofahyperlink.[*]You'llmostoftenseeandusethe<a>tagwithits
hrefattributetodefineasourcehyperlink.Thevalueofthehrefattributeisthe
URLofthedestination.
[*]Thenomenclaturehereisabitunfortunate:the"anchor"tagshouldmarkjustadestination,notthejumping-offpointof
ahyperlink,too.You"dropanchor";youdon'tjumpoffone.Wewon'tevenmentiontheatrociouslyconfusingterminology
theW3Cusesforthevariouspartsofahyperlink,excepttosaythatsomeonegotthingsall"bass-ackward."
Thecontentsofthesource<a>tagthewordsand/orimagesbetweenitandits</a>
endtagistheportionofthedocumentthatisspeciallyactivatedinthebrowser
displayandthatusersselecttotakeahyperlink.Theseanchorcontentsusually
lookdifferentfromthesurroundingcontent(textinadifferentcoloror
underlined,imageswithspeciallycoloredborders,orothereffects),andthe
mouse-pointericonchangeswhenpassedoverthem.The<a>tagcontents,
therefore,shouldbetextoranimage(iconsaregreat)thatexplicitlyor
intuitivelytellsuserswherethehyperlinkwilltakethem.[<a>,6.3.1]
Forinstance,thebrowserwillspeciallydisplayandchangethemousepointer
whenitpassesoverthe"KumquatArchive"textinthefollowingexample:
Formoreinformationonkumquats,visitour
<ahref="http://www.kumquat.com/archive.html">
KumquatArchive</a>
Iftheuserclicksthemousebuttononthattext,thebrowserautomatically
retrievesfromtheserverwww.kumquat.comaweb(http:)pagenamed
archive.html,thendisplaysitfortheuser.
2.7.3.HyperlinkNamesandNavigation
Pointingtoanotherdocumentinsomecollectionsomewhereontheothersideof
theworldisnotonlycool,butitalsosupportsyourownwebdocuments.Yetthe
hyperlink'schiefdutyistohelpusersnavigateyourcollectionintheirsearchfor
valuableinformation.Hence,theconceptofthehomepageandsupporting
documentshasarisen.
Noneofyourdocumentsshouldrunonandon.First,there'saserious
performanceissue:thevalueofyourworksuffers,nomatterhowrichitis,ifthe
documenttakesforevertodownloadandif,onceitisretrieved,usersmust
endlesslyscrollupanddownthroughthedisplaytofindaparticularsection.
Rather,designyourworkasacollectionofseveralcompactandsuccinctpages,
likechaptersinabook,eachfocusedonaparticulartopicforquickselectionand
browsingbytheuser.Thenusehyperlinkstoorganizethatcollection.
Forinstance,useyourhomepagetheleadingdocumentofthecollectionasa
masterindexfullofbriefdescriptionsandrespectivehyperlinkstotherestofyour
collection.
Youcanalsouseeitherthenamevariantofthe<a>tagortheidattributeofnearly
alltagstospeciallyidentifysectionsofyourdocument.Tagidsandnameanchors
serveasinternalhyperlinktargetsinyourdocumentstohelpuserseasily
navigatewithinthesamedocumentorjumptoaparticularsectionwithinanother
document.Refertothatid'dsectioninahyperlinkbyappendingapoundsign(#)
andthesectionnameasthesuffixtotheURL.
Forinstance,toreferenceaspecifictopicinanarchive,suchas"KumquatStew
Recipes"inourexampleKumquatArchive,firstmarkthesectiontitlewithanid:
...precedingcontent...
<h3id="Stews">KumquatStewRecipes</h3>
inthesameoranotherdocument,thenprepareasourcehyperlinkthatpoints
directlytothoserecipesbyincludingthesection'sidvalueasasuffixtothe
document'sURL,separatedbyapoundsign:
Formoreinformationonkumquats,visitour
<ahref="http://www.kumquat.com/archive.html">
KumquatArchive</a>,
andperhapstryoneortwoofour
<ahref="http://www.kumquat.com/archive.html#Stews">
KumquatStewRecipes</a>.
Ifselectedbytheuser,thelatterhyperlinkcausesthebrowsertodownloadthe
archive.htmldocumentandstartthedisplayatour"Stews"section.
2.7.4.AnchorsBeyond
HyperlinksarenotlimitedtootherHTMLandXHTMLdocuments.Anchorsletyou
pointtonearlyanytypeofdocumentavailableovertheInternet,includingother
Internetservices.
However,"let"and"enable"aretwodifferentthings.Browserscanmanagethe
variousInternetservices,suchasFTPandGopher,sothatuserscandownload
non-HTMLdocuments.Theydon'tyetfullyorgracefullyhandlemultimedia.
Today,therearefewstandardsforthemanytypesandformatsofmultimedia.
ComputersystemsconnectedtotheWebvarywildlyintheircapabilitiestodisplay
thosesoundandvideoformats.Exceptforsomegraphicsimages,standard
HTML/XHTMLgivesyounospecificprovisionfordisplayofmultimediadocuments
excepttheabilitytoreferenceoneinananchor.Thebrowser,whichretrievesthe
multimediadocument,mustactivateaspecialhelperapplication,downloadand
executeanassociatedapplet,orhaveaplug-inaccessoryinstalledtodecodeand
displayitfortheuserrightwithinthedocument'sdisplay.
AlthoughHTMLandmostwebbrowserscurrentlyavoidtheconfusionby
sidesteppingit,thatdoesn'tmeanyoucan'torshouldn'texploitmultimediain
yourdocuments:justbeawareofthelimitations.
2.8.ImagesAreSpecial
Imagefilesaremultimediaelementsthatyoucanreferencewithanchorsinyour
documentforseparatedownloadanddisplaybythebrowser.But,unlikeother
multimedia,standardHTMLandXHTMLhaveanexplicitprovisionforimage
display"inline"withthetext,andimagescanserveasintricatemapsof
hyperlinks.That'sbecausethereissomeconsensusintheindustryconcerning
imagefileformatsspecifically,GIF,PNG,andJPEGandthegraphicalbrowsershave
built-indecodersthatintegratethoseimagetypesintoyourdocument.[*]
[*]SomebrowserssupportothermultimediabesidesGIFandJPEGgraphicsforinlinedisplay.InternetExplorer,for
instance,supportsatagthatplaysbackgroundaudio.Inaddition,theHTML4andXHTMLstandardsprovideawayto
displayothertypesofmultimediainlinewithdocumenttextthroughageneraltag.
2.8.1.InlineImages
TheHTML/XHTMLtagforinlineimagesis<img>;itsrequiredsrcattributeisthe
imagefilethatyouwanttodisplayinthedocument.[<img>,5.2.6]
Thebrowserseparatelyloadsimagesandplacesthemintothetextflowasthough
theimageweresomespecial,albeitsometimesverylarge,character.Normally,
thatmeansthebrowseralignsthebottomoftheimagetothebottomofthe
currentlineoftext.YoucanchangethatwiththespecialCSSalignproperty,
whosevalueyousettoputtheimageatthetop,middle,orbottomofadjacenttext.
ExamineFigures2-2through2-4fortheimagealignmentyouprefer.Ofcourse,
wideimagesmaytakeupthewholelineandhencebreakthetextflow.Youcan
alsoplaceanimagebyitself,byincludingprecedingandfollowingdivision,
paragraph,orline-breaktags.
Figure2-2.Aninlineimagealignedwiththebottomofthetext
(default)
Figure2-3.Aninlineimagespeciallyalignedwiththemiddleof
thetext
Figure2-4.Aninlineimagespeciallyalignedwiththetopofthe
text
ExperiencedHTMLauthorsuseimagesnotonlyassupportingillustrations,but
alsoasquitesmallinlinecharactersorglyphs,addedtoaidbrowsingreaders'
eyesandtohighlightsectionsofthedocuments.VeteranHTMLauthors[*]
commonlyaddcustomlistbulletsormoredistinctivesectiondividersthanthe
conventionalhorizontalrules.Images,too,maybeincludedinahyperlinksothat
usersmayselectaninlinethumbnailsketchtodownloadafull-screenimage.The
possibilitieswithinlineimagesareendless.
[*]XHTMListoonewtocallanyoneaveteranorexperiencedXHTMLauthor.
Wealsoshouldmentionthealtattribute.Giveitsometextvaluethatexplains
theimagedisplayforthosewhohavedisabledimagedisplay,orforbrowsersthat
maybeabletoreadtothedisableduser.
2.8.2.ImageMaps
Imagemapsareimageswithinananchorwithaspecialattribute:theymay
containmorethanonehyperlink.
Onewaytoenableanimagemapisbyaddingtheismapattributetoan<img>tag
placedinsideananchortag(<a>).Whentheuserclickssomewhereintheimage,
thegraphicalbrowsersendstherelativeX,Ycoordinatesofthemousepositionto
theserverthatisalsodesignatedintheanchor.Aspecialserverprogramthen
translatestheimagecoordinatesintosomespecialaction,suchasdownloading
anotherdocument.[Server-sideconsiderations,6.5.1.1]
Agoodexampleoftheuseofanimagemapmightbetolocateahotelwhile
traveling.Forexample,whentheuserclicksonamapoftheregionheintendsto
visit,yourimagemap'sserverprogrammightreturnthenames,addresses,and
phonenumbersoflocalaccommodations.
Whiletheyareverypowerfulandvisuallyappealing,theseso-calledserver-side
imagemapsmeanthatauthorsmusthavesomeaccesstothemap'scoordinate-
processingprogramontheserver.Manyauthorsdon'tevenhaveaccesstothe
server,letaloneaprogramontheserver.Abettersolutionistotakeadvantageof
client-sideimagemaps.
Insteadofdependingonawebserver,theusemapattributeforthe<img>tag,with
the<map>and<area>tags,allowsauthorstoembedtheinformationthebrowser
needstoprocessanimagemapinthesamedocumentastheimage.Becauseof
theirreducednetworkbandwidthandserverindependence,theclient-sideimage
mapsarepopularamongdocumentauthorsandsystemadministrators.[Client-
SideImageMaps,6.5.2]
2.9.Lists,SearchableDocuments,andForms
Thoughtwe'dexhaustedtextelements?Headers,paragraphs,andlinebreaksare
justtherudimentarytext-organizationalelementsofadocument.Thelanguages
alsoprovideseveraladvancedtext-basedstructures,includingthreetypesoflists,
"searchable"documents,andforms.Searchabledocumentsandformsgobeyond
textformatting,too;theyareawaytointeractwithyourreaders.Formsletusers
entertextandclickcheckboxesandradiobuttonstoselectparticularitemsand
thensendthatinformationbacktotheserver.Aspecialserverapplicationthen
processestheform'sinformationandrespondsaccordingly;forexample,fillinga
productorderorcollectingdataforausersurvey.[*]
[*]Theserver-sideprogrammingrequiredforprocessingformsisbeyondthescopeofthisbook.Wegivesomebasic
guidelinesintheappropriatechapters,butpleaseconsulttheserverdocumentationandyourserveradministratorfor
details.
Thesyntaxforthesespecialfeaturesandtheirvariousattributescangetrather
complicated;they'renotquick-startgrist.We'llmentionthemhere,butweurge
youtoreadonfordetailsinlaterchapters.
2.9.1.Unordered,Ordered,andDefinitionLists
Thethreetypesoflistsmatchthosewearemostfamiliarwith:unordered,
ordered,anddefinitionlists.Anunorderedlistoneinwhichtheorderofitemsis
notimportant,suchasalaundryorgrocerylistgetsboundedby<ul>and</ul>
tags.Eachiteminthelist,usuallyawordorshortphrase,ismarkedbythe<li>
(list-item)tagand,particularlywithXHTML,the</li>endtag.Whenrendered,
thelistitemtypicallyappearsindentedfromtheleftmargin,precededbyabullet
symbol.[<ul>,7.1.1][<li>,7.3]
Orderedlists,boundedbythe<ol>and</ol>tags,areidenticalinformatto
unorderedones,includingthe<li>tag(and</li>endtagwithXHTML)formarking
listitems.However,theorderofitemsisimportantasinequipmentassembly
steps,forinstance.Thebrowseraccordinglydisplayseachiteminthelist
precededbyanascendingnumber.[<ol>,7.2.1]
Definitionlistsareslightlymorecomplicatedthanunorderedandorderedlists.
Withinadefinitionlist'senclosing<dl>and</dl>tags,eachlistitemhastwoparts,
eachwithaspecialtag:ashortnameortitle,containedwithina<dt>tag,followed
byitscorrespondingvalueordefinition,denotedbythe<dd>tag(XHTMLincludes
respectiveendtags).Whenthetagsarerendered,thebrowserusuallyputsthe
itemnameonaseparateline(althoughnotindented),andthedefinition,which
mayincludeseveralparagraphs,indentedbelowit.[<dl>,7.5.1]
Thevarioustypesoflistsmaycontainnearlyanytypeofcontentnormally
allowedinthebodyofthedocument.Soyoucanorganizeyourcollectionof
digitizedfamilyphotographsintoanorderedlist,forexample,orputthemintoa
definitionlistcompletewithtextannotations.Themarkuplanguagestandards
evenletyouputlistsinsideoflists(nesting),openingupawealthofinteresting
combinations.
2.9.2.SearchableDocumentsandForms
TheoriginaltypeofuserinteractionprovidedbyearlyversionsofHTMLstill
availabletoday,thoughdeprecatedinthestandards,isan<isindex>-based
searchabledocument.Thebrowserprovidessomewayfortheusertotypeoneor
morewordsintoatextinputboxandtopassthosekeywordstoarelated
processingapplicationontheserver.[*]Obviously,searchabledocumentsarevery,
verylimitedoneperdocumentandonlyoneuser-inputelement.Fortunately,
HTMLandXHTMLprovidebetter,moreextensivesupportforcollectinguserinput
throughforms.[<isindex>,6.6.1][<form>,9.2]
[*]Fewauthorshaveusedthetag,apparently.The<isindex>taghasbeen"deprecated"inHTMLversion4.0sentout
topasture,sotospeak,butnotyetlaidtorest.
Youcancreateoneormorespecialformsectionsinyourdocument,boundedwith
the<form>and</form>tags.Insidetheform,youmayputpredefinedaswellas
customizedtext-inputboxesallowingforbothsingleandmultilineinput.Youmay
alsoinsertcheckboxesandradiobuttonsforsingle-andmultiple-choiceselections
andspecialbuttonsthatworktoresettheformorsenditscontentstotheserver.
Usersfillouttheformattheirleisure,perhapsafterreadingtherestofthe
document,andclickaspecialsendbuttonthatmakesthebrowsersendtheform's
datatotheserver.Aspecialserver-sideprogramyouprovidethenprocessesthe
formandrespondsaccordingly,perhapsbyrequestingmoreinformationfromthe
user,modifyingsubsequentdocumentstheserversendstotheuser,andsoon.
[<form>,9.2]
Formsprovideeverythingyoumightexpectofanautomatedform,includinginput
arealabels,integratedcontentsforinstructions,defaultinputvalues,andso
onexceptautomaticinputverification,suchastocheckforthecorrectnumberof
digitsinazipcodeorphonenumber,forinstance;yourserver-sideprogramor
client-sideJavaScriptsneedtoperformthatfunction.
2.10.Tables
Foralanguagethatemergedfromacademiaaworldsteepedindatait'snot
surprisingtofindthatHTML(andnowitsprogeny,XHTML)supportsasetoftags
fordatatablesthatnotonlyalignyournumbers,butcanspeciallyformatyour
text,too.
Eighttagsenabletables;includingthe<table>tagitselfanda<caption>tagfor
includingadescriptionofthetable.Specialtagattributesletyouchangethelook
anddimensionsofthetable.Youcreateatablerowbyrow,puttingbetweenthe
tablerow(<tr>)taganditsendtag(</tr>)eithertableheader(<th>)ortabledata
(<td>)tagsandtheirrespectivecontentsforeachcellinthetable(endtags,too,
withXHTML).Headersanddatamaycontainnearlyanyregularcontent,including
text,images,forms,andevenanothertable.Asaresult,youcanalsousetables
foradvancedtextformatting,suchasformulticolumntextandsidebarheaders
(seeFigure2-5).Formoreinformation,seeChapter10.
Figure2-5.Tablesletyouperformpagelayouttricks,too
2.11.Frames
Anyonewhohashadmorethanoneapplicationwindowopenonhergraphical
desktopatatimecanimmediatelyappreciatethebenefitsofframes.Frameslet
youdividethebrowserwindowintomultipledisplayareas,eachcontaininga
differentdocument.
Figure2-6isanexampleofaframedisplay.Itshowshowthedocumentwindow
maybedividedintoindependentwindowsseparatedbyrulelinesandscrollbars.
Whatisnotimmediatelyapparentintheexample,though,isthateachframe
displaysanindependentdocument,andnotnecessarilyHTMLorXHTMLones,
either.Aframemaycontainanyvalidcontentthatthebrowseriscapableof
displaying,includingmultimedia.Iftheframe'scontentsincludeahypertextlink
thattheuserselects,thenewdocument'scontents,evenanotherframe
document,mayreplacethatsameframe,anotherframe'scontent,ortheentire
browserwindow.
Figure2-6.Framesdividethebrowser'swindowintotwoor
moreindependentdocumentdisplays
Framesaredefinedinaspecialdocument,inwhichyoureplacethe<body>tagwith
oneormore<frameset>tagsthattellthebrowserhowtodivideitsmainwindow
intodiscreteframes.Special<frame>tagsgoinsidethe<frameset>tagandpointto
thedocumentsthatgoinsidetheframes.[<frameset>,11.3.1]
Theindividualdocumentsreferencedanddisplayedintheframedocument
windowactindependently,toadegree;theframedocumentcontrolstheentire
window.Youcan,however,directoneframe'sdocumenttoloadnewcontentinto
anotherframe.InFigure2-6,forexample,selectingaChapterhyperlinkinthe
TableofContentsframehasthebrowserloadanddisplaythatchapter'scontents
intheframeontheright.Thatway,thetableofcontentsisalwaysavailableto
theuserashebrowsesthecollection.Formoreinformationonframes,see
Chapter11.
2.12.StylesheetsandJavaScript
BrowsersalsohavesupportfortwopowerfulinnovationstoHTML:stylesheetsand
JavaScript.Liketheirdesktoppublishingcousins,stylesheetsletyoucontrolhow
yourwebpageslooktextfontstylesandsizes,colors,backgrounds,alignments,
andsoon.Moreimportant,stylesheetsgiveyouawaytoimposedisplay
characteristicsuniformlyovertheentiredocumentandoveranentirecollection
ofdocuments.
JavaScriptisaprogramminglanguagewithfunctionsandcommandsthatletyou
controlhowthebrowserbehavesfortheuser.Now,thisisnotaJavaScript
programmingbook,butwedocoverthelanguageinfairdetailinlaterchaptersto
showyouhowtoembedJavaScriptprogramsintoyourdocumentsandachieve
someverypowerfulandfuneffects.
TheW3CtheputativestandardsorganizationprefersthatyouusetheCSSmodel
forHTML/XHTMLdocumentdesign.AllmodernGUIbrowserssupportCSSand
JavaScript.TheancientNetscape4alonealsosupportsaJavaScriptStyleSheet
(JSS)model,whichwedescribeinChapter12,butwedonotrecommendthatyou
useit.Let'srephrasethatdon'twasteyourtimeonJSS.CSSistheuniversally
approved,universallysupportedwaytocontrolhowyourdocumentsmight(not
will)usuallybedisplayedonusers'browsers.
ToillustrateCSS,here'sawaytomakeallthetop-level(h1)headertextinyour
HTMLdocumentappearinthecolorred:
<html>
<head>
<title>CSSExample</title>
<!HideCSSpropertieswithincommentssooldbrowsers
don'tchokeonordisplaytheunfamiliarcontents.>
<styletype="text/css">
<!
h1{color:red}
>
</style>
</head>
<body>
<h1>I'llberedifyourbrowsersupportsCSS</h1>
Somethinginbetween.
<h1>Ishouldbered,too!</h1>
</body>
</html>
Ofcourse,youcan'tseeredinthisblack-and-whitebook,sowewon'tshowthe
resultinafigure.Believeus,orproveittoyourselfbytypinginandloadingthe
exampleinyourbrowser:the<h1>-enclosedtextappearsredonacolorscreen.
JavaScriptisanobject-basedlanguage.Itviewsyourdocumentandthebrowser
thatdisplaysyourdocumentsasacollectionofparts("objects")thathavecertain
propertiesthatyoumaychangeorcompute.Thisissomeverypowerfulstuff,but
notsomethingthatmostauthorswillwanttohandle.Rather,mostofusprobably
willsnatchthequickandeasy,yetpowerfulJavaScriptprogramsthatproliferate
acrosstheWebandembedtheminourowndocuments.Wewilltellyouhowin
Chapter12.
2.13.ForgingAhead
Clearly,thischapterrepresentsthetipoftheiceberg.Ifyou'vereadthisfar,
hopefullyyourappetitehasbeenwhettedformore.Bynowyou'vegotabasic
understandingofthescopeandfeaturesofHTMLandXHTML;proceedthrough
subsequentchapterstoexpandyourknowledgeandlearnmoreabouteach
feature.
Chapter3.AnatomyofanHTMLDocument
MostHTMLandXHTMLdocumentsareverysimple,andwritingoneshouldn't
intimidateeventhemosttimidofcomputerusers.First,althoughyoumightusea
fancyWYSIWYGeditortohelpyoucomposeit,adocumentisultimatelystored,
distributed,andreadbyabrowserasasimpletextfile.[*]That'swhyeventhe
poorestuserwithabarebonestexteditorcancomposethemostelaborateofweb
pages.(Accomplishedwebmastersoftenelicittheadmirationof"newbies"by
composingastonishinglycoolpagesusingthecrudesttexteditoronacheap
laptopcomputerandperforminginoddplaces,suchasonabusorinthe
bathroom.)Authorsshould,however,keepseveralofthepopularbrowserson
hand,includingrecentversionsofeach,andalternateamongthemtoviewnew
documentsunderconstruction.Remember,browsersdifferinhowtheydisplaya
page,notallbrowsersimplementallofthelanguagestandards,andsomehave
theirownspecialextensions.
[*]Informally,boththetextandthemarkuptagsareASCIIcharacters.Technically,unlessyouspecifyotherwise,textand
tagsaremadeupof8-bitcharactersasdefinedinthestandardISO-8859-1Latincharacterset.TheHTML/XHTML
standardssupportalternativecharacterencodings,includingArabicandCyrillic.SeeAppendixFfordetails.
3.1.AppearancesCanDeceive
Documentsneverlookalikewhendisplayedbyatexteditorandwhendisplayed
byabrowser.TakealookatanysourcedocumentontheWeb.Attheveryleast,
returncharacters,tabs,andleadingspaces,althoughimportantforreadabilityof
thesourcetextdocument,areignoredforthemostpartwhendisplayedbyan
HTML/XHTMLbrowser.Therealsoisalotofextratextinasourcedocument,
mostlyfromthedisplaytagsandinteractivitymarkersandtheirparametersthat
affectportionsofthedocumentbutdon'tappearinthedisplay.
Accordingly,newauthorsareconfrontedwithhavingtodevelopnotonlya
presentationstylefortheirwebpages,butalsoadifferentstylefortheirsource
text.Thesourcedocument'slayoutshouldhighlighttheprogramming-likemarkup
aspectsofHTMLandXHTML,nottheirdisplayaspects.Anditshouldbereadable
notonlybyyou,theauthor,butbyothersaswell.
Experienceddocumentwriterstypicallyadoptaprogramming-likestyle,albeit
veryrelaxed,fortheirsourcetext.Wedothesamethroughoutthisbook,and
thatstylewillbecomeapparentasyoucompareoursourceexampleswiththe
actualdisplayofthedocumentbyabrowser.
Ourformattingstyleissimple,butitservestocreatereadable,easilymaintained
documents:
Exceptforthestructuraltagssuchas<html>,<head>,<frameset>,and<body>,we
placeelementsthatstructurethecontentofadocumentonaseparateline
andindentedtoshowitsnestinglevelwithinthedocument.Structural
elementsincludelists,forms,tables,andsimilartags.
Elementsthatcontroltheappearanceorstyleoftextgetinsertedinthe
currentlineoftext.Theseincludebasicfontstyletagssuchas<b>(boldtext)
anddocumentlinkagessuchas<a>(hypertextanchor).
Avoid,wherepossible,breakingaURLontotwolines.
Addextranewlinecharacterstosetapartspecialsectionsofthesource
documentforinstance,aroundparagraphsortables.
Thetaskofmaintainingtheindentationofyoursourcefilerangesfromtrivialto
onerous.Sometexteditors,suchasEmacs,managetheindentation
automatically;others,suchascommonwordprocessors,couldn'tcarelessabout
indentationandleavethetaskcompletelyuptoyou.Ifyoureditormakesyour
lifedifficult,youmightconsiderstrikingacompromise,perhapsbyindentingthe
tagstoshowstructure,butleavingtheactualtextwithoutindentationtomake
modificationseasier.
Nomatterwhatcompromisesorstandsyoumakeonsource-codestyle,it's
importantthatyouadoptone.You'llbeverygladyoudidwhenyougobackto
thatdocumentyouwrotethreemonthsagosearchingforthatreallycooltrickyou
didwith...now,wherewasthat?
3.2.StructureofanHTMLDocument
HTMLandXHTMLdocumentsconsistoftext,whichdefinesthecontentofthe
document,andtags,whichdefinethestructureandappearanceofthedocument.
ThestructureofanHTMLdocumentissimple,consistingofanouter<html>tag
enclosingthedocument:[*]
[*]ThestructureofanXHTMLdocumentisslightlymorecomplicated,aswedetailinChapter16.
<html>
<head>
<title>BarebonesHTMLDocument</title>
</head>
<body>
Thisillustrates,inavery<i>simp</i>leway,
thebasicstructureofanHTMLdocument.
</body>
</html>
Mostdocumentshaveaheadandabody,delimitedbythe<head>and<body>tags.
Theheadiswhereyougiveyourdocumentatitleandwhereyouindicateother
parametersthebrowsermayusewhendisplayingthedocument.Thebodyis
whereyouputtheactualcontentsofthedocument.Thisincludesthetextfor
displayanddocument-controlmarkers(tags)thatadvisethebrowserhowto
displaythetext.Tagsalsoreferencespecial-effectsfiles,includinggraphicsand
sound,andindicatethehotspots(hyperlinksandanchors)thatlinkyour
documenttootherdocuments.
3.3.TagsandAttributes
Forthemostpart,tagsthemarkupelementsofHTMLandXHTMLaresimpleto
understandanduse,sincetheyaremadeupofcommonwords,abbreviations,and
notations.Forinstance,the<i>and</i>tagsrespectivelytellthebrowsertostart
andstopitalicizingthetextcharactersthatcomebetweenthem.Accordingly,the
syllable"simp"inourbarebonesexampleinFigure3-1shouldappearitalicized
whendisplayedbythebrowser.
Figure3-1.ComparethisbrowserdisplaywithitsBarebones
sourceHTMLshownearlier
TheHTMLandXHTMLstandardsandtheirvariousextensionsdefinehowand
whereyouplacetagswithinadocument.Let'stakeacloserlookatthatsyntactic
sugarthatholdstogetheralldocuments.
3.3.1.TheSyntaxofaTag
Everytagconsistsofatagname,sometimesfollowedbyanoptionallistoftag
attributes,allplacedbetweenopeningandclosingbrackets(<and>).Thesimplest
tagisnothingmorethananameappropriatelyenclosedinbrackets,suchas<head>
and<i>.Morecomplicatedtagscontainoneormoreattributes,whichspecifyor
modifythebehaviorofthetag.
AccordingtotheHTMLstandard,tagandattributenamesarenotcase-sensitive.
There'snodifferenceineffectbetween<head>,<Head>,<HEAD>,andeven<HeaD>;allof
themareequivalent.WithXHTML,caseisimportant:allcurrentstandardtagand
attributenamesareinlowercase;always<head>,never<HEAD>.
ForbothHTMLandXHTML,thevaluesthatyouassigntoaparticularattribute
maybecase-sensitive,dependingonyourbrowserandserver.Inparticular,file
locationandnamereferencesorURLsarecase-sensitive.[ReferencingDocuments:
TheURL,6.2]
Tagattributes,ifany,belongafterthetagname,eachseparatedbyoneormore
tab,space,orreturncharacters.Theirorderofappearanceisnotimportant.
Atagattribute'svalue,ifany,followsanequalssign(=)aftertheattributename.
Youmayincludespacesaroundtheequalssignsothatwidth=6,width=6,width=6,
andwidth=6allmeanthesame.Forreadability,however,weprefernottoinclude
spaces.Thatway,it'seasiertopickoutanattribute/valuepairfromacrowdof
pairsinalengthytag.
WithHTML,ifanattribute'svalueisasinglewordornumber(nospaces),you
maysimplyadditaftertheequalssign.Youshouldencloseallothervaluesin
singleordoublequotationmarks,especiallythosevaluesthatcontainseveral
wordsseparatedbyspaces.WithXHTML,allattributevaluesmustbeenclosedin
quotes.Thelengthofthevalueislimitedto1,024characters.
Mostbrowsersaretolerantofhowtagsarepunctuatedandbrokenacrosslines.
Nonetheless,avoidbreakingtagsacrosslinesinyoursourcedocumentwhenever
possible.ThisrulepromotesreadabilityandreducespotentialerrorsinyourHTML
documents.
3.3.2.SampleTags
Herearesometagswithattributes:
<ahref="http://www.oreilly.com/catalog.html">
<ulcompact>
<ulcompact="compact">
<inputtype=textname=filenamesize=24maxlength=80>
<linktitle="TableofContents">
Thefirstexampleisthe<a>tagforahyperlinktoourpublisher'sweb-based
catalogofproducts.Ithasasingleattribute,href,followedbythecatalog's
addressincyberspaceitsURL.
ThesecondexampleshowsanHTMLtagthatformatstextintoanunorderedlist
ofitems.Itssingleattributecompact,whichlimitsthespacebetweenlistitemsdoes
notrequireavalue.
Thethirdexampledemonstrateshowthesecondexamplemustbewrittenin
XHTML.Noticethecompactattributenowhasavalue,albeitaredundantone,and
thatitsvalueisenclosedindoublequotes.
ThefourthexampleshowsanHTMLtagwithmultipleattributes,eachwithavalue
thatdoesnotrequireenclosingquotationmarks.Ofcourse,withXHTML,each
attributevaluemustbeenclosedindoublequotes.
Thelastexampleshowsproperuseofenclosingquotationmarkswhenthe
attributevalueismorethanonewordlong.
WhatisnotimmediatelyevidentintheseexamplesisthatwhileHTMLattribute
namesarenotcase-sensitive(hrefworksthesameasHREFandHreFinHTML),most
attributevaluesarecase-sensitive.Thevaluefilenameforthenameattributeinthe
<input>tagexampleisnotthesameasthevalueFilename,forinstance.
3.3.3.StartingandEndingTags
Wealludedearliertothefactthatmosttagshaveabeginningandanendand
affecttheportionofcontentbetweenthem.Thatenclosedsegmentmaybelarge
orsmall,fromasingletextcharacter,syllable,orwordsuchastheitalicized
"simp"syllableinourbarebonesexampletothe<html>tagthatboundstheentire
document.Thestartingcomponentofanytagisthetagnameanditsattributes,if
any.Thecorrespondingendingtagisthetagnamealone,precededbyaslash(/).
Endingtagshavenoattributes.
3.3.4.ProperandImproperNesting
Youcanputtagsinsidetheaffectedsegmentofanothertag(nested)formultiple
tageffectsonasinglesegmentofthedocument.Forexample,aportionofthe
followingtextisbothboldandincludedaspartofananchordefinedbythe<a>
tag:
<body>
Thisissometextinthebody,witha
<ahref="another_doc.html">link,aportionofwhich
is<b>setinbold.</b></a>
</body>
AccordingtotheHTMLandXHTMLstandards,youmustendnestedtagsby
startingwiththemostrecentoneandworkingyourwaybackoutfirstin,lastout.
Forinstance,inthisexample,weendtheboldtag(</b>)beforeendingthelink
tag(</a>)becausewestartedinthereverseorder:<a>tagfirst,then<b>tag.It'sa
goodideatofollowthatstandard,eventhoughmostbrowsersdon'tabsolutely
insistyoudoso.Youmaygetawaywithviolatingthisnestingruleforone
browser,andsometimesevenwithallcurrentbrowsers.Buteventuallyanew
browserversionwon'tallowtheviolation,andyou'llbehard-pressedtostraighten
outyoursourceHTMLdocument.Also,beawarethattheXHTMLstandard
explicitlyforbidsimpropernesting.
3.3.5.TagsWithoutEnds
AccordingtotheHTMLstandard,afewtagsdonothaveendingtags.Infact,the
standardforbidsuseofanendtagforthesespecialones,althoughmostbrowsers
arelenientandignoretheerrantendtag.Forexample,the<br>tagcausesaline
break;ithasnoeffectotherwiseonthesubsequentportionofthedocumentand,
hence,doesnotneedanendingtag.
TheHTMLtagsthatdonothavecorrespondingendtagsare:
<area> <base> <basefont>
<br> <col> <frame>
<hr> <img> <input>
<isindex> <link> <meta>
<param>
XHTMLalwaysrequiresendtags.[HandlingEmptyElements,16.3.3]
3.3.6.OmittingTags
Youoftenseedocumentsinwhichtheauthorseeminglyhasforgottentoinclude
anendingtag,inapparentviolationoftheHTMLandcertainlytheXHTML
standards.Sometimeseventhe<body>tagismissing.Butyourbrowserdoesn't
complain,andthedocumentdisplaysjustfine.Whatgives?TheHTMLstandard
letsyouomitcertaintagsortheirendingsforclarityandeaseofpreparation.The
HTMLstandardwritersdidn'tintendthelanguagetobetedious.
Forexample,the<p>tagthatdefinesthestartofaparagraphhasacorresponding
endtag,</p>,buttheendtagrarelyisused.Infact,manyHTMLauthorsdon't
evenknowitexists.[<p>,4.1.2]
TheHTMLstandardletsyouomitastartingtagorendingtagwheneveritcanbe
unambiguouslyinferredbythesurroundingcontext.Manybrowsersmakegood
guesseswhenconfrontedwithmissingtags,leadingthedocumentauthorto
assumethatavalidomissionwasmade.
Werecommendthatyoualmostalwaysaddtheendingtag.It'llmakelifeeasier
foryourselfasyoutransitiontoXHTMLaswellasforthebrowserandanyonewho
mightneedtomodifyyourdocumentinthefuture.
3.3.7.IgnoredorRedundantTags
HTMLbrowserssometimesignoretags.Thisusuallyhappenswithredundanttags
whoseeffectsmerelycancelorsubstituteforthemselves.Thebestexampleisa
seriesof<p>tags,oneaftertheother,withnointerveningcontent.Unlikeatext-
processingtool,mostbrowsersstarttoanewlineonlyonce.Theextra<p>tags
areredundantandthebrowserusuallyignoresthem.
Inaddition,mostHTMLbrowsersignoreanytagthattheydon'tunderstandor
thatthedocumentauthorspecifiedincorrectly.Browsershabituallyforgeahead
andmakesomesenseofadocument,nomatterhowbadlyformedanderror
riddenitmaybe.Thisisn'tjustatactictoovercomeerrors;it'salsoanimportant
strategyforextensibility.Imaginehowmuchharderitwouldbetoaddnew
featurestothelanguageiftheexistingbaseofbrowserschokedonthem.
Thethingtowatchoutforwithnonstandardtagsthataren'tsupportedbymost
browsersistheirenclosedcontents,ifany.Browsersthatrecognizethenewtag
mayprocessthosecontentsdifferentlythanthosethatdon'tsupportthenewtag.
Forexample,olderbrowsers,someofwhicharestillinusebymanypeopletoday,
don'tsupportstyles.Dutifully,theyignorethe<style>tag,butthengoonto
renderitscontentsontheuser'sscreen,effectivelydefeatingthetag'spurposein
additiontoruiningthedocument'sappearance.[Document-LevelStylesheets,
8.1.2]
3.4.Well-FormedDocumentsandXHTML
XHTMLisHTML'sprissycousin.Whatwouldpassmostbeautycontestsasavery
properandcompleteHTMLdocument,doneaccordingtothebookandincluding
end-paragraphtags,mightwellberejectedbytheXMLjudgesasamalformed
file.
ToconformwithXML,XHTMLinsiststhatdocumentsbe"wellformed."Among
otherthings,thatmeansthateverytagmusthaveanendingtageventheones
like<br>and<hr>forwhichtheHTMLstandardforbidstheuseofanendtag.With
XHTML,theendingisplacedinsidethestarttag:<br/>,forexample.[Handling
EmptyElements,16.3.3]
Italsomeansthattagandattributenamesarecase-sensitiveand,accordingto
thecurrentXHTMLstandard,mustbeinlowercase.Hence,only<head>is
acceptable,anditisnotthesameas<HEAD>or<HeAd>,asitiswiththeHTML
standard.[CaseSensitivity,16.3.4]
Well-formedXHTMLdocuments,likeHTMLstandardones,mustalsoconformto
propernesting.Noargumentthere.[CorrectlyNestedElements,16.3.1]
Intheirdefense,theXMLstandardanditsoffspring,XHTML,emphasize
extensibility.Thatway,<p>canmeanthebeginningofaparagraphinHTML,
whereasanothervariantofthelanguagemaydefinethecontentsofthe<P>tagto
beelection-pollresultsthatdisplayquitedifferentlyperhapsintabularform,with
red,white,andbluestripesandaccompanyingpatrioticmusic.
WewilldiscussthisfurtherinChapters15and16,inwhichwedetailtheXMLand
XHTMLstandards(andtheForcesofConformity).
3.5.DocumentContent
NearlyeverythingelseyouputintoyourHTMLorXHTMLdocumentthatisn'ta
tagis,bydefinition,content,andthemajorityofthatistext.Liketags,document
contentisencodedusingaspecificcharactersetbydefault,theISO-8859-1Latin
characterset.ThischaractersetisasupersetofconventionalASCII,addingthe
necessarycharacterstosupporttheWesternEuropeanlanguages.Ifyour
keyboarddoesnotallowyoutodirectlyenterthecharactersyouneed,youcan
usecharacterentitiestoinsertthedesiredcharacters.
3.5.1.AdviceVersusControl
PerhapsthehardestruletorememberwhenmarkingupanHTMLorXHTML
documentisthatallthetagsyouinsertregardingtextdisplayandformattingare
onlyadviceforthebrowser:theydonotexplicitlycontrolhowthebrowserwill
displaythedocument.Infact,thebrowsercanchoosetoignoreallofyourtags
anddowhatitpleaseswiththedocumentcontent.What'sworse,theuser(ofall
people!)hascontroloverthetext-displaycharacteristicsofherownbrowser.
Getusedtothislackofcontrol.Thebestwaytousemarkuptocontrolthe
appearanceofyourdocumentsistoconcentrateonthecontentofthedocument,
notonitsfinalappearance.Ifyoufindyourselfworryingexcessivelyabout
spacing,alignment,textbreaks,andcharacterpositioning,you'llsurelyendup
withulcers.YouwillhavegonebeyondtheintentofHTML.Ifyoufocuson
deliveringinformationtousersinanattractivemanner,usingthetagstoadvise
thebrowserastohowbesttodisplaythatinformation,youareusingHTMLor
XHTMLeffectively,andyourdocumentswillrenderwellonawiderangeof
browsers.
3.5.2.CharacterEntities
Besidescommontext,HTMLandXHTMLgiveyouawaytodisplayspecialtext
charactersthatyounormallymightnotbeabletoincludeinyoursource
documentorthathaveotherpurposes.Agoodexampleistheless-thanor
openingbracketsymbol(<).InHTML,itnormallysignifiesthestartofatag,soif
youinsertitsimplyaspartofyourtext,thebrowserwillgetconfusedand
probablymisinterpretyourdocument.
ForbothHTMLandXHTML,theampersandcharacter(&)instructsthebrowserto
useaspecialcharacter,formallyknownasacharacterentity.Forexample,the
command<insertsthatpeskyless-thansymbolintotherenderedtextandthe
browserdoesnotconfuseittomeanthestartofatag.Similarly,>insertsthe
greater-thansymbol,and&insertsanampersand.Therecanbenospaces
betweentheampersand,theentityname,andtherequired,trailingsemicolon.
(Semicolonsaren'tspecialcharacters;youdon'tneedtouseanampersand
sequencetodisplayasemicolonnormally.)[HandlingSpecialCharacters,16.3.7]
Youalsomayreplacetheentitynameaftertheampersandwithapoundsymbol
(#)andadecimalvaluecorrespondingtotheentity'spositioninthecharacterset.
Hence,thesequence<doesthesamethingas<andrepresentstheless-
thansymbol.Infact,youcouldsubstituteallthenormalcontentcharacterswithin
anHTMLdocumentwithampersandspecialcharacters,suchasAforthe
capitalletterAoraforitslowercaseversion,butthatwouldbesilly.Youcan
findacompletelistingofallcharactersandtheirnamesandnumerical
equivalentsinAppendixF.
Keepinmindthatnotallspecialcharacterscanberenderedbyallbrowsers.
Somebrowsersjustignoremanyofthespecialcharacters;withothers,the
charactersaren'tavailableinthecharactersetsonaspecificplatform.Besureto
testyourdocumentsonarangeofbrowsersbeforeelectingtousesomeofthe
moreobscurecharacterentities.
3.5.3.Comments
CommentsareanothertypeoftextualcontentthatappearsinthesourceHTML
documentbutisnotrenderedbytheuser'sbrowser.Commentsfallbetweenthe
special<!and>markupelements.Browsersignorethetextbetweenthecomment
charactersequences.Herearesomesamplecomments:
<!Thisisacomment>
<!Thisisa
multiple-linecomment
thatendsonthisline>
Theremustbeaspaceaftertheinitial<!andprecedingthefinal>,butotherwise
youcanputnearlyanythinginsidethecomment.Thebiggestexceptiontothis
ruleisthattheHTMLstandarddoesn'tletyounestcomments.[*]
[*]EarlyversionsofNetscapedidletyounestcomments,butnolonger.Thepracticeistricky,sojustsayno.
InternetExploreralsoletsyouplacecommentswithinaspecial,nonstandard
<comment>tag.Everythingbetweenthe<comment>and</comment>tagsisignoredby
InternetExplorer.Allotherbrowsersdisplaythecommenttotheuser.Obviously,
becauseofthisundesirablebehavior,wedonotrecommendusingthe<comment>
tag.Instead,alwaysusethe<!--and-->sequencestodelimitcomments.
Besidestheobvioususeofcommentsforsourcedocumentation,manyweb
serversusecommentstotakeadvantageoffeaturesspecifictothedocument
serversoftware.Theseserversscanthedocumentforspecificcharacter
sequenceswithinconventionalHTML/XHTMLcommentsandthenperformsome
actionbaseduponthecommandsembeddedinthecomments.Theactionmight
beassimpleasincludingtextfromanotherfile(knownasaserver-sideinclude)
orascomplexasexecutingothercommandsontheservertogeneratethe
documentcontentsdynamically.
3.6.HTML/XHTMLDocumentElements
EveryHTMLdocumentshouldconformtotheHTMLSGMLDTD,theformal
DocumentTypeDefinitionthatdefinestheHTMLstandard.TheDTDdefinesthe
tagsandsyntaxthatareusedtocreateanHTMLdocument.Youcaninformthe
browserwhichDTDyourdocumentcomplieswithbyplacingaspecialStandard
GeneralizedMarkupLanguage(SGML)commandinthefirstlineofthedocument:
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN">
Thiscrypticmessageindicatesthatyourdocumentisintendedtobecompliant
withtheHTML4.01finalDTDdefinedbytheWorldWideWebConsortium(W3C).
OtherversionsoftheDTDdefinemorerestrictedversionsoftheHTMLstandard,
andnotallbrowserssupportallversionsoftheHTMLDTD.Infact,specifyingany
other<!DOCTYPE>maycausethebrowsertomisinterpretyourdocumentwhen
displayingitfortheuser.It'salsounclearwhat<!DOCTYPE>touseifyouinclude
nonstandard,albeitpopularextensionsintheHTMLdocumentevenforthe
deprecatedHTML3.0standard,forwhichaDTDwasneverreleased.
HTMLdevelopersareincreasinglyincludinganappropriateSGMLDOCTYPE
commandasaprefixintheirHTMLdocuments.Becauseoftheconfusionof
versionsandstandards,ifyoudochoosetoincludeaDOCTYPEinyourHTML
document,choosetheappropriateonetoensurethatyourdocumentisrendered
correctly.
ForXHTMLauthors,wedostronglyrecommendthatyouincludetheproper
DOCTYPEstatementinyourXHTMLdocuments,inconformancewithXML
standards.ReadChapters15and16formoreaboutDTDsandtheXMLand
XHTMLstandards.
3.6.1.The<html>Tag
Aswesawearlier,the<html>and</html>tagsservetodelimitthebeginningand
endofadocument.Sincethetypicalbrowsercaneasilyinferfromtheenclosed
sourcethatitisanHTMLorXHTMLdocument,youdon'treallyneedtoincludethe
taginyoursourceHTMLdocument.
<html>
Function DelimitsacompleteHTMLorXHTMLdocument
Attributes dir ,lang,version
Endtag </html>;maybeomittedinHTML
Contains head_tag,body_tag,frames
Thatsaid,it'sconsideredgoodformtoincludethistagsothatothertools,
particularlymoremundanetext-processingones,canrecognizeyourdocumentas
anHTMLdocument.Attheveryleast,thepresenceofthebeginningandend
<html>tagsensuresthatthebeginningortheendofthedocumenthasnot
inadvertentlybeendeleted.Besides,XHTMLrequiresthe<html>and</html>tags.
Between<html>and</html>arethedocument'sheadandbody.Withinthehead,
you'llfindtagsthatidentifythedocumentanddefineitsplacewithinadocument
collection.Withinthebodyistheactualdocumentcontent,definedbytagsthat
determinethelayoutandappearanceofthedocumenttext.Asyoumightexpect,
thedocumentheadiscontainedwithin<head>and</head>tagsandthebodyis
within<body>and</body>tags,allofwhichwedefineinmoredetaillaterinthis
chapter.[*]
[*]ForthespecialHTML/XHTMLframedocument,a<frameset>tagreplacesthe<body>tag;moreaboutthisin
Chapter11.
Byfar,themostcommonformofthe<html>tagissimply:
<html>
documentheadandbodycontent
</html>
3.6.1.1.Thedirattribute
Thedirattributespecifiesinwhichdirectionthebrowsershouldrendertextwithin
thecontainingelement.Whenusedwithinthe<html>tag,itdetermineshowtext
willbepresentedwithintheentiredocument.Whenusedwithinanothertag,it
controlsthetext'sdirectionforjustthecontentofthattag.
Bydefault,thevalueofthistagisltr,indicatingthattextispresentedtotheuser
lefttoright.Usetheothervalue,rtl,todisplaytextrighttoleft,forlanguages
likeArabicandHebrew.Ofcourse,theresultsdependonyourcontentandthe
browser'ssupportofHTML4orXHTML.NetscapeandInternetExplorerversions4
andearlierignorethedirattribute.TheHTML4-compliantInternetExplorer
versions5and6simplyright-justify(dir=rtl)thetext,althoughifyoulookclosely
atFigure3-2,you'llnoticethatthebrowsermovesthepunctuation(theperiod)
totheothersideofthesentence.Netscape6right-justifiedeverything,including
theendingperiod,butversions7and8didnot(yetanothersignthatthebrowser
warsareover):
<htmldir=rtl>
<head>
<title>DisplayDirections</title>
</head>
<body>
ThisishowIE6rendersright-to-leftdirectedtext.
</body>
</html>
Figure3-2.Allcurrentbrowsersjustright-justifytextwiththe
dirattribute,andgetthepunctuationwrong,toboot
3.6.1.2.Thelangattribute
Whenincludedwithinthe<html>tag,thelangattributespecifiesthelanguage
you'vegenerallyusedwithinthedocument.Whenusedwithinothertags,thelang
attributespecifiesthelanguageyouusedwithinthattag'scontent.Ideally,
browserseventuallywilluselangtobetterrenderthetextfortheuser.
SetthevalueofthelangattributetoanISO-639standardtwo-characterlanguage
code.YoumayalsoindicateadialectbyfollowingtheInternationalOrganization
forStandardization(ISO)languagecodewithadashandasubcodename.For
example,"en"istheISOlanguagecodeforEnglish;"en-US"isthecompletecode
forU.S.English.Othercommonlanguagecodesinclude"fr"(French),"de"
(German),"it"(Italian),"nl"(Dutch),"el"(Greek),"es"(Spanish),"pt"
(Portuguese),"ar"(Arabic),"he"(Hebrew),"ru"(Russian),"zh"(Chinese),"ja"
(Japanese),and"hi"(Hindi).
3.6.1.3.Theversionattribute
UsetheversionattributetodefinetheHTMLstandardversionthatyoufollowed
whencomposingthedocument.Itsvalue,forHTMLversion4.01,shouldread
exactly:
version="-//W3C//DTDHTML4.01//EN"
Ingeneral,versioninformationwithinthe<html>tagismoretroublethanitis
worth,andthisattributehasbeendeprecatedinHTML4.Seriousauthorsshould
insteaduseanSGML<!DOCTYPE>tagatthebeginningoftheirdocuments,likethis:
<!DOCTYPEHTMLPUBLIC"-//W3C/DTDHTML4.01//EN"
"http://www.w3c.org/TR/html4/strict.dtd">
3.7.TheDocumentHeader
Thedocumentheaderdescribesthevariouspropertiesofthedocument,including
itstitle,positionwithintheWeb,andrelationshipwithotherdocuments.Mostof
thedatacontainedwithinthedocumentheaderisneveractuallyrenderedas
contentvisibletotheuser.
3.7.1.The<head>Tag
The<head>tagservestoencapsulateotherheadertags.Placeitatthebeginningof
yourdocument,justafterthe<html>tagandbeforethe<body>or<frameset>tag.
Boththe<head>taganditscorrespondingend</head>tagcanbeunambiguously
inferredbythebrowserandsocanbesafelyomittedfromanHTML,butnotfrom
anXHTML,document.Weencourageyoutoincludetheminallyourdocuments,
sincetheypromotereadabilityandsupportdocumentautomation.
<head>
Function Definesthedocumentheader
Attributes dir,lang,profile
Endtag </head>;rarelyomittedinHTML
Contains head_content
Usedin html_tag
The<head>tagmaycontainanumberofothertagsthathelpdefineandmanage
thedocument'scontent.Theseinclude,inanyorderofappearance:<base>,
<isindex>,<link>,<meta>,<nextid>,<object>,<script>,<style>,and<title>.
3.7.1.1.Thedirandlangattributes
Aswediscussedinthesectionsaboutthe<html>tagattributes,dirandlanghelp
extendHTMLandXHTMLtoaninternationalaudience.[Thedirattribute,3.6.1.1]
[Thelangattribute,3.6.1.2]
3.7.1.2.Theprofileattribute
Often,theheaderofadocumentcontainsanumberof<meta>tagsusedtoconvey
additionalinformationaboutthedocumenttothebrowser.Inthefuture,authors
mayusepredefinedprofilesofstandarddocumentmetadatatobetterdescribe
theirdocuments.TheprofileattributesuppliestheURLoftheprofileassociated
withthecurrentdocument.
Theformatofaprofileandhowabrowsermightuseitarenotyetdefined;this
attributeisprimarilyaplaceholderforfuturedevelopment.
3.7.2.The<title>Tag
The<title>tagdoesexactlywhatyoumightexpect:thewordsyouplaceinsideits
beginningandendtagsdefinethetitleforyourdocument.(Thisstuffispretty
muchself-explanatoryandeasierthanyoumightthinkatfirstglance.)The
browserusesthetitleinsomespecialmanner,anditismostoftenplacedinthe
browserwindow'stitlebaroronastatusline.Usually,too,thetitlebecomesthe
defaultnameforalinktothedocumentifthedocumentisaddedtoalink
collectionortoauser'sfavoritesorbookmarkslist.
<title>
Function Definesthedocumenttitle
Attributes dir,lang
Endtag </title>;neveromitted
Contains plain_text
Usedin head_content
The<title>tagistheonlythingrequiredwithinadocument'shead.Becausethe
<head>tagitselfandeventhe<html>tagcansafelybeomitted,the<title>tagcould
bethefirstlinewithinavalidHTMLdocument.Beyondthat,mostbrowserswill
evensupplyagenerictitlefordocumentslackinga<title>tag,suchasthe
document'sfilename,soyoudon'tevenhavetosupplyatitle.Thatgoesabittoo
farevenforourdown-and-dirtytastes,though.Norespectableauthorshould
serveupadocumentmissingthe<title>tagandatitle.
Whenyoudoincludea<title>,don'tforgettocloseitwiththe</title>endtag.
Otherwise,yourtitle'stextendsupdisplayedinthebodyofyourdocument,even
thoughitmayprecedethe<body>tag.
Browsersdonotspeciallyformattitletext,andtheyignoreanythingotherthan
textinsidethetitlebeginningandendtags.Forinstance,theywillignoreany
imagesorlinkstootherdocuments.
Here'sanevenbarerbarebonesexampleofavalidHTMLdocument,tohighlight
theheaderandtitletags;watchwhathappenswhenNetscapedisplaysitinFigure
3-3:
<html>
<head>
<title>HTMLandXHTML:TheDefinitiveGuide</title>
</head>
</html>
Figure3-3.What'sina<title>?
3.7.2.1.What'sinatitle?
Selectingtherighttitleiscrucialtodefiningadocumentandensuringthatitcan
beeffectivelyusedontheWeb.
Keepinmindthatuserscanaccesseachdocumentinyourcollectioninnearlyany
orderandindependentlyofoneanother.Eachdocument'stitleshouldtherefore
definethedocumentbothwithinthecontextofyourotherdocumentsandonits
ownmerits.
Titlesthatincludereferencestodocumentsequencingareusuallyinappropriate.
Simpletitles,like"Chapter2"and"PartVI,"dolittletohelpauserunderstand
whatthedocumentmightcontain.Moredescriptivetitles,suchas"Chapter2:
AdvancedSquareDancing"and"PartVI:Churchill'sYouthandAdulthood,"convey
bothasenseofplacewithinalargersetofdocumentsandspecificcontentthat
invitesthereadertoreadon.
Self-referentialtitlesalsoaren'tveryuseful.Atitlesuchas"HomePage"is
completelycontent-free,asaretitleslike"FeedbackPage"and"PopularLinks."
Youwantatitletoconveyasenseofcontentandpurposesothatuserscan
decide,baseduponthetitlealone,whethertovisitthatpage."TheKumquat
Lover'sHomePage"isdescriptiveandlikelytodrawinloversofthebitterfruit,as
are"KumquatLover'sFeedbackPage"and"PopularLinksFrequentedbyKumquat
Lovers."
PeoplespendagreatdealoftimecreatingdocumentsfortheWeb,oftenonlyto
squanderthateffortwithanuninviting,ineffectivetitle.Asspecialsoftwarethat
automaticallycollectslinksforusersbecomesmoreprevalentontheWeb,the
onlydescriptivephrasesassociatedwithyourpageswhentheyareinsertedinto
somevastlinkdatabasewillbethetitlesyouchooseforthem.Wecan't
emphasizethisenough:takecaretoselectdescriptive,useful,context-
independenttitlesforeachofyourdocuments.
3.7.2.2.Thedirandlangattributes
ThedirandlangattributeshelpextendHTMLandXHTMLtoaninternational
audience.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
3.7.3.RelatedHeaderTags
Othertagsyoumayincludewithinthe<head>tagdealwithspecificaspectsof
documentcreation,management,linking,automation,orlayout.That'swhywe
onlymentionthemhereanddescribethemingreaterdetailinother,more
appropriatesectionsandchaptersofthisbook.Briefly,thespecialheadertags
are:
<base>and<link>
Definethecurrentdocument'sbaselocationandrelationshiptoother
documents.[<base>,6.7.1][<link>,6.7.2]
<isindex>
DeprecatedinHTML4,the<isindex>tagatonetimecouldbeusedtocreate
automaticdocumentindexingforms,allowinguserstosearchdatabasesof
informationusingthecurrentdocumentasaqueryingtool.[<isindex>,6.6.1]
<nextid>
NotsupportedinHTML4orXHTML,the<nextid>tagtriedtomakecreationof
uniquelabelseasierwhenusingdocumentautomationtools.[<nextid>,
6.8.2]
<meta>
Providesadditionaldocumentdatanotsuppliedbyanyoftheother<head>
tags.[<meta>,6.8.1]
<object>
Definesmethodsbywhichthebrowsercanrendernonstandardobjects.
[<object>,12.2.1]
<script>
Definesoneormorescriptsthatelementswithinthedocumentcaninvoke.
[<script>,12.3.1]
<style>
LetsyoucreateCascadingStyleSheet(CSS)propertiestocontrolbody-
contentdisplaycharacteristicsfortheentiredocument.[<style>,8.1.2]
3.8.TheDocumentBody
Thedocumentbodyisthemeatofthematter.It'swhereyouputthecontentsof
yourdocument.Thebeginning<body>andend</body>tagsdelimitthedocument
body.
3.8.1.The<body>Tag
WithinHTML4andXHTML,the<body>taghasanumberofattributesthatcontrol
thecolorandbackgroundofyourdocument.Variousbrowsershaveextendedthe
tagtogiveevengreatercontroloveryourdocument'sappearance.
<body>
Function Definesthedocumentbody
Attributes
alink,background,bgcolor,bgproperties,class,dir,id,lang,leftmargin,link,onBlur,
onClick,onDblClick,onFocus,onKeyDown,onKeyPress,onKeyUp,onLoad,onMouseDown,
onMouseMove,onMouseOut,onMouseOver,onMouseUp,onUnload,style,text,title,
topmargin,vlink
Endtag </body>;maybeomittedinHTML
Contains body_content
Usedin html_tag
Anythingbetweenthebeginning<body>andend</body>tagsiscalledbodycontent.
Thesimplestdocumentmighthaveonlyasequenceoftextparagraphswithinthe
<body>tag.Morecomplexdocumentsmightincludeheavilyformattedtext,
graphicalfigures,tables,andavarietyofspecialeffects.
Becausethebrowsercaninferthepositionofthe<body>and</body>tags,theycan
safelybeomittedfromanHTML,butnotanXHTML,document.Likethe<html>and
<head>tags,werecommendthatyouincludeboththe<body>and</body>tagsinyour
HTMLdocuments,too,tomakethemmoreeasilyreadableandmaintainable.
Thevariousattributesforthe<body>tagcanbelooselygroupedintothreesets:
thosethatgiveyousomecontroloverthedocument'sappearance,thosethat
associateprogrammablefunctionswiththedocumentitself,andthosethatlabel
andidentifythebodyforlaterreference.Weaddresstheappearanceattributes
(alink,background,bgcolor,bgproperties,leftmargin,link,text,topmargin,andvlink)in
Chapter5;theclassandstyleattributesforCSSinChapter8;JavaScript
stylesheetsandtheprogrammaticattributes(the"on-event"ones)inChapter12;
thelanguageattributes(dirandlang)earlierinthischapter;andtheidentification
attributes(idandtitle)inChapter4.[Thedirattribute,3.6.1.1][Thelang
attribute,3.6.1.2][Theidattribute,4.1.1.4][Thetitleattribute,4.1.1.5]
3.8.2.Frames
TheHTMLandXHTMLstandardsdefineaspecialtypeofdocumentinwhichyou
replacethe<body>tagwithoneormore<frameset>tags.Thisso-calledframe
documentdividesthedisplaywindowintooneormoreindependentwindows,
eachdisplayingadifferentdocument.Wethoroughlydescribethisinnovationin
Chapter11.
3.9.EditorialMarkup
HTML4.0introducedtwotagsthatcanhelpgroupsofauthorscollaborateinthe
developmentofdocumentsandmaintainsomesemblanceofeditorialandversion
control.Theinsert(<ins>)anddelete(<del>)tagsrespectivelyletyoueither
designateportionsofyourdocument'sbodyasneworaddedcontentordesignate
oldstuffthatshouldbereplaced.Andwithspecialattributes,youcanindicate
whenyoumadethechange(datetime)andareferencetoadocumentthatmay
explainthechange(cite).
3.9.1.The<ins>and<del>Tags
The<ins>and<del>tagsletauthorssetoffportionsofbodycontentthatthey
intendtoaddtoordeletefromthecurrentversionsoftheirdocuments.HTML
4/XHTML-compliantbrowsersdisplaythecontentsofthe<ins>and<del>tagsin
somespecialwaysothatreaderscanquicklyscanthedocumentforthechanges.
<ins>and<del>
Function Defineinsertedanddeleteddocumentcontent(seeFigure3-4)
Attributes cite,class,datetime,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,
onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </ins>and</del>;neveromitted
Contains body_content
Usedin body_content
Netscape4andearlierversionsignorethetags,asdidInternetExplorer4andits
earlierversions.Allcurrentpopularbrowsersnowsupportthetags.
Figure3-4.The<ins>and<del>tagsinaction
3.9.1.1.Theciteattribute
Theciteattributeletsyoudocumentthereasonsfortheinsertionordeletion.Its
valuemustbeaURLthatpointstosomeotherdocumentthatexplainsthe
inserted/deletedtext.Howabrowsertreatsciteisaquestionforthefuture.
3.9.1.2.Thedatetimeattribute
Althoughthereasonforthechangeisimportant,knowingwhenachangewas
madeisoftenmoreimportant.Thedatetimeattributeforthe<ins>and<del>tags
takesasinglevalue:aspeciallyencodeddateandtimestamp.Therigorousformat
forthedatetimevalueisYYYY-MM-DDThh:mm:ssTZD.Thecomponentsare:
YYYYistheyear,suchas1998or2010.
MMisthemonth;01forJanuarythrough12forDecember.
DDistheday;01through31.
Tisarequiredcharacterdesignatingthebeginningofthetimesegmentofthe
stamp.
hhisthehourin24-hourformat;00(midnight)through23(11p.m.).(Adda
followingcolonifyouincludetheminutes.)
mmaretheminutesonthehour;00through59.(Addafollowingcolonifyou
includetheseconds.)
ssaretheseconds;00through59.
TZDisthetime-zonedesignator.Itcanbeoneofthreevalues:Z,indicating
GreenwichMeanTime,[*]orthehours,minutes,andsecondsbefore(-)or
after(+)CoordinatedUniversalTime(UTC),wheretimeisrelativetothetime
inGreenwich,England.
[*]GreenwichMeanTimeisalsoknowas"Zulu,"thusthevalueof"Z."
Forexample:
2007-02-22T14:26Z
decodestoFebruary22,2007at2:26p.m.GreenwichMeanTime.Tospecify
EasternStandardTime,thecodeforthesametimeanddateis:
2003-02-22T09:26-05:00
Noticethatthelocaltimezonemaychangedependingonwherethedocument
getsedited,whereastheuniversaltimewillstaythesame.
3.9.1.3.Theclass,dir,event,id,lang,style,title,andeventsattributes
ThereareseveralnearlyuniversalattributesforthemanyHTMLandXHTMLtags.
Theseattributesgiveyouacommonwaytoidentify(title)andlabel(id)atag's
contentsforlaterreferenceorautomatedtreatment,tochangethecontents'
displaycharacteristics(class,style),andtoreferencethelanguageused(lang)and
relateddirectionthetextshouldflow(dir).Therearealsoinputeventsthatmay
happeninandaroundthetaggedcontentsthatyoumayreacttoviaanon-event
attributeandsomeprogramming.[Thedirattribute,3.6.1.1][Thelangattribute,
3.6.1.2][Theidattribute,4.1.1.4][Theidattribute,4.1.1.4][InlineStyles:The
styleAttribute,8.1.1][StyleClasses,8.3][JavaScriptEventHandlers,12.3.3]
3.9.2.UsingEditorialMarkup
Theusesof<ins>and<del>areobvioustoanyonewhohasuseda"boilerplate"
documentorformorhascollaboratedwithothersinthepreparationofa
document.
Forexample,lawfirmstypicallyhaveacollectionofonlinelegaldocumentsthat
arespeciallycompletedforeachclient.Lawclerksusuallydothe"fillin,"andthe
finaldocumentgetsreviewedbyalawyer.Tohighlightthosechangesinthe
documentsothattheyarereadilyevidenttothereviewer,youmightusethe<ins>
tagtoindicateaddedtextandthe<del>tagtomarkthetextthatwasreplaced.
Optionally,usetheciteanddatetimeattributestoindicatewhyandwhenthe
changesweremade.
Forexample,theclerkmightfillinaboilerplatedocumentwiththelawfirm'sand
representative'snames,indicatingthetimeandsourceforthechange:
Thepartyofthefirstpart,asrepresentedby
<insdatetime=2002-06-22T08:30Z
cite="http://www.mull+dull.com/tom_muller.html">
ThomasMullerofMullerandDuller
</ins>
<del>[insertrepresentationhere]</del>
Theeditorialmarkuptagscouldalsobeusedbyeditingtoolstodenotehow
documentsweremodifiedasauthorsmakechangesoveraperiodoftime.With
thecorrectuseoftheciteanddatetimeattributes,itwouldbepossibletorecreate
aversionofadocumentfromaspecificpointintime.
3.10.The<bdo>Tag
Aswementionedearlier,theauthorsoftheHTML4standardmadeaconcerted
efforttoincludestandardwaysthatwebagents(browsers)aresupposedtotreat
anddisplaythemanydifferenthumanlanguagesanddialects.Accordingly,the
HTML4standardanditsprogeny,XHTML,containtheuniversaldirandlang
attributesthatletyouexplicitlyadvisethebrowserthatthewholedocumentor
specifictaggedsegmentswithinitareinaparticularlanguage.Theselanguage-
relatedattributes,then,mayaffectsomedisplaycharacteristics;forexample,the
dirattributetellsthebrowsertowritethewordsacrossthedisplayfromeither
lefttoright(dir=ltr),asformostWesternlanguages,orrighttoleft(dir=rtl),as
formanyAsianlanguages.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
ThevariousUnicodeandISOstandardsforlanguageencodinganddisplaymay
conflictwithyourbestintentions.Inparticular,thecontentsofsomeother
documents,suchasaMultipurposeInternetMailExtension(MIME)-encodedfile,
mayalreadybeproperlyformatted,andyourdocumentmaymisadvisethe
browsertoundothatencoding.Hence,theHTML4andXHTMLstandardshavethe
<bdo>tag.Withit,youoverrideanycurrentandinheriteddirspecifications.And
withthetag'srequireddirattribute,youdefinitivelyspecifythedirectioninwhich
thetag'scontentsshouldbedisplayed.
Forexample,Figure3-5showshowInternetExplorerhandlesthefollowingHTML
fragmentcontaininga<bdo>redirection:
<bdodir=rtl>ThiswouldbereadableifinChinese,perhaps.</bdo>
BacktotheWesternwayofreadingandwriting.
Figure3-5.Trickswith<bdo>redirectedtextflow
Admittedly,theeffectsofthe<bdo>tagareabitesoteric,andtheopportunitiesto
useitcurrentlyarerare.
<bdo>
Function Overridesbidirectionalalgorithmsforcontentdisplay
Attributes class,dir,id,lang,style,title
Endtag </bdo>;neveromitted
Contains text
Usedin body_content
Chapter4.TextBasics
Anysuccessfulpresentation,evenathoughtfultome,shouldhaveitstext
organizedintoanattractive,effectivedocument.Organizingtextintoattractive
andeffectivedocumentsisHTMLandXHTML'sforte.Thelanguagesgiveyoua
numberoftoolsthathelpyoumoldyourtextandgetyourmessageacross.They
alsohelpstructureyourdocumentsothatyourtargetaudiencehaseasyaccessto
yourwords.
Alwayskeepinmindwhiledesigningyourdocuments(herewegoagain!)thatthe
markuptags,particularlywithregardtotext,onlyadvisetheydonotdictatehowa
browserwillultimatelyrenderthedocument.Renderingvariesfrombrowserto
browser.Don'tgettooentangledwithtryingtogetjusttherightlookandlayout.
Yourattemptsmayandprobablywillbethwartedbythebrowser.
4.1.DivisionsandParagraphs
Likemosttextprocessors,abrowserwrapsthewordsitfindstofitthehorizontal
widthofitsviewingwindow.Widenthebrowser'swindow,andwords
automaticallyflowupwardtofillthewiderlines.Squeezethewindow,andwords
wrapdownward.
Unlikemosttextprocessors,however,HTMLandXHTMLuseexplicitdivision
(<div>),paragraph(<p>),andline-break(<br>)tagstocontrolthealignmentand
flowoftext.Returncharacters,althoughquiteusefulforreadabilityofthesource
document,typicallyareignoredbythebrowserauthorsmustusethe<br>tagto
explicitlyforceacommontextlinebreak.The<p>tag,whilealsocausingaline
break,carrieswithitmeaningandeffectsbeyondasimplereturn.
The<div>tagisalittledifferent.WhenoriginallycodifiedintheHTML3.2
standard,<div>wasmeanttobeasimpleorganizationaltooltodividethe
documentintodiscretesections.Thatsomewhatobtusemeaningmeantfew
authorsusedit.Butrecentinnovations(alignment,styles,andtheidattributefor
documentreferencingandautomation)nowletyoumoredistinctlylabeland
therebydefineindividualsectionsofyourdocuments,aswellascontrolthe
alignmentandappearanceofthosesections.Thesefeaturesbreathereallifeand
meaningintothe<div>tag.
Byassociatinganidandaclassnamewiththevarioussectionsofyourdocument,
eachdelimitedbya<divid=nameclass=name>tagandattributes(youcandothesame
withothertags,like<p>,too),younotonlylabelthosedivisionsforlaterreference
byahyperlinkandforautomatedprocessingandmanagement(collectingallthe
bibliographydivisions,forinstance),butyoumayalsodefinedifferent,distinct
displaystylesforthoseportionsofyourdocument.Forinstance,youmightdefine
onedivisionalclassforyourdocument'sabstract(<divclass=abstract>,for
example),anotherforthebody,athirdfortheconclusion,andafourthdivisional
classforthebibliography(<divclass=biblio>,forexample).
Eachclass,then,mightbegivenadifferentdisplaydefinitioninadocument-level
orexternallyrelatedstylesheet:forexample,theabstractindentedandinan
italictypeface(suchasdiv.abstract{left-margin:+0.5in;font-style:italic});the
bodyinaleft-justifiedromantypeface;theconclusionsimilartotheabstract;and
thebibliographyautomaticallynumberedandformattedappropriately.
Weprovideadetaileddescriptionofstylesheets,classes,andtheirapplicationsin
Chapter8.
4.1.1.The<div>Tag
AsdefinedintheHTML4.01andXHTML1.0and1.1standards,a<div>tagdivides
yourdocumentintoseparate,distinctsections.Itmaybeusedstrictlyasan
organizationaltool,withoutanysortofformattingassociatedwithit,butit
becomesmoreeffectiveifyouaddtheidandclassattributestolabelthedivisions.
The<div>tagalsomaybecombinedwiththealignattributetocontrolthe
alignmentofwholesectionsofyourdocument'scontentinthedisplayandwith
themanyprogrammatic"onevent"attributesforuserinteraction.
<div>
Function Definesablockoftext
Attributes align,class,dir,id,lang,nowrap ,onClick,onDblClick,onKeyDown,onKeyPress,
onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </div>;usuallyomittedinHTML
Contains body_content
Usedin block
4.1.1.1.Thealignattribute
Thealignattributefor<div>positionstheenclosedcontenttotheleft(default),
center,orrightofthedisplay.Inaddition,youcanspecifyjustifytoalignboththe
leftandtherightmarginsofthetext.The<div>tagmaybenested,andthe
alignmentofthenested<div>tagtakesprecedenceoverthecontaining<div>tag.
Further,othernestedalignmenttags,suchas<center>,alignedparagraphs(see<p>
insection4.1.2),orspeciallyalignedtablerowsandcellsoverridetheeffectsof
<div>.Likethealignattributeforothertags,itisdeprecatedintheHTMLand
XHTMLstandardsindeferencetostylesheet-basedlayoutcontrols.
4.1.1.2.Thenowrapattribute
SupportedbyInternetExplorerandOpera,butnotFirefoxorNetscapeNavigator,
thenowrapattributesuppressesautomaticwordwrappingofthetextwithinthe
division.Linebreakswilloccuronlywhereyouhaveplacedcarriagereturnsin
yoursourcedocument.
Whilethenowrapattributeprobablydoesn'tmakemuchsenseforlargesectionsof
textthatwouldotherwisebeflowedtogetheronthepage,itcanmakethingsabit
easierwhencreatingblocksoftextwithmanyexplicitlinebreaks:poetry,for
example,oraddresses.Youdon'thavetoinsertallthoseexplicit<br>tagsina
textflowwithina<divnowrap>tag.Ontheotherhand,alargenumberofusers
withbrowsersthatignorethenowrapattributewillseeyourtextflowmerrilyalong.
IfyouaretargetingonlyInternetExplorerorOperawithyourdocuments,
considerusingnowrapwhereneeded,butotherwise,wecan'trecommendthis
attributeforgeneraluse.
4.1.1.3.Thedirandlangattributes
Thedirattributeletsyouadvisethebrowserinwhichdirectionthetextshouldbe
displayed,andthelangattributeletsyouspecifythelanguageusedwithinthe
division.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
4.1.1.4.Theidattribute
Usetheidattributetolabelthedocumentdivisionforlaterreferencebya
hyperlink,stylesheet,applet,orotherautomatedprocess.Ingeneral,an
acceptableidvalueisanyquote-enclosedstringthatuniquelyidentifiesthe
divisionandthatlatercanbeusedtoreferencethatdocumentsection
unambiguously.Specifically,thevaluemustbeginwithaletter,andcancontain
letters,numbers,hyphens,colons,underscores,andperiods,butnotspaces.
Althoughwe'reintroducingitwithinthecontextofthe<div>tag,thisattributecan
beusedwithalmostanytag.
Whenusedasanelementlabel,thevalueoftheidattributecanbeaddedtoa
URLtoaddressthelabeledelementuniquelywithinthedocument.Youcanlabel
bothlargeportionsofcontent(viaataglike<div>)andsmallsnippetsoftext
(usingataglike<i>or<span>).Forexample,youmightlabeltheabstractofa
technicalreportusing<divid="abstract">.AURLcouldjumprighttothatabstract
byreferencingreport.html#abstract.Whenusedinthismanner,thevalueoftheid
attributemustbeuniquewithrespecttoallotheridattributeswithinthe
documentandallthenamesdefinedbyany<a>tagswiththenameattribute.
[LinkingWithinaDocument,6.3.3]
Whenusedasastylesheetselector,thevalueoftheidattributeisthenameofa
stylerulethatcanbeassociatedwiththecurrenttag.Thisprovidesasecondset
ofdefinablestylerules,similartothevariousstyleclassesyoumaycreate.Atag
canuseboththeclassandtheidattributestoapplytwodifferentrulestoasingle
tag.Inthiscase,thenameassociatedwiththeidattributemustbeuniquewith
respecttoallotherstyleIDswithinthecurrentdocument.Youcanfindamore
completedescriptionofstyleclassesandIDsinChapter8.
4.1.1.5.Thetitleattribute
Usetheoptionaltitleattributeandquote-enclosedstringvaluetoassociatea
descriptivephrasewiththedivision.Liketheidattribute,thetitleattributecan
beusedwithalmostanytagandbehavessimilarlyforalltags.
Thereisnostandards-definedusageforthevalueofthetitleattribute,but
currentbrowsersdisplaythetitlewhenthemousepausesoverthatelementin
thiscase,anywhereinthe<div>-definedtextarea.Forexample,usethetitle
attributetoprovidehelpfultipswithinyourdocument.
4.1.1.6.Theclassandstyleattributes
Usethestyleattributewiththe<div>tagtocreateaninlinestyleforthecontent
enclosedbythetag.Theclassattributeletsyouapplythestyleofapredefined
classofthe<div>tagtothecontentsofthisdivision.Thevalueoftheclass
attributeisthenameofastyledefinedinsomedocument-levelorexternally
definedstylesheet.Inaddition,class-identifieddivisionslendthemselveswellto
computerprocessingofyourdocuments;forexample,extractingalldivisionswith
theclassname"biblio,"fortheautomatedassemblyofamasterbibliography.
[InlineStyles:ThestyleAttribute,8.1.1][StyleClasses,8.3]
4.1.1.7.Eventattributes
Manyuser-relatedeventsmayhappeninandaroundadivision,suchaswhena
userclicksordouble-clicksthemousewithinitsdisplayspace.Thebrowser
recognizestheseeventsifitconformstothecurrentHTMLorXHTMLstandard(all
thepopularonesdo).Withtherespectiveonattributeandvalue,youmayreactto
thoseeventsbydisplayingauserdialogboxoractivatingsomemultimediaevent.
[JavaScriptEventHandlers,12.3.3]
4.1.2.The<p>Tag
The<p>tagsignalsthestartofaparagraph.That'snotwellknownevenbysome
veteranwebmasters,becauseitrunscounterintuitivetowhatwe'vecometo
expectfromexperience.Mostwordprocessorswe'refamiliarwithusejustone
specialcharacter,typicallythereturncharacter,tosignaltheendofaparagraph,
notthebeginning.Bycontrast,inHTMLandXHTML,eachparagraphshouldstart
withtheparagraphtag<p>andendwiththecorresponding</p>endtag.Moreover,
whileaseriesofnewlineorreturncharactersinatextprocessor-displayed
document,createdwhentheauthorhitstheEnterkeyrepeatedly,createsan
emptyparagraphforeachone,browserstypicallyignoreallbutthefirst
paragraphtag,aswellasnewlinecharacters.
Inpractice,withHTMLyoucanignorethestarting<p>tagatthebeginningofthe
firstparagraphandthe</p>tagsattheendofeachparagraph:theycanbe
impliedfromothertagsthatoccurinthedocumentandhencesafelyomitted.[*]
Forexample:
[*]XHTML,ontheotherhand,requiresexplicitstartingandendingtags.
<body>
Thisisthefirstparagraph,attheverybeginningofthebodyof
thisdocument.
<p>
Thetagabovesignalsthestartofthissecondparagraph.Whenrendered
byabrowser,itwillbeginslightlybelowtheendofthefirstparagraph,
withabitofextrawhitespacebetweenthetwoparagraphs.
<p>
Thisisthelastparagraphintheexample.
</body>
Noticethatwehaven'tincludedtheparagraphstarttag(<p>)forthefirst
paragraphoranyendparagraphtags;theycanbeunambiguouslyinferredbythe
HTMLbrowserandarethereforeunnecessary.
<p>
Function Definesaparagraphoftext
Attributes align,class,dir,id,lang,onDblClick,onKeyDown,onKeyPress,onKeyUp,onMouseDown,
onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </p>;oftenomittedinHTML
Contains text
Usedin block
Ingeneral,you'llfindthathumandocumentauthorstendtoomitpostulatedtags
wheneverpossible,andautomaticdocumentgeneratorstendtoinsertthem.That
maybebecausethesoftwaredesignersdidn'twanttoruntheriskofhavingtheir
productschidedbycompetitorsasnotadheringtotheHTMLstandard,even
thoughwe'resplittingletter-of-the-lawhairshere.Goaheadandbedefiant:omit
thatfirstparagraph's<p>taganddon'tgiveasecondthoughttoparagraph-ending
</p>tagsprovided,ofcourse,thatyourdocument'sstructureandclarityarenot
compromised(thatis,aslongasyouareawarethatXHTMLfrownsseverelyon
suchlaxity,too).
4.1.2.1.Paragraphrendering
Whenencounteringanewparagraph(<p>)tag,thebrowsertypicallyinsertsone
blanklineplussomeextraverticalspaceintothedisplaybeforestartingthenew
paragraph.Thebrowserthencollectsallthewordsand,ifpresent,inlineimages
intothenewparagraph,ignoringleadingandtrailingspaces(notspacesbetween
words,ofcourse)andreturncharactersinthesourcetext.Thebrowsersoftware
thenflowstheresultingsequenceofwordsandimagesintoaparagraphthatfits
withinthemarginsofitsdisplaywindow,automaticallygeneratinglinebreaksas
neededtowrapthetextwithinthewindow.Forexample,comparehowabrowser
arrangesthetextintolinesandparagraphs(Figure4-1)tohowthepreceding
exampleisprintedonthepage.Thebrowsermayalsoautomaticallyhyphenate
longwords,andtheparagraphmaybefull-justifiedtostretchthelineofwords
outtowardbothmargins.
Figure4-1.Browsersignorecommonreturncharactersinthe
sourceHTML/XHTMLdocument
Thenetresultisthatyoudonothavetoworryaboutlinelength,wordwrap,and
linebreakswhencomposingyourdocuments.Thebrowserwilltakeanyarbitrary
sequenceofwordsandimagesanddisplayanicelyformattedparagraph.
Ifyouwanttocontrollinelengthandbreaksexplicitly,considerusinga
preformattedtextblockwiththe<pre>tag.Ifyouneedtoforcealinebreak,use
the<br>tag.[<pre>,4.6.5][<br>,4.6.1]
4.1.2.2.Thealignattribute
Mostbrowsersautomaticallyleft-justifyanewparagraph.Tochangethisbehavior,
HTML4andXHTMLgiveyouthealignattributeforthe<p>tagandprovidefour
kindsofcontentjustification:left,right,center,andjustify.
Figure4-2showstheeffectofvariousalignmentsasrenderedfromthefollowing
source:
<palign=right>
Rightoverhere!
<br>
Thisistoo.
<palign=left>
Slidebackleft.
<palign=center>
Smackinthemiddle.
</p>
Leftisthedefault.
Figure4-2.Effectofthealignattributeonparagraph
justification
NoticeintheHTMLexamplethattheparagraphalignmentremainsineffectuntil
thebrowserencountersanother<p>tagoranending</p>tag.Wedeliberatelyleft
outafinal<p>tagintheexampletoillustratetheeffectsofthe</p>endtagon
paragraphjustification.Otherbodyelementsincludingforms,headers,tables,and
mostotherbodycontent-relatedtagsmayalsodisruptthecurrentparagraph
alignmentandcausesubsequentparagraphstoreverttothedefaultleft
alignment.
NotethatthealignattributeisdeprecatedinHTML4andXHTML,indeferenceto
stylesheet-basedalignments.
4.1.2.3.Thedirandlangattributes
Thedirattributeletsyouadvisethebrowserinwhichdirectionthetextwithinthe
paragraphshouldbedisplayed,andthelangattributeletsyouspecifythe
languageusedwithinthatparagraph.Thedirandlangattributesaresupportedby
thepopularbrowsers,eventhoughtherearenobehaviorsdefinedforanyspecific
language.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
4.1.2.4.Theclass,id,style,andtitleattributes
Usetheidattributetocreatealabelfortheparagraphthatcanlaterbeusedto
unambiguouslyreferencethatparagraphinahyperlinktarget,forautomated
searches,asastylesheetselector,andwithahostofotherapplications.[Theid
attribute,4.1.1.4]
Usetheoptionaltitleattributeandquote-enclosedstringvaluetoprovidea
descriptivephrasefortheparagraph.[Thetitleattribute,4.1.1.5]
Usethestyleattributewiththe<p>tagtocreateaninlinestylefortheparagraph's
contents.Theclassattributeletsyoulabeltheparagraphwithanamethatrefers
toapredefinedclassofthe<p>tagpreviouslydeclaredinsomedocument-levelor
externallydefinedstylesheet.Class-identifiedparagraphslendthemselveswellto
computerprocessingofyourdocumentsforexample,extractingallparagraphs
whoseclassnameis"citation,"forautomatedassemblyofamasterlistof
citations.[InlineStyles:ThestyleAttribute,8.1.1][StyleClasses,8.3]
4.1.2.5.Eventattributes
Aswithdivisions,abrowserrecognizesmanyuser-initiatedevents,suchaswhen
auserclicksordouble-clickswithinatag'sdisplayspace,ifthebrowserconforms
tothecurrentHTMLorXHTMLstandard.Withtherespectiveonattributeand
value,youmayreacttothoseeventsbydisplayingauserdialogboxoractivating
somemultimediaevent.[JavaScriptEventHandlers,12.3.3]
4.1.2.6.Allowedparagraphcontent
Aparagraphmaycontainanyelementallowedinatextflow,including
conventionalwordsandpunctuation,links(<a>),images(<img>),linebreaks(<br>),
fontchanges(<b>,<i>,<tt>,<u>,<strike>,<big>,<small>,<sup>,<sub>,and<font>),and
content-basedstylechanges(<acronym>,<cite>,<code>,<dfn>,<em>,<kbd>,<samp>,
<strong>,and<var>).Ifanyotherelementoccurswithintheparagraph,itimplies
thattheparagraphhasended,andthebrowserassumesthattheclosing</p>tag
wasnotspecified.
4.1.2.7.Allowedparagraphusage
Youmayspecifyaparagraphonlywithinablock,alongwithotherparagraphs,
lists,forms,andpreformattedtext.Ingeneral,thismeansthatparagraphscan
appearwhereaflowoftextisappropriate,suchasinthebodyofadocument,in
anelementinalist,andsoon.Technically,paragraphscannotappearwithina
header,anchor,orotherelementwhosecontentisstrictlytext-only.Inpractice,
mostbrowsersignorethisrestrictionandformattheparagraphasapartofthe
containingelement.
4.2.Headings
Usershaveahardenoughtimereadingwhat'sdisplayedonascreen.Alongflow
oftext,unbrokenbytitle,subtitles,andotherheaders,crossestheeyesand
numbsthemind,nottomentionthefactthatitmakesitnearlyimpossibletoscan
thetextforaspecifictopic.
Youshouldalwaysbreakaflowoftextintoseveralsmallersectionswithinoneor
moreheadings(likethisbook).TherearesixlevelsofHTML/XHTMLheadingsthat
youcanusetostructureatextflowintoamorereadable,moremanageable
document.And,aswediscussinChapters5and8,thereareavarietyof
graphicalandtext-styletricksthathelpdivideyourdocumentandmakeits
contentsmoreaccessibleaswellasmorereadable.
4.2.1.HeadingTags
Thesixheadingtagswrittenas<h1>,<h2>,<h3>,<h4>,<h5>,and<h6>indicatethe
highest(<h1>)tolowest(<h6>)precedenceaheadingmayhaveinthedocument.
<h1>,<h2>,<h3>,<h4>,<h5>,<h6>
Function Defineoneofsixlevelsofheaders
Attributes align,class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </h1>,</h2>,</h3>,</h4>,</h5>,</h6>;neveromitted
Contains text
Usedin body_content
Thetextenclosedwithinaheadingtypicallyisrenderedbythebrowseruniquely,
dependinguponthedisplaytechnologyavailabletoit.Thebrowsermaychooseto
center,formatinboldface,enlarge,italicize,underline,orchangethecolorof
headingstomakeeachstandoutwithinthedocument.Andinordertothwartthe
mosttediouswriters,oftenusersthemselvescanalterhowabrowserrendersthe
differentheadings.
Fortunately,inpracticemostbrowsersuseadiminishingcharacterpointsizefor
thesequenceofheaderssothat<h1>textisquitelargeand<h6>textisquite
minuscule(seeFigure4-3,forexample).
Figure4-3.Browserstypicallyusediminishingtextsizesfor
renderingheadings
Bytradition,authorshavecometouse<h1>headersfordocumenttitles,<h2>
headersforsectiontitles,andsoon,oftenmatchingthewaymanyofuswere
taughttooutlineourworkwithheads,subheads,andsub-subheads.
Finally,don'tforgettoincludetheappropriateheadingendtagsinyour
document.Thebrowserwon'tinsertthemautomaticallyforyou,andomittingthe
endingtagforaheadingcanhavedisastrousconsequencesforyourdocument.
4.2.1.1.Thealignattribute
Thedefaultheadingalignmentformostbrowsersisleft.Aswiththe<div>and<p>
tags,thealignattributecanchangethealignmenttoleft,center,right,orjustify.
Figure4-4showsthesealternativealignmentsasrenderedfromthefollowing
source:
<h1align=right>Rightoverhere!</h1>
<h2align=left>Slidebackleft.</h2>
<h3align=center>Smackinthemiddle.</h3>
Figure4-4.Theheading'salignattributeinaction
Thejustifyvalueforalignisnotyetsupportedbyanybrowser,anddon'tholdyour
breath.ThealignattributeisdeprecatedinHTML4andXHTML,indeferenceto
stylesheet-basedcontrols.
4.2.1.2.Thedirandlangattributes
Thedirattributeletsyouadvisethebrowserinwhichdirectionthetextwithin
thatparagraphshouldbedisplayed,andlangletsyouspecifythelanguageused
withintheheading.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
4.2.1.3.Theclass,id,style,andtitleattributes
Usetheidattributetocreatealabelfortheheadingthatcanlaterbeusedto
unambiguouslyreferencethatheadinginahyperlinktarget,forautomated
searches,asastylesheetselector,andwithahostofotherapplications.[Theid
attribute,4.1.1.4]
Usetheoptionaltitleattributeandquote-enclosedstringvaluetoprovidea
descriptivephrasefortheheading.[Thetitleattribute,4.1.1.5]
Usethestyleattributewiththeheadingtagstocreateaninlinestyleforthe
headings'contents.Theclassattributeletsyoulabeltheheadingwithanamethat
referstoapredefinedclassdeclaredinsomedocument-levelorexternallydefined
stylesheet.[InlineStyles:ThestyleAttribute,8.1.1][StyleClasses,8.3]
4.2.1.4.Eventattributes
Eachuser-initiatedeventthatmayhappeninandaroundaheadingisrecognized
bythebrowserifitconformstotheHTMLorXHTMLstandard.Withtherespective
onattributeandvalue,youmayreacttothateventbydisplayingauserdialogbox
oractivatingsomemultimediaevent.[JavaScriptEventHandlers,12.3.3]
4.2.2.AppropriateUseofHeadings
It'softengoodformtorepeatyourdocument'stitleinthefirstheadingtag
becausethetitleyouspecifyinthe<head>ofyourdocumentdoesn'tappearinthe
user'smaindisplaywindow.ThefollowingHTMLsegmentisagoodexampleof
repeatingthedocument'stitleintheheaderandinthebodyofthedocument:
<html>
<head>
<title>KumquatFarminginNorthAmerica</title>
</head>
<body>
<h3>KumquatFarminginNorthAmerica</h3>
<p>
Perhapsoneofthemostenticingofallfruitsisthe...
Typically,thebrowserplacesthe<title>textalongthetopofthemaindisplay.It
mayalsoplacethetitleelsewhereinthedocumentwindowanduseittocreate
bookmarksorfavoritesentries,allofwhichvaguelyaresomewhereontheuser's
desktop.Thelevel-threetitleheadinginthisexample,ontheotherhand,will
alwaysappearattheverybeginningofthedocumentdisplay.Itservesasa
visibletitletothedocument,regardlessofhowthebrowserhandlesthe<title>
tag'scontents.And,unlikethe<title>text,theheadingtitlegetsprintedatthe
beginningofthefirstpageshouldtheuserelecttoprintthedocument,becauseit
ispartofthemaintext.[<title>,3.7.2]
Inourexample,wechosetousealevel-threeheading(<h3>)whoserenderedfont
typicallyisjustabitlargerthantheregulardocumenttext.Levelsoneandtwo
arelargerstillandoftenareabitoverbearing.Choosealevelofheadingthatyou
findusefulandattractiveandusethatlevelconsistentlythroughoutyour
documents.Toobiganditoverwhelmsthedisplaywindow;toosmallandit's
easilymissedvisually.
Onceyouhaveestablishedthetop-levelheadingforyourdocument,use
additionalheadingsatthesameorlowerlevelsthroughouttoaddstructureand
"scanability"tothedocument.Ifyouusealevel-threeheadingforthedocument
title,forexample,breakyourdocumentintosubsectionsusinglevel-four
headings.Ifyouhavetheurgetosubdivideyourtextfurther,considerusinga
level-twoheadingforthetitle,levelthreeforthesectiondividers,andlevelfour
forthesubsections.
4.2.3.UsingHeadingsforSmallerText
Formostgraphicalbrowsers,thefontsusedtodisplay<h1>,<h2>,and<h3>headers
arelarger,<h4>isthesame,and<h5>and<h6>aresmallerthantheregulartext
size.Authorstypicallyusethelattertwosizesforboilerplatetext,suchasa
disclaimeroracopyrightnotice.Thoughstylerulesoughttobeusedinstead,
someauthorsuseheadersfortheirsmallertexttoformattablesofcontentsor
homepagesthatdisplayasite'scontents.Experimentwith<h5>and<h6>togetthe
effectyouwant.Figure4-5showshowatypicalbrowserrendersthecopyright
referenceinthefollowingsampleXHTMLsegment:
resultinginyearsofsuccessfulkumquatproduction
throughoutNorthAmerica.
</p>
<h6>Thisdocumentcopyright2007bytheKumquatGrowersof
America.Allrightsreserved.</h6>
</body>
</html>
Figure4-5.HTML/XHTMLauthorstypicallyuseheadinglevelsix
forboilerplatetext
4.2.4.AllowedHeadingContent
Aheadingmaycontainanyelementallowedintext,includingconventionaltext,
hyperlinks(<a>),images(<img>),linebreaks(<br>),fontembellishments(<b>,<i>,
<tt>,<u>,<strike>,<big>,<small>,<sup>,<sub>,and<font>),andcontent-basedstyles
(<acronym>,<cite>,<code>,<dfn>,<em>,<kbd>,<samp>,<strong>,and<var>).Inpractice,
however,fontorstylechangesmaynottakeeffectwithinaheadingbecausethe
headingitselfprescribesafontchangewithinthebrowser.
Atonetimeearlyon,therewaswidespreadabuseoftheheadingtagsasawayto
changethefontofentiresectionsofadocument.Technically,paragraphs,lists,
andotherblockelementsarenotallowedwithinaheadingandmaybemistaken
bythebrowsertoindicatetheimpliedendoftheheading.Inpractice,most
browsersapplythestyleoftheheadingtoallcontainedparagraphs.We
discouragethispracticebecauseitisnotonlyaviolationofHTMLandXHTML
standards,butalsoisusuallyuglytolookat.Imagineifyourlocalpaperprinted
allthecopyinheadlinetype!
Largesectionsofheadingtextdefeatthepurposeofthetag.Ifyoureallywantto
changethefontortypesizesinyourdocument,usethestandardcascadingstyle
definitions.SeeChapter8fordetails.
Westronglyrecommendthatyoucarefullytestyourpageswithmorethanone
browserandatseveraldifferentresolutions.Asyoumightexpect,your<h6>text
maybereadableat640x480resolution,butmaydisappearona1280x1024
display.
4.2.5.AllowedHeadingUsage
Formally,theHTMLandXHTMLstandardsallowheadingsonlywithinbody
content.Inpractice,mostbrowsersrecognizeheadingsalmostanywhere,
formattingtherenderedtexttofitwithinthecurrentelement.Inallcases,the
occurrenceofaheadingsignifiestheendofanyprecedingparagraphorothertext
element,soyoucan'tusetheheadingtagstochangefontsizesinthesameline.
Rather,usecascadingstyledefinitionstoachievethoseacutedisplayeffects.
[InlineStyles:ThestyleAttribute,8.1.1]
4.2.6.AddingImagestoHeadings
Itispossibletoinsertoneormoreimageswithinyourheadings,fromsmall
bulletsoriconstofull-sizelogos.Combiningaconsistentsetofheadingswith
correspondingiconsacrossafamilyofdocumentsisnotonlyvisuallyattractive
butalsoaneffectivewayofaidingusers'perusalofyourdocumentcollection.
[<img>,5.2.6]
Addinganimagetoaheadingiseasy.Forexample,thefollowingtextputsan
"information"iconinsidethe"ForMoreInformation"heading,asyoucanseein
Figure4-6:
<h2>
<imgsrc="info.gif">
ForMoreInformation</h2>
Figure4-6.Animagewithinaheading
Ingeneral,imageswithinheadingslookbestatthebeginningoftheheading,
alignedwiththebottomormiddleoftheheadingtext.
4.3.ChangingTextAppearanceandMeaning
Anumberoftagschangetheappearanceofandassociatehiddenmeaningwith
text.Ingeneral,thesetagscanbegroupedintotwoflavors:content-basedstyles
andphysicalstyles.
Inaddition,theWorldWideWebConsortium(W3C)standardforCascadingStyle
Sheets(CSS)isnowwellsupportedbythepopularbrowsers,providinganother,
morecomprehensivewayforauthorstocontrolthelookandlayoutoftheir
documenttext.Wedescribethetag-basedtextstylesinthischapter.SeeChapter
8fordetailsaboutCSS.
4.3.1.Content-BasedStyles
Content-basedstyletagsinformthebrowserthattheenclosedtexthasaspecific
meaning,context,orusage.Thebrowserthenformatsthetextinamanner
consistentwiththatmeaning,context,orusage.Notethedistinctionhere.
Content-basedstyletagsconfermeaning,notformatting.Accordingly,theyare
importantforautomatedprocesses;machinesdon'tcarewhatthedocumentlooks
likeatleastfornow.
Becausefontstyleisspecifiedviasemanticclues,thebrowsercanchoosea
displaystylethatisappropriatefortheuser.Becausesuchstylesvarybylocale,
usingcontent-basedstyleshelpsensurethatyourdocumentswillhavemeaning
toabroaderrangeofreaders.Thisisparticularlyimportantwhenabrowseris
targetedatblindorhandicappedreaderswhosedisplayoptionsareradically
differentfromconventionaltextorareextremelylimitedinsomeway.
ThecurrentHTMLandXHTMLstandardsdonotdefineaformatforeachcontent-
basedstyle;theyonlyspecifythattheymustberenderedinamannerdifferent
fromtheregulartextinadocument.Thestandardsdon'teveninsistthatthe
content-basedstylesberendereddifferentlyfromoneanother.Inpractice,you'll
findthatmanyofthesetagshavefairlyobviousrelationshipswithconventional
print,havingsimilarmeaningsandrenderedstyles,andarerenderedinthesame
styleandfontsbymostbrowsers.
4.3.2.PhysicalStyles
Weusethewordintentalotwhenwetalkaboutcontent-basedstyletags.That's
becausethemeaningconveyedbythetagismoreimportantthanthewaya
browserdisplaysthetext.Insomecases,however,youmightwantthetextto
appearexplicitlyinsomespecialwayitalicorbold,forexampleperhapsforlegalor
copyrightreasons.Inthosecases,useaphysicalstyleforthetext.
Whilethetendencywithothertext-processingsystemsistocontrolstyleand
appearanceexplicitly,withHTMLorXHTMLyoushouldavoidphysicaltagsexcept
onrareoccasions.Providethebrowserwithasmuchcontextualinformationas
possible.Usethecontent-basedstyles.Eventhoughcurrentbrowsersmaydo
nothingmorethandisplaytheirtextinitalicorbold,futurebrowsersandvarious
document-generationtoolsmayusethecontent-basedstylesinanynumberof
creativeways.
4.4.Content-BasedStyleTags
IttakesdisciplinetouseHTML/XHTMLcontent-basedstyletagsbecauseitis
easiertosimplythinkofhowyourtextshouldlook,notnecessarilywhatitmay
alsomean.Onceyougetstartedusingcontent-basedstyles,yourdocumentswill
bemoreconsistentandbetterlendthemselvestoautomatedsearchingand
contentcompilation.
Content-BasedStyleTags
Function Altertheappearanceoftextbaseduponthemeaning,context,orusageofthe
text
Attributes class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,onMouseDown,
onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtags Neveromitted
Contains text
Usedin text
4.4.1.The<abbr>Tag
FirstintroducedinHTML4.0,the<abbr>tagindicatesthattheenclosedtextisan
abbreviatedformofalongerwordorphrase.Thebrowsermightusethis
informationtochangethewayitrenderstheenclosedtextorsubstitute
alternativetext.Noticethatwesaidmightnotallofthepopularbrowsers
currentlydoanythingtothetextenclosedbythe<abbr>tag,andwecan'tpredict
howotherbrowserswillimplementthetaginthefuture.
4.4.2.The<acronym>Tag
The<acronym>tagindicatesthattheenclosedtextisanacronym,anabbreviation
usuallyformedfromthefirstletterofeachwordinanameorphrase,suchas
HTMLandIBM.Like<abbr>,notallbrowserschangethedisplayofthe<acronym>
content-basedstyletag'senclosedtext.
4.4.3.The<cite>Tag
The<cite>tagusuallyindicatesthattheenclosedtextisabibliographiccitation,
suchasabookormagazinetitle.Byconvention,thecitationtextisrenderedin
italics.SeeFigure4-7forhowInternetExplorerrendersthissourcetext:
WhilekumquatsarenotmentionedinMelville's
<cite>MobyDick</cite>,itisnonethelessapparent
thatthemightycetaceanrepresentsthebitter
"kumquat-ness"withineveryman.Indeed,whenAhab
spearsthebeast,itsfleshistough,muchlikethenoblefruit.
Figure4-7.InternetExplorerrenders<cite>initalics
Usethe<cite>tagtosetapartanyreferencetoanotherdocument,especially
thoseintraditionalmedia,suchasbooks,magazines,journalarticles,andthe
like.Ifanonlineversionofthereferencedworkexists,youalsoshouldenclose
thecitationwithinthe<a>taginordertomakeitahyperlinktothatonline
version.
The<cite>tagalsohasahiddenfeature:itenablesyouorsomeoneelseto
automaticallyextractabibliographyfromyourdocuments.Itiseasytoenvisiona
browserthatcompilestablesofcitationsautomatically,displayingthemas
footnotesorasaseparatedocumententirely.Thesemanticsofthe<cite>taggo
farbeyondchangingtheappearanceoftheenclosedtext;theyenablethe
browsertopresentthecontenttotheuserinavarietyofusefulways.
4.4.4.The<code>Tag
Softwarecodewarriorshavebecomeaccustomedtoaspecialstyleoftext
presentationfortheirsourceprograms.The<code>tagisforthem.Itrendersthe
enclosedtextinamonospaced,teletype-stylefontsuchasCourier,familiarto
mostprogrammersandreadersofO'Reillybookssuchasthisone.
Thisfollowingbitofen<code>edtextisrenderedinamonospacedfontstyleby
Firefox,asshowninFigure4-8(thoughtheeffectisnotdramatic,admittedly):
Thearrayreference<code>a[i]</code>isidenticalto
thepointerreference<code>*(a+i)</code>.
Figure4-8.Use<code>topresentcomputer-speak
Youshouldusethe<code>tagfortextthatrepresentscomputersourcecodeor
othermachine-readablecontent.Whilethe<code>tagusuallyjustmakestext
appearinamonospacedfont,theimplicationisthatitissourcecode,andfuture
browsersmayaddotherdisplayeffects.[*]
[*]Noneofthepopularbrowsersformat<code>segmentsasatextprocessormight.Rather,usethe<pre>tagin
conjunctionwith<code>toachieveprogrammingcode-likedisplayeffects.
Forexample,aprogrammer'sbrowsermightlookfor<code>segmentsandperform
someadditionaltextformatting,suchasspecialindentationofloopsand
conditionalclauses.Iftheonlyeffectyoudesireisamonospacedfont,usethe<tt>
tag.Ifyouwanttodisplaytheprogrammingcodeinrigidlyformattedmonospaced
text,usethe<pre>tag.[The<tt>Tag,4.5.10][<pre>,4.6.5]
4.4.5.The<dfn>Tag
Use<dfn>totagdefininginstancesofspecialtermsorphrases.Thepopular
browserstypicallydisplay<dfn>textinitalics.Inthefuture,<dfn>mightassistin
creatingadocumentindexorglossary.
Forexample,usethe<dfn>tagtointroduceanewphrasetothereader:
Whenanalyzingannualcropyields,<dfn>rindspectroscopy</dfn>mayproveuseful.By
comparingtherelativelevelsofsaturatedhydrocarbonsinfruitfromadjacenttrees,
rindspectroscopyhasbeenshowntobe87%effectiveinpredictinganoutbreakof
trunkdropsyintreesunderfouryearsold.
Noticethatwedelimitonlythefirstoccurrenceof"rindspectroscopy"witha<dfn>
tagintheexample.Goodstyletellsusnottoclutterthetextwithhighlighted
text.Aswiththemanyother,content-relatedandphysicalstyletags,thefewer
thebetter.[*]Asageneralstyle,especiallyintechnicaldocumentation,setoffnew
termswhentheyarefirstintroducedtohelpyourreadersbetterunderstandthe
topicathand,butresisttaggingthetermsthereafter.
[*]Ifyouneedconvincingthatlessisbetterwhenapplyingthecontent-basedandphysicalstyletags,tryreadinga
collegetextbookinwhichsomeonehashighlightedwhatheconsideredimportantwordsandphraseswithayellow
marker.
4.4.6.The<em>Tag
The<em>tagtellstheclientbrowsertopresenttheenclosedtextwithemphasis.
Fornearlyallbrowsers,thismeansthetextisrenderedinitalic.Forexample,the
popularbrowserswillemphasizebyitalicizingthewordsalwaysandneverinthe
followingHTML/XHTMLsource:
Kumquatgrowersmust<em>always</em>refertokumquats
as"thenoblefruit,"<em>never</em>asjusta"fruit."
Addingemphasistoyourtextistrickybusiness.Toolittle,andtheemphatic
phrasesmaybelost.Toomuch,andyoulosetheurgency.Likeanyseasoning,
emphasisisbestusedsparingly.
Althoughinvariablydisplayedinitalic,the<em>taghasbroaderimplicationsas
well,andsomedaybrowsersmayrenderemphasizedtextwithadifferentspecial
effect.The<i>tagexplicitlyitalicizestext;useitifallyouwantisitalic.
Alternatively,youcanincludetextdisplay-alteringcascadingstyledefinitionsin
yourdocument.[The<i>Tag,4.5.4]
Besidesforemphasis,alsoconsiderusing<em>whenpresentingnewtermsorasa
fixedstylewhenreferringtoaspecifictypeoftermorconcept.Forinstance,one
ofO'Reilly'sbookstylesistospeciallyformatfileanddevicenames.Youmight
usethe<em>tagtodifferentiatethosetermsfromsimpleitalicsusedforemphasis.
4.4.7.The<kbd>Tag
Speakingofspecialstylesfortechnicalconcepts,thereisthe<kbd>tag.Asyou
probablyalreadysuspect,itisusedtoindicatetextthatistypedonakeyboard.
Itsenclosedtexttypicallyisrenderedbythebrowserinamonospacedfont.
The<kbd>tagismostoftenusedincomputer-relateddocumentationandmanuals,
suchasinthisexample:
Type<kbd>quit</kbd>toexittheutility,ortype
<kbd>menu</kbd>toreturntothemainmenu.
4.4.8.The<samp>Tag
The<samp>tagindicatesasequenceofliteralcharactersthatshouldhavenoother
interpretationbytheuser.Thistagismostoftenusedwhenasequenceof
charactersistakenoutofitsnormalcontext.Forexample,thefollowingsource:
The<samp>ae</samp>charactersequencemaybeconverted
totheæligatureifdesired.
isrenderedbyNetscape,forinstance,asshowninFigure4-9.
Figure4-9.Settingoffsampletextusingthe<samp>tag
ThespecialHTMLreferencefortheaeligatureentityisæandisconvertedto
itsappropriateæligaturecharacterbymostbrowsers.Formoreinformation,see
AppendixF.
The<samp>tagisnotusedveryoften.Youshoulduseitinthosefewcaseswhere
specialemphasisneedstobeplacedonsmallcharactersequencestakenoutof
theirnormalcontext.
4.4.9.The<strong>Tag
Likethe<em>tag,the<strong>tagisforemphasizingtext,exceptwithmoregusto.
Browserstypicallydisplaythe<strong>tagdifferentlythanthe<em>tag,usuallyby
makingthetextbold(versusitalic)sothatuserscandistinguishbetweenthetwo.
Forexample,inthefollowingtext,theemphasized"never"appearsinitalicby
Opera,andthe<strong>"forbidden"isrenderedinboldcharacters(seeFigure4-
10):
Oneshould<em>never</em>makeadisparagingremarkaboutthe
noblefruit.Inparticular,mentioningkumquatsinconjunction
withvulgarphrasesisexpressly<strong>forbidden</strong>by
theAssociationbylaws.
Figure4-10.Strongandemphasizedtextarerendered
differently
Ifcommonsensetellsusthatthe<em>tagshouldbeusedsparingly,the<strong>
tagshouldappearindocumentsevenmoreinfrequently.<em>textislikeshouting.
<strong>textisnothingshortofascream.Likeawell-chosenepithetvoicedbyan
otherwisetaciturnperson,restraintintheuseof<strong>makesitsusethatmuch
morenoticeableandeffective.
4.4.10.The<var>Tag
The<var>tag,anothercomputer-documentationtrick,indicatesavariablenameor
auser-suppliedvalue.Thetagisoftenusedinconjunctionwiththe<code>and
<pre>tagsfordisplayingparticularelementsofcomputer-programmingcode
samplesandthelike.Browserstypicallyrender<var>-taggedtextinitalics,as
showninFigure4-11,whichdisplaysthefollowingexample:
Theusershouldtype
<pre>
cp<var>source-file</var><var>dest-file</var>
</pre>
replacingthe<var>source-file</var>withthenameof
thesourcefile,and<var>dest-file</var>withthename
ofthedestinationfile.
Figure4-11.The<var>tagtypicallyappearsinpreformatted
(<pre>)computercode
Liketheothercomputer-programminganddocumentation-relatedtags,the<var>
tagnotonlymakesiteasyforuserstounderstandandbrowseyour
documentation,butautomatedsystemsmightsomedayusetheappropriately
taggedtexttoextractinformationandusefulparametersmentionedinyour
documents.Onceagain,themoresemanticinformationyouprovidetoyour
browser,thebetteritcanpresentthatinformationtotheuser.
4.4.11.Theclass,style,id,andtitleAttributes
Althougheachcontent-basedtaghasadefaultdisplaystyle,youcanoverridethat
stylebydefininganewlookforeachtag.Youcanapplythisnewlooktothe
content-basedtagsusingeitherthestyleortheclassattribute.[InlineStyles:The
styleAttribute,8.1.1][StyleClasses,8.3]
Youalsomayassignauniqueidentifier(id)tothecontent-basedstyletag,aswell
asalessrigoroustitle,usingtherespectiveattributesandtheiraccompanying
quote-enclosedstringvalues.[Theidattribute,4.1.1.4][Thetitleattribute,
4.1.1.5]
4.4.12.ThedirandlangAttributes
Thedirattributeadvisesthebrowserinwhichdirectionthetextwithinthe
content-basedstyletagshouldbedisplayed,andlangletsyouspecifythe
languageusedwithinthetag.[Thedirattribute,3.6.1.1][Thelangattribute,
3.6.1.2]
4.4.13.EventAttributes
Thingshappeninandaroundacontent-basedtag'scontent,and,withthe
respectiveonattributeandvalueyoumayreacttothateventbydisplayingauser
dialogoractivatingsomemultimediaevent.[JavaScriptEventHandlers,12.3.3]
4.4.14.SummaryofContent-BasedTags
Thevariousgraphicalbrowsersrendertextinsidecontent-basedtagsinsimilar
fashion;text-onlybrowserssuchasLynxhaveconsistentstylesforthetags.Table
4-1summarizesthesebrowsers'displaystylesforthenativetags.However,
stylesheetdefinitionsmayoverridethesenativedisplaystyles.
Table4-1.Content-basedtags
Tag NetscapeNavigator InternetExplorer MozillaFirefox Opera Lynx
<abbr> N/A N/A N/A N/A N/A
<acronym> N/A N/A N/A N/A N/A
<cite> italic italic italic italic monospace
<code> monospace monospace monospace monospace monospace
<dfn> italic italic italic italic N/A
<em> italic italic italic italic monospace
<kbd> monospace monospace monospace monospace monospace
<samp> monospace monospace monospace monospace monospace
<strong> bold bold bold bold monospace
<var> italic italic italic italic monospace
4.4.15.AllowedContent
Anycontent-basedstyletagmaycontainanyitemallowedintext,including
conventionaltext,anchors,images,andlinebreaks.Inaddition,othercontent-
basedandphysicalstyletagscanbeembeddedwithinthecontent.
4.4.16.AllowedUsage
Anycontent-basedstyletagmaybeusedanywhereanitemallowedintextis
used.Inpractice,thismeansyoucanusethe<em>,<code>,andothersimilartags
anywhereinyourdocumentexceptinside<title>,<listing>,and<xmp>tagged
segments.Youcanusetextstyletagsinheadings,too,buttheireffectsmaybe
overriddenbytheeffectsoftheheadingtagsthemselves.
4.4.17.CombiningContent-BasedStyles
Itmayhaveoccurredtoyoutocombinetwoormoreofthevariouscontent-based
stylestocreateinterestingandperhapsevenusefulhybrids.Thus,anemphatic
citationmightbeachievedwith:
<cite><em>MobyDick</em></cite>
Inpractice,Dr.Frankenstein,thebrowserusuallyignoresthemonsterasyoucan
testbytypingandviewingtheexampleyourself,"MobyDick"getsthecitation
withoutemphasis.
TheHTMLandXHTMLstandardsdonotrequirethebrowsertosupportevery
possiblecombinationofcontent-basedstylesanddonotdefinehowthebrowser
shouldhandlesuchcombinations.Somedaymaybe;fornow,it'sbesttochoose
onetag.
4.5.PhysicalStyleTags
ThecurrentHTMLandXHTMLstandardscurrentlyprovideninephysicalstyles:
bold,italic,monospaced,underlined,strikethrough,larger,smaller,superscripted,
andsubscriptedtext.Muchtoourrelief,InternetExplorerhasstoppedsupporting
atenthphysicalstyle,"blinking"text.Wewishtheotherswould"getit."All
physicalstyletagsrequireendingtags.
Aswediscussphysicaltagsindetail,keepinmindthattheyconveyanacute
stylingfortheimmediatetext.Formorecomprehensive,document-widecontrol
oftextdisplay,usestylesheets(seeChapter8).
PhysicalStyleTags
Function Specifyphysicalstylesfortext
Attributes class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,onMouseDown,
onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtags Neveromitted
Contains text
Usedin text
4.5.1.The<b>Tag
The<b>tagisthephysicalequivalentofthe<strong>content-basedstyletag,but
withoutthelatter'sextendedmeaning.The<b>tagexplicitlyboldfacesacharacter
orsegmentoftextthatisenclosedbetweenitanditscorrespondingendtag
(</b>).Ifaboldfacefontisnotavailable,thebrowsermayusesomeother
representation,suchasreversevideoorunderlining.
4.5.2.The<big>Tag
The<big>tagmakesiteasytoincreasethesizeoftext.Itcouldn'tbesimpler:the
browserrendersthetextbetweenthe<big>taganditsmatching</big>endingtag
onefontsizelargerthanthesurroundingtext.Ifthattextisalreadyatthe
largestsize,<big>hasnoeffect.[<font>,4.10.3]
Evenbetter,youcannest<big>tagstoenlargethetext.Each<big>tagmakesthe
textonesizelarger,uptoalimitofsizeseven,asdefinedbythefontmodel.
4.5.3.The<blink>Tag(ObsoleteExtension)
Textcontainedbetweenthe<blink>taganditsendtag,</blink>,doesjustthat:it
blinksonandoff.Firefox,forexample,simplyandreiterativelyreversesthe
backgroundandforegroundcolorsforthe<blink>-enclosedtext.NeithertheHTML
northeXHTMLstandardincludes<blink>.Originally,itwassupportedasan
extensiononlybyNetscapeNavigatorversionsbeforeversion6;thenitwas
droppedinversion6,andwasreinstatedinversions7andlater.Operaand
Firefoxsupportit,tooonlyInternetExplorereschewsit.Youshould,too.
Wecannoteffectivelyreproducetheanimatedeffectinthesestaticpages,butitis
easytoimagineandbestlefttotheimagination,too.Blinkingtexthastwo
primaryeffects:itgetsyourreaders'attentionandthenpromptlyannoysthemto
noend.Forgetaboutblinkingtext.
4.5.4.The<i>Tag
The<i>tagislikethe<em>content-basedstyletag.Itanditsnecessaryendtag
(</i>)tellthebrowsertorendertheenclosedtextinanitalicorobliquetypeface.
Ifthetypefaceisnotavailabletothebrowser,highlighting,reversevideo,or
underliningmightbeused.
4.5.5.The<s>Tag(Deprecated)
The<s>tagisanabbreviatedformofthe<strike>tagsupportedbyallcurrent
browserseventhoughitisdeprecatedinHTML4andXHTML.Inotherwords,the
"s"standsforshy:don'tuseit;<s>willgoaway,eventually.
4.5.6.The<small>Tag
The<small>tagworksjustlikeits<big>counterpart(see[The<big>Tag,4.5.2]),
exceptitdecreasesthesizeoftextinsteadofincreasingit.Iftheenclosedtextis
alreadyatthesmallestsizesupportedbythefontmodel,<small>hasnoeffect.
Asyoucanwith<big>,youcannest<small>tagstosequentiallyshrinktext.Each
<small>tagmakesthetextonesizesmallerthanthecontaining<small>tag,toa
limitofsize1.
4.5.7.The<strike>Tag(Deprecated)
Thepopularbrowsersputalinethrough("strikethrough")textthatappears
insidethe<strike>tagandits</strike>endtag.Presumably,itisaneditingmarkup
thattellsthereadertoignorethetextpassage,reminiscentofthedaysbefore
typewritercorrectiontape.You'llrarely,ifever,seethetaginusetoday:itis
deprecatedinHTML4andXHTML,justonestepawayfromcompleteelimination
fromthestandard.
4.5.8.The<sub>Tag
Thetextcontainedbetweenthe<sub>tagandits</sub>endtaggetsdisplayedhalf
acharacter'sheightlower,butinthesamefontandsizeasthecurrenttextflow.
Both<sub>andits<sup>counterpartareusefulformathequationsandinscientific
notation,aswellaswithchemicalformulæ.
4.5.9.The<sup>Tag
The<sup>tagandits</sup>endtagsuperscripttheenclosedtext;itgetsdisplayed
halfacharacter'sheighthigher,butinthesamefontandsizeasthecurrenttext
flow.Thistagisusefulforaddingfootnotestoyourdocuments,alongwith
exponentialvaluesinequations.Whenyouuseitincombinationwiththe<a>tag,
youcancreatenice,hyperlinkedfootnotes:
Thelarvalquat
weevil<ahref="footnotes.html#note74"><sup><small>74</small></sup></a>isa
Thisexampleassumesthatfootnotes.htmlcontainsallyourfootnotes,
appropriatelydelimitedasnameddocumentfragments.
4.5.10.The<tt>Tag
Likethe<code>and<kbd>tags,the<tt>taganditsnecessary</tt>endtagdirect
thebrowsertodisplaytheenclosedtextinamonospacedtypeface.Forthose
browsersthatalreadyuseamonospacedtypeface,thistagmaymakeno
discerniblechangeinthepresentationofthetext.
4.5.11.The<u>Tag(Deprecated)
Thistagtellsthebrowsertounderlinethetextcontainedbetweenthe<u>andthe
corresponding</u>tag.Theunderliningtechniqueissimplistic,drawingtheline
underspacesandpunctuationaswellasthetext.ThistagisdeprecatedinHTML
4andXHTML,butthepopularbrowserssupportit.
Thesamedisplayeffectsforthe<u>tagarebetterachievedbyusingstylesheets,
coveredinChapter8.
4.5.12.ThedirandlangAttributes
Thedirattributeletsyouadvisethebrowserinwhichdirectionthetextwithinthe
physicaltagshouldbedisplayed,andlangletsyouspecifythelanguageused
withinthetag.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
4.5.13.Theclass,style,id,andtitleAttributes
Althougheachphysicaltaghasadefinedstyle,youcanoverridethatstyleby
definingyourownlookforeachtag.Youcanapplythisnewlooktothephysical
tagsusingeitherthestyleortheclassattribute.[InlineStyles:Thestyle
Attribute,8.1.1][StyleClasses,8.3]
YoualsomayassignauniqueIDtothephysicalstyletag,aswellasaless
rigoroustitle,usingtherespectiveattributeandaccompanyingquote-enclosed
stringvalue.[Theidattribute,4.1.1.4][Thetitleattribute,4.1.1.5]
4.5.14.EventAttributes
Aswithcontent-basedstyletags,user-initiatedmouseandkeyboardeventscan
happeninandaroundaphysicalstyletag'scontents.Thebrowserrecognizes
manyoftheseeventsifitconformstocurrentstandards,andwiththerespective
onattributeandvalue,youmayreacttotheeventbydisplayingauserdialogbox
oractivatingsomemultimediaevent.[JavaScriptEventHandlers,12.3.3]
4.5.15.SummaryofPhysicalStyleTags
Thevariousgraphicalbrowsersrendertextinsidethephysicalstyletagsina
similarfashion.Table4-2summarizesthesebrowsers'displaystylesforthese
tags.Stylesheetdefinitionsmayoverridethesenativedisplaystyles.
Table4-2.Physicalstyletags
Tag Meaning Displaystyle
<b> Boldcontents Bold
<big> Increasedfontsize Biggertext
<blink>(obsolete) Alternatingfore-andbackgroundcolors Blinkingtext
<i> Italiccontents Italic
<small> Decreasedfontsize Smallertext
<s>,<strike>(deprecated) Strikethroughtext Strike
<sub> Subscriptedtext subscript
<sup> Superscriptedtext superscript
<tt> Teletypewriterstyle monospaced
<u>(deprecated) Underlinedcontents Underlined
ThefollowingHTMLsourceexampleillustratessomeofthevariousphysicaltags
asrenderedbyFirefox(seeFigure4-12):
Explicitly<b>boldfaced</b>,<i>italicized</i>,or
<tt>teletype-style</tt>textshouldbeused
<big><big>sparingly</big></big>.
Otherwise,drink<strike>lots</strike>1x10<sup>6</sup>
dropsofH<sub><small><small>2</small></small></sub>O.
Figure4-12.Usephysicaltexttagswithcaution
4.5.16.AllowedContent
Anyphysicalstyletagmaycontainanyitemallowedintext,including
conventionaltext,anchors,images,andlinebreaks.Youcanalsocombine
physicalstyletagswithothercontent-basedtags.
4.5.17.AllowedUsage
Youcanuseanyphysicalstyletaganywhereyoucanuseanitemallowedintext.
Ingeneral,thismeansanywherewithinadocument,exceptinthe<title>,
<listing>,and<xmp>tags.Youcanuseaphysicalstyletaginaheading,butthe
browserwillprobablyoverrideandignoreitseffectinlieuoftheheadingtag.
4.5.18.CombiningPhysicalStyles
Youwillprobablyhavebetterluckcombiningphysicaltagsthanyoumighthave
combiningcontent-basedtagstoachievemultipleeffects.Forinstance,allthe
popularbrowsersrenderthefollowinginboldanditalictypeface:
<b><i>Tharsheblows!</i></b>
Otherbrowsersmayelecttoignoresuchnesting.Thestandardsrequirethe
browserto"doitsbest"tosupporteverypossiblecombinationofstyles,butdonot
definehowthebrowsershouldhandlesuchcombinations.Althoughmostbrowsers
makeagoodattemptatdoingso,donotassumeallcombinationswillbeavailable
toyou.
4.6.PreciseSpacingandLayout
CSSnotwithstanding,theoriginalconceptofHTMLisforspecifyingdocument
contentwithoutindicatingformat;todelineatethestructureandsemanticsofa
document,nothowthatdocumentistobepresentedtotheuser.Normally,you
shouldleavewordwrapping,characterandlinespacing,andotherpresentation
detailsuptothebrowser.Thatway,thedocument'scontentitsrichinformation,
notitsgoodlooksiswhatmatters.Whenlooksmattermore,suchasfor
commercialpresentations,looktostylesheetsforlayoutcontrol(seeChapter8).
4.6.1.The<br>Tag
The<br>taginterruptsthenormallinefillingandwordwrappingofparagraphs
withinanHTMLorXHTMLdocument.IthasnoendingtagwithHTML;[*]itsimply
marksthepointintheflowwhereanewlineshouldbegin.Mostbrowserssimply
stopaddingwordsandimagestothecurrentline,movedownandovertotheleft
margin,andresumefillingandwrapping.
[*]WithXHTML,puttheendinsidethestarttag:<br/>.SeeChapter16fordetails.
<br>
Function Insertsalinebreakintoatextflow
Attributes class,clear,id,style,title
Endtag NoneinHTML;</br>or<br.../>inXHTML
Contains Nothing
Usedin text
Thiseffectishandywhenformattingconventionaltextwithfixedlinebreaks,
suchasaddresses,songlyrics,andpoetry.Notice,forexample,thelyricalbreaks
whenthefollowingsourceisrenderedbyaGUIbrowser:
<h3>
HeartbreakHotel</h3>
<p>
Eversincemybabyleftme<br>
I'vefoundanewplacetodwell.<br>
It'sdownattheendoflonelystreet<br>
Called<cite>HeartbreakHotel</cite>.
</p>
TheresultsareshowninFigure4-13.
Figure4-13.Givelyricstheirbreaks(<br>)
Alsonoticehowthe<br>tagsimplycausestexttostartanewline,andthe
browser,whenencounteringthe<p>tag,typicallyinsertssomeverticalspace
betweenadjacentparagraphs.[<p>,4.1.2]
4.6.1.1.Theclearattribute
Normally,the<br>tagtellsthebrowsertostopthecurrentflowoftext
immediatelyandresumeattheleftmarginofthenextlineoragainsttheright
borderofaleft-justifiedinlinegraphicortable.Sometimesyou'dratherthe
currenttextflowresumebelowanytablesorimagescurrentlyblockingtheleftor
rightmargin.
HTML4andXHTMLprovidethatcapabilitywiththeclearattributeforthe<br>tag.
Itcanhaveoneofthreevaluesleft,right,oralleachrelatedtooneorbothofthe
margins.Whenthespecifiedmarginormarginsareclearofimages,thebrowser
resumesthetextflow.
Figure4-14illustratestheeffectsoftheclearattributewhenthebrowserrenders
thefollowingHTMLfragment:
<imgsrc="kumquat.gif"align=left>
Thistextshouldwraparoundtheimage,flowingbetweenthe
imageandtherightmarginofthedocument.
<brclear=left>
Thistextwillflowaswell,butwillbebelowtheimage,
extendingacrossthefullwidthofthepage.Therewillbe
whitespaceabovethistextandtotherightoftheimage.
Figure4-14.Clearingimagesbeforeresumingtextflowafterthe
<br>tag
Inlineimagesarejustthatnormallyinlinewithtext,butusuallyonlyasingleline
oftext.Additionallinesoftextflowbelowtheimage,unlessthatimageis
speciallyalignedbyrightorleftattributevaluesforthe<img>tag(similarlyfor
<table>).Hence,theclearattributeforthe<br>tagworksonlyincombinationwith
left-orright-alignedimagesortables.[<img>,5.2.6][Thealignattribute
(deprecated),10.2.1.1]
ThefollowingXHTMLcodefragmentillustrateshowtousethe<br>taganditsclear
attributeaswellasthe<img>tag'salignmentattributestoplacecaptionsdirectly
above,centeredontheright,andbelowanimagethatisalignedagainsttheleft
marginofthebrowserwindow:
Paragraphtagsseparateleadingandfollowing
textflowfromthecaptions.
<p>
I'mthecaptionontopoftheimage.
<br/>
<imgsrc="kumquat.gif"align="absmiddle">
Thisone'scenteredontheright.
<brclear="left"/>
Thiscaptionshouldbedirectlybelowtheimage.
</p>
<p/>
Figure4-15illustratestheresultsofthisexamplecode.
Figure4-15.Captionsplacedontop,center-right,andbelowan
image
Youmightalsoincludea<brclear=all>tagjustafteran<img>tagortablethatisat
theveryendofasectionofyourdocument.Thatway,youensurethatthe
subsequentsection'stextdoesn'tflowupandagainstthatimageandconfusethe
reader.[<img>,5.2.6]
4.6.1.2.Theclass,id,style,andtitleattributes
Youcanassociateadditionaldisplayrulesforthe<br>tagusingstylesheets.You
canapplytherulestothe<br>tagusingeitherthestyleortheclassattribute.
[InlineStyles:ThestyleAttribute,8.1.1][StyleClasses,8.3]
YoualsomayassignauniqueIDtothe<br>tag,aswellasalessrigoroustitle,
usingtherespectiveattributeandaccompanyingquote-enclosedstringvalue.
[Theidattribute,4.1.1.4][Thetitleattribute,4.1.1.5]
4.6.2.The<nobr>Tag(Extension)
Occasionally,youmaywantaphrasetoappearunbrokenonasinglelineinthe
user'sbrowserwindow,evenifthatmeansthetextextendsbeyondthevisible
regionofthewindow.Computercommandsaregoodexamples.Typically,youtype
inacomputercommandevenamultiwordoneonasingleline.Becauseyoucannot
predictexactlyhowmanywordswillfitinsideanindividual'sbrowserwindow,the
sequenceofcomputer-commandwordsmayendupbrokenintotwoormorelines
oftext.Commandsyntaxisconfusingenough;itdoesn'tneedtheextracross-
eyedeffectofbeingwrappedontotwolines.
WithstandardHTMLandXHTML,thewaytomakesuretextphrasesstayintact
acrossthebrowserdisplayistoenclosethosesegmentsina<pre>tagandformat
<nobr>
Function Createsaregionofnonbreakingtext
Attributes None
Endtag </nobr>;alwaysused
Contains text
Usedin block
Thecurrentbrowsersofferthe<nobr>tagalternativeto<pre>,whichkeepsenclosed
textintactonasinglelinewhileretainingnormaltextstyle.[*]<nobr>makesthe
browsertreatthetag'scontentsasthoughtheyareasingle,unbrokenword.The
tagcontentsretainthecurrentfontstyle,andyoucanchangetoanotherstyle
withinthetag.
[*]Beawarethat<nobr>anditscolleague<wbr>areextensionstothelanguageandnotpartoftheHTMLstandard.
Here'sthe<nobr>taginactionwithourcomputer-commandexample:
Whenpromptedbythecomputer,enter
<nobr>
<tt>find.-name\*.html-execrm\{\}\;</tt>.
</nobr>
<br>
<nobr>Afterafewmoments,theloadonyourserverwillbegin
todiminishandwilleventuallydroptozero.</nobr>
Noticeintheexamplesourceanditsdisplay(Figure4-16)thatwe'veincludedthe
special<tt>taginsidethefirst<nobr>tag,therebyrenderingthecontentsin
monospacedfont.Ifthe<nobr>-taggedtextcannotfitonapartiallyfilledlineof
text,theextendedbrowserprecedesitwithalinebreak,asshowninthefigure.
Thesecond<nobr>segmentintheexampledemonstratesthatthetextmayextend
beyondtherightwindowboundaryifthesegmentistoolongtofitonasingle
line.Forsomereason,Netscape,butnottheotherpopularbrowsers,failsto
provideahorizontalscrollbarsothatuserscanreadtheextendedtext,though.
[The<tt>Tag,4.5.10]
Figure4-16.The<nobr>extensionsuppressestextwrapping;
forreasonsunknown,Netscapedoesn'tenableascrollbarso
thatyoucanreadtheextendedtext
The<nobr>tagdoesnotsuspendthebrowser'snormalline-fillingprocess;itstill
collectsandinsertsimagesandbelieveitornotassertsforcedlinebreakscaused
bythe<br>and<p>tags,forexample.The<nobr>tag'sonlyactionistosuppressan
automaticlinebreakwhenthecurrentlinereachestherightmargin.
Inaddition,youmightthinkthistagisneededonlytosuppresslinebreaksfor
phrases,notforasequenceofcharacterswithoutspacesthatcanexceedthe
browserwindow'sdisplayboundaries.Today'sbrowsersdonothyphenatewords
automatically,butsomedaysoontheyprobablywill.Itmakessensetoprotectany
break-sensitivesequencesofcharacterswiththe<nobr>tag.
4.6.3.The<wbr>Tag(Extension)
The<wbr>tagistheheightoftext-layoutfinesse,offeredasanextensionby
InternetExplorer,butnotanyothers.Usedwiththe<nobr>tag,<wbr>advises
InternetExplorerwhenitmayinsertalinebreakinanotherwisenonbreakable
sequenceoftext.Unlikethe<br>tag,whichalwayscausesalinebreak,even
withinan<nobr>-taggedsegment,the<wbr>tagworksonlywhenplacedinsidean
<nobr>-taggedcontentsegmentandcausesalinebreakonlyifthecurrentlinehas
alreadyextendedbeyondthebrowser'sdisplaywindowmargins.
<wbr>
Function Definesapotentialline-breakpointifneeded
Attributes None
Endtag NoneinHTML;</wbr>or<wbr.../>inXHTML
Contains Nothing
Usedin text
Now,<wbr>mayseemincrediblyesoterictoyou,butscowlnot.Theremaycomea
timewhenyouwanttomakesureportionsofyourdocumentappearonasingle
line,butyoudon'twanttooverrunthebrowserwindowmarginssofarthat
readerswillhavetocamponthehorizontalscrollbarjusttoreadyourfineprose.
Byinsertingthe<wbr>tagatappropriatepointsinthenonbreakingsequence,you
letthebrowsergentlybreakthetextintomoremanageablelines:
<nobr>
Thisisaverylongsequenceoftextthatis
forcedtobeonasingleline,evenifdoingsocauses
<wbr>
thebrowsertoextendthedocumentwindowbeyondthe
sizeoftheviewingpaneandthepoorusermustscrollright
<wbr>
toreadtheentireline.
</nobr>
You'llnoticeinourInternetExplorer-renderedversion(Figure4-17)thatboth
<wbr>tagstakeeffect.Byincreasingthehorizontalwindowsizeorreducingthe
fontsize,youmayfittheentiresegmentbeforethefirst<wbr>tagwithinthe
browserwindow.Inthatcase,onlythesecond<wbr>wouldhaveaneffect;allthe
textleadinguptoitwouldextendbeyondthewindow'smargins.
Figure4-17.GentlelinebreakswithInternetExplorer's
<wbr>extensiontag
4.6.4.BetterLine-BreakingRules
Unlikesomebrowsers,andtotheircredit,thepopularbrowsersdonotconsider
tagstobeline-breakopportunities.Considertheunfortunateconsequencesto
yourdocument'sdisplayif,whilerenderingthefollowingexamplesegment,the
browserputsthecommaadjacenttothe"du"ortheperiodadjacenttothe"df"on
aseparateline.
Makesureyoutype<tt>du</tt>,not<tt>df</tt>.
4.6.5.The<pre>Tag
TheHTML/XHTMLstandards'<pre>taganditsrequiredendtag(</pre>)definea
segmentinsidewhichthebrowserrenderstextinexactlythecharacterandline
spacingwritteninthesourcedocument.Normalwordwrappingandparagraph
fillingaredisabled,andextraneousleadingandtrailingspacesarehonored.
Browsersdisplayalltextbetweenthe<pre>and</pre>tagsinamonospacedfont.
<pre>
Function Rendersablockoftextwithoutanyformatting
Attributes class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,onMouseDown,
onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title,width
Endtag </pre>;neveromitted
Contains pre_content
Usedin block
Authorsmostoftenusethe<pre>formattingtagwhentheintegrityofcolumnsand
rowsofcharactersmustberetained;forinstance,intablesofnumbersthatmust
lineupcorrectly.Anotherapplicationfor<pre>istosetasideablanksegmenta
seriesofblanklinesinthedocumentdisplay,perhapstoclearlyseparateone
contentsectionfromanotherortotemporarilyhideaportionofthedocument
whenitfirstloadsandisrenderedbytheuser'sbrowser.
Tabcharactershavetheirdesiredeffectwithinthe<pre>block,withtabstops
definedateveryeighthcharacterposition.Wediscouragetheiruse,however,
becausetabsaren'tconsistentlyimplementedamongthevariousbrowsers.Use
spacestoensurecorrecthorizontalpositioningoftextwithin<pre>-formattedtext
segments.
Acommonuseofthe<pre>tagistopresentcomputersourcecode,asinthe
followingexample:
<p>
Theprocessingprogramis:
<pre>
main(intargc,char**argv)
{
FILE*f;
inti;
if(argc!=2)
fprintf(stderr,"usage:%s<file>\n",
argv[0]);
<ahref="http:process.c">process</a>(argv[1]);
exit(0);
}
</pre>
Figure4-18showstheresult.
Figure4-18.Usethe<pre>tagtopreservetheintegrityof
columnsandrows
4.6.5.1.Allowablecontent
Thetextwithina<pre>segmentmaycontainphysicalandcontent-basedstyle
changes,alongwithanchors,images,andhorizontalrules.Whenpossible,the
browsershouldhonorstylechanges,withintheconstraintofusingamonospaced
fontfortheentire<pre>block.Tagsthatcauseaparagraphbreak(heading,<p>,
and<address>tags,forexample)mustnotbeusedwithinthe<pre>block.Some
browserswillinterpretparagraph-endingtagsassimplelinebreaks,butthis
behaviorisnotconsistentacrossallbrowsers.
Stylemarkupandothertagsareallowedina<pre>block,soyoumustuseentity
equivalentsfortheliteralcharacters:<for<,>for>,and&for&.
Youplacetagsintothe<pre>blockasyouwouldinanyotherportionofthe
HTML/XHTMLdocument.Forinstance,studythereferencetothe"process"
functioninthepreviousexample.Itcontainsahyperlink(usingthe<a>tag)toits
sourcefile,process.c.
4.6.5.2.Thewidthattribute
The<pre>taghasanoptionalattribute,width,whichdeterminesthenumberof
characterstofitonasinglelinewithinthe<pre>block.Thebrowsermayusethis
valuetoselectafontorfontsizethatfitsthespecifiednumberofcharacterson
eachlineinthe<pre>block.Itdoesnotmeanthatthebrowserwillwrapandfill
texttothespecifiedwidth.Rather,lineslongerthanthespecifiedwidthsimply
extendbeyondthevisibleregionofthebrowser'swindow.
Thewidthattributeisonlyadvicefortheuser'sbrowser;itmayormaynotbeable
toadjusttheviewfonttothespecifiedwidth.
4.6.5.3.Thedirandlangattributes
Thedirattributeletsyouadvisethebrowserinwhichdirectionthetextwithinthe
<pre>segmentshouldbedisplayed,andlangletsyouspecifythelanguageused
withinthattag.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
4.6.5.4.Theclass,id,style,andtitleattributes
Althoughthebrowsersusuallydisplay<pre>contentinadefinedstyle,youcan
overridethatstyleandaddspecialeffects,suchasabackgroundpicture,by
definingyourownstyleforthetag.Youcanapplythisnewlooktothe<pre>tags
usingeitherthestyleortheclassattribute.[InlineStyles:ThestyleAttribute,
8.1.1][StyleClasses,8.3]
YoualsomayassignauniqueIDtothe<pre>tag,aswellasalessrigoroustitle,
usingtherespectiveattributeandaccompanyingquote-enclosedstringvalue.
[Theidattribute,4.1.1.4][Thetitleattribute,4.1.1.5]
4.6.5.5.Eventattributes
Aswithmostothertaggedsegmentsofcontent,user-relatedeventscanhappen
inandaround<pre>content,suchaswhenauserclicksordouble-clickswithinits
displayspace.Currentbrowsersrecognizemanyoftheseevents.Withthe
respectiveonattributeandvalue,youmayreacttothoseeventsbydisplayinga
userdialogboxoractivatingsomemultimediaevent.[JavaScriptEventHandlers,
12.3.3]
4.6.6.The<center>Tag(Deprecated)
The<center>tagisanotheronewithobviouseffects:itscontents,includingtext,
graphics,tables,andsoon,arecenteredhorizontallyinsidethebrowser'swindow.
Fortext,thismeansthateachlinegetscenteredafterthetextflowisfilledand
wrapped.The<center>alignmentremainsineffectuntilitiscanceledwithits
</center>endtag.
<center>
Function Centersasectionoftext
Attributes align,class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </center>;neveromitted
Contains body_content
Usedin block
Linebylineisacommon,albeitprimitive,waytocentertext,anditshouldbe
usedjudiciously;browsersdonotattempttobalanceacenteredparagraphor
otherblock-relatedelements,suchaselementsinalist,sokeepyourcentered
textshortandsweet.Titlesmakegoodcenteringcandidates;acenteredlist
usuallyisdifficulttofollow.HTMLauthorscommonlyuse<center>tocenteratable
orimageinthedisplaywindow,too.Thereisnoexplicitcenteralignmentoption
forinlineimagesortables,buttherearewaystoachievetheeffectusing
stylesheets.
Becauseuserswillhavevaryingwindowwidths,displayresolutions,andsoon,
youmayalsowanttoemploythe<nobr>and<wbr>extensiontags(seesections
4.6.2and4.6.3)tokeepyourcenteredtextintactandlookinggood.Forexample:
<center>
<nobr>
Copyright2000byQuatCoEnterprises.<wbr>
Allrightsreserved.
</nobr>
</center>
The<nobr>tagsinthesamplesourcehelpensurethatthetextremainsonasingle
line,andthe<wbr>tagcontrolswherethelinemaybebrokenifitexceedsthe
browser'sdisplay-windowwidth.
Centeringisusefulforcreatingdistinctivesectionheaders,althoughyoumay
achievethesameeffectwithanexplicitalign=centerattributeintherespective
headingtag.Youmightalsocentertextusingalign=centerinconjunctionwiththe
<div>or<p>tag.Ingeneral,the<center>tagcanbereplacedbyanequivalent<div
align=center>orsimilartag,anditsuseisdiscouraged.
Indeed,like<font>andotherHTML3.2standardtagsthathavefallenintodisfavor
inthewakeofstylesheets,the<center>tagisdeprecatedintheHTML4and
XHTMLstandards,tobereplacedbyitsCSSequivalent.Nonetheless,itsusein
HTMLdocumentsisfairlycommon,andthepopularbrowsersaresuretosupport
itformanyrevisionstocome.Still,beawareofitseventualdemise.
4.6.6.1.Thedirandlangattributes
Thedirattributeletsyouadvisethebrowserinwhichdirectionthetextwithinthe
<center>segmentshouldbedisplayed,andlangletsyouspecifythelanguageused
withinthetag.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
4.6.6.2.Theclass,id,style,andtitleattributes
Usethestyleattributetospecifyaninlinestyleforthe<center>tag,orusethe
classattributetoapplyapredefinedstyleclasstothetag.[InlineStyles:Thestyle
Attribute,8.1.1][StyleClasses,8.3]
YoumayassignauniqueIDtothe<center>tag,aswellasatitle,usingthe
respectiveattributeandaccompanyingquote-enclosedstringvalue.[Theid
attribute,4.1.1.4][Thetitleattribute,4.1.1.5]
4.6.6.3.Eventattributes
Aswithmostothertaggedsegmentsofcontent,user-relatedeventscanhappen
inandaroundthe<center>tag,suchaswhenauserclicksordouble-clickswithin
itsdisplayspace.Thecurrentbrowsersrecognizemanyoftheseevents.Withthe
respectiveonattributeandvalue,youmayreacttothoseeventsbydisplayinga
userdialogboxoractivatingsomemultimediaevent.[JavaScriptEventHandlers,
12.3.3]
4.6.7.The<listing>Tag(Obsolete)
The<listing>tagisanobsoletetag,explicitlyremovedfromtheHTML4standard,
meaningthatyoushouldn'tuseit.Weincludeithereforhistoricalreasons
becausesomebrowserssupportit,andithasthesameeffectontextformatting
asthe<pre>tagwithaspecifiedwidthof132characters.
<listing>
Function Rendersablockoftextwithoutanyformatting
Attributes class,style
Endtag </listing>;neveromitted
Contains literal_text
Usedin block
Theonlydifferencebetween<pre>and<listing>isthatnoothermarkupisallowed
withinthe<listing>tag,soyoudon'thavetoreplacetheliteral<,>,and&
characterswiththeirentityequivalentsina<listing>block,asyoumustinsidea
<pre>block.
Becausethe<listing>tagisthesameasa<prewidth=132>tag,andbecauseitmight
notbesupportedinlaterversionsofthepopularbrowsers,werecommendthat
youstayawayfromusing<listing>.
4.6.8.The<xmp>Tag(Obsolete)
Likethe<listing>tag,the<xmp>tagisobsoleteandyoushouldnotuseit,even
thoughthepopularbrowserssupportit.Weincludeitheremostlyforhistorical
reasons.
<xmp>
Function Rendersablockoftextwithoutanyformatting
Attributes class,style
Endtag </xmp>;neveromitted
Contains literal_text
Usedin block
The<xmp>tagformatstextjustlikethe<pre>tagwithaspecifiedwidthof80
characters.However,unlikethe<pre>tag,youdon'thavetoreplacetheliteral<,>,
and&characterswiththeirentityequivalentswithinan<xmp>block.Thename
<xmp>isshortfor"example";thelanguage'sdesignersintendedthatthetagbe
usedtoformatexamplesoftextoriginallydisplayedon80-column-widedisplays.
Becausethe80-columndisplayhasmostlygonethewayofgreenscreensand
teletypesandtheeffectofan<xmp>tagisbasicallythesameas<prewidth=80>,don't
use<xmp>;itmaydisappearinsubsequentversionsofHTML.
4.6.9.The<plaintext>Tag(Obsolete)
Throwthe<plaintext>tagoutofyourbagofHTMLtricks;it'sobsolete,like<listing>
and<xmp>,andisincludedhereforhistoricalreasons.Authorsonceused<plaintext>
totellthebrowsertotreattherestofthedocument'stextaswritten,withno
markup.Therewasnoendingtagfor<plaintext>(ofcourse,nomarkup!),but
therewasanendto<plaintext>.Forgetaboutit.
<plaintext>
Function Rendersablockoftextwithoutanyformatting
Attributes None
Endtag None
Contains literal_text
Usedin block
4.7.BlockQuotes
Acommonelementinconventionaldocumentsistheblockquote,alengthycopy
oftextfromanotherdocument.Traditionally,shortquotesaresetoffwith
quotationmarks,andblockquotesaremadeentirelyofseparateparagraphs
withinthemaindocument,typicallywithspecialindentationandsometimes
italicizedfeaturesthatyoumaychangethroughstyleorclassdefinitions(see
Chapter8).
4.7.1.The<blockquote>Tag
Allofthetextwithinthe<blockquote>and</blockquote>tagsissetofffromthe
regulardocumenttext,usuallywithindentedleftandrightmarginsand
sometimesinitalicizedtypeface.Actualrenderingvariesfrombrowsertobrowser,
ofcourse.
<blockquote>
Function Definesablockquotation
Attributes cite,class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </blockquote>;neveromitted
Contains body_content
Usedin block
TheHTMLandXHTMLstandardsallowanyandallmarkupwithinthe<blockquote>,
althoughsomephysicalandcontent-basedstylesmayconflictwiththefontthe
browserusesfortheblockquote.Experimentationwillrevealthosewarts.
The<blockquote>tagisoftenusedtosetofflongquotationsfromothersources.For
example,popularbrowsersdisplaythefollowingasanindentedblockoftext:
WeactedincorrectlyinarbitrarilychangingtheKumquat
Festivaldate.QuotingfromtheKumquatGrowers'Bylaws:
<blockquote>
ThedateoftheKumquatFestivalmayonlybechangedby
atwo-thirdsvoteoftheGeneralMembership,provided
thata<strong>60percentquorum</strong>oftheMembership
ispresent.
</blockquote>
(Emphasismine)Sincesuchaquorumwasnotpresent,the
voteisinvalid.
Figure4-19displaystheresults.
Figure4-19.Blockquotesgettheirownspace
4.7.1.1.Theciteattribute
Theciteattributeletsyouindicatethesourceofaquote.Theattribute'svalue
shouldbeaquote-enclosedURLthatpointstotheonlinedocumentand,if
possible,theexactlocationinthedocumentwherethequotecamefrom.
Forinstance,youcouldcitethespecificsectionintheKumquatGrowers'Bylaws
inourexample.Presumably,somedaythebrowsermayactuallyletyouclickand
viewthatspecificcitationviaitsembeddedURL.Today,youmustembedan
explicithyperlinktothedocument;seeChapter6:
<blockquotecite="http://www.kumquat.com/growers/bylaws#s23.4">
4.7.1.2.Thedirandlangattributes
Thedirattributeletsyouadvisethebrowserinwhichdirectionthetextwithinthe
<blockquote>segmentshouldbedisplayed,andlangletsyouspecifythelanguage
usedwithinthattag.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
4.7.1.3.Theclass,id,style,andtitleattributes
Usethestyleattributetospecifyaninlinestyleforthe<blockquote>tag,orusethe
classattributetoapplyapredefinedstyleclasstothetag.[InlineStyles:Thestyle
Attribute,8.1.1][StyleClasses,8.3]
YoumayassignauniqueIDtothe<blockquote>tag,aswellasatitle,usingthe
respectiveattributeandaccompanyingquote-enclosedstringvalue.[Theid
attribute,4.1.1.4][Thetitleattribute,4.1.1.5]
4.7.1.4.Eventattributes
Aswithmostothertaggedsegmentsofcontent,user-relatedeventscanhappen
inandaroundthe<blockquote>tag,suchaswhenauserclicksordouble-clicks
withinitsdisplayspace.Thecurrentbrowsersrecognizemanyoftheseevents.
Withtherespectiveonattributeandvalue,youmayreacttothoseeventsby
displayingauserdialogboxoractivatingsomemultimediaevent.[JavaScript
EventHandlers,12.3.3]
4.7.2.The<q>Tag
IntroducedinHTML4.0,the<q>tagisvirtuallyidenticaltoits<blockquote>
counterpart.Thedifferenceisintheirdisplayandapplication.Youuse<q>for
shortquotesthatmaybeinlinewithsurroundingplaintext.TheHTMLandXHTML
standardsdictatethatthe<q>-enclosedtextbeginandendwithdoublequotes.All
thepopularbrowsersexceptInternetExplorersupport<q>andplacedoublequotes
ateachendoftheenclosedtext.Theresultisthatyou'llgettwosetsofquotation
marksifyouincludeyourownquotestosatisfyInternetExplorer.Nonetheless,
werecommendthatyouusethe<q>tag,notonlybecausewelikestandards,but
becauseweseebeyondtheirdisplayeffectstoapplicationsindocumenthandling,
informationextraction,andsoforth.
Usethe<blockquote>tag,ontheotherhand,forlongersegmentsthatthebrowser
willsetoffusuallyasanindentedblockfromthesurroundingcontent,suchasthat
showninFigure4-20.
<q>
Function Definesashortquotation
Attributes cite,class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </q>;neveromitted
Contains body_content
Usedin text
4.7.2.1.Theciteattribute
Theciteattributeworkswiththe<q>tagjustlikeitdoesforthe<blockquote>tag:it
letsyouindicatethesourceofaquote.Theattribute'svalueshouldbeaquote-
enclosedURLthatpointstotheonlinedocumentand,ifpossible,theexact
locationinthedocumentwherethequotecamefrom.
4.7.2.2.Thedirandlangattributes
Thedirattributeletsyouadvisethebrowserinwhichdirectionthetextwithinthe
<q>segmentshouldbedisplayed,andlangletsyouspecifythelanguageused
withinthattag.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
4.7.2.3.Theclass,id,style,andtitleattributes
Usethestyleattributetospecifyaninlinestyleforthe<q>tag,orusetheclass
attributetoapplyapredefinedstyleclasstothetag.[InlineStyles:Thestyle
Attribute,8.1.1][StyleClasses,8.3]
YoumayassignauniqueIDtothe<q>tag,aswellasatitle,usingtherespective
attributeandaccompanyingquote-enclosedstringvalue.[Theidattribute,
4.1.1.4][Thetitleattribute,4.1.1.5]
4.7.2.4.Eventattributes
Aswithmostothertaggedsegmentsofcontent,user-relatedeventscanhappen
inandaroundthe<q>tag,suchaswhenauserclicksordouble-clickswithinits
displayspace.Thecurrentbrowsersrecognizemanyoftheseevents.Withthe
respectiveonattributeandvalue,youmayreacttothoseeventsbydisplayinga
userdialogboxoractivatingsomemultimediaevent.[JavaScriptEventHandlers,
12.3.3]
4.8.Addresses
Addressesarecommonelementsintextdocuments,sothereisaspecialtagthat
setsaddressesapartfromtherestofadocument'stext.Whilethismayseemabit
extravagantaddresseshavefewformattingpeculiaritiesthatwouldrequirea
specialtagitisyetanotherexampleofcontent,notformat,beingtheprimary
focusofHTMLandXHTMLmarkup.
Bydefiningtextthatconstitutesanaddress,theauthorletsthebrowserformat
thattextinadifferentmannerandprocessthattextinwayshelpfultousers.It
alsomakesthecontentreadilyaccessibletoautomatedreadersandextractors.
Forinstance,anonlinedirectorymightincludeaddressesthebrowsercollectsinto
aseparatedocumentortable,orautomatedtoolsmightextractaddressesfroma
collectionofdocumentstobuildaseparatedatabaseofaddresses.
4.8.1.The<address>Tag
The<address>taganditsrequiredendtag(</address>)tellabrowserthatthe
enclosedtextisacontactaddress,typicallysnailmailoremail.Theaddressmay
includeothercontactinformation,too.Thebrowsermayformatthetextina
differentmannerfromtherestofthedocumenttextorusetheaddressinsome
specialway.Youalsohavecontroloverthedisplaypropertiesthroughthestyle
andclassattributesforthetag(seeChapter8).
<address>
Function Definesanaddress
Attributes class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,onMouseDown,
onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </address>;neveromitted
Contains body_content
Usedin address_content
Thetextwithinthe<address>tagmaycontainanyelementnormallyfoundinthe
bodyofadocument,excludinganother<address>tag.Stylechangesareallowed,
buttheymayconflictwiththestylethebrowserchosetorenderthe<address>
element.
Wethinkthatmost,ifnotall,documentsshouldhavetheirauthors'addresses
includedsomewhereconvenienttotheuser,usuallyattheend.Attheveryleast,
theaddressshouldbetheauthororwebmaster'semailaddress,alongwithalink
totheirhomepage.Streetaddressesandphonenumbersareoptional;personal
onesusuallyarenotincluded,forprivacyreasons.
Forexample,theaddressforthewebmasterresponsibleforacollectionof
commercialwebdocumentsoftenappearsinsourcedocumentsasfollows,
includingthespecialmailto:URLprotocolthatletsusersactivatethebrowser's
emailtool:
<address>
<ahref="mailto:webmaster@oreilly.com">Webmaster</a><br>
O'Reilly<br>
Cambridge,Massachusetts<br>
</address>
Figure4-20displaystheresults,whichareidenticalforallthepopularbrowsers
inthat,bydefault,thebodyoftheaddressgetsdisplayedinitalics.
Figure4-20.The<address>taginaction
Whetheritisshortandsweetorlongandcomplete,makesureeverydocument
youcreatehasanaddressattachedtoit.Ifsomethingisworthcreatingand
puttingontheWeb,itisworthcommentandquerybyyourreadership.
AnonymousdocumentscarrylittlecredibilityontheWeb.
4.8.1.1.Thedirandlangattributes
Thedirattributeletsyouadvisethebrowserinwhichdirectionthetextwithinthe
<address>segmentshouldbedisplayed,andlangletsyouspecifythelanguageused
withinthattag.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
4.8.1.2.Theclass,id,style,andtitleattributes
Usethestyleattributetospecifyaninlinestyleforthe<address>tag,orusethe
classattributetoapplyapredefinedstyleclasstothetag.[InlineStyles:Thestyle
Attribute,8.1.1][StyleClasses,8.3]
YoumayassignauniqueIDtothe<address>tag,aswellasatitle,usingthe
respectiveattributeandaccompanyingquote-enclosedstringvalue.[Theid
attribute,4.1.1.4][Thetitleattribute,4.1.1.5]
4.8.1.3.Eventattributes
Aswithmostothertaggedsegmentsofcontent,user-relatedeventscanhappen
inandaroundthe<address>tag,suchaswhenauserclicksordouble-clickswithin
itsdisplayspace.Thecurrentbrowsersrecognizemanyoftheseevents.Withthe
respectiveonattributeandvalue,youmayreacttothoseeventsbydisplayinga
userdialogboxoractivatingsomemultimediaevent.[JavaScriptEventHandlers,
12.3.3]
4.9.SpecialCharacterEncoding
Forthemostpart,characterswithindocumentsthatarenotpartofatagare
renderedasisbythebrowser.However,somecharactershavespecialmeaning
andarenotdirectlyrendered,andothercharacterscan'tbetypedintothesource
documentfromaconventionalkeyboard.Specialcharactersneedeitheraspecial
nameoranumericcharacterencodingforinclusioninadocument.
4.9.1.SpecialCharacters
Ashasbecomeobviousinthediscussionandexamplesleadinguptothissection,
threecharactersinsourcedocumentshaveveryspecialmeaning:theless-than
sign(<),thegreater-thansign(>),andtheampersand(&).Thesecharacters
delimittagsandspecialcharacterreferences.They'llconfuseabrowserifleft
danglingaloneorwithimpropertagsyntax,soyouhavetogooutofyourwayto
includetheiractual,literalcharactersinyourdocuments.[*]
[*]Theonlyexceptionisthatthesecharactersmayappearliterallywithinthe<listing>and<xmp>tags,butthisisa
mootpointbecausethetagsareobsolete.
Similarly,youhavetousespecialencodingtoincludedoublequotationmark
characterswithinaquotedstring,orwhenyouwanttoincludeaspecialcharacter
thatdoesn'tappearonyourkeyboardbutispartoftheISOLatin-1characterset
thatmostbrowsersimplementandsupport.
4.9.2.InsertingSpecialCharacters
Toincludeaspecialcharacterinyourdocument,encloseeitheritsstandardentity
nameorapoundsign(#)anditsnumericpositionintheLatin-1standard
characterset[*]insidealeadingampersandandanendingsemicolon,withoutany
spacesinbetween.Whew.That'salongexplanationforwhatisreallyasimple
thingtodo,asthefollowingexamplesillustrate.Thefirstexampleshowshowto
includeagreater-thansigninasnippetofcodebyusingthecharacter'sentity
name.Theseconddemonstrateshowtoincludeagreater-thansigninyourtext
byreferencingitsLatin-1numericvalue:
[*]ThepopularASCIIcharactersetisasubsetofthemorecomprehensiveLatin-1characterset.Composedbythewell-
respectedInternationalOrganizationforStandardization(ISO),theLatin-1setisalistofallletters,numbers,punctuation
marks,andsoon,commonlyusedbyWestern-languagewriters,organizedbynumberandencodedwithspecial
names.AppendixFcontainsthecompleteLatin-1charactersetandencoding.
4.10.HTML'sObsoleteExpandedFontHandling
Inearlierversionsofthisbook,werejoicedthatHTMLversion3.2hadintroduced
afont-handlingmodelforricher,moreversatiletextdisplays.WhenHTML4
deprecatedthesespecialfont-handlingtags,wenonethelessincludedtheminthe
sameprominentpositionwithinthischapterbecausetheywerestillpartofthe
HTML3.2standardandwerestillverypopularwithHTMLauthors,besidesbeing
wellsupportedbyallthepopularbrowsers.Wecouldnotdothesameforthis
editionofthebook.
LikemanydeprecatedHTMLtagsandattributes,theexpandedfont-handlingtags
ofHTML3.2werehereyesterdayandaregonetoday.InternetExplorer,the
world'smostpopularbrowser,displaysallofthem;otherbrowsersdisplaysome,
butnototherfont-relatedtags.Accordingly,weincludetheExtendedFontModel
tagsinthischapter,butattheendofthischapterandwithalltheimplicitred
flagswavinghard.
TheW3CwantsauthorstouseCSS,notacutetagsandattributes,forexplicit
controlofthefontstyles,colors,andsizesofthetextcharacters.That'swhy
theseextendedfonttagsandrelatedattributeshavefallenintodisfavor.It'snow
timeforyoutoeschewtheextendedfonttags,too.
4.10.1.TheExtendedFontSizeModel
Insteadofabsolutepointvalues,theExtendedFontModelofHTML3.2usesa
relativemeansforsizingfonts.Sizesrangefrom1,thesmallest,to7,thelargest;
thedefault(base)fontsizeis3.
Itisalmostimpossibletostatereliablytheactualfontsizesusedforthevarious
virtualsizes.Mostbrowserslettheuserchangethephysicalfontsize,andthe
defaultsizesvaryfrombrowsertobrowser.Itmaybehelpfultoknow,however,
thateachvirtualsizeissuccessively20percentlargerorsmallerthanthedefault
fontsize,3.Thus,fontsize4is20percentlarger,fontsize5is40percentlarger,
andsoon,andfontsize2is20percentsmallerandfontsize1is40percent
smallerthanfontsize3.
4.10.2.The<basefont>Tag(Deprecated)
The<basefont>tagletsyoudefinethebasicsizeforthefontthatthebrowserwill
usetorendernormaldocumenttext.Wedon'trecommendthatyouuseit,asit
hasbeendeprecatedintheHTML4andXHTMLstandardsandisnolonger
supportedbymostbrowsers,exceptInternetExplorer.
<basefont>
Function Definesthebasefontsizeforrelativefont-sizechanges
Attributes color,face,id,name,size
Endtag </basefont>;oftenomittedinHTML
Contains Nothing
Usedin block,head_content
The<basefont>tagrecognizesthesizeattribute,whosevaluedeterminesthe
document'sbasefontsize.Youmayspecifyitasanabsolutevalue,from1to7,or
asarelativevalue(byplacingaplusorminussignbeforethevalue).Inthelatter
case,thebasefontsizeisincreasedordecreasedbythatrelativeamount.The
defaultbasefontsizeis3.
InternetExplorersupportstwoadditionalattributesforthe<basefont>tag:color
andname.HTML4alsodefinesthefaceattributeasasynonymforthename
attribute.Theseattributescontrolthecolorandtypefaceusedforthetextina
documentandareusedjustliketheanalogouscolorandfaceattributesforthe
<font>tag,describedinthenextsection.
HTML4alsodefinestheidattributeforthe<basefont>tag,allowingyoutolabelthe
taguniquelyforlateraccesstoitscontents.[Theidattribute,4.1.1.4]
Authorstypicallyincludethe<basefont>tagintheheadofanHTMLdocument,ifat
all,tosetthebasefontsizefortheentiredocument.Nonetheless,thetagmay
appearnearlyanywhereinthedocument,anditmayappearseveraltimes
throughoutthedocument,eachwithanewsizeattribute.Witheachoccurrence,
the<basefont>tag'seffectsareimmediateandholdforallsubsequenttext.
InanegregiousdeviationfromtheHTMLandStandardGeneralizedMarkup
Language(SGML)standards,InternetExplorerdoesnotinterprettheending
</basefont>tagasterminatingtheeffectsofthemostrecent<basefont>tag.Instead,
the</basefont>endtagresetsthebasefontsizetothedefaultvalueof3,whichis
thesameaswriting<basefontsize=3>.
ThefollowingexamplesourceandFigure4-21illustratehowInternetExplorer
respondstothe<basefont>tagand</basefont>endtag:
Unlessthebasefontsizewasresetabove,
InernetExplorerrendersthispartinfontsize3.
<basefontsize=7>
Thistextshouldberatherlarge(size7).
<basefontsize=6>Oh,
<basefontsize=4>no!
<basefontsize=2>I'm
<basefontsize=1>shrinking!
</basefont><br>
Ahhhh,backtonormal.
Figure4-21.Playingwith<basefont>
Werecommendagainstusing</basefont>;use<basefontsize=3>instead.
4.10.3.The<font>Tag(Deprecated)
The<font>tagletsyouchangethesize,style,andcoloroftext.Wedon't
recommendthatyouuseit,becauseithasbeendeprecatedintheHTML4and
XHTMLstandards,eventhoughallthepopularbrowsersstillsupportit.Butshould
youdecidetoignoreouradvice,useitlikeanyotherphysicalorcontent-based
styletagforchangingtheappearanceofashortsegmentoftext.
<font>
Function Setsthefontsizefortext
Attributes class,color,dir,face,id,lang,size,style,title
Endtag </font>;neveromitted
Contains text
Usedin text
Tocontrolthecoloroftextfortheentiredocument,seetheattributesforthe
<body>tag,described.[AdditionsandExtensionstothe<body>Tag,5.3.1]
4.10.3.1.Thesizeattribute
Thevalueofthesizeattributemustbeoneofthevirtualfontsizes(17)described
earlier,definedasanabsolutesizefortheenclosedtextorprecededbyaplusor
minussign(+or-)todefinearelativefontsizethatthebrowseraddstoor
subtractsfromthebasefontsize(seesection4.10.2).Thebrowsersautomatically
roundthesizeto1or7ifthecalculatedvalueexceedseitherboundary.
Ingeneral,useabsolutesizevalueswhenyouwanttherenderedtexttobean
extremesize,eitherverylargeorverysmall,orwhenyouwantanentire
paragraphoftexttobeaspecificsize.
Forexample,usingthelargestfontforthefirstcharacterofaparagraphmakes
foracrudeformofilluminatedmanuscript(seeFigure4-22):
<p>
<fontsize=7>C</font>allmeIshmael.
Figure4-22.Exaggeratingthefirstcharacterofasentencewith
thesizeattributefor<font>
Also,useanabsolutefontwheninsertingadelightfullyunreadablebitof"fine"
printboilerplateorlegaleseatthebottomofyourdocument(seeFigure4-23):
<p>
<fontsize=1>
Allrightsreserved.Unauthorizedredistributionofthisdocumentis
prohibited.Opinionsexpressedhereinarethoseoftheauthors,notthe
InternetServiceProvider.
Figure4-23.Usethetiniestfontforboilerplatetext
Exceptfortheextremes,userelativefontsizestorendertextinasizedifferent
fromthesurroundingtext,toemphasizeawordorphrase.Foranexaggerated
example,seeFigure4-24:
<p>
Makesureyou<fontsize=+2>always</font>signanddatetheform!
Figure4-24.Userelativesizesformosttextembellishments
Ifyourrelativesizechangeresultsinasizegreaterthan7,thebrowserusesfont
size7.Similarly,fontsizeslessthan1arerenderedwithfontsize1.
Notethatspecifyingsize=+1orsize=-1isidenticalineffecttousingthe<big>and
<small>tags,respectively.However,nestedrelativechangestothefontsizeare
notcumulative,astheyareforthealternativetags.Each<font>tagisrelativeto
thebasefontsize,notthecurrentfontsize.Forexample(seeFigure4-25):
<p>
Theghostmoaned,"oo<fontsize=+1>oo<fontsize=+2>oo<font
size=+3>oo</font>oo</font>oo</font>oo."
Figure4-25.Relativefontsizesaccumulate
Contrastthiswiththe<big>and<small>tags,whichincreaseordecreasethefont
sizeonelevelforeachnestingofthetags.[The<big>Tag,4.5.2]
4.10.3.2.Thecolorattribute
Stillsupportedbythepopularbrowsers,thecolorattributeforthe<font>tagsets
thecoloroftheenclosedtext.Thevalueoftheattributemaybeexpressedin
eitheroftwoways:asthered,green,andblue(RGB)componentsofthedesired
color,orasastandardcolorname.Enclosingquotesarerecommendedbutnot
required.
TheRGBcolorvalue,denotedbyaprecedingpoundsign,isasix-digit
hexadecimalnumber.Thefirsttwodigitsaretheredcomponent,from00(nored)
toFF(brightred).Similarly,thenexttwodigitsarethegreencomponentandthe
lasttwodigitsarethebluecomponent.Blackistheabsenceofcolor,#000000;
whiteisallcolors,#FFFFFF.
Forexample,tocreatebasicyellowtext,youmightuse:
Herecomesthe<fontcolor="#FFFF00">sun</font>!
Alternatively,youcansettheenclosedfontcolorusinganyoneofthemany
standardcolornames.SeeAppendixGforalistofcommonones.Forinstance,
youcouldhavemadetheprevioussampletextyellowwiththefollowingsource:
Herecomesthe<fontcolor=yellow>sun</font>!
4.10.3.3.Thefaceattribute
Inearlierversions,InternetExplorerandNetscapeNavigatorletyouchangethe
fontstyleinatextpassagewiththefaceattributeforthe<font>tag.[*]Whilethis
isstillsupportedinmostbrowsers,westronglyrecommendthatyoumanageyour
fontfacesusingappropriatestyles.Interpretationofthefaceattributevaries
amongbrowsersandmissingglyphswithinafontcancauseunexpectedbehavior
withthedisplayedtext.
[*]FortheHTMLpurist,theonce-powerfuluserwhohadultimatecontroloverthebrowser,thisisegregiousindeed.
Formoverfunction;lookovercontentwhat'snext?Embeddedvideocommercialsyoucan'tstop?
Thequote-enclosedvalueoffaceisoneormoredisplayfontnamesseparatedwith
commas.Thefontfacedisplayedbythebrowserdependsonwhichfontsare
availableontheindividualuser'ssystem.Thebrowserparsesthelistoffont
names,oneaftertheother,untilitmatchesonewithafontnamesupportedby
theuser'ssystem.Ifnonematches,thetextdisplaydefaultstothefontstylethe
usersetinthebrowser'spreferences.Forexample:
Thistextisinthedefaultfont.But,
<fontface="Braggadocio,Machine,ZapfDingbats">
heavenonlyknows</font>
whatfontfaceisthisone?
IfthebrowseruserhastheBraggadocio,Machine,ornoneofthelistedfont
typefacesinstalledinhersystem,shewillbeabletoreadthe"heavenonly
knows"messageintherespectiveordefaultfontstyle.Otherwise,themessage
maybegarbled,becausetheZapfDingbatsfontcontainssymbols,notletters.Of
course,thealternativeistrue,too;youmayintendthatthemessagebea
symbol-encodedsecret.
4.10.3.4.Thedirandlangattributes
Thedirattributeletsyouadvisethebrowserinwhichdirectionthetextwithinthe
tagshouldbedisplayed,andlangletsyouspecifythelanguageusedforthetag's
contents.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
4.10.3.5.Theclass,id,style,andtitleattributes
Youcanassociateadditionaldisplayrulesforthe<font>tagusingstylesheets.You
canapplytherulestothe<font>tagusingeitherthestyleorclassattribute.[Inline
Styles:ThestyleAttribute,8.1.1][StyleClasses,8.3]
YoualsocanassignauniqueIDtothe<font>tag,aswellasalessrigoroustitle,
usingtherespectiveattributeandaccompanyingquote-enclosedstringvalue.
[Theidattribute,4.1.1.4][Thetitleattribute,4.1.1.5]
Chapter5.Rules,Images,andMultimedia
Whilethebodyofmostdocumentsistext,anappropriateseasoningofhorizontal
rules,images,andothermultimediaelementsmakesforamuchmoreinviting
andattractivedocument.Thesefeaturesarenotsimplygratuitousgeegawsthat
makeyourdocumentslookpretty,mindyou.MultimediaelementsbringHTMLand
XHTMLdocumentsalive,providingadimensionofvaluableinformationoften
unavailableinothermedia,suchasprint.Inthischapter,wedescribeindetail
howyoucaninsertspecialmultimediaelementsintoyourdocuments,whentheir
useisappropriate,andhowtoavoidoverdoingit.
YoualsomightwanttojumpaheadandskimChapter12,wherewedescribesome
catchalltags(theHTML4andXHTMLstandard<object>andthepopularbrowsers'
<embed>)thatletyouinsertallkindsofcontentanddatafiletypes,including
multimedia,intoyourdocuments.
5.1.HorizontalRules
Horizontalrulesgiveyouawaytoseparatesectionsofyourdocumentvisually.
Thatway,yougivereadersaclean,consistent,visualindicationthatoneportion
ofyourdocumenthasendedandanotherportionhasbegun.Horizontalrules
effectivelysetoffsmallsectionsoftext,delimitdocumentheadersandfooters,
andprovideextravisualpunchtoheadingswithinyourdocument.
5.1.1.The<hr>Tag
The<hr>tagtellsthebrowsertoinsertahorizontalruleacrossthedisplay
window.WithHTML,ithasnoendtag.ForXHTML,includetheend-tagslash(/)
symbolasthelastcharacterinthetagitselfafteranyattributes(<hr.../>),or
includeanendtagimmediatelyfollowing(<hr></hr>).
Likethe<br>tag,<hr>forcesasimplelinebreak.Unlike<br>,<hr>causesthe
paragraphalignmenttoreverttothedefault(leftjustified).Thebrowserplaces
theruleimmediatelybelowthecurrentline,andcontentflowresumesbelowthe
rule.[<br>,4.6.1]
<hr>
Function Breakstextflowandinsertsahorizontalrule
Attributes align,class,color ,dir,id,lang,noshade,onClick,onDblClick,onKeyDown,
onKeyPress,onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,
size,style,title,width
Endtag NoneinHTML;</hr>or<hr.../>inXHTML
Contains Nothing
Usedin body_content
Thebrowserdecideshowtorenderahorizontalrule.Typically,theruleextends
acrosstheentiredocument.Graphicalbrowsersalsomayrenderitwithachiseled
orembossedeffect;character-basedbrowsersmostlikelyusedashesor
underscorestocreatetherule.
Thereisnoadditionalspaceaboveorbelowahorizontalrule.Ifyouwanttosetit
offfromthesurroundingtext,youmustexplicitlyplacetheruleinanew
paragraph,followedbyanotherparagraphcontainingthesubsequenttext.For
example,notethespacingaroundthehorizontalrulesinthefollowingHTML
sourceandinFigure5-1:
Figure5-1.Paragraphtagsgiveyourtextextraelbowroom
Thistextisdirectlyabovetherule.
<hr>
Andthistextisimmediatelybelow.
<p>
Whereasthistextwillhavespacebeforetherule.
<p>
<hr>
<p>
Andthistexthasspaceaftertherule.
Aparagraphtagfollowingtheruletagisnecessaryifyouwantthecontent
beneaththerulelinealignedinanystyleotherthanthedefaultleft.
5.1.1.1.Thesizeattribute
Normally,browsersrenderhorizontalrules2to3pixels[*]thickwithachiseled,
3Dappearance,makingtherulelookincisedintothepage.Youmaythickenthe
ruleswiththesizeattribute.Therequiredvalueisthethickness,inpixels.You
canseetheeffectsofthisattributeinFigure5-2,asconstructedfromthe
followingsource:
[*]Apixelisoneofthemanytinydotsthatmakeupthedisplayonyourcomputer.Whiledisplaysizesvary,agoodruleof
thumbisthatonepixelequalsonepointona75-dot-per-inchdisplaymonitor.Apointisaunitofmeasureusedinprinting
andisroughlyequalto1/72ofaninch(thereare72.27pointsinaninch,tobeexact).Typicaltypefacesusedbyvarious
browsersareusually12pointstall,yieldinguptosixlinesoftextperinch.
Figure5-2.Thepopularbrowsersletyouvarythehorizontalrule
size
<p>
Thisisconventionaldocumenttext,
followedbythestandard2-pixeltallruleline.
<hr>
Thenextthreerulelinesare12,36,and72pixels
tall,respectively.
<hrsize=12>
<hrsize=36>
<hrsize=72>
ThesizeattributeisdeprecatedinHTML4andXHTMLbecauseyoucanachieveits
effectswithappropriateuseofstylesheets.
5.1.1.2.Thenoshadeattribute
Youmaynotwanta3Druleline,preferringaflat,2Drule.Justaddthenoshade
attributetothe<hr>tagtoeliminatethe3Deffect.Novalueisrequiredwith
HTML.Usenoshade="noshade"withXHTML.
Notethedifferenceinappearanceofa"normal"3Druleversusthenoshade2Done
inFigure5-3.(We'vealsoexaggeratedtherule'sthicknessforobviouseffect,as
evidentinthesourceHTMLfragment.)
Figure5-3.Normal3Druleversusthenoshade2Doption
<hrsize=32>
<p>
<hrsize=32noshade>
Interestingly,InternetExplorer'snoshaderulehasbluntendsinsteadofthe
roundedonestheotherbrowsersrender,likethatinFigure5-3.Nevertheless,the
noshadeattributeisdeprecatedinHTML4andXHTMLbecauseyoucanachieveits
effectswithappropriateuseofstylesheets.
5.1.1.3.Thewidthattribute
Thedefaultruleisdrawnacrossthefullwidthoftheviewwindow.Youcan
shortenorlengthenruleswiththewidthattribute,creatingrulelinesthateither
areanabsolutenumberofpixelswideorextendacrossacertainpercentageof
thecurrenttextflow.Mostbrowsersautomaticallycenterpartial-widthrules;see
thealignattribute(seesection4.1.1.1)toleft-orright-justifyhorizontalrules.
Herearesomeexamplesofwidth-specifiedhorizontalrules(seeFigure5-4):
Figure5-4.Thelongandshortofabsoluteandrelativerule
widths
Thefollowingrulesare40and320pixelswidenomatter
theactualwidthofthebrowserwindow:
<hrwidth=40>
<hrwidth=320>
Whereasthesenexttworuleswillalwaysextendacross
10and75percentofthewindow,regardlessofitswidth:
<hrwidth="10%">
<hrwidth="75%">
Notice,too,thattherelative(percentage)valueforthewidthattributeisenclosed
inquotationmarks;theabsolute(integer)pixelvalueisnot.Infact,the
quotationmarksaren'tabsolutelynecessarywithstandardHTML(thoughtheyare
requiredforXHTML).Further,becausethepercentsymbolnormallymeansthat
anencodedcharacterfollowsit,failuretoenclosethepercentageforthewidth
valueinquotationmarksmayconfusesomebrowsersandtrashaportionofyour
rendereddocument.
Ingeneral,itisn'tagoodideatospecifythewidthofaruleasanexactnumberof
pixels.Browserwindowsvarygreatlyintheirwidth,andwhatmightbeasmall
ruleononebrowsermightbeannoyinglylargeonanother.Forthisreason,we
recommendspecifyingrulewidthasapercentageofthewindowwidth.Thatway,
whenthewidthofthebrowserwindowchangestherulesretaintheirsame
relativesize.
ThewidthattributeisdeprecatedinHTML4andXHTMLbecauseyoucanachieve
itseffectswithappropriateuseofstylesheets.
5.1.1.4.Thealignattribute
Thealignattributeforahorizontalrulecanhaveoneofthreevalues:left,center,
orright.Forthoseruleswhosewidthislessthanthatofthecurrenttextflow,the
rulewillbepositionedaccordingly,relativetothewindowmargins.Thedefault
alignmentiscenter.
Avariedrulealignmentmakesfornicesectiondividers.Forexample,the
followingsourcealternatesa35-percent-widerulefromrighttocentertotheleft
margin(seeFigure5-5):
Figure5-5.Varyinghorizontalrulealignmentmakesforsubtle
sectiondividers
<hrwidth="35%"align=right>
<h3>FruitPackingAdvice</h3>
...
<hrwidth="35%"align=center>
<h3>ShippingKumquats</h3>
...
<hrwidth="35%"align=left>
<h3>JuiceProcessing</h3>
...
ThealignattributeisdeprecatedinHTML4andXHTMLbecauseyoucanachieve
itseffectswithappropriateuseofstylesheets.
5.1.1.5.Thecolorattribute
SupportedbyInternetExplorerandNetscapeNavigatorversions7and8,butnot
otherpopularbrowserssuchasOpera,thecolorattributeletsyousetthecolorof
theruleline.Thevalueofthisattributeiseitherthenameofacolorora
hexadecimaltripletthatdefinesaspecificcolor.Foracompletelistofcolornames
andvalues,seeAppendixG.
Bydefault,aruleissettothesamecolorasthedocumentbackground,withthe
chiselededgesslightlydarkerandlighterthanthebackgroundcolor.Youlosethe
3Deffectwhenyouspecifyanothercolor,eitherinastylesheetorwiththecolor
attribute.
5.1.1.6.Combiningruleattributes
Youmaycombinethevariousruleattributes;theirorderisn'timportant.Tocreate
bigrectangles,forexample,combinethesizeandwidthattributes(seeFigure5-
6):
Figure5-6.Combiningruleattributesforspecialeffects
<hrsize=32width="50%"align=center>
Infact,somecombinationsofruleattributesarenecessaryalignandwidth,for
example.Alignaloneappearstodonothingbecausethedefaultrulewidth
stretchesallthewayacrossthedisplaywindow.
5.1.1.7.Theclass,dir,event,id,lang,style,andtitleattributes
Thereareseveralnearlyuniversalattributesforthemanycontenttags.These
attributesgiveyouacommonwaytoidentify(title)andlabel(id)atag's
contentsforlaterreferenceorautomatedtreatment,tochangethecontents'
displaycharacteristics(class,style),toreferencethelanguage(lang)used,andto
specifythedirectioninwhichthetextshouldflow(dir).Ofcourse,howlanguage
andthedirectionoftextaffectahorizontalruleisunclear.Nonetheless,theyare
standardattributesforthetag.[Thedirattribute,3.6.1.1][Thelangattribute,
3.6.1.2][Theidattribute,4.1.1.4][Thetitleattribute,4.1.1.5][InlineStyles:
ThestyleAttribute,8.1.1][StyleClasses,8.3]
Inaddition,therearealltheusereventsthatmayhappeninandaroundthe
horizontalrulethatthebrowsersensesandthatyoumayreacttoviaanon-event
attributeandsomeprogramming.[JavaScriptEventHandlers,12.3.3]
5.1.2.UsingRulestoDivideYourDocument
Horizontalrulesprovideahandyvisualnavigationdeviceforyourreaders.Touse
<hr>effectivelyasasectiondivider,firstdeterminehowmanylevelsofheadings
yourdocumenthasandhowlongyouexpecteachsectionofthedocumenttobe.
Thendecidewhichofyourheadingswarrantsbeingsetapartbyarule.
Ahorizontalrulecanalsodelimitthefrontmatterofadocument,separatingthe
tableofcontentsfromthedocumentbody,forexample.Alsouseahorizontalrule
toseparatethedocumentbodyfromatrailingindex,bibliography,orlistof
figures.
Experiencedauthorsalsousehorizontalrulestomarkthebeginningandendofa
form.Thisisespeciallyhandyforlongformsthatmakeusersscrollupanddown
thepagetoviewallthefields.Byconsistentlymarkingthebeginningandendofa
formwitharule,youhelpusersstaywithintheform,betterensuringthatthey
won'tinadvertentlymissaportionwhenfillingoutitscontents.
5.1.3.UsingRulesinHeadersandFooters
Afundamentalstyleapproachtocreatingdocumentfamiliesistohavea
consistentlookandfeel,includingastandardheaderandfooterforeach
document.Typically,theheadercontainsnavigationaltoolsthathelpuserseasily
jumptointernalsectionsaswellasrelateddocumentsinthefamily,andthe
footercontainsauthoranddocumentinformationaswellasfeedback
mechanisms,suchasanemaillinktothewebmaster.
Toensurethattheseheadersandfootersdon'tinfringeonthemaindocument
contents,considerusingrulesdirectlybelowtheheaderandabovethefooter.For
example(seealsoFigure5-7):
Figure5-7.Clearlydelineateheadersandfooterswithhorizontal
rules
<body>
KumquatGrowersHandbook-GrowingSeasonGuidelines
<hr>
<h1align=center>GrowingSeasonGuidelines</h1>
Growingseasonforthenoblefruitvariesthroughout
NorthAmerica,asshowninthefollowingmap:
<p>
<imgsrc="pics/growing-season.gif">
<p>
<hr>
<i>Providedasapublicservicebythe
<ahref="feedback.html">KumquatLoversofAmerica</a></i>
Byconsistentlysettingapartyourheadersandfootersusingrules,youhelpusers
locateandfocusuponthemainbodyofyourdocument.
5.2.InsertingImagesinYourDocuments
OneofthemostcompellingfeaturesofHTMLandXHTMListheirabilitytoinclude
imageswithyourdocumenttext,eitherasintrinsiccomponentsofthedocument
(inlineimages),asseparatedocumentsspeciallyselectedfordownloadvia
hyperlinks,orasbackgroundtoyourdocumentorelementswithinthedocument.
Whenjudiciouslyaddedtothebodycontent,imagesstaticandanimatedicons,
pictures,illustrations,drawings,andsooncanmakeyourdocumentsmore
attractive,inviting,andprofessionallooking,aswellasinformativeandeasyto
browse.Youmayalsospeciallyenableanimagesothatitbecomesavisualmap
ofhyperlinks.Whenusedtoexcess,however,imagesmakeyourdocument
cluttered,confusing,andinaccessible,andtheyunnecessarilylengthenthetimeit
takesforuserstodownloadandviewyourpages.
5.2.1.UnderstandingImageFormats
NeitherHTMLnorXHTMLprescribesanofficialformatforimages.However,the
popularbrowsersspecificallyaccommodatecertainimageformats:GIF,PNG,and
JPEG,inparticular(seethefollowingsectionsforexplanations).Mostother
multimediaformatsrequirespecialaccessoryapplicationsthateachbrowser
ownermustobtain,install,andsuccessfullyoperatetoviewthespecialfiles.So
it'snottoosurprisingthatGIF,PNG,andJPEGarethedefactoimagestandards
ontheWeb.
BothimageformatswerealreadyinwidespreadusebeforetheWebcameinto
being,sothere'slotsofsupportingsoftwareouttheretohelpyouprepareyour
graphicsforeitherformat.However,eachhasitsownadvantagesanddrawbacks,
includingfeaturesthatsomebrowsersexploitforspecialdisplayeffects.
5.2.1.1.GIF
TheGraphicsInterchangeFormat(GIF)wasfirstdevelopedforimagetransfer
amongusersoftheCompuServeonlineservice.Theformathasseveralfeatures
thatmakeitpopularforuseinHTMLandXHTMLdocuments.Itsencodingiscross-
platformsothatwithappropriateGIF-decodingsoftware(includedwithmost
browsers),thegraphicsyoucreateandmakeintoaGIFfileonaMacintosh,for
example,canbeloadedintoaWindows-basedPC,decoded,andviewedwithouta
lotoffuss.ThesecondmainfeatureisthatGIFusesspecialcompression
technologythatcansignificantlyreducethesizeoftheimagefileforfaster
transferoveranetwork.GIFcompressionis"lossless,"too;noneofanimage's
originaldataisalteredordeleted,sotheuncompressedanddecodedimage
exactlymatchesitsoriginal.Also,GIFimagescanbeeasilyanimated.
EventhoughGIFimagefilesinvariablyhavethe.gif(or.GIF)filenamesuffix,
thereactuallyaretwoGIFversions:theoriginalGIF87andanexpandedGIF89a,
whichsupportsseveralnewfeaturesincludingtransparentbackgrounds,interlaced
storage,andanimationthatarepopularwithwebauthors(seesection5.2.1.2).
ThecurrentlypopularbrowserssupportbothGIFversions,whichusethesame
encodingschemethatmaps8-bitpixelvaluestoacolortable,foramaximumof
256colorsperimage.MostGIFimageshaveevenfewercolors;therearespecial
toolstosimplifythecolorsinmoreelaborategraphics.BysimplifyingtheGIF
images,youcreateasmallercolormapandenhancepixelredundancyforbetter
filecompressionand,consequently,fasterdownloading.
However,becauseofthelimitednumberofcolors,aGIF-encodedimageisnot
alwaysappropriate,particularlyforphotorealisticpictures(seethediscussionin
section5.2.1.3).GIFsmakeexcellenticons,reduced-colorimages,anddrawings.
BecausemostgraphicalbrowsersexplicitlysupporttheGIFformat,itiscurrently
themostwidelyacceptedimage-encodingformatontheWeb.Itisacceptablefor
bothinlineimagesandexternallylinkedones.Whenindoubtastowhichimage
formattouse,chooseGIF.[*]Itwillworkinalmostanysituation.
[*]WecannotresistthetemptationtopointoutthatchoosyauthorschooseGIF.
5.2.1.2.Interlacing,transparency,andanimation
YoucanmakeGIFimagesperformthreespecialtricks:interlacing,transparency,
andanimation.Withinterlacing,aGIFimageseeminglymaterializesonthe
display,insteadofprogressivelyflowingontoitfromtoptobottom.Normally,a
GIF-encodedimageisasequenceofpixeldatainorder,rowbyrow,fromthetop
tothebottomoftheimage.WhilethecommonGIFimagerendersonscreenlike
pullingdownawindowshade,interlacedGIFsopenlikeaVenetianblind.That's
becauseinterlacingsequenceseveryfourthrowoftheimage.Usersgettoseea
fullimagetoptobottom,albeitfuzzyinaquarterofthetimeittakestodownload
anddisplaytheremainderoftheimage.Theresultingquarter-doneimageusually
isclearenoughsothatuserswithslownetworkconnectionscanevaluatewhether
totakethetimetodownloadtheremainderoftheimagefile.
Notallgraphicalbrowsers,althoughabletodisplayaninterlacedGIF,areactually
abletodisplaythematerializingeffectsofinterlacing.Withthosethatdo,users
stillcandefeattheeffectbychoosingtodelayimagedisplayuntilafterdownload
anddecoding.Olderbrowsers,ontheotherhand,alwaysdownloadanddecode
imagesbeforedisplayanddon'tsupporttheeffectatall.
AnotherpopulareffectavailablewithGIFimagesGIF89a-formattedimages,that
isistheabilitytomakeaportionofthemtransparentsothatwhat'sunderneath
(usually,thebrowserwindow'sbackground)showsthrough.ThetransparentGIF
imagehasonecolorinitscolormapdesignatedasthebackgroundcolor.The
browsersimplyignoresanypixelintheimagethatusesthatbackgroundcolor,
therebylettingthedisplaywindow'sbackgroundshowthrough.Bycarefully
croppingitsdimensionsandbyusingasolid,contiguousbackgroundcolor,you
canmakeatransparentimageseamlesslymeldintoorfloataboveapage's
surroundingcontent.
TransparentGIFimagesaregreatforanygraphicthatyouwanttomeldintothe
documentandnotstandoutasarectangularblock.TransparentGIFlogosare
verypopular,asaretransparenticonsanddingbatsanygraphicthatshouldappear
tohaveanarbitrary,naturalshape.Youmayalsoinsertatransparentimage
inlinewithconventionaltexttoactasaspecialcharacterglyphwithin
conventionaltext.
ThedownsidetotransparencyisthattheGIFimagewilllooklousyifyoudon't
removeitsborderwhenitisincludedinahyperlinkanchor(<a>)tagoris
otherwisespeciallyframed.Andcontentflowhappensaroundtheimage's
rectangulardimensions,notadjacenttoitsapparentshape.Thatcanleadto
unnecessarilyisolatedimagesorodd-lookingsectionsinyourwebpages.
ThethirduniquetrickavailablewithGIF89a-formattedimagesistheabilitytodo
simpleframe-by-frameanimation.UsingspecialGIF-animationsoftwareutilities,
youmayprepareasingleGIF89afilethatcontainsaseriesofGIFimages.The
browserdisplayseachimageinthefile,oneaftertheother,somethinglikethe
page-flippinganimationbookletswehadandperhapsdrewaskids.Specialcontrol
segmentsbetweeneachimageintheGIFfileletyousetthenumberoftimesthe
browserrunsthroughthecompletesequence(looping),howlongtopause
betweeneachimage,whethertheimagespacegetswipedtobackgroundbefore
thebrowserdisplaysthenextimage,andsoon.Bycombiningthesecontrol
featureswiththosenormallyavailableforGIFimages,includingindividualcolor
tables,transparency,andinterlacing,youcancreatesomeveryappealingand
elaborateanimations.[*]
[*]SonglineStudioshaspublishedanentirebookdedicatedtoGIFanimation:GIFAnimationStudio,byRichardKoman.
SimpleGIFanimationispowerfulforoneotherimportantreason:youdon'tneed
tospeciallyprogramyourHTMLdocumentstoachieveanimation.Butthereisone
majordownsidethatlimitstheiruseforanythingotherthansmall,icon-size,or
thinbandsofspaceinthebrowserwindow:GIFanimationfilesgetlargefast,
evenifyouarecarefulnottorepeatstaticportionsoftheimageinsuccessive
animationcells.Andifyouhaveseveralanimationsinonedocument,download
delaysmayandusuallywillannoytheuser.Ifanyfeaturedeservesclosescrutiny
forexcess,it'sGIFanimation.
AnyandallGIFtricksinterlacing,transparency,andanimationdon'tjusthappen;
youneedspecialsoftwaretopreparetheGIFfile.Manyimagetoolsnowsave
yourcreationsoracquiredimagesinGIFformat,andmostnowletyouenable
transparencyandmakeinterlacedGIFfiles.Therealsoareaslewofshareware
andfreewareprogramsspecializedforthesetasks,aswellasforcreatingGIF
animations.LookintoyourfavoriteInternetsoftwarearchivesforGIFgraphics
andconversiontools,andseeChapter17fordetailsoncreatingtransparent
images.
5.2.1.3.JPEG
TheJointPhotographicExpertsGroup(JPEG)isastandardsbodythatdeveloped
whatisnowknownastheJPEGimage-encodingformat.LikeGIFs,JPEGimages
areplatformindependentandspeciallycompressedforhigh-speedtransfervia
digitalcommunicationtechnologies.UnlikeGIF,JPEGsupportstensofthousands
ofcolorsformoredetailed,photorealisticdigitalimages.AndJPEGusesspecial
algorithmsthatyieldmuchhigherdata-compressionratios.Itisnotuncommon,
forexample,fora200KBGIFimagetobereducedtoa30KBJPEGimage.To
achievethatamazingcompression,JPEGdoeslosesomeimagedata.However,
youcanadjustthedegreeof"lossiness"withspecialJPEGtoolssothatalthough
theuncompressedimagemaynotexactlymatchtheoriginal,itwillbeclose
enoughthatmostpeoplecannottellthedifference.
AlthoughJPEGisanexcellentchoiceforphotographs,it'snotaparticularlygood
choiceforillustrations.Thealgorithmsusedforcompressinganduncompressing
theimageleavenoticeableartifactswhendealingwithlargeareasofonecolor.
Therefore,ifyou'retryingtodisplayadrawing,theGIFformatmaybepreferable.
TheJPEGformat,usuallydesignatedbythe.jpg(or.JPG)filenamesuffix,is
nearlyuniversallyunderstoodbytoday'sgraphicalbrowsers.Onrareoccasions,
you'llcomeacrossanolderbrowserthatcannotdirectlydisplayJPEGimages.
5.2.1.4.PNG
ThePortableNetworkGraphics(PNG)technologyoriginatedtoreplaceGIF,but
notbecauseGIFwasn'tuptothejob.Indeed,GIFwasandprobablystillisthe
mostwidelyimplementedgraphicsformatontheInternet.Instead,manyInternet
usersgotenragedwhenin1993,afterGIFhadattaineditspopularityand
widespreaduse,UnisysdecidedtoenforceitspatentandcollectroyaltiesonGIF's
essentialcompressiontechnology.Thatactionranagainstthewidespread
philosophyoffreeexchangeanduseenjoyedbythemostlyacademiccommunity
ofInternetusers,andpromptedaninformalInternetworkinggroupledby
ThomasBoutelltodevelopthePNGalternative.
PNG'sadvantagesoverGIFandJPEG,besidesprovidingalitigation-free
alternativeformat,includeabroaderselectionofcolorformats(24-bittrue-color
RGB,agrayscaleandGIF-like8-bitpalette)andbetterlosslesscompression.
PNG'suniqueandattractivefeaturesincludealphachannelswhichletyouspecify
manymorethanGIF'sonelayeroftransparency(morethan65,000,actually)
andcansimulate3Dimagery,gammacorrectionwhichcontrolscross-platform
imagebrightnessformorevividgraphics,andtwo-dimensionalinterlacingwhich
providesforafinerprogressivelydevelopingimage.
PNGdoesnotsupportanimation.ThoughyoumayhesitatetousePNGonthat
basisalone,weencourageyoutotryitoutanyway,especiallyforhigh-colorand
high-qualityimages.
5.2.2.WhentoUseImages
Mostpicturesareworthathousandwords.Butdon'tforgetthatnoonepays
attentiontoablabbermouth.Firstandforemost,thinkofyourdocumentimages
asvisualtools,notasgratuitoustrappings.Theyshouldsupportyourtextcontent
andhelpreadersnavigateyourdocuments.Useimagestoclarify,illustrate,or
exemplifythecontents.Content-supportingphotographs,charts,graphs,maps,
anddrawingsareallnaturalandappropriatecandidates.Productphotographsare
essentialcomponentsinonlinecatalogsandshoppingguides,forexample.And
link-enablediconsanddingbats,includinganimatedimages,canbeeffective
visualguidestointernalandexternalresources.Ifanimagedoesn'tdoanyof
thesevaluableservicesforyourdocument,throwitoutalready!
Oneofthemostimportantconsiderationswhenaddingimagestoadocumentis
theadditionaldelaytheyaddtotheretrievaltimeforadocumentoverthe
network,particularlyformodemconnections.Whileacommontextdocument
mightrun,atmost,10,000or15,000bytes,imagescaneasilyextendto
hundredsofthousandsofbyteseach.Andthetotalretrievaltimeforadocument
isnotonlyequaltothesumofallitscomponentparts,butalsotocompounded
networkingoverheaddelays.
Dependingonthespeedoftheconnection(bandwidth,usuallyexpressedasbits
orbytespersecond)aswellasnetworkcongestionthatcandelayconnections,a
singledocumentcontainingone100KBimagemaytakelessthanasecond
throughacablemodemconnectionintheweehoursofthemorning,whenmost
everyoneelseisasleep,towellover10minuteswithacellphoneatnoon.You
getthepicture?
Withthatsaid,ofcourse,picturesandothermultimediaaredrivingInternet
providerstocomeupwithfaster,better,morerobustwaystodeliverwebcontent.
Modemconnectionsarequicklygoingthewayofthehorseandcarriage,replaced
bytechnologieslikehigh-speedcablemodemsandtheAsymmetricDigital
SubscriberLine(ADSL).
Still,asthepricelowers,usegoesup,sothereistheissueofcongestion.And
don'tforgetcellphonebrowsersandourThirdWorldneighbors,where
connectionsarespottyandslow.Besides,ifyouarecompetingforaccesstoan
overburdenedserver,itdoesn'tmatterhowfastyourconnectionmaybe.
5.2.3.WhentoUseText
Texthasn'tgoneoutofstyle.Forsomeusers,itistheonlyaccessibleportionof
yourdocument.Wearguethat,inmostcircumstances,yourdocumentsshouldbe
usablebyreaderswhocannotviewimages,orhavedisabledautomaticdownload
intheirbrowserstoimprovetheirconnections.Whiletheurgetoaddimagesto
allofyourdocumentsmaybestrong,sometimespuretextdocumentsmakemore
sense.
DocumentsbeingconvertedtotheWebfromotherformatsrarelyhaveembedded
images.Referencematerialsandotherseriouscontentoftenarecompletely
usableinatext-onlyform.
Youshouldcreatetext-onlydocumentswhenaccessspeediscritical.Ifyouknow
thatmanyuserswillbevyingforyourpages,youshouldaccommodatethemby
avoidingtheuseofimageswithinyourdocuments.Insomeextremecases,you
mightprovideahome(leading)pagethatletsreadersdecidebetweenduplicate
collectionsofyourwork:onecontainingtheimagesandanotherstrippedofthem.
(Thepopularbrowsersincludespecialpictureiconsasplaceholdersforyet-to-be-
downloadedimages,whichcantrashandmuddleyourdocument'slayoutintoan
unreadablemess.)
Textismostappropriatesupportingimagesonly,withoutfrillsandnonessential
graphicsifyourdocumentsaretobereadilysearchablebyanyofthemanyweb
indexingservices.Thesesearchenginesalmostalwaysignoreimages.Ifyou
providethemajorcontentofyourpageswithimages,verylittleinformationabout
yourdocumentswillfinditswayintotheonlinewebdirectories.
5.2.4.SpeedingImageDownloads
Thereareseveralwaystoreducetheoverheadanddelaysinherentwithimages,
besidesbeingverychoosyaboutwhichtoincludeinyourdocuments:
Keepitsimple
Afull-screen,24-bitcolorgraphic,evenwhenreducedinsizebydigital
compressionwithoneofthestandardformats,suchasGIF,PNG,orJPEG,is
stillgoingtobeanetwork-bandwidthhog.Firstdecidebetweenimage
integrityandsize.Thenacquireandusetheproperimage-managementtool
thatoptimizesyourimagefortheapplication,particularlyforspecialeffects
likeGIFanimationorPNG's3Deffects.Simplifyyourdrawings.Stayaway
frompanoramicphotographs.Avoidlarge,emptybackgroundsinyourimages,
aswellasgratuitousbordersandotherspace-consumingelements.Alsoavoid
dithering(blendingtwocolorsamongadjacentpixelstoachieveathirdcolor);
thistechniquecansignificantlyreducethecompressibilityofyourimages.
Striveforlargeareasofuniformcolors,whichcompressreadily.
Reuseimages
ThisisparticularlytrueforiconsandGIFanimations.Mostbrowserscache
incomingdocumentcomponentsinlocalstoragefortheverypurposeofquick,
network-connectionlessretrievalofdata.ForsmallerGIFanimationfiles,try
toprepareeachsuccessiveimagetoupdateonlyportionsthatchangeinthe
animation,insteadofredrawingtheentireimage(thisspeedsupthe
animation,too).
Dividelargedocumentsintosmallersegments
Thisisageneralrulethatincludesimages.Manysmalldocumentsegments,
organizedthroughhyperlinksandeffectivetablesofcontents,tendtobe
betteracceptedbyusersthanafewlargedocuments.Ingeneral,people
wouldrather"flip"severalpagesthandawdle,waitingforalargeoneto
download.(It'srelatedtotheTVchannel-surfingsyndrome.)Oneaccepted
ruleofthumbistokeepyourdocumentssmallerthan50KBeach,soeven
theslowestconnectionswon'toverlyfrustrateyourreaders.
Isolatenecessarilylargegraphics
Provideaspeciallinktolargeimages,perhapsonethatincludesathumbnail
ofthegraphic,therebylettingreadersdecidewhetherandwhentheywantto
spendthetimedownloadingthefullimage.Becausethedownloadedimage
isn'tmixedwithotherdocumentcomponentslikeinlineimages,it'salsomuch
easierforthereadertoidentifyandsavetheimageonhersystem'slocal
storageforlaterstudy.(Fordetailsonnoninlineimagedownloads,seesection
5.6.2.)
Specifyimagedimensions
Finally,anotherwaytoimproveperformanceisbyincludingtheimage's
rectangularheightandwidthinformationinitstag.Bysupplyingthose
dimensions,youeliminatetheextrastepstheextendedbrowsersmusttaketo
download,examine,andcalculateanimage'sspaceinthedocument,allowing
themtorenderthepagemorequickly.Thereisadownsidetothisapproach,
however,thatweexploreinsection5.2.6.12.
5.2.5.JPEG,PNG,orGIF?
YoumaychoosetouseonlyonetypeofimageformatinyourHTMLdocumentsif
yoursourcesforimagesoryoursoftwaretoolsetpreferoneovertheother
format.Allarenearlyuniversallysupportedbytoday'sbrowsers,sothere
shouldn'tbeanyuser-viewingproblems.
Nevertheless,werecommendthatyouacquirethefacilitiestocreateandconvert
toatleastthethreeformatswedescribeinthischaptertotakeadvantageoftheir
uniquecapabilities.Forinstance,useGIF'sanimationandPNG'stransparency
featureforiconsanddingbats.Alternatively,useJPEG'sdeepcompression,albeit
atalossofsomeintegrity,forlargeandcolorfulimagesforfasterdownloading.
5.2.6.The<img>Tag
The<img>tagletsyoureferenceandinsertagraphicimageintothecurrenttext
flowofyourdocument.Thereisnoimpliedlineorparagraphbreakbeforeorafter
the<img>tag,soimagescanbetruly"inline"withtextandothercontent.
<img>
Function Insertsanimageintoadocument
Attributes
align,alt,border,class,controls ,dir,dynsrc ,height,hspace,id,ismap,lang,
longdesc ,loop ,lowsrc ,name ,onAbort,onClick,onDblClick,onError,
onKeyDown,onKeyPress,onKeyUp,onLoad,onMouseDown,onMouseMove,onMouseOut,
onMouseOver,onMouseUp,src,start ,style,title,usemap,vspace,width
Endtag NoneinHTML;</img>or<img.../>inXHTML
Contains Nothing
Usedin text
TheformatoftheimageitselfisnotdefinedbytheHTMLorXHTMLstandard,
althoughthepopulargraphicalbrowserssupportmostcommonformatslikeGIF,
PNG,andJPEGimages.Thestandardsdon'tspecifyorrestrictthesizeor
dimensionsoftheimage,either.Imagesmayhaveanynumberofcolorsas
allowedbytheirformat,buthowthosecolorsarerenderedishighlybrowser
dependent.
Imagepresentationingeneralisverybrowserspecific.Imagesmaybeignoredby
nongraphicalbrowsers.Browsersoperatinginaconstrainedenvironmentmay
modifytheimagesizeorcomplexity.Andusers,particularlythosewithslow
networkconnections,maychoosetodeferimageloadingaltogether.Accordingly,
youshouldmakesureyourdocumentsmakesenseandareusefulevenifthe
imagesarecompletelyremoved.
TheHTMLversionofthe<img>taghasnoendtag.WithXHTML,eitheruse</img>
immediatelyfollowingthe<img>taganditsattributes,ormakethelastcharacter
inthetagtheend-tagslashmark:<imgsrc="kumquat.gif"/>,forexample.
5.2.6.1.Thesrcattribute
Thesrcattributeforthe<img>tagisrequired(unlessyouusedynsrcwithInternet
Explorer-basedmovies;seesection5.2.7.1).Itsvalueistheimagefile'sURL,
eitherabsoluteorrelativetothedocumentreferencingtheimage.Tounclutter
theirdocumentstorage,authorstypicallycollectimagefilesintoaseparatefolder,
whichtheyoftennamesomethinglike"pics"or"images."[Referencing
Documents:TheURL,6.2]
Forexample,thisHTMLfragmentplacesanimageofafamouskumquatpacking
plantintothenarrativetext(seeFigure5-8):
Figure5-8.Imageintegratedwithtext
Hereweare,onday17ofthetour,inthekumquatpackingplant:
<p>
<imgsrc="pics/packing_plant.gif">
<p>
Whatanexcitingmoment,toseetheboxesoffruitpiledhighto
Intheexample,theparagraph(<p>)tagssurroundingthe<img>tagcausethe
browsertorendertheimagebyitself,withsomeverticalspaceafterthe
precedingtextandbeforethetrailingtext.Textmayalsoabuttheimage,aswe
describeinsection4.1.1.1.
5.2.6.2.Thelowsrcattribute
Tothebenefitofusers,particularlythosewithslownetworkconnections,early
versionsofNetscapeprovidedthelowsrccompaniontothesrcattributeinthe<img>
tagasawaytospeedupdocumentrendering.Thelowsrcattribute'svalue,like
src,istheURLofanimagefile.Netscapebeforeversion6wouldloadanddisplay
thelowsrcimagewhenitfirstencounteredthe<img>tag.Then,whenthedocument
hadbeencompletelyloadedandtheusercouldreadit,Netscapewouldretrieve
theimagespecifiedbythesrcattribute.
NootherbrowserbesidesNetscapeversions4andearliersupportslowsrc.
Netscapeversion6simplyusesthedimensionsofthelowsrcimagetotemporarily
allocatedisplayspacefortheimageasitrendersthedocument.Theearlier
versionsofNetscapealsousedthelowsrcdimensionstoresizethefinalimage,
whichyoucouldexploitforsomespecialeffects.Thisnolongerworks.Instead,we
recommendthatyoueschewtheNetscapeextensionandexplicitlyallocateimage
spacewiththeheightandwidthattributesdescribedlaterinthischapter.
5.2.6.3.Thealtandlongdescattributes
Thealtattributespecifiesalternativetextthebrowsermayshowifimagedisplay
isnotpossibleorisdisabledbytheuser.Especiallyfavoredbyvisuallyimpaired
users,thepopularbrowsersalsoletuschoosetodisplayalttextalongwiththe
image.Soalthoughit'sanoption,it'sonewehighlyrecommendyouexercisefor
mostimagesinyourdocument.Thisway,iftheimageisnotavailable,theuser
stillhassomeindicationofwhat'smissing.Andforuserswithcertaindisabilities,
altoftenistheonlywaytheycanappreciateyourimages.
Inaddition,InternetExplorerdisplaysthealternativedescriptioninatextbox
whenuserspassthemouseovertheimage.Accordingly,youmightembedshort,
parentheticalinformationthatpopsupwhenuserspassoverasmall,inlineicon,
suchasthatshowninFigure5-9.
Figure5-9.InternetExplorerdisplaysalttextinatemporary
pop-upwindow
Thevalueforthealtattributeisatextstringofupto1,024characters,including
spacesandpunctuation.Thestringmustbeenclosedinquotationmarks.Thealt
textmaycontainentityreferencestospecialcharacters,butitmaynotcontain
anyothersortofmarkup;inparticular,styletagsaren'tallowed.
Graphicalbrowsersdon'tnormallydisplaythealtattributeiftheimageis
availableandtheuserhasenabledpicturedownloading.Otherwise,theyinsert
thealtattribute'stextasalabelnexttoanimage-placeholdericon.Well-chosen
altlabelstherebyadditionallysupportthoseuserswithgraphicalbrowserswho
havedisabledautomaticimagedownloadbecauseofaslowconnectiontothe
Web.
Nongraphical,text-onlybrowserssuchastheancientLynxputthealttextdirectly
intothecontentflow,justlikeanyothertextelement.So,whenusedeffectively,
thealttagsometimescantransparentlysubstituteformissingimages.(Yourtext-
onlybrowseruserswillappreciatenotbeingconstantlyremindedoftheirsecond-
classwebcitizenship.)Forexample,considerusinganasteriskasthealtattribute
alternativetoaspecialbulleticon:
<h3><imgsrc="pics/fancy_bullet.gif"alt="*">Introduction</h3>
Agraphicalbrowserdisplaysthebulletimage;inanongraphicalbrowser,thealt
asterisktakestheplaceofthemissingbullet.Similarly,usealttexttoreplace
specialimagebulletsforlistitems.Forexample,thefollowingcode:
<ul>
<li>Kumquatrecipes<imgsrc="pics/new.gif"alt="(New!)">
<li>Annualharvestdates
</ul>
displaysthenew.gifimagewithgraphicalbrowsersandthetext"(New!)"with
text-onlybrowsers.Thealtattributeusesevenmorecomplextext(seeFigure5-
10):
Figure5-10.Text-onlybrowserssuchasLynxdisplayanimage's
altattributetext
Hereweare,onday17ofthetour,inthekumquat
packingplant:
<p>
<imgsrc="pics/packing_plant.gif"
alt="[Imageofourtourgroupoutsidethemainpackingplant]">
<p>
Whatanexcitingmoment,toseetheboxesoffruitmoving
AccordingtotheHTML4.01specification,thealtattributeisrequiredforall<img>
tags.Tobetrulycompliant,includeemptyaltattributes(alt="")withallyour
images.
Thelongdescattributeissimilartothealtattributebutallowsforlonger
descriptions.ThevalueoflongdescistheURLofadocumentcontaininga
descriptionoftheimage.Ifyouhaveadescriptionlongerthan1,024characters,
usethelongdescattributetolinktoit.NeitherHTML4norXHTMLspecifieswhat
thecontentofthedescriptionmustbe,andnobrowserscurrentlyimplement
longdesc;allbetsareoffwhendecidinghowtocreatethoselongdescriptions.
5.2.6.4.Thealignattribute
Thestandardsdon'tdefineadefaultalignmentforimageswithrespecttoother
textandimagesinthesamelineoftext:youcan'talwayspredicthowthetext
andimageswilllook.[*]HTMLimagesnormallyappearinlinewithasinglelineof
text.Commonprintmediasuchasmagazineswraptextaroundimages,with
severallinesnexttoandabuttingtheimage,notjustasingleline.
[*]Mostofthepopulargraphicalbrowsersinsertanimagesothatitsbasealignswiththebaselineofthetextthesame
alignmentspecifiedbytheattributevalueofbottom.Butdocumentdesignersshouldassumethatalignmentvaries
amongbrowsersandshouldalwaysincludethedesiredtypeofimagealignment.
Fortunately,documentdesignersalsocanexertsomecontroloverthealignment
ofimageswiththesurroundingtextthroughthealignattributeforthe<img>tag.
TheHTMLandXHTMLstandardsspecifyfiveimage-alignmentattributevalues:
left,right,top,middle,andbottom.Theleftandrightvaluesflowanysubsequent
texttotheleftorrightoftheimage,whichismovedtothecorrespondingmargin
(Figure5-11).Theremainingthreealigntheimageverticallywithrespecttothe
surroundingtext.
Figure5-11.Standardinlineimagealignments
Allofthepopularbrowsers,includingOpera,Firefox,Netscape,andInternet
Explorer,agreethatalign=bottomisthedefaultverticalalignment,andsimilarly
positionimagesatthetopoftheuppermostcharacterinthelineoftext,also
showninFigure5-11.
Thebrowsersdisagree,however,onwheretoplaceanalign=middleimagewith
regardtotext.AsshowninFigure5-11,NetscapeandOperaplaceitinthe
apparentmiddleofthetext.InternetExplorerandFirefox,ontheotherhand,
placetheimageatthemiddleofthetallestelement,notnecessarilythetallest
text(Figure5-12).
Figure5-12.InternetExplorerandFirefoxalignthemiddleof
imagestothemiddleofthetallestelement,nottothemiddleof
thetext
Thebrowsersalsosupport,tovaryingdegrees,fiveverticalimagealignment
extensionstexttop,center,absmiddle,baseline,andabsbottom(ifyouareconfusedasto
exactlywhateachalignmentvaluemeans,pleaseraiseyourhand):
texttop
Thealign=texttopattributeandvaluetellthebrowsertoalignthetopofthe
imagewiththetopofthetallesttextiteminthecurrentline,asopposedto
thetopoption,whichalignsthetopoftheimagewiththetopofthetallest
item,imageortext,inthecurrentline.Ifthelinecontainsnootherimages
thatextendabovethetopofthetext,texttopandtophavethesameeffect.
Operadoesnotsupporttexttop,whereastheotherpopularbrowserstreatit
identicallyasdescribed.
center
OriginallyintroducedbyInternetExplorer,thecenterimagealignmentvalue
getstreatedbyInternetExplorer,Netscape,andFirefoxexactlythesameas
theyindividuallytreatmiddle,which,asyoumayrecall,differsamongthe
browsers.Opera,ontheotherhand,ignoresalign=centeraltogether.
absmiddle
Ifyousetthealignattributeofthe<img>tagtoabsmiddle,thebrowserwillfit
theabsolutemiddleoftheimagetotheabsolutemiddleofthecurrentline.
Thisisdifferentfromthecommonmiddleandcenteroptions,whichalignthe
middleoftheimagewiththebaselineofthecurrentlineoftext(thebottom
ofthecharacters).ThoughNetscapeandOperadonotdistinguishabsmiddle
frommiddlealignments,FirefoxandInternetExploreruseittodifferentially
alignimagesfromtheirmiddlevaluesinotherwords,FirefoxandInternet
Explorer'sabsmiddlealignmentisthesameasNetscape'smiddle.
bottomandbaseline(default)
Thebottomandbaselineimage-alignmentvalueshavethesameeffectasifyou
didn'tincludeanyalignmentattributeatall:thebrowsersalignthebottomof
theimageinthesamehorizontalplaneasthebaselineofthetext.Thisisnot
tobeconfusedwithabsbottom,whichtakesintoaccountletterdescenders.(Did
weseeahandupintheaudience?)
absbottom
Thealign=absbottomattribute-valuepairtellsthebrowsertoalignthebottomof
theimagewiththetruebottomofthecurrentlineoftext.Thetruebottomis
thelowestpointinthetext,takingintoaccountdescenders,evenifthereare
nocharacterswithdescendersintheline.Adescenderisthetailona"y,"for
example;thebaselineofthetextisthebottomofthe"v"inthe"y"character.
Opera,thestandardbearer,ignoresabsbottom,whereastheotherpopular
browserstreatitasadvertised(Figure5-13).
Figure5-13.Browserstakeintoaccounttextdescenderswhen
aligningimageswiththealign=absbottomattribute
Usethetopormiddlealignmentvalueforbestintegrationoficons,dingbats,or
otherspecialinlineeffectswiththetextcontent.Otherwise,align=bottom(the
default)usuallygivesthebestappearance.Whenaligningoneormoreimageson
asingleline,selectthealignmentthatgivesthebestoverallappearancetoyour
document.
5.2.6.5.Wrappingtextaroundimages
Theleftandrightimage-alignmentvaluestellthebrowsertoplaceanimage
againsttheleftorrightmargin,respectively,ofthecurrenttextflow.Thebrowser
thenrenderssubsequentdocumentcontentintheremainingportionoftheflow
adjacenttotheimage.Thenetresultisthatthedocumentcontentfollowingthe
imagegetswrappedaroundtheimage:
<imgsrc="pics/kumquat.gif"align=left>
Thekumquatisthesmallestofthecitrusfruits,similarinappearancetoa
tinyorange.Thesimilarityendswithitsappearance,however.Whileoranges
aregenerally
sweet,kumquatsareextremelybitter.Theirsisanacquiredtaste,tobesure.
Figure5-14showstextflowaroundaleft-alignedimage.
Figure5-14.Textflowaroundaleft-alignedimage
Youcanplaceimagesagainstbothmarginssimultaneously(Figure5-15),andthe
textwillrundownthemiddleofthepagebetweenthem:
Figure5-15.Runningtextbetweenleft-andright-aligned
images
<imgsrc="pics/kumquat.gif"align=left>
<imgsrc="pics/tree.gif"align=right>
Thekumquatisthesmallestofthecitrusfruits,similarinappearancetoa
tinyorange.Thesimilarityendswithitsappearance,however.Whileoranges
aregenerallysweet,kumquatsareextremelybitter.Theirsisanacquiredtaste,
tobesure.
Whiletextisflowingaroundanimage,theleft(orright)marginofthepageis
temporarilyredefinedtobeadjacenttotheimageasopposedtotheedgeofthe
page.Subsequentimageswiththesamealignmentwillstackupagainsteach
other.Thefollowingsourcefragmentachievesthatstaggeredimageeffect:
<imgsrc="pics/marcia.gif"align=left>
Marcia!
<br>
<imgsrc="pics/jan.gif"align=left>
Jan!
<br>
<imgsrc="pics/cindy.gif"align=left>
Cindy!
TheresultsofthisexampleareshowninFigure5-16.
Figure5-16.Threeverylovelygirlsfromaveryoldsitcom
Whenthetextflowsbeyondthebottomoftheimage,themarginreturnstoits
formerposition,typicallyattheedgeofthebrowserwindow.
5.2.6.6.Centeringanimage
Haveyounoticedthatyoucan'thorizontallycenteranimageinthebrowser
windowwiththealignattribute?Themiddleandabsmiddlevaluescentertheimage
verticallywiththecurrentline,buttheimageishorizontallyjustifieddepending
onwhatcontentcomesbeforeitinthecurrentflowandthedimensionsofthe
browserwindow.
Youcanhorizontallycenteraninlineimageinthebrowserwindow,butonlyifit's
isolatedfromsurroundingcontent,suchasbyparagraph,division,orline-break
tags.Then,eitherusethe<center>tagorusethealign=centerattributeorcenter-
justifiedstyleintheparagraphordivisiontagtocentertheimage.Forexample:
Kumquatsaretastytreats
<br>
<center>
<imgsrc="pics/kumquat.gif">
</center>
thateveryoneshouldstrivetoeat!
Usetheparagraphtagwithitsalign=centerattributeifyouwantsomeextraspace
aboveandbelowthecenteredimage:
Kumquatsaretastytreats
<palign=center>
<imgsrc="pics/kumquat.gif">
</p>
thateveryoneshouldstrivetoeat!
5.2.6.7.Alignand<center>aredeprecated
TheHTML4andXHTMLstandardshavedeprecatedthealignattributeforalltags,
including<img>,indeferencetostylesheets.They'vedeprecated<center>,too.
Nonetheless,theattributeandtagareverypopularamongHTMLauthorsand
remainwellsupportedbythepopularbrowsers.So,whilewedoexpectthat
somedaybothalignand<center>willdisappear,itwon'tbeanytimesoon.Justdon't
saywedidn'twarnyou.
Whatifyoudon'twanttousealignor<center>?Someauthorsandmanyofthe
WYSIWYGeditorsuseHTML/XHTMLtablestoaligncontent.That'soneway,albeit
involved(seeChapter10).TheWorldWideWebConsortium(W3C)wantsyouto
usestyles.Forexample,usethemargin-leftstyletoindenttheimagefromtheleft
sideofthedisplay.YoucanreadlotsmoreaboutCascadingStyleSheets(CSS)in
Chapter8.
5.2.6.8.Theborderattribute
Browsersnormallyrenderimagesthatalsoarehyperlinks(i.e.,imagesincludedin
an<a>tag)witha2-pixel-widecoloredborder,indicatingtothereaderthathecan
selecttheimagetovisittheassociateddocument.Usetheborderattributeanda
pixel-widththicknessvaluetoremove(border=0)orwidenthatimageborder.Be
awarethatthisattribute,too,isdeprecatedinHTML4andXHTML,indeferenceto
stylesheets,butcontinuestobewellsupportedbythepopularbrowsers.
Figure5-17showsyouthethickandthinofimageborders,asrenderedby
InternetExplorerfromthefollowingXHTMLsource:
Figure5-17.Thethickandthinofimageborders
<ahref="test.html">
<imgsrc="pics/kumquat.gif"border="1"/>
</a>
<ahref="test.html">
<imgsrc="pics/kumquat.gif"border="2"/>
</a>
<ahref="test.html">
<imgsrc="pics/kumquat.gif"border="4"/>
</a>
<ahref="test.html">
<imgsrc="pics/kumquat.gif"border="8"/>
</a>
5.2.6.9.Removingtheimageborder
Youcaneliminatetheborderaroundanimagehyperlinkaltogetherwiththe
border=0attributewithinthe<img>tag.Forsomeimages,particularlyimagemaps,
theabsenceofabordercanimprovetheappearanceofyourpages.Imagesthat
areclearlylinkbuttonstootherpagesmayalsolookbestwithoutborders.
Becareful,though,thatbyremovingtheborder,youdon'tdiminishyourpage's
usability.Nobordermeansyou'veremovedacommonvisualindicatorofalink,
makingitmoredifficultforyourreaderstofindthelinksonthepage.Browsers
willchangethemousecursorasthereaderpassesitoveranimagethatisa
hyperlink,butyoushouldnotassumetheywill,norshouldyoumakereaderstest
yourborderlessimagestofindhiddenlinks.
Westronglyrecommendthatwithborderlessimagesyouusesomeadditionalway
toletyourreadersknowtoclicktheimages.Evenincludingsimpletext
instructionswillgoalongwaytowardmakingyourpagesmoreaccessibleto
readers.
5.2.6.10.Theheightandwidthattributes
Everwatchthedisplayofapage'scontentsshiftarounderraticallywhilethe
documentisloading?Thathappensbecausethebrowserreadjuststhepagelayout
toaccommodateeachloadedimage.Thebrowserdeterminesthesizeofan
imageand,hence,therectangularspacetoreserveforitinthedisplaywindowby
retrievingtheimagefileandextractingitsembeddedheightandwidth
specifications.Thebrowserthenadjuststhepage'sdisplaylayouttoinsertthat
pictureinthedisplay.[*]Thisisnotthemostefficientwaytorenderadocument
becausethebrowsermustsequentiallyexamineeachimagefileandcalculateits
screenspacebeforerenderingadjacentandsubsequentdocumentcontent.That
cansignificantlyincreasetheamountoftimeittakestorenderthedocumentand
candisruptreadingbytheuser.
[*]Anotherreminderthatimagesareseparatefiles,whichareloadedindividuallyandinadditiontothesourcedocument.
Amoreefficientwayforauthorstospecifyanimage'sdimensionsiswiththe
heightandwidth<img>attributes.Thatway,thebrowsercanreservespacebefore
actuallydownloadinganimage,speedingdocumentrenderingandeliminatingthe
contentshifting.Bothattributesrequireanintegervaluethatindicatestheimage
sizeinpixels;theorderinwhichtheyappearinthe<img>tagisnotimportant.
5.2.6.11.Resizingandflood-fillingimages
Ahiddenfeatureoftheheightandwidthattributesisthatyoudon'tneedtospecify
theactualimagedimensions;theattributevaluescanbelargerorsmallerthan
theactualsizeoftheimage.Thebrowserautomaticallyscalestheimagetofitthe
predefinedspace.Thisgivesyouadown-and-dirtywayofcreatingthumbnail
versionsoflargeimagesandawaytoenlargeverysmallpictures.Becareful,
though:thebrowserstillmustdownloadtheentirefile,nomatterwhatitsfinal
renderedsizeis,andyouwilldistortanimageifyoudon'tretainitsoriginal
heightversuswidthproportions.
Anothertrickwithheightandwidthprovidesaneasywaytoflood-fillareasofyour
pageandcanalsoimprovedocumentperformance.Supposeyouwanttoinserta
coloredbaracrossyourdocument.[ ]Insteadofcreatinganimagetofillthefull
dimensions,createonethatisjust1pixelhighandwideandsetittothedesired
color.Thenusetheheightandwidthattributestoscaleittothelargersize:
[ ]Thisisonewaytocreatecoloredhorizontalrules,sinceNetscapedoesn'tsupportthecolorattributeforthe<hr>
tag.
<imgsrc="pics/one-pixel.gif"width=640height=20>
Thesmallerimagedownloadsmuchfasterthanafull-scaleone,andthewidthand
heightattributeshaveFirefox,forexample,createthedesiredbright-redcolored
barafterthetinyimagearrivesatthebrowser(Figure5-18).
Figure5-18.Thiscoloredhorizontalbarwasmadefroma1-
pixelimage
Onelasttrickwiththewidthattributeistouseapercentagevalueratherthanan
absolutepixelvalue.Thiscausesthebrowsertoscaletheimagetoapercentage
ofthedocumentwindowwidth.Thus,tocreateacoloredbar20pixelshighand
thewidthofthewindow,youcoulduse:
<imgsrc="pics/one-pixel.gif"width="100%"height=20>
Asthedocumentwindowchangessize,theimagewillchangesizeaswell.
Ifyouprovideapercentagewidthandomittheheight,thebrowserwillretainthe
image'saspectratioasitgrowsandshrinks.Thismeansthattheheightwill
alwaysbeinthecorrectproportiontothewidth,andtheimagewilldisplay
withoutdistortion.
5.2.6.12.Problemswithheightandwidth
Althoughtheheightandwidthattributesforthe<img>tagcanimproveperformance
andletyouperformneattricks,thereisaknottydownsidetousingthem.The
browsersetsasidethespecifiedrectangleofspacetotheprescribeddimensionsin
thedisplaywindow,eveniftheuserhasturnedoffautomaticdownloadofimages.
Whattheuseroftenisleftwithisapagefullofsemi-emptyframeswith
meaninglesspicture-placeholdericonsinside.Thepagelooksterriblyunfinished
andismostlyuseless.Withoutaccompanyingdimensions,ontheotherhand,the
browsersimplyinsertsaplaceholdericoninlinewiththesurroundingtext,soat
leastthere'ssomethingtheretoreadinthedisplay.
Wedon'thaveasolutionforthisdilemma,otherthantoinsistthatyouusethe
altattributewithsomedescriptivetextsothatusersatleastknowwhattheyare
missing.Wedorecommendthatyouincludethesesizeattributesbecausewe
encourageanypracticethatimprovesdisplayperformance.
5.2.6.13.Thehspaceandvspaceattributes
Graphicalbrowsersusuallydon'tgiveyoumuchspacebetweenanimageandthe
textaroundit.Andunlessyoucreateatransparentimageborderthatexpands
thespacebetweenthem,thetypical2-pixelbufferbetweenanimageand
adjacenttextisjusttoocloseformostdesigners'comfort.Addtheimageintoa
hyperlink,andthespecialcoloredborderwillnegateanytransparentbufferspace
youlaboredtocreate,aswellasdrawingevenmoreattentiontohowclosethe
adjacenttextbuttsupagainsttheimage.
Thehspaceandvspaceattributescangiveyourimagesbreathingroom.Withhspace,
youspecifythenumberofpixelsofextraspacetoleavebetweentheimageand
textontheleftandrightsidesoftheimage;thevspacevalueisthenumberof
pixelsonthetopandbottom:
<imgsrc="pics/kumquat.gif"align=left>
Thekumquatisthesmallestofthecitrusfruits,similar
inappearancetoatinyorange.Thesimilarityendswithits
appearance,however.Whileorangesaregenerallysweet,
kumquatsareextremelybitter.Theirsisanacquiredtaste,
tobesure.Mostfolks,atfirsttaste,wonderhowyoucould
evereatanother,letaloneenjoyit!
<p>
<imgsrc="pics/kumquat.gif"align=lefthspace=10vspace=10>
Thekumquatisthesmallestofthecitrusfruits,similar
inappearancetoatinyorange.Thesimilarityendswithits
appearance,however.Whileorangesaregenerallysweet,
kumquatsareextremelybitter.Theirsisanacquiredtaste,
tobesure.Mostfolks,atfirsttaste,wonderhowyoucould
evereatanother,letaloneenjoyit!
Figure5-19showsthedifferencebetweentwowrappedimages.
Figure5-19.Improveimage/textinterfaceswithvspaceand
hspace
We'resureyou'llagreethattheadditionalspacearoundtheimagemakesthetext
easiertoreadandtheoverallpagemoreattractive.
5.2.6.14.Theismapandusemapattributes
Theismapandusemapattributesforthe<img>tagtellthebrowserthattheimageisa
specialmouse-selectablevisualmapofoneormorehyperlinks,commonlyknown
asanimagemap.Youcanspecifytheismapstyleofimagemapsonlywithinan<a>
taghyperlink.[<a>,6.3.1]
Forexample(noticetheredundantattributeandvalue,aswellasthetrailing
end-tagslashmarkinthe<img>tag,whicharetelltalesignsofXHTML):
<ahref="/cgi-bin/images/map2">
<imgsrc="pics/map2.gif"ismap="ismap"/>
</a>
Thebrowserautomaticallysendsthecoordinatesofthemouserelativetothe
upper-leftcorneroftheimagetotheserverwhentheuserclickssomewhereon
theismapimage.Specialserversoftware(the/cgi-bin/images/map2program,in
theexample)maythenusethosecoordinatestodeterminearesponse.
Theismapattributeisaserver-sidemechanismbecauseitreliesontheserverfor
processinguserinput.Theusemapattributeprovidesaclient-sideimage-map
mechanismthateffectivelyeliminatesserver-sideprocessingofthemouse
coordinatesanditsincumbentnetworkdelaysandproblems.Usingspecial<map>
and<area>tags,HTMLauthorsprovideamapofcoordinatesforthehyperlink-
sensitiveregionsintheusemapimage,alongwithrelatedhyperlinkURLs.Thevalue
oftheusemapattributeisaURLthatpointstothatspecial<map>section.The
browserontheuser'sclientcomputertranslatesthecoordinatesofaclickofthe
mouseontheimageintosomeaction,includingloadinganddisplayinganother
document.[<map>,6.5.3][<area>,6.5.4]
Forexample,thefollowingsourcespeciallyencodesthe100x100-pixelmap2.gif
imageintofoursegments,eachofwhich,ifclickedbytheuser,linkstoadifferent
document.Noticethatwe'veincluded,validly,theismapimage-mapprocessing
capabilityintheexample<img>tagsothatusersofother,usemap-incapablebrowsers
haveaccesstothealternative,server-sidemechanismtoprocesstheimagemap:
<ahref="/cgi-bin/images/map2">
<imgsrc="pics/map2.gif"ismapusemap="#map2">
</a>
...
<mapname="map2">
<areacoords=0,0,49,49"href="link1.html">
<areacoords="50,0,99,49"href="link2.html">
<areacoords="0,50,49,99"href="link3.html">
<areacoords="50,50,99,99"href="link4.html">
</map>
Geographicalmapsmakeexcellentismapandusemapexamples:browsinga
nationwidecompany'spages,forinstance,theusersmightclickontheir
hometownsonamaptogettheaddressesandphonenumbersfornearbyretail
outlets.Theadvantageofusemapclient-sideimage-mapprocessingisthatitdoes
notrequireaserverorspecialserversoftwareandso,unliketheismap
mechanism,canbeusedinnonweb(networkless)environments,suchaslocal
filesandCD-ROMs.
Pleasereadourmorecompletediscussionofanchorsandlinks,includingimage
mapswithinlinks,insection6.5.
5.2.6.15.Theclass,dir,event,id,lang,style,andtitleattributes
Severalnearlyuniversalattributesgiveyouacommonwaytoidentify(title)and
label(id)theimagetag'scontentsforlaterreferenceorautomatedtreatment,to
changethecontents'displaycharacteristics(class,style),toreferencethe
language(lang)used,andtospecifythedirectioninwhichthetextshouldflow
(dir).And,ofcourse,therearealltheusereventsthatmayhappeninandaround
thetaggedcontentsthatthebrowsersensesandthatyoumayreacttoviaanon-
eventattributeandsomeprogramming.[InlineStyles:ThestyleAttribute,8.1.1]
[StyleClasses,8.3]
OfthesemanyHTML4andXHTMLattributes,idisthemostimportant.Itletsyou
labeltheimageforlateraccessbyaprogramorbrowseroperation(seeChapter
12).[Theidattribute,4.1.1.4]
Theremainingattributeshavequestionablemeaningincontextwith<img>.
Granted,afewstylesheetoptionsareavailablethatmayinfluenceanimage's
display,andit'sgoodtoincludeatitle(althoughaltisbetter).However,it'shard
toimaginetheinfluencethatlanguage(lang)oritspresentationdirection(dir)
mighthaveonanimage.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
5.2.6.16.Thename,onAbort,onError,onLoad,andothereventattributes
Therearefour<img>attributesoriginallysupportedbyNetscapeandnowbyallthe
popularbrowsersthatenableyoutouseJavaScripttomanipulateimages.The
firstisthenameattribute.[*]Nowredundantwiththeidattribute,nameletsyoulabel
theimagesothataJavaScriptappletcanreferenceit.Forexample:
[*]HTMLversion4.01andXHTMLhaveadoptedthenameattribute,too.
<imgsrc="pics/kumquat.gif"name="kumquat">
letsyoulaterrefertothatpictureofakumquatassimply"kumquat"ina
JavaScriptapplet,perhapstoeraseorotherwisemodifyit.Youcannotindividually
manipulateanimagewithJavaScriptifitisnotnamedordoesn'thavean
associatedid.
TheotherthreeattributesletyouprovidesomespecialJavaScripteventhandlers.
ThevalueofeachattributeisachunkofJavaScriptcode,enclosedinquotation
marks;itmayconsistofoneormoreJavaScriptexpressions,separatedby
semicolons.
ThepopularbrowsersinvoketheonAborteventhandleriftheuserstopsloadingan
image,usuallybyclickingthebrowser'sStopbutton.Youmight,forinstance,use
anonAbortmessagetowarnusersiftheystoploadingsomeessentialimage,such
asanimagemap(seesection6.5):
<imgsrc="pics/kumquat.gif"usemap="#map1"
onAbort="window.alert('Caution:Thisimagecontainsimportanthyperlinks.
Pleaseloadtheentireimage.')">
TheonErrorattributeisinvokedifsomeerroroccursduringtheloadingofthe
image,butnotforamissingimageoronethattheuserchosetostoploading.
Presumably,theappletcouldattempttorecoverfromtheerrororloadadifferent
imageinitsplace.
ThecurrentlypopularbrowsersexecutetheJavaScriptcodeassociatedwiththe
<img>tag'sonLoadattributerightafterthebrowsersuccessfullyloadsanddisplays
theimage.
Seesection12.3.3formoreinformationaboutJavaScriptandeventhandlers.
5.2.6.17.Combining<img>attributes
Youmaycombineanyofthevariousstandardandextensionattributesforimages
whereandwhentheymakesense.Theorderforinclusionofmultipleattributesin
the<img>tagisnotimportant,either.Justbecarefulnottouseredundant
attributes,oryouwon'tbeabletopredicttheoutcome.
5.2.7.VideoExtensions
InternetExplorersupportsspecialvideo-related<img>attributeextensionsthatlet
youembedmoviesintoyourHTMLdocuments:controls,dynsrc,loop,andstart.
ThesearenotHTML4andareunlikelytobecomeXHTMLstandardattributes.In
fact,usershavetospecificallyenablethemwithInternetExplorer's"Playvideoin
webpages"AdvancedInternetOptions.
Equivalentbehaviorisavailablewithallthepopularbrowsersviaanextension
programknownasaplug-in.Plug-insplaceanadditionalburdenontheuserin
thateachusermustfindandinstalltheappropriateplug-insoftwarebeforebeing
abletoviewtheinlinevideo.TheInternetExplorer<img>tagextensions,onthe
otherhand,madevideodisplayanintrinsicpartofthebrowser.[Embedded
Content,12.2]
5.2.7.1.Thedynsrcattribute
Usethedynsrcattributeextensioninthe<img>tagtoreferenceanAVI,MPGor
MPEG,MOV,WMV,oranypopularmovieformatforinlinedisplaybyInternet
Explorer.ItsrequiredvalueistheURLofthemoviefile,enclosedinquotation
marks.Forexample,thistextdisplaysthetagandattributeforanAVImoviefile
titledintro.avi:
<imgdynsrc="movies/intro.avi">
InternetExplorersetsasideavideoviewportintheHTMLdisplaywindowand
playsthemovie,withaudioifit'sincludedintheclipandifyourcomputerisable
toplayaudio.InternetExplorertreatsdynsrcmoviessimilartoinlineimages:in
linewithcurrentbodycontentandaccordingtothedimensionofthevideoframe.
And,likecommonimages,thedynsrc-referencedmoviefilegetsdisplayed
immediatelyafterdownloadfromtheserver.Youmaychangethosedefaultsand
addsomeusercontrolswithotherattributes,asdescribedlater.
BecauseallotherbrowserscurrentlyignorethespecialInternetExplorer
attributesformovies,theymaybecomeconfusedbyan<img>tagthatdoesnot
containtheotherwiserequiredsrcattributeandanimageURL.Werecommend
thatyouincludethesrcattributeandavalidimagefileURLinall<img>tags,
includingthosethatreferenceamovieforInternetExplorerusers.Theother
browsersdisplaythestillimageinplaceofthemovie;InternetExplorerdoesthe
reverseandplaysthemovie,butdoesnotdisplaytheimage.Notethattheorder
ofattributesdoesnotmatter.Forexample:
<imgdynsrc="movies/intro.avi"src="pics/mvstill.gif">
InternetExplorerloadsandplaystheAVImovieintro.avi;othergraphical
browserswillloadanddisplaythemvstill.gifimageinstead.
5.2.7.2.Thecontrolsattribute
Normally,InternetExplorerplaysamovieinsideaframedviewportonce,without
anyvisibleusercontrols.AlthoughnolongersupportedinInternetExplorer
version5orlater,witholderversionsofthebrowserthecontrolsattribute(no
value)enableduserstorestart,stop,andcontinuethemoviebyclickinginside
thatviewportwiththemouse.Ifthemovieclipincludesasoundtrack,theearlier
InternetExplorerprovidedanaudiovolumecontrolaswell.Forexample:
<imgdynsrc="movies/intro.avi"controlssrc="pics/mvstill.gif">
5.2.7.3.Theloopattribute
InternetExplorernormallyplaysamovieclipfrombeginningtoendonce,after
download.Theloopattributeforthemovie<img>tagletsyouhavetheclipplay
repeatedlyforanintegernumberoftimessetbytheattribute'svalue,orforever
ifthevalueisinfinite.Theusermaystillcuttheloopshortbyclickingthe
browser'sStopbuttonorbymovingontoanotherdocument.
Thefollowingintro.avimovieclipwillplayfrombeginningtoend,thenrestartat
thebeginningandplaythroughtotheendninemoretimes:
<imgdynsrc="movies/intro.avi"loop=10src="pics/mvstill.gif">
Whereasthefollowingmoviewillplayoverandoveragain,incessantly:
<imgdynsrc="movies/intro.avi"loop=infinitesrc="pics/mvstill.gif">
Loopingmoviesaren'tnecessarilymeanttoannoy.Somespecial-effects
animations,forinstance,areasequenceofrepeatedframesorsegments.Instead
ofstringingtheredundantsegmentsintoonelongmovie,whichextendsits
downloadtime,simplyloopthesingle,compactsegment.
5.2.7.4.Thestartattribute
Normally,anInternetExplorermovieclipstartsplayingassoonasit's
downloaded.Youcanmodifythatbehaviorwiththestartattributeinthemovie's
<img>tag.Bysettingitsvaluetomouseover,youdelayplaybackuntiltheuserpasses
themousepointeroverthemovieviewport.Theothervalidstartattributevalue,
fileopen,isthedefault:startplaybackjustafterdownload.Itisincludedbecause
bothvaluesmaybecombinedinthestartattribute,tocausethemovietoplay
backautomaticallyonce,afterdownload,andthenwhenevertheuserpassesthe
mouseoveritsviewport.Whencombiningthestartattributevalues,addavalue-
separatingcomma,withnointerveningspaces,orelseenclosetheminquotes.
Forexample,ourby-now-infamousintro.avimoviewillplayoncewhenitshost
HTMLdocumentisloadedbytheInternetExploreruserandagainwheneverhe
passesthemouseoverthemovie'sviewport:
<imgdynsrc="movies/intro.avi"start="fileopen,mouseover"src="pics/mvstill.gif">
5.2.7.5.Combiningmovie<img>attributes
TreatInternetExplorerinlinemoviesasyouwouldanyimage,mixingand
matchingthevariousmovie-specificaswellasthestandardandextended<img>
tagattributesandvaluessupportedbythebrowser.Forexample,youmightalign
themovie(oritsimagealternative,ifdisplayedbyanotherbrowser)totheright
ofthebrowserwindow:
<imgdynsrc="movies/intro.avi"src="pics/mvstill.gif"align=right>
Combiningattributestoachieveaspecialeffectisgood.Wealsorecommendthat
youcombineattributestogivecontroltotheuser,whenappropriate.
5.3.DocumentColorsandBackgroundImages
TheHTML4andXHTMLstandardsprovideanumberofattributesforthe<body>tag
thatletyoudefinetext,link,anddocumentbackgroundcolors,inadditionto
defininganimagetobeusedasthedocumentbackground.Allthepopular
browsersadditionallyextendtheseattributestoincludedocumentmarginsand
betterbackgroundimagecontrol.And,ofcourse,thelateststylesheet
technologiesintegratedintothecurrentbrowsersletyoumanipulateallofthese
variousdisplayparameters.
5.3.1.AdditionsandExtensionstothe<body>Tag
Theattributesthatcontrolthedocumentbackground,textcolor,anddocument
marginsareusedwiththe<body>tag.[<body>,3.8.1]
5.3.1.1.Thebgcolorattribute
Onestandard,althoughdeprecated,wayyoucanchangethedefaultbackground
colorinthebrowserwindowtoanotherhueiswiththebgcolorattributeforthe
<body>tag.Likethecolorattributeforthe<font>tag,therequiredvalueofthe
bgcolorattributemaybeexpressedineitheroftwoways:asthered,green,and
blue(RGB)componentsofthedesiredcolor,orasastandardcolorname.
AppendixGprovidesacompletediscussionofRGBcolorencodingalongwitha
tableofacceptablecolornamesyoucanusewiththebgcolorattribute.
Settingthebackgroundcoloriseasy.TogetapureredbackgroundusingRGB
encoding,try:
<bodybgcolor="#FF0000">
Forasubtlerbackground,try:
<bodybgcolor="peach">
5.3.1.2.Thebackgroundattribute
Ifasplashofcolorisn'tenough,youmayalsoplaceanimageintothebackground
ofadocumentwiththebackgroundattributeinthe<body>tag.
TherequiredvalueofthebackgroundattributeistheURLofanimage.Thebrowser
automaticallyrepeats(tiles)theimagebothhorizontallyandverticallytofillthe
entirewindow.
Younormallyshouldchooseasmall,somewhatdimimagetocreateaninteresting
butunobtrusivebackgroundpattern.Besides,asmall,simpleimagetraversesthe
networkmuchfasterthananintricate,full-screenimage.
Figure5-20and5-21showyouhowtheextendedbrowsersrenderasinglewood
panelasanindividualpictureandthentileittocreateapaneledwallwhen
includedasadocument'sbackground:
Figure5-20.Asinglewoodpanel...
Figure5-21....becomesmanyasthe<body>background
<body>
<imgsrc="pics/wood_panel.gif">
versus:
<bodybackground="pics/wood_panel.gif">
Backgroundimagesofvariousdimensionsandsizescreateinterestingverticaland
horizontaleffectsonthepage.Forinstance,atall,skinnyimagemightsetoff
yourdocumentheading:
<bodybackground="pics/vertical_fountain.gif">
<h3>KumquatLore</h3>
Forcenturies,manymythsandlegendshavearisenaroundthekumquat.
...
Ifvertical_fountain.gifisanarrow,tallimagewhosecolorgrowslightertowardits
baseandwhoselengthexceedsthelengthofthedocumentbody,theresulting
documentmightlookliketheoneshowninFigure5-22.
Figure5-22.Atallandskinnybackground
Youcanachieveasimilareffecthorizontallywithanimagethatismuchwider
thanitislong(seeFigure5-23).
Figure5-23.Alongandskinnybackground
ThebackgroundattributeisdeprecatedinHTML4andXHTMLbecauseyoucan
achievesimilareffectsusingstylesheets.
5.3.1.3.Thebgpropertiesattribute
Thepopularbrowsersnolongersupportthebgpropertiesattributeextensionforthe
<body>tag.Itworkedonlyinconjunctionwiththebackgroundattributeextensionand
hadasinglevalue,fixed.Itseffectwastofreezethebackgroundimagetothe
browserwindow,soitdidnotscrollwiththeotherwindowcontents.Hence,the
exampleH2Omark.gifbackgroundimagemightserveasawatermarkforthe
document:
<bodybackground="pics/H2Omark.gif"bgproperties="fixed">
5.3.1.4.Thetextattribute
Onceyoualteradocument'sbackgroundcolororaddabackgroundimage,you
alsomightneedtoadjustthetextcolortoensurethatuserscanreadthetext.
TheHTML4/XHTMLtextstandardattributeforthe<body>tagdoesjustthat:itsets
thecolorofallnonanchortextintheentiredocument.
Givethetextattributeacolorvalueinthesameformatasyouusetospecifya
backgroundcolor(seebgcolorintheearliersection,5.3.1.1)anRGBtripletorcolor
name,asdescribedinAppendixG.Forexample,toproduceadocumentwithblue
textonapaleyellowbackground,use:
<bodybgcolor="#777700"text="blue">
Ofcourse,it'sbesttoselectatextcolorthatcontrastswellwithyourbackground
colororimage.
ThetextattributeisdeprecatedinHTML4andXHTMLbecauseyoucanachieve
similareffectsusingstylesheets.
5.3.1.5.Thelink,vlink,andalinkattributes
Thelink,vlink,andalinkattributesofthe<body>tagcontrolthecolorofhypertext
(textinsidethe<a>tag)inyourdocuments.Allthreeacceptvaluesthatspecifya
colorasanRGBtripletorcolorname,justlikethetextandbgcolorattributes.
Thelinkattributedeterminesthecolorofallhyperlinkstheuserhasnotyet
followed.Thevlinkattributesetsthecolorofalllinkstheuserhasfollowedatone
timeoranother.Thealinkattributedefinesacolorforactivelinktexti.e.,alink
thatiscurrentlyselectedbytheuserandisunderthemousecursorwiththe
mousebuttondepressed.
Liketextcolor,youshouldbecarefultoselectlinkcolorsthatcanbereadagainst
thedocumentbackground.Moreover,thelinkcolorsshouldbedifferentfromthe
regulartextaswellasfromeachother.
TheseattributesaredeprecatedinHTML4andXHTMLbecauseyoucanachieve
similareffectsusingstylesheets.
5.3.1.6.Theleftmarginattribute
OncepeculiartoInternetExplorerbutnowsupportedbyallthepopularbrowsers,
theleftmarginattributeextensionforthe<body>tagletsyouindenttheleftmargin
relativetotheleftedgeofthebrowser'swindow,muchlikeamarginonasheetof
paper.Antiquatedbrowsersignorethisattribute,andjustleft-justifythebody
contenttotheleftedgeofthedocumentwindow.
Thevalueoftheleftmarginattributeistheintegernumberofpixelsforthatleft-
marginindent;avalueof10isthedefault.Themarginisfilledwiththe
backgroundcolororimage.
Forexample,InternetExplorerrendersthefollowingtextjustifiedagainsta
margin50pixelsawayfromtheleftedgeofthebrowserwindow(seeFigure5-
24):
Figure5-24.Theleftmarginattributeforindentingbodycontent
<bodyleftmargin=50>
Modernbrowsersletsyouindentthe<br>
<leftmargin<br>
awayfromtheleftedgeofthewindow.
</body>
5.3.1.7.Thetopmarginattribute
Likeleftmargin,thetopmarginattributeextensionusedtobeexclusivetoInternet
Explorer,butnowallthepopularbrowserssupportitwell.Youmayincludeitin
the<body>tagtosetamarginofspaceatthetopofthedocument.Themargin
spaceisfilledwiththedocument'sbackgroundcolororimage.
Bodycontentbeginsflowingbelowtheintegernumberofpixelsyouspecifyasthe
valuefortopmargin;avalueof0isthedefault.
Forexample,Operarendersthefollowingtextatleast50pixelsdownfromthe
topedgeofthebrowserwindow(seeFigure5-25):
Figure5-25.Thetopmarginattributeforloweringbodycontent
<bodytopmargin=50>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Modernbrowsersgiveyourdocuments
alittleextraheadroomwithtopmargin.
</body>
5.3.1.8.Thestyleandclassattributes
Youalsocansetallthevariousstyle-related<body>features,andthensome,with
CSS.Butalthoughyoumayincludethestyleattributewiththe<body>tagtocreate
aninlinestylefortheentiredocumentbody,werecommendthatyousetthose
stylesatthedocumentlevel(usingthe<style>taginsidethedocumenthead)or
viaacollection-level(imported)stylesheet.
Usetheclassattributeandnamevaluetoapplytheappropriatestyleofa
predefinedclassofthe<body>tagtothecontents.(Becausetherecanbeonlyone
bodyperdocument,whatisthepointofsettingaclassnameotherwise?)We
covertheuseofstyleandclassdefinitionsinChapter8.
5.3.1.9.Mixingandmatchingbodyattributes
Althoughbackgroundandbgcolorattributescanappearinthesame<body>tag,a
backgroundimagewilleffectivelyhidetheselectedbackgroundcolorunlessthe
imagecontainssubstantialportionsoftransparentareas,aswedescribedearlier
inthischapter.Buteveniftheimagedoeshidethebackgroundcolor,goahead
andincludethebgcolorattributeandsomeappropriatecolorvalue.Userscanturn
offimagedownloading,whichincludesbackgroundimages,sootherwisetheymay
findyourpageleftnakedandunappealing.Moreover,withoutabgcolorattributeor
adownloaded(forwhateverreason)backgroundimage,thebrowsersmerrily
ignoreyourtextandlinkcolorattributes,too,revertinginsteadtotheirown
defaultvaluesortheonestheuserhaschosen.
5.3.2.ExtendingaWarning
MuchlikeearlyusersoftheMacintoshfeltcompelledtocreatedocumentsusing
ransom-notetypography("I'vegot40fontsonthisthing,andI'mgoingtouse
themall!"),manyauthorscannotavoidaddingsomesortoftexturedbackground
toeverydocumenttheycreate("I'vegot13woodgrainsand22kindsof
marbling,andI'mgoingtousethemall!").
Inreality,texture-mappedbackgrounds,exceptfortheverycleverones,addno
informationtoyourdocuments.Thevalueofyourdocumentultimatelyliesinits
textandimagery,notthecheesyblueswirlypatterninthebackground.No
matterhowcoolitlooks,yourreadersarenotbenefitingandyoucouldbelosing
readability.
Weadviseyounottousethecolorextensionsexceptforcomparativelyfrivolous
endeavorsorunlesstheextensionreallyaddstothedocument'svalue,suchas
forbusinessadvertisingandmarketingpages.
5.3.2.1.Problemswithbackgroundimages
Herearesomeofthethingsthatcangowrongwithbackgroundimages:
Thetimetoloadthedocumentisincreasedbytheamountoftimeneededto
loadtheimage.Untilthebackgroundimageiscompletelydownloaded,no
furtherdocumentrenderingispossible.
Thebackgroundimagetakesuproominthebrowser'slocalcache,displacing
otherimagesthatmightactuallycontainusefulinformation.Thismakesother
documents,whichmightnotevenhavebackgrounds,takelongertoload.
Thecolorsintheimagemaynotbeavailableontheuser'sdisplay,forcingthe
browsertodithertheimage.Thisreplaceslargeareasofasinglecolorwith
repeatingpatternsofseveralothercloser,butnotcleaner,colorsandcan
makethetextmoredifficulttoread.
Becausethebrowsermustactuallydisplayanimageinthebackground,as
opposedtofillinganareawithasinglecolor,scrollingthroughthedocument
cantakemuchlonger.
Evenifit'sclearonscreen,textprintedontopofanimageinvariablyismore
difficult,ifnotimpossible,toread.
Fontsvarywidelyamongmachines;theonesyouusewithyourbrowserthat
workfinewithabackgroundpatternoftenendupjaggedanddifficulttoread
onanothermachine.
5.3.2.2.Problemswithbackground,text,andlinkcolors
Youalsowillencounteraslewofproblemsifyouplaywithbackgroundcolors,
includingthefollowing:
Thecoloryouchoose,whilejustlovelyinyoureyes,maylookterribletothe
user.Whyannoythembychangingwhatusersmostlikelyhavealreadysetas
theirowndefaultbackgroundcolors?
Whileyoumaybeamemberofthe"lighttextonadarkbackground"school
ofdocumentdesign,manypeoplealsofavorthe"darktextonalight
background"stylethathasbeenconsistentlypopularformorethan3,000
years.Insteadofbuckingthetrend,assumethatusershavealreadysettheir
browserstoacomfortablecolorscheme.
Someusersarecolorblind.Whatmaybeanifty-lookingcombinationofcolors
toyoumaybecompletelyunreadabletoothers.Onecombinationinparticular
toavoidisgreenforunvisitedlinksandredforvisitedlinks.Millionsofmen
areafflictedwithred/greencolorblindness.
Yourbrillianthuemaynotbeavailableontheuser'sdisplay,andthebrowser
maybeforcedtochooseonethat'scloseinstead.Somecolorsforthetextand
thebackgroundmightbethesamecoloronlimited-colordisplays!
Forthesamereasonjustlisted,active,unvisited,andvisitedlinksmaywind
upasthesamecoloronlimited-colordisplays.
Bychangingtextcolors,particularlythoseforvisitedandunvisitedlinks,you
maycompletelyconfuseusers.Bychangingthosecolors,youeffectivelyforce
themtoexperimentwithyourpage,clickingafewlinkshereandthereto
learnyourcolorscheme.
Mostpagedesignershavenoformaltrainingincognitivepsychology,finearts,
graphicarts,orindustrialdesign,yetfeelfullycapableofselecting
appropriatecolorsfortheirdocuments.Ifyoumustfiddlewiththecolors,ask
aprofessionaltopickthemforyou.
5.3.2.3.Andthenagain
Thereisnodenyingthefactthattheseextensionsresultinsomeverystunning
HTMLandXHTMLdocuments.Andtheyarefuntoexploreandplaywith.So,
insteadofleavingthissectiononasournoteofcaution,weencourageyoutogo
aheadandplayjustplaycarefully.
5.4.BackgroundAudio
Oneotherformofinlinemultimediaisgenerallyavailabletowebsurfersaudio.
Mostbrowserstreataudiomultimediaasseparatedocuments,downloadedand
displayedbyspecialhelperapplications,applets,orplug-ins.InternetExplorer
andOpera,ontheotherhand,containbuilt-insounddecodersandsupporta
specialtag(<bgsound>)thatletsyouintegratewithyourdocumentanaudiofilethat
playsinthebackgroundasasoundtrackforyourpage.[AppletsandObjects,
12.1][EmbeddedContent,12.2]
WeapplaudthedevelopersofInternetExplorerandOperaforprovidinga
mechanismthatmorecleanlyintegratesaudiointoHTMLandXHTMLdocuments.
Thepossibilitieswithaudioareveryenticing,butatthesametime,wecaution
authorsthatspecialtagsandattributesforaudiodon'tworkwithotherbrowsers,
andwhetherthisisthemethodthatthemajorityofbrowserswilleventually
supportisnotatallassured.
5.4.1.The<bgsound>Tag
Usethe<bgsound>tagtoplayasoundtrackinthebackground.Thistagisfor
InternetExplorerandOperadocumentsonly.Otherbrowsersignorethetag.It
downloadsandplaysanaudiofilewhentheuserfirstdownloadsanddisplaysthe
hostdocument.Thebackgroundsoundfilealsowillreplaywhenevertheuser
refreshesthebrowserdisplay.
<bgsound>
Function Playsasoundtrackinthedocument'sbackground
Attributes loop,src
Endtag NoneinHTML
Contains Nothing
Usedin body_content
5.4.1.1.Thesrcattribute
Thesrcattributeisrequiredforthe<bgsound>tag.ItsvaluereferencestheURLfor
therelatedsoundfile.Forexample,whenInternetExplorerorOperausersfirst
downloadadocumentcontainingthetag:
<bgsoundsrc="audio/welcome.wav">
theywillhearthewelcome.wavaudiofileperhapsaninvitingmessageplayonce
throughtheircomputers'soundsystems.
Currently,<bgsound>canhandleseveraldifferentsoundformatfiles,including.wav,
thenativeformatforPCs;.au,thenativeformatformostUnixworkstations;and
MIDI,auniversalmusic-encodingscheme(seealsoTable5-1).
Table5-1.Commonmultimediaformatsandrespectivefilenameextensions
Format Type Extension Platformoforigin
GraphicsInterchangeFormat Image gif Any
JointPhotographicExpertsGroup Image jpg,jpeg,jpe Any
XBitMap Image xbm Unix
TaggedImageFileFormat Image tif,tiff Any
PICT Image pic,pict Apple
Rasterfile Image ras Sun
PortableNetworkGraphics Image png Any
MovingPicturesExpertGroup Movie mpg,mpeg Any
AudioVideoInterleave Movie avi Microsoft
QuickTime Movie qt,mov Apple
WindowsMediaVideo Movie wmv Microsoft
Shockwave Movie dvr Macromedia
RealVideo Movie ra,rm,ram RealNetworks
DivX Movie div,divx,tix,mp4 DivX
AU Audio au,snd Sun
WaveformAudio Audio wav Microsoft
AudioInterchangeFileFormat Audio aif,aiff Apple
MusicalInstrumentDigitalInterface Audio midi,mid Any
PostScript Document ps,eps,ai Any
Acrobat Document pdf Any
5.4.1.2.Theloopattribute
Aswithinlinemovies,theloopattributeforthebrowser's<bgsound>tagletsyou
replayabackgroundsoundtrackacertainnumberoftimes(orindefinitely),at
leastuntiltheusermovesontoanotherpageorquitsthebrowser.
Thevalueoftheloopattributeistheintegernumberoftimestoreplaytheaudio
file,orinfinite,whichmakesthesoundtrackrepeatendlessly.
Forexample:
<bgsoundsrc="audio/tadum.wav"loop=10>
repeatstheta-dumsoundtrack10times,whereas:
<bgsoundsrc="audio/noise.wav"loop=infinite>
continuouslyplaysthenoisesoundtrack.
5.4.2.AlternativeAudioSupport
Thereareotherwaystoincludeaudioinyourdocuments,usingmoregeneral
mechanismsthatsupportotherembeddedmediaaswell.Themostcommon
alternativetothe<bgsound>tagisthe<embed>tag,originallyimplementedby
Netscapeandsupplantedbythe<object>tagintheHTML4andXHTMLstandards.
TakealookinChapter12fordetails.
Ultimately,youshouldhandleallbackgroundaudio,includingspoken(aural)
documentcontent,usingthevariousaudioextensionsdefinedinaCSSstandard.
Whilewecoverthespeechsynthesis-relatedextensionsinChapter8,theyare
notyetsupportedbyanybrowser.Whensuchsupportbecomeswidelyavailable,
alloftheseearlyaudioextensionswillgothewayofthe<blink>and<isindex>tags,
earlyspecializedtagsdeprecatedinfavorofmoregeneralizedandpowerful
features.
5.5.AnimatedText
Inwhatappearstobeanefforttowooadvertisers,InternetExploreraddeda
formofanimatedtexttoHTMLthatallthepopularbrowsersnowsupport.The
animationissimpletextscrollinghorizontallyacrossthedisplaybuteffectivefor
movingbannersandotherelementsthatreadilyandeasilyanimateanotherwise
staticdocument.Ontheotherhand,likethe<blink>tag,animatedtextcaneasily
becomeintrusiveandabusiveforthereader.Usewithcaution,please,ifatall.
5.5.1.The<marquee>Tag
The<marquee>tagdefinesthetextthatscrollsacrosstheuser'sdisplay.The
<marquee>tagisnotastandardtag.Forthisreasonalone,wedonotrecommend
thatyouusethisextension.
<marquee>
Function Createsascrollingtextmarquee
Attributes align,behavior,bgcolor,class,controls,direction,height,hspace,loop,
scrollamount,scrolldelay,style,vspace,width
Endtag </marquee>;neveromitted
Contains plain_text
Usedin body_content
Thetextbetweenthe<marquee>taganditsrequired</marquee>endtagscrolls
horizontallyacrossthedisplay.Thevarioustagattributescontrolthesizeofthe
displayarea,itsappearance,itsalignmentwiththesurroundingtext,andthe
scrollingspeed.
The<marquee>tagandattributesareignoredbysomebrowsers,butitscontentsare
not.Theyaredisplayedasstatictext,sansanyalignmentorspecialtreatment
affordedbythe<marquee>tagattributes.
5.5.1.1.Thealignattribute
Thepopularbrowsersplace<marquee>textintothesurroundingbodycontentjust
asifitwereanembeddedimage.Asaresult,youcanalignthemarqueewithin
thesurroundingtext.
Thealignattributeacceptsavalueoftop,middle,orbottom,meaningthatthe
specifiedpointofthemarqueewillbealignedwiththecorrespondingpointinthe
surroundingtext.Thus:
<marqueealign=top>
alignsthetopofthemarqueeareawiththetopofthesurroundingtext.Alsosee
theheight,width,hspace,andvspaceattributes(laterinthischapter),whichcontrol
thedimensionsofthemarquee.
5.5.1.2.Thebehavior,direction,andloopattributes
Together,thesethreeattributescontrolthestyle,direction,anddurationofthe
scrollinginyourmarquee.
Thebehaviorattributeacceptsthreevalues:
scroll(default)
ThisvaluecausesthemarqueetoactlikethegrandmarqueeinTimes
Square:themarqueeareaisinitiallyempty;thetextthenscrollsinfromone
side(controlledbythedirectionattribute),continuesacrossuntilitreaches
theothersideofthemarquee,andthenscrollsoffuntilthemarqueeisonce
againempty.
slide
Thisvaluecausesthemarqueetostartempty.Textthenscrollsinfromone
side(controlledbythedirectionattribute),stopswhenitreachestheother
side,andremainsonscreen.
alternate
Thisvaluecausesthemarqueetostartwiththetextfullyvisibleatoneendof
themarqueearea.Thetextthenscrollsuntilitreachestheotherend,
whereuponitreversesdirectionandscrollsbacktoitsstartingpoint.
Ifyoudonotspecifyamarqueebehavior,thedefaultbehaviorisscroll.
Thedirectionattributesetsthedirectionformarqueetextscrolling.Acceptable
valuesareeitherleft(thedefault)orright.Notethatthestartingendforthe
scrollingisoppositetothedirection:leftmeansthatthetextstartsattherightof
themarqueeandscrollstotheleft.Rememberalsothatrightward-scrollingtextis
counter-intuitivetoanyonewhoreadslefttoright.
Theloopattributedetermineshowmanytimesthemarqueetextscrolls.Ifan
integervalueisprovided,thescrollingactionisrepeatedthatmanytimes.Ifthe
valueisinfinite,thescrollingrepeatsuntiltheusermovesontoanother
documentwithinthebrowser.
Puttingsomeoftheseattributestogether:
<marqueealign=centerloop=infinite>
Kumquatsaren'tfilling
..........Tastegreat,too!
</marquee>
Theexamplemessagestartsattherightsideofthedisplaywindow(default),
scrollsleftwardallthewayacrossandoffthedisplay,andthenstartsoveragain
untiltheusermovesontoanotherpage.Noticetheinterveningperiodsand
spacesforthe"trailer";youcan'tappendonemarqueetoanother.
Also,theslidestyleofscrollinglooksjerkywhenrepeatedandshouldbescrolled
onlyonce.Otherscrollingbehaviorsworkwellwithrepeatedscrolling.
5.5.1.3.Thebgcolorattribute
Thebgcolorattributeletsyouchangethebackgroundcolorofthemarqueearea.It
acceptseitheranRGBcolorvalueoroneofthestandardcolornames.See
AppendixGforafulldiscussionofbothcolor-specificationmethods.
Tocreateamarqueeareawhosecolorisyellow,youwouldwrite:
<marqueebgcolor=yellow>
5.5.1.4.Theheightandwidthattributes
Theheightandwidthattributesdeterminethesizeofthemarqueearea.Ifnot
specified,themarqueeareaextendsallthewayacrossthedisplayandwillbejust
highenoughtoenclosethemarqueetext.
Bothattributesaccepteitheranumericvalue,indicatinganabsolutesizein
pixels,orapercentage,indicatingthesizeasapercentageofthebrowserwindow
heightandwidth.
Forexample,tocreateamarqueethatis50pixelstallandoccupiesone-thirdof
thedisplaywindowwidth,use:
<marqueeheight=50width="33%">
Whileitisgenerallyagoodideatoensurethattheheightattributeislargeenough
tocontaintheenclosedtext,itisnotuncommontospecifyawidththatissmaller
thantheenclosedtext.Inthiscase,thetextscrollsthesmallermarqueearea,
resultinginakindof"viewport"marqueefamiliartomostpeople.
5.5.1.5.Thehspaceandvspaceattributes
Thehspaceandvspaceattributesletyoucreatesomespacebetweenthemarquee
andthesurroundingtext.Thisusuallymakesthemarqueestandoutfromthe
textaroundit.
Bothattributesrequireanintegervaluespecifyingthespaceneededinpixels.
Thehspaceattributecreatesspacetotheleftandrightofthemarquee;thevspace
attributecreatesspaceaboveandbelowthemarquee.Tocreate10pixelsofspace
allthewayaroundyourmarquee,forexample,use:
<marqueevspace=10hspace=10>
5.5.1.6.Thescrollamountandscrolldelayattributes
Theseattributescontrolthespeedandsmoothnessofthescrollingmarquee.
Thescrollamountattributevalueisthenumberofpixelsneededtomovetexteach
successivemovementduringthescrollingprocess.Lowervaluesmeansmoother
butslowerscrolling;highernumberscreatefaster,jerkiertextmotion.
Thescrolldelayattributeletsyousetthenumberofmillisecondstowaitbetween
successivemovementsduringthescrollingprocess.Thesmallerthisvalue,the
fasterthescrolling.
Youcanusealowscrolldelaytomitigatetheslownessofasmall,smooth
scrollamount.Forexample:
<marqueescrollamount=1scrolldelay=1>
scrollsthetextonepixelforeachmovementbutdoessoasfastaspossible.In
thiscase,thescrollingspeedislimitedbythecapabilitiesoftheuser'scomputer.
5.6.OtherMultimediaContent
TheWebiscompletelyopen-mindedaboutthetypesofcontentthatcanbe
exchangedbyserversandbrowsers.Inthissection,welookatadifferentwayto
referenceimages,alongwithaudio,video,andotherdocumentformats.
5.6.1.EmbeddedVersusReferencedContent
Imagescurrentlyenjoyaspecialstatusamongthevariousmediathatcanbe
includedwithinanHTMLorXHTMLdocumentanddisplayedinlinewithother
contentbyallbutafewbrowsers.Sometimes,however,aswediscussedearlierin
thischapter,youmayalsoreferenceimagesexternallyparticularlylargeonesin
whichdetailsareimportantbutnotimmediatelynecessarytothedocument
content.Othermultimediaelements,includingdigitalaudioandvideo,canbe
referencedasseparatedocumentsexternaltothecurrentone.
Younormallyusetheanchortag(<a>)tolinkexternalmultimediaelementstothe
currentdocument.Justlikeotherlinkelementsselectedbytheuser,thebrowser
downloadsthemultimediaobjectandpresentsittotheuser,possiblywiththe
assistanceofanexternalapplicationorplug-in.Referencedcontentisalwaysa
two-stepprocess:presentthedocumentthatlinkstothedesiredmultimedia
object,thenpresenttheobjectiftheuserselectsthelink.[<a>,6.3.1]
Inthecaseofimages,youcanchoosehowtopresentimagestotheuser:inline
andimmediatelyavailableviathe<img>tag,orreferencedandsubsequently
availableviathe<a>tag.Ifyourimagesaresmallandcriticaltothecurrent
document,youshouldprovidetheminline.Iftheyarelargeorareonlya
secondaryelementofthecurrentdocument,makethemavailableasreferenced
contentviathe<a>tag.
Ifyouchoosetoprovideimagesviathe<a>tag,itissometimesacourtesytoyour
readerstoindicatethesizeofthereferencedimageinthereferencingdocument
andperhapsprovideathumbnailsketch.Userscanthendeterminewhetheritis
worththeirtimeandexpensetoretrieveit.
5.6.2.ReferencingAudio,Video,andImages
Youreferenceanyexternaldocument,regardlessoftypeorformat,viaa
conventionalanchor(<a>)link:
The<ahref="sounds/anthem.au">KumquatGrower'sAnthem</a>isarousingtributeto
thethousandsof'quatgrowersaroundtheworld.
Justlikeanyreferenceddocument,theserverdeliversthedesiredmultimedia
objecttothebrowserwhentheuserselectsthelink.Ifthebrowserfindsthatthe
documentisnotHTMLorXHTML,butrathersomeotherformat,itautomatically
invokesanappropriaterenderingtooltodisplayorotherwiseconveythecontents
oftheobjecttotheuser.
Youcanconfigureyourbrowserwithspecialhelperapplicationsthathandle
differentdocumentformatsindifferentways.Audiofiles,forexample,mightbe
passedtoanaudio-processingtool,andvideofilesaregiventoavideo-playing
tool.Ifabrowserhasnotbeenconfiguredtohandleaparticulardocumentformat,
thebrowserwillinformyouandoffertosimplysavethedocumenttodisk.You
canlateruseanappropriateviewingtooltoexaminethedocument.
Browsersidentifyandspeciallyhandlemultimediafilesfromoneoftwodifferent
hints:eitherfromthefile'sMultipurposeInternetMailExtension(MIME)type,
providedbytheserver,orfromaspecialsuffixinthefile'sname.Thebrowser
prefersMIMEbecauseofitsricherdescriptionofthefileanditscontents,butit
willinferthefile'scontents(typeandformat)fromthefilesuffix:.gifor.jpg,for
GIForJPEGencodedimages,forexample,or.auforaspecialsoundfile.
BecausenotallbrowserslookforaMIMEtypeorarenecessarilycorrectly
configuredwithhelperapplicationsbytheirusers,youshouldalwaysusethe
correctfilesuffixinthenamesofmultimediaobjects.RefertoTable5-1formore
information.
5.6.3.AppropriateLinkingStyles
Creatingeffectivelinkstoexternalmultimediadocumentsiscritical.Theuser
needssomeindicationofwhattheobjectisandperhapsthekindofapplication
thelinkedobjectneedstoexecute.Moreover,mostmultimediaobjectsarequite
large,socommoncourtesytellsustoprovideuserswithsomeindicationofthe
timeandexpenseinvolvedindownloadingthem.
Inlieuof,orinadditionto,theanchorandsurroundingtext,asmallthumbnailof
alargeimage,orafamiliariconthatindicatesthereferencedobject'sformat,is
useful.
5.6.4.EmbeddingOtherDocumentTypes
TheWebcandelivernearlyanytypeofelectronicdocument,notjustgraphics,
sound,andvideofiles.Todisplaythem,however,theclientbrowserneedsa
helperapplicationinstalledandreferenced.Recentbrowsersalsosupportplug-in
accessorysoftwareand,asdescribedinChapter12,mayextendthebrowserfor
somespecialfunction,includinginlinedisplayofmultimediaobjects.
Forexample,consideracompanywhoseextensiveproductdocumentationwas
preparedandstoredinsomepopularlayoutapplicationsuchasAdobeAcrobat,
FrameMaker,QuarkXPress,orPageMaker.TheWeboffersanexcellentwayfor
distributingthatdocumentationoveraworldwidenetwork,butconvertingto
HTMLorXHTMLwouldbetoocostlyatthistime.
ThesolutionistoprepareafewHTMLorXHTMLdocumentsthatcatalogandlink
thealternativefilesandinvoketheappropriatedisplayapplet.Or,makesurethat
theusers'browsershavetheplug-insoftwareorareconfiguredtoinvokethe
appropriatehelperapplication.Adobe'sAcrobatReaderisaverypopularplug-in,
forexample.IfthedocumentisinAcrobat(.pdf)formatandifalinktoanAcrobat
documentischosen,thetoolisstartedandaccordinglydisplaysthedocument,
oftenrightinthebrowser'swindow.
Chapter6.LinksandWebs
Uptothispoint,we'vedealtwithHTMLandXHTMLdocumentsasstandalone
entities,concentratingonthelanguageelementsyouuseforstructureandto
formatyourwork.Thetruepowerofthesemarkuplanguages,however,liesin
theirabilitytojoincollectionsofdocumentstogetherintoafulllibraryof
informationandtolinkyourlibraryofdocumentswithothercollectionsaround
theworld.Justasreadershaveconsiderablecontroloverhowthedocumentlooks
onscreen,withhyperlinkstheyalsohavecontrolovertheorderofpresentationas
theynavigatethroughyourinformation.It'sthe"HT"inHTMLand
XHTMLhypertextandit'sthetwistthatspinstheWeb.
6.1.HypertextBasics
Afundamentalfeatureofhypertextisthatyoucanhyperlinkdocuments;youcan
pointtoanotherplaceinsidethecurrentdocument,insideanotherdocumentin
thelocalcollection,orinsideadocumentanywhereontheInternet.The
documentsbecomeanintricatelywovenwebofinformation.(Getthename
analogynow?)Thetargetdocumentusuallyissomehowrelatedtoandenriches
thesource;thelinkingelementinthesourceshouldconveythatrelationshipto
thereader.
Youcanusehyperlinksforallkindsofeffects.Youcanusetheminsidetablesof
contentsandlistsoftopics.Withaclickofthemouseontheirbrowserscreenora
pressofakeyontheirkeyboard,readersselectandautomaticallyjumptoatopic
ofinterestinthesamedocumentortoanotherdocumentlocatedinanentirely
differentcollectionsomewherearoundtheworld.
Hyperlinksalsopointreaderstomoreinformationaboutamentionedtopic."For
moreinformation,seeKumquatsonParade,"forexample.Authorsusehyperlinks
toreducerepetitiveinformation.Forinstance,werecommendyousignyourname
toeachdocument.Insteadofincludingfullcontactinformationineachdocument,
youcanuseahyperlinktoconnectyournametoasingledocumentthatcontains
youraddress,phonenumber,andsoforth.
Ahyperlink,oranchorinstandardparlance,ismarkedbythe<a>tagandcomes
intwoflavors.Aswedescribeindetaillater,onetypeofanchorcreatesahotspot
inthedocumentthat,whenactivatedandselected(usuallywithamouse)bythe
user,causesthebrowsertolink.Itautomaticallyloadsanddisplaysanother
portionofthesameoranotherdocumentortriggerssomeInternetservice-
relatedaction,suchassendingemailordownloadingaspecialfile.Theothertype
ofanchorcreatesalabel,aplaceinadocumentthatcanbereferencedasa
hyperlink.[*]
[*]Bothtypesofanchorsusethesametag;perhapsthat'swhytheyhavethesamename.Wefindit'seasierifyou
differentiatethemandthinkofthetypethatprovidesthehotspotandaddressofahyperlinkasthe"link"andthetypethat
marksthetargetportionofadocumentasthe"anchor."
Also,somemouse-relatedeventsareassociatedwithhyperlinks,which,through
JavaScript,letyouincorporatesomeexcitingeffects.
6.2.ReferencingDocuments:TheURL
EverydocumentontheWebhasauniqueaddress.(Imaginethechaosifthey
didn't.)Thedocument'saddressisknownasitsuniformresourcelocator(URL).[ ]
[ ]"URL"usuallyispronounced"youareell,"not"earl."
SeveralHTML/XHTMLtagsincludeaURLattributevalue,includinghyperlinks,
inlineimages,andforms.AllusethesameURLsyntaxtospecifythelocationofa
webresource,regardlessofthetypeorcontentofthatresource.That'swhyit's
knownasauniformresourcelocator.
BecausetheycanbeusedtorepresentalmostanyresourceontheInternet,URLs
comeinavarietyofflavors.AllURLs,however,havethesametop-levelsyntax:
scheme:scheme_specific_part
TheschemedescribesthekindofobjecttheURLreferences;thescheme_specific_part
is,well,thepartthatispeculiartothespecificscheme.Theimportantthingto
noteisthattheschemeisalwaysseparatedfromthescheme_specific_partbyacolon,
withnointerveningspaces.
6.2.1.WritingaURL
WriteURLsusingthedisplayablecharactersintheUS-ASCIIcharacterset.For
example,surelyyouhaveheardwhathasbecomeannoyinglycommononthe
radioforanannouncedbusinesswebsite:"h,t,t,p,colon,slash,slash,w,w,w,
dot,blah-blah,dot,com."That'sasimpleURL,written:
http://www.blah-blah.com
IfyouneedtouseacharacterinaURLthatisnotpartofthischaracterset,you
mustencodethecharacterusingaspecialnotation.Theencodingnotation
replacesthedesiredcharacterwiththreecharacters:apercentsignandtwo
hexadecimaldigitswhosevaluescorrespondtothepositionofthecharacterinthe
ASCIIcharacterset.
Thisiseasierthanitsounds.Oneofthemostcommonspecialcharactersisthe
space(ownersofolderMacintoshes,takespecialnotice),whosepositioninthe
charactersetis20hexadecimal.[*]Youcan'ttypeaspaceinaURL(well,youcan,
butitwon'twork).Rather,replacespacesintheURLwith%20:
[*]Hexadecimalnumberingisbasedon16characters:0through9followedbyAthroughF,whichindecimalare
equivalenttovalues0through15.Also,lettercasefortheseextendedvaluesisnotsignificant;"a"(10decimal)isthe
sameas"A,"forexample.
http://www.kumquat.com/new%20pricing.html
ThisURLactuallyretrievesadocumentnamednewpricing.htmlfromthe
www.kumquat.comserver.
6.2.1.1.Handlingreservedandunsafecharacters
Inadditiontothenonprintingcharacters,you'llneedtoencodereservedand
unsafecharactersinyourURLsaswell.
ReservedcharactersarethosethathaveaspecificmeaningwithintheURLitself.
Forexample,theslashcharacterseparateselementsofapathnamewithinaURL.
IfyouneedtoincludeinaURLaslashthatisnotintendedtobeanelement
separator,you'llneedtoencodeitas%2F:
http://www.calculator.com/compute?3%2f4
ThisURLactuallyreferencestheresourcenamedcomputeonthe
www.calculator.comserverandpassesthestring3/4toit,asdelineatedbythe
questionmark(?).Presumably,theresourceisaserver-sideprogramthat
performssomearithmeticfunctiononthepassedvalueandreturnsaresult.
UnsafecharactersarethosethathavenospecialmeaningwithintheURLbutmay
haveaspecialmeaninginthecontextinwhichtheURLiswritten.Forexample,
doublequotes("")delimitURLattributevaluesintags.Ifyouweretoincludea
doublequotationmarkdirectlyinaURL,youwouldprobablyconfusethebrowser.
Instead,youshouldencodethedoublequotationmarkas%22toavoidanypossible
conflict.
Table6-1showsotherreservedandunsafecharactersthatshouldalwaysbe
encoded.
Table6-1.ReservedandunsafecharactersandtheirURLencodings
Character Description Usage Encoding
; Semicolon Reserved %3B
/ Slash Reserved %2F
? Questionmark Reserved %3F
: Colon Reserved %3A
@ Atsign Reserved %40
= Equalssign Reserved %3D
& Ampersand Reserved %26
< Less-thansign Unsafe %3C
> Greater-thansign Unsafe %3E
" Doublequotationmark Unsafe %22
# Hashsymbol Unsafe %23
% Percent Unsafe %25
{ Leftcurlybrace Unsafe %7B
} Rightcurlybrace Unsafe %7D
| Verticalbar Unsafe %7C
\ Backslash Unsafe %5C
^ Caret Unsafe %5E
~ Tilde Unsafe %7E
[ Leftsquarebracket Unsafe %5B
] Rightsquarebracket Unsafe %5D
' Backsinglequotationmark Unsafe %60
Ingeneral,youshouldalwaysencodeacharacterifthereissomedoubtasto
whetheritcanbeplacedasisinaURL.Asaruleofthumb,anycharacterother
thanaletter,number,oranyofthesymboliccharacterslike$-_.+!*'()shouldbe
encoded.
Itisneveranerrortoencodeacharacter,unlessthatcharacterhasaspecific
meaningintheURL.Forexample,encodingtheslashesinanHTTPURLcauses
themtobeusedasregularcharacters,notaspathnamedelimiters,breakingthe
URL.Similarly,encodinganampersandwhenitisusedasaparameterseparator
inaURLwilldefeattheintendedpurpose.Instead,writetheseampersandsusing
&tokeeptheirintendedfunctionintact.
6.2.2.AbsoluteandRelativeURLs
YoumayaddressaURLinoneoftwoways:absoluteorrelative.AnabsoluteURL
isthecompleteaddressofaresourceandhaseverythingyoursystemneedsto
findadocumentanditsserverontheWeb.Attheveryleast,anabsoluteURL
containstheschemeandallrequiredelementsofthescheme_specific_partofthe
URL.Itmayalsocontainanyoftheoptionalportionsofthescheme_specific_part.
WitharelativeURL,youprovideanabbreviateddocumentaddressthat,when
automaticallycombinedwithabaseaddressbythesystem,becomesacomplete
addressforthedocument.WithintherelativeURL,anycomponentoftheURL
maybeomitted.Thebrowserautomaticallyfillsinthemissingpiecesofthe
relativeURLusingcorrespondingelementsofabaseURL.ThisbaseURLisusually
theURLofthedocumentcontainingtherelativeURL,butitmaybeanother
documentspecifiedwiththe<base>tag,aswewilldiscusslaterinthischapter.
[<base>,6.7.1]
6.2.2.1.Relativeschemesandservers
AcommonformofarelativeURLismissingtheschemeandservername.
Becausemanyrelateddocumentsareonthesameserver,itmakessensetoomit
theschemeandservernamefromtherelativeURL.Forinstance,assumethe
basedocumentwaslastretrievedfromtheserverwww.kumquat.com.This
relativeURL:
another-doc.html
isequivalenttotheabsoluteURL:
http://www.kumquat.com/another-doc.html
Table6-2showshowthebaseandrelativeURLsinthisexamplearecombinedto
formanabsoluteURL.
Table6-2.ForminganabsoluteURL
Protocol Server Directory File
BaseURL http www.kumquat.com /
RelativeURL another-doc.html
AbsoluteURL http www.kumquat.com /another-doc.html
6.2.2.2.Relativedocumentdirectories
AnothercommonformofarelativeURLomitstheleadingslashandoneormore
directorynamesfromthebeginningofthedocumentpathname.Thedirectoryof
thebaseURLisautomaticallyassumedtoreplacethesemissingcomponents.It's
themostcommonabbreviation,becausemostauthorsplacetheircollectionsof
documentsandsubdirectoriesofsupportresourcesinthesamedirectorypathas
thehomepage.Forexample,youmighthaveaspecialsubdirectorycontaining
FTPfilesreferencedinyourdocument.Let'ssaythattheabsoluteURLforthat
documentis:
http://www.kumquat.com/planting/guide.html
ArelativeURLforthefileREADME.txtinthespecialsubdirectorylookslikethis:
ftp:special/README.txt
You'llactuallyberetrieving:
ftp://www.kumquat.com/planting/special/README.txt
Visually,theoperationlookslikethatinTable6-3.
Table6-3.ForminganabsoluteFTPURL
Protocol Server Directory File
BaseURL http www.kumquat.com /planting guide.html
RelativeURL ftp special README.txt
AbsoluteURL ftp www.kumquat.com /planting/special README.txt
6.2.2.3.UsingrelativeURLs
RelativeURLsaremorethanjustatypingconvenience.Becausetheyarerelative
tothecurrentserveranddirectory,youcanmoveanentiresetofdocumentsto
anotherdirectoryorevenanotherserverandneverhavetochangeasingle
relativelink.Imaginethedifficultiesifyouhadtogointoeverysourcedocument
andchangetheURLforeverylinkeverytimeyoumovedit.You'dloatheusing
hyperlinks!UserelativeURLswhereverpossible.
6.2.3.ThehttpURL
ThehttpURLisbyfarthemostcommon.Itisusedtoaccessdocumentsfroma
webserver,andithastwoformats:
http://server:port/path#fragment
http://server:port/path?search
Someofthepartsareoptional.Infact,themostcommonformofthehttpURLis
simply:
http://server/path
whichdesignatestheuniqueserverandthedirectorypathandnameofa
document.
6.2.3.1.Thehttpserver
TheserveristheuniqueInternetnameorIPnumericaladdressofthecomputer
systemthatstoresthewebresource.Wesuspectyou'llmostlyusemoreeasily
rememberedInternetnamesfortheserversinyourURLs.[*]Thenameconsistsof
severalparts,includingtheserver'sactualnameandthesuccessivenamesofits
networkdomain,eachpartseparatedbyaperiod.TypicalInternetnameslooklike
www.oreilly.comorhoohoo.ncsa.uiuc.edu.[ ]
[*]EachInternet-connectedcomputerhasauniqueaddressanumeric(InternetProtocol,orIP)address,ofcourse,
becausecomputersdealonlyinnumbers.Humansprefernames,sotheInternetfolksprovideuswithacollectionof
specialserversandsoftware(thedomainnamesystem,orDNS)thatautomaticallyresolveInternetnamesintoIP
addresses.
[ ]Thethree-lettersuffixofthedomainnameidentifiesthetypeoforganizationorbusinessthatoperatesthatportionof
theInternet.Forinstance,"com"isacommercialenterprise,"edu"isanacademicinstitution,and"gov"identifiesa
government-baseddomain.OutsidetheUnitedStates,aless-descriptivesuffixisoftenassignedtypicallyatwo-letter
abbreviationofthecountryname,suchas"jp"forJapanand"de"forDeutschland.Manyorganizationsaroundtheworld
nowusethegenericthree-lettersuffixesinplaceofthemoreconventionaltwo-letternationalsuffixes.
Ithasbecomesomethingofaconventionthatwebmastersnametheirservers
wwwforquickandeasyidentificationontheWeb.Forinstance,O'ReillyMedia's
webserver'snameiswww,which,alongwiththepublisher'sdomainname,
becomestheveryeasilyrememberedwebsite,www.oreilly.com.Similarly,
MobileRobots'webserverisnamedwww.mobilerobots.com.Beinganonprofit
organization,theWorldWideWebConsortium'smainserverhasadifferent
domainsuffix:www.w3c.org.Thenamingconventionhasveryobviousbenefits,
whichyou,too,shouldtakeadvantageofifyouarecalledupontocreateaweb
serverforyourorganization.
YoumayalsospecifytheaddressofaserverusingitsnumericalIPaddress.The
addressisasequenceoffournumbers,0to255,separatedbyperiods.ValidIP
addresseslooklike137.237.1.87or192.249.1.33.
It'dbeadulldiversiontotellyounowwhatthenumbersmeanorhowtoderive
anIPaddressfromadomainname,particularlybecauseyou'llrarely,ifever,use
oneinaURL.Rather,thisisagoodplacetohyperlink:pickupanygoodInternet
networkingtreatiseforrigorousdetailonIPaddressing,suchasEdKrol'sThe
WholeInternetUser'sGuideandCatalog(O'Reilly).
6.2.3.2.Thehttpport
Theportisthenumberofthecommunicationportbywhichtheclientbrowser
connectstotheserver.It'sanetworkingthingserversperformmanyfunctions
besidesservingupwebdocumentsandresourcestoclientbrowsers:electronic
mail,FTPdocumentfetches,filesystemsharing,andsoon.Althoughallthat
networkactivitymaycomeintotheserveronasinglewire,it'stypicallydivided
intosoftware-managed"ports"forservice-specificcommunicationssomething
analogoustoboxesatyourlocalpostoffice.
ThedefaultURLportforwebserversis80.SpecialsecurewebserversSecure
HTTP(SHTTP)orSecureSocketsLayer(SSL)runonport443.Mostwebservers
todayuseport80;youneedtoincludeaportnumberalongwithanimmediately
precedingcoloninyourURLifthetargetserverdoesnotuseport80forweb
communication.
WhentheWebwasinitsinfancy,pioneerwebmastersrantheirWildWildWeb
connectionsonallsortsofportnumbers.Fortechnicalandsecurityreasons,
system-administratorprivilegesarerequiredtoinstallaserveronport80.
Lackingsuchprivileges,thesewebmasterschoseother,moreeasilyaccessible,
portnumbers.
Nowthatwebservershavebecomeacceptableandareunderthecareand
feedingofresponsibleadministrators,documentsbeingservedonsomeportother
than80or443shouldmakeyouwonderwhetherthatserverisreallyontheup
andup.Mostlikely,themaverickserverisbeingrunbyacleveruser
unbeknownsttotheserver'sbonafidesystemadministrators.
6.2.3.3.Thehttppath
ThedocumentpathistheUnix-stylehierarchicallocationofthefileintheserver's
storagesystem.Thepathnameconsistsofoneormorenamesseparatedby
slashes.Allbutthelastnamerepresentdirectoriesleadingdowntothedocument.
Thelastnameisusuallythatofthedocumentitself,thoughthewebserverwill
typicallydefaulttoafilecalledindex.html.
Ithasbecomeaconventionthatforeasyidentification,HTMLdocumentnames
endwiththesuffix.html(otherwise,they'replainASCIItextfiles,remember?).
AlthoughrecentversionsofWindowsallowlongersuffixes,old-timedevelopers
oftensticktothethree-letter.htmnamesuffixforHTMLdocuments.
AlthoughtheservernameinaURLisnotcase-sensitive,thedocumentpathname
maybe.BecausemostwebserversarerunonLinux-basedsystems,andLinux
filenamesarecase-sensitive,thosedocumentpathnameswillbecase-sensitive,
too.WebserversrunningonWindowsmachinesarenotcase-sensitive,sothose
documentpathnamesarenot.Becauseitisimpossibletoknowtheoperating
systemoftheserveryouareaccessing,alwaysassumethattheserverhascase-
sensitivepathnamesandtakecaretogetthecasecorrectwhentypingyourURLs.
Certainconventionsregardingthedocumentpathnamehavearisen.Ifthelast
elementofthedocumentpathisadirectory,notasingledocument,theserver
usuallywillsendbackeitheralistingofthedirectorycontentsortheHTMLindex
documentinthatdirectory.Youshouldendthedocumentnameforadirectory
withatrailingslashcharacter,butinpractice,mostserverswillhonortherequest
evenifthischaracterisomitted.
Ifthedirectorynameisjustaslashalone,ornothingatall,theserverdecides
whattoservetoyourbrowsertypically,aso-calledhomepageintheroot
directorystoredasafilenamedindex.html.Everywell-designedwebserver
shouldhaveanattractive,well-designedhomepage;it'sashorthandwayfor
userstoaccessyourwebcollectionbecausetheydon'tneedtorememberthe
document'sactualfilename,justyourserver'sname.That'swhy,forexample,you
cantypehttp://www.oreilly.comintoNetscape'sOpendialogboxandgetO'Reilly's
homepage.
Anothertwist:ifthefirstcomponentofthedocumentpathstartswiththetilde
character(~),itmeansthattherestofthepathnamebeginsfromthepersonal
directoryinthehomedirectoryofthespecifieduserontheservermachine.For
instance,theURLhttp://www.kumquat.com/~chuckwouldretrievethetop-level
pagefromChuck'sdocumentcollection.
Differentservershavedifferentwaysoflocatingdocumentswithinauser'shome
directory.Manysearchforthedocumentsinadirectorynamedpublic_html.Unix-
basedserversarefondofthenameindex.htmlforhomepages.Whenallelse
fails,serverstendtocoughupadirectorylistingorthedefaultHTMLdocumentin
thehomepagedirectory.
6.2.3.4.Thehttpdocumentfragment
Thefragmentisanidentifierthatpointstoaspecificsectionofadocument.In
URLspecifications,itfollowstheserverandpathnameandisseparatedbythe
poundsign(#).Afragmentidentifierindicatestothebrowserthatitshouldbegin
displayingthetargetdocumentattheindicatedfragmentname.Aswedescribein
moredetaillaterinthischapter,youinsertfragmentnamesintoadocument
eitherwiththeuniversalidtagattributeorwiththenameattributeforthe<a>tag.
Inthefollowingexample,thebrowserloadsthefilenamed
kumquat_locations.htmlfromthewww.kumquat.comserver,andthendisplaysthe
documentstartingatthesectionofthepagenamedNortheast:
http://www.kumquat.com/kumquat_locations.html#Northeast
Likeapathname,afragmentnamemaybeanysequenceofcharacters,aslongas
youarecarefulwithspacesandothersymboliccharacters.
Thefragmentnameandtheprecedinghashsymbolareoptional;omitthemwhen
referencingadocumentwithoutdefinedfragments.
Formally,thefragmentelementappliesonlytoHTMLandXHTMLdocuments.If
thetargetoftheURLissomeotherdocumenttype,thebrowsermaymisinterpret
thefragmentname.
Fragmentsareusefulforlongdocuments.Byidentifyingkeysectionsofyour
documentwithafragmentname,youmakeiteasyforreaderstolinkdirectlyto
thatportionofthedocument,avoidingthetediumofscrollingorsearching
throughthedocumenttogettothesectionthatintereststhem.
Asaruleofthumb,werecommendthateverysectionheaderinyourdocuments
beaccompaniedbyanequivalentfragmentname.Byconsistentlyfollowingthis
rule,you'llmakeitpossibleforreaderstojumptoanysectioninanyofyour
documents.Fragmentsalsomakeiteasiertobuildtablesofcontentsforyour
documentfamilies.
6.2.3.5.Thehttpsearchparameter
ThesearchcomponentofthehttpURL,alongwithitsprecedingquestionmark,is
optional.Itindicatesthatthepathisasearchableorexecutableresourceonthe
server.Thecontentofthesearchcomponentispassedtotheserveras
parametersthatcontrolthesearchorexecutionfunction.
Theactualencodingofparametersinthesearchcomponentdependsuponthe
serverandtheresourcebeingreferenced.Wecovertheparametersfor
searchableresourceslaterinthischapter,whenwediscusssearchabledocuments.
WediscussparametersforexecutableresourcesinChapter9.
AlthoughourinitialpresentationofhttpURLsindicatedthataURLmayhave
eitherafragmentidentifierorasearchcomponent,somebrowsersletyouuse
bothinasingleURL.Ifyousodesire,youcanfollowthesearchparameterwitha
fragmentidentifier,tellingthebrowsertobegindisplayingtheresultsofthe
searchattheindicatedfragment.Netscape,forexample,supportsthisusage.
Wedon'trecommendthiskindofURL,though.Firstandforemost,itdoesn'twork
onallbrowsers.Justasimportant,usingafragmentimpliesthatyouaresure
thattheresultsofthesearchwillhaveafragmentofthatnamedefinedwithin
thedocument.Forlargedocumentcollections,thisishardlylikely.Youarebetter
offomittingthefragment,showingthesearchresultsfromthebeginningofthe
document,andavoidingpotentialconfusionamongyourreaders.
6.2.3.6.SamplehttpURLs
HerearesomesamplehttpURLs:
http://www.oreilly.com/catalog.html
http://www.oreilly.com
http://www.kumquat.com:8080
http://www.kumquat.com/planting/guide.html#soil_prep
http://www.kumquat.com/find_a_quat?state=Florida
ThefirstexampleisanexplicitreferencetoabonafideHTMLdocumentnamed
catalog.htmlthatisstoredintherootdirectoryofthewww.oreilly.comserver.The
secondreferencesthetop-levelhomepageonthatsameserver.Thathomepage
mayormaynotbecatalog.html.Samplethreealsoassumesthatthereisahome
pageintherootdirectoryofthewww.kumquat.comserverandthattheweb
connectionistothenonstandardport8080.
ThefourthexampleistheURLforretrievingthewebdocumentnamedguide.html
fromtheplantingdirectoryonthewww.kumquat.comserver.Onceretrieved,the
browsershoulddisplaythedocumentbeginningatthefragmentnamedsoil_prep.
Thelastexampleinvokesanexecutableresourcenamedfind_a_quatwiththe
parameternamedstatesettothevalueFlorida.Presumably,thisresource
generatesanHTMLorXHTMLresponse,presumablyanewdocumentabout
kumquatsinFloridathatissubsequentlydisplayedbythebrowser.
6.2.4.ThefileURL
ThefileURLisperhapsthesecondmostcommononeused,butitisnotreadily
recognizedbywebusersandparticularlywebauthors.Itpointstoafilestoredon
acomputerwithoutindicatingtheprotocolusedtoretrievethefile.Assuch,it
haslimiteduseinanetworkedenvironment.That'sagoodthing.ThefileURLlets
youloadanddisplayalocallystoreddocumentandisparticularlyusefulfor
referencingpersonalHTML/XHTMLdocumentcollections,suchasthose"under
construction"andnotyetreadyforgeneraldistribution,ordocumentcollections
onCD-ROM.ThefileURLhasthefollowingformat:
file://server/path
6.2.4.1.Thefileserver
Thefileservercanbe,likethehttpone,anInternetdomainnameorIPaddress
ofthecomputercontainingthefiletoberetrieved.Unlikehttp,however,which
requiresTransmissionControlProtocol/InternetProtocol(TCP/IP)networking,the
fileservermayalsobetheunqualifiedbutuniquenameofacomputerona
personalnetwork,orastoragedeviceonthesamecomputer,suchasaCD-ROM,
ormappedfromanothernetworkedcomputer.Noassumptionsaremadeasto
howthebrowsermightcontactthemachinetoobtainthefile;presumablythe
browsercanmakesomeconnection,perhapsviaaNetworkFileSystemorFTP,to
obtainthefile.
Ifyouomittheservernamebyincludinganextraslash(/)intheURL,orifyou
usethespecialnamelocalhost,thebrowserretrievesthefilefromthemachineon
whichthebrowserisrunning.Inthiscase,thebrowsersimplyaccessesthefile
usingthenormalfacilitiesofthelocaloperatingsystem.Infact,thisisthemost
commonusageofthefileURL.BycreatingdocumentfamiliesonadisketteorCD-
ROMandreferencingyourhyperlinksusingthefile:///URL,youcreatea
distributable,standalonedocumentcollectionthatdoesnotrequireanetwork
connectiontouse.
6.2.4.2.Thefilepath
Thisisthepathofthefiletoberetrievedonthedesiredserver.Thesyntaxofthe
pathmaydifferbasedontheoperatingsystemoftheserver;besuretoencode
anypotentiallydangerouscharactersinthepath.
6.2.4.3.SamplefileURLs
ThefileURLiseasy:
file://localhost/home/chuck/document.html
file:///home/chuck/document.html
file://marketing.kumquat.com/monthly_sales.html
file://D:/monthly_sales.html
ThefirstURLretrieves/home/chuck/document.htmlfromtheuser'slocalmachine
offthecurrentstoragedevice,typicallyC:\onaWindowsPC.Thesecondis
identicaltothefirst,exceptwe'veomittedthelocalhostreferencetotheserver;
theservernamedefaultstothelocaldrive.
Thethirdexampleusessomeprotocoltoretrievemonthly_sales.htmlfromthe
marketing.kumquat.comserver,andthefourthexampleusesthelocalPC's
operatingsystemtoretrievethesamefilefromtheD:\driveordevice.
6.2.5.ThemailtoURL
ThemailtoURLisverycommoninHTML/XHTMLdocuments.Ithasthebrowser
sendanelectronicmailmessagetoanamedrecipient.Ithastheformat:
mailto:address
Theaddressisanyvalidemailaddress,usuallyoftheform:
user@server
Thus,atypicalmailtoURLmightlooklike:
mailto:chuckandbill@kumquats.com
YoumayincludemultiplerecipientsinthemailtoURL,separatedbycommas.For
example,thisURLaddressesthemessagetoallthreerecipients:
mailto:chuck@kumquats.com,bill@kumquats.com,booktech@ora.com
ThereshouldbenospacesbeforeorafterthecommasintheURL.
6.2.5.1.Definingmailheaderfields
Thepopularbrowsersopenanemailhelperorplug-inapplicationwhentheuser
selectsamailtoURL.Itmaybethedefaultemailprogramfortheirsystem,ora
commonapplicationsuchasOutlookExpresswithInternetExplorerorNetscape's
built-inCommunicator.Withsomebrowsers,userscandesignatetheirownemail
programsforhandlingmailtoURLsbyalteringaspecificationintheirbrowsers'
OptionsorPreferences.
LikehttpsearchparametersthatyouattachattheendoftheURL,separatedby
questionmarks(?),youincludeemail-relatedparameterswiththemailtoURLin
theHTMLdocument.Typically,additionalparametersmayincludethemessage's
headerfields,suchasthesubject,cc(carboncopy),andbcc(blindcarboncopy)
recipients.Howtheseadditionalfieldsarehandleddependsontheemailprogram.
Afewexamplesareinorder:
mailto:chuckandbill@kumquats.com?subject=Lovedyourbook!
mailto:chuck@kumquats.com?cc=booktech@oreilly.com
mailto:bill@kumquats.com?bcc=archive@myserver.com
Asyoucanprobablyguess,thefirstURLsetsthesubjectofthemessage.Note
thatsomeemailprogramsallowspacesintheparametervalueandothersdonot.
Annoyingly,youcan'treplacespaceswiththeirhexadecimalequivalent,%20,
becausemanyemailprogramswon'tmakethepropersubstitution.It'sbesttouse
spacesbecausetheemailprogramsthatdon'thonorthespacessimplytruncate
theparametertothefirstword.
ThesecondURLplacestheaddressbooktech@oreilly.comintheccfieldofthe
message.Similarly,thelastexamplesetsthebccfield.Youmayalsosetseveral
fieldsinoneURLbyseparatingthefielddefinitionswithampersands.For
example,thisURLsetsthesubjectandccaddresses:
mailto:chuckandbill@kumquats.com?subject=Lovedyourbook!&cc=booktech@oreilly.com&bcc
=archive@myserver.com
Notallemailprogramsacceptorrecognizethebccandccextensionsinthemailto
URLsomeeitherignorethemorappendthemtoaprecedingsubject.Thus,when
formingamailtoURL,it'sbesttoordertheextrafieldsassubjectfirst,followed
byccandbcc.Anddon'tdependontheccandbccrecipientsbeingincludedinthe
email.
6.2.6.TheftpURL
TheftpURLisusedtoretrievedocumentsfromaFileTransferProtocol(FTP)
server.[*]Ithastheformat:
[*]FTPisanancientInternetprotocolthatdatesbacktotheDarkAges,around1975.Itwasdesignedasasimplewayto
movefilesamongmachinesandispopularandusefultothisday.ManyHTML/XHTMLauthorsuseFTPtoplacefileson
theirwebservers.
ftp://user:password@server:port/path;type=typecode
6.2.6.1.Theftpuserandpassword
FTPisanauthenticatedservice,meaningthatyouusuallymusthaveavalid
usernameandpasswordinordertoretrievedocumentsfromaserver.However,
mostFTPserversalsosupportrestricted,nonauthenticatedaccessknownas
anonymousFTP.Inthismode,anyonecansupplytheusername"anonymous"or
"guest"andbegrantedaccesstoalimitedportionoftheserver'sdocuments.Most
FTPserversalsoassume(butmaynotgrant)anonymousaccessiftheusername
andpasswordareomitted.
IfyouareusinganauthenticatedftpURLtoaccessasitethatrequiresa
usernameandpassword,includetheuserandpasswordcomponentsintheURL,
alongwiththecolon(:)andatsign(@).Ifyoukeeptheusercomponentandat
signbutomitthepasswordandtheprecedingcolon,mostbrowserspromptyou
forapasswordafterconnectingtotheFTPserver.Thisistherecommendedwayof
accessingauthenticatedresourcesonanFTPserverbecauseitpreventsothers
fromseeingyourpassword.
WerecommendyouneverplaceanftpURLwithausernameandpasswordinany
HTML/XHTMLdocument.Thereasoningissimple:anyonecanretrievethesimple
textdocument,extracttheusernameandpasswordfromtheURL,logintotheFTP
server,andtamperwithitsdocuments.
6.2.6.2.Theftpserverandport
Theftpserverandportoperatebythesamerulesastheserverandportinan
httpURL.TheservermustbeavalidInternetdomainnameorIPaddress,andthe
optionalportspecifiestheportonwhichtheserverislisteningforrequests.If
omitted,thedefaultportnumberis21.
6.2.6.3.Theftppathandtypecode
ThepathcomponentofanftpURLrepresentsaseriesofdirectories,separatedby
slashes,leadingtothefiletoberetrieved.Bydefault,thefileisretrievedasa
binaryfile;youcanchangethisbyaddingthetypecode(andthepreceding
;type=)totheURL.
Ifthetypecodeissettod,thepathisassumedtobeadirectory.Thebrowser
requestsalistingofthedirectorycontentsfromtheserveranddisplaysthis
listingtotheuser.Ifthetypecodeisanyotherletter,itisusedasaparameterto
theFTPtypecommandbeforeretrievingthefilereferencedbythepath.While
someFTPserversmayimplementothercodes,mostserversacceptitoinitiatea
binarytransferandatotreatthefileasastreamofASCIItext.
6.2.6.4.SampleftpURLs
HerearesomesampleftpURLs:
ftp://www.kumquat.com/sales/pricing
ftp://bob@bobs-box.com/results;type=d
ftp://bob:secret@bobs-box.com/listing;type=a
Thefirstexampleretrievesthefilenamedpricingfromthesalesdirectoryonthe
anonymousFTPserveratwww.kumquat.com.ThesecondlogsintotheFTPserver
onbobs-box.comasuserbob,promptingforapasswordbeforeretrievingthe
contentsofthedirectorynamedresultsanddisplayingthemtotheuser.Thelast
examplelogsintobobs-box.comasbobwiththepasswordsecretandretrievesthe
filenamedlisting,treatingitscontentsasASCIIcharacters.
6.2.7.ThejavascriptURL
ThejavascriptURLactuallyisapseudoprotocol,notusuallyincludedin
discussionsofURLs.WithadvancedbrowserssuchasNetscape,Opera,Firefox,
andInternetExplorer,thejavascriptURLcanbeassociatedwithahyperlinkand
usedtoexecuteJavaScriptcommandswhentheuserselectsthelink.Whilethese
URLswillwork,wedon'trecommendusingthem.Instead,authorsshouldusethe
onclickattributetoassociateJavaScriptcommandswithelementsintheir
documents.
6.2.7.1.ThejavascriptURLarguments
Followingthejavascriptpseudoprotocolisoneormoresemicolon-separated
JavaScriptexpressionsandmethods,includingreferencestomulti-expression
JavaScriptfunctionsthatyouembedwithinthe<script>taginyourdocuments
(seeChapter12fordetails).Forexample:
javascript:window.alert('Hello,world!')
javascript:doFlash('red','blue');window.alert('Donotpressme!')
arevalidURLsyoumayincludeasthevalueforalinkreference(seesection
6.3.1.2).ThefirstexamplecontainsasingleJavaScriptmethodthatactivatesan
alertdialogwiththesimplemessage"Hello,world!",iftheuserallowsJavaScript
torunwiththeirbrowser.
ThesecondjavascriptURLexamplecontainstwoarguments:thefirstcallsa
JavaScriptfunction,doFlash,whichpresumablyyouhavelocatedelsewhereinthe
documentwithinthe<script>tagandwhichperhapsflashesthebackgroundcolor
ofthedocumentwindowbetweenredandblue.Thesecondexpressionisthe
samealertmethodasinthefirstexample,withaslightlydifferentmessage.
ThejavascriptURLmayappearinahyperlinksansarguments,too.Inthatcase,
thebrowsermayopen,ifenabled,aspecialJavaScripteditorwhereintheuser
typesinandtestsvariousexpressionsandmethods.
6.2.8.ThenewsURL
Althoughrarelyusedanymore,thenewsURLaccesseseitherasinglemessageor
anentirenewsgroupwithintheUsenetnewssystem.Ithastwoforms:
news:newsgroup
news:message_id
AnunfortunatelimitationinnewsURLsisthattheydon'tallowyoutospecifya
newsserver.Rather,usersspecifynewsserversintheirbrowserpreferences.At
onetime,notlongago,Internetnewsgroupswerenearlyuniversallydistributed;
allnewsserverscarriedallthesamenewsgroupsandtheirrespectivearticles,so
onenewsserverwasasgoodasany.Today,thesheerbulkofdiskspaceneeded
tostorethedailyvolumeofnewsgroupactivityisoftenprohibitiveforanysingle
newsserver,andthere'salsolocalcensorshipofnewsgroups.Hence,youcannot
expectthatallnewsgroups,andcertainlynotallarticlesforaparticular
newsgroup,willbeavailableontheuser'snewsserver.
Manyusers'browsersmaynotbecorrectlyconfiguredtoreadnews.We
recommendthatyouavoidplacingnewsURLsinyourdocumentsexceptinrare
cases.
6.2.8.1.Accessingentirenewsgroups
Severalthousandnewsgroupsaredevotedtonearlyeveryconceivabletopic
underthesun,andbeyond.Eachgrouphasauniquename,composedof
hierarchicalelementsseparatedbyperiods.Forexample,theWorldWideWeb
announcementsnewsgroupis:
comp.infosys.www.announce
Toaccessthisgroup,usetheURL:
news:comp.infosys.www.announce
6.2.8.2.Accessingsinglemessages
Everymessageonanewsserverhasauniquemessageidentifier(ID)associated
withit.ThisIDhastheform:
unique_string@server
Theunique_stringisasequenceofASCIIcharacters;theserverisusuallythename
ofthemachinefromwhichthemessageoriginated.Theunique_stringmustbe
uniqueamongallthemessagesthatoriginatedfromtheserver.AsampleURLto
accessasinglemessagemightbe:
news:12A7789B@news.kumquat.com
Ingeneral,messageIDsarecrypticsequencesofcharactersnotreadily
understoodbyhumans.Moreover,thelifespanofamessageonaserveris
usuallymeasuredindays,afterwhichthemessageisdeletedandthemessageID
isnolongervalid.Thebottomline:single-messagenewsURLsaredifficultto
create,becomeinvalidquickly,andgenerallyarenotused.
6.2.9.ThenntpURL
ThenntpURLgoesbeyondthenewsURLtoprovideacompletemechanismfor
accessingarticlesintheUsenetnewssystem.Ithastheform:
nntp://server:port/newsgroup/article
6.2.9.1.Thenntpserverandport
Thenntpserverandportaredefinedsimilarlytothehttpserverandport,
describedearlier.TheservermustbetheInternetdomainnameorIPaddressof
annntpserver;theportistheportonwhichthatserverislisteningforrequests.
Iftheportanditsprecedingcolonareomitted,thedefaultportof119isused.
6.2.9.2.Thenntpnewsgroupandarticle
Thenewsgroupisthenameofthegroupfromwhichanarticleistoberetrieved,
asjustdefinedinsection6.2.8ThearticleisthenumericIDofthedesiredarticle
withinthatnewsgroup.Althoughthearticlenumberiseasiertodeterminethana
messageID,itfallspreytothesamelimitationsofsingle-messagereferences
usingthenewsURL,justdescribedinsection6.2.8.Specifically,articlesdonot
lastlongonmostnntpservers,andnntpURLsquicklybecomeinvalidasaresult.
6.2.9.3.SamplenntpURLs
AsamplenntpURLmightbe:
nntp://news.kumquat.com/alt.fan.kumquats/417
ThisURLretrievesarticle417fromthealt.fan.kumquatsnewsgroupon
news.kumquat.com.Keepinmindthatthearticlewillbeservedonlytomachines
thatareallowedtoretrievearticlesfromthisserver.Ingeneral,mostnntp
serversrestrictaccesstothosemachinesonthesamelocalareanetwork.
6.2.10.ThetelnetURL
ThetelnetURLopensaninteractivesessionwithadesiredserver,allowingthe
usertologinandusethemachine.Often,theconnectiontothemachine
automaticallystartsaspecificservicefortheuser;inothercases,theusermust
knowthecommandstotypetousethesystem.ThetelnetURLhastheform:
telnet://user:password@server:port
6.2.10.1.TheTelnetuserandpassword
SpecifytheTelnetuserandpasswordaredefinedexactlyliketheuserand
passwordcomponentsoftheftpURL,describedpreviously.Inparticular,thesame
caveatsapplyregardingprotectingyourpasswordandneverplacingitwithina
URL.
JustliketheftpURL,ifyouomitthepasswordfromtheURL,thebrowsershould
promptyouforapasswordjustbeforecontactingtheTelnetserver.
Ifyouomitboththeuserandthepassword,theTelnetoccurswithoutsupplyinga
username.Forsomeservers,Telnetautomaticallyconnectstoadefaultservice
whennousernameissupplied.Forothers,thebrowsermaypromptfora
usernameandpasswordwhenmakingtheconnectiontotheTelnetserver.
6.2.10.2.TheTelnetserverandport
TheTelnetserverandportaredefinedsimilarlytothehttpserverandport,
describedearlier.TheservermustbetheInternetdomainnameorIPaddressofa
Telnetserver;theportistheportonwhichthatserverislisteningforrequests.If
theportanditsprecedingcolonareomitted,thedefaultportof23isused.
6.2.11.ThegopherURL
Gopherisaweb-likedocument-retrievalsystemthatachievedsomepopularityon
theInternetjustbeforetheWebtookoff,makinggopherobsolete.Somegopher
serversstillexist,though,andthegopherURLletsyouaccessgopherdocuments.
ThegopherURLhastheform:
gopher://server:port/path
6.2.11.1.Thegopherserverandport
Thegopherserverandportaredefinedsimilarlytothehttpserverandport,
describedpreviously.TheservermustbetheInternetdomainnameorIPaddress
ofagopherserver;theportistheportonwhichthatserverislisteningfor
requests.
Iftheportanditsprecedingcolonareomitted,thedefaultportof70isused.
6.2.11.2.Thegopherpath
Thegopherpathcantakeoneofthreeforms:
type/selectortype/selector%09searchtype/selector%09search%09gopherplus
Thetypeisasinglecharactervaluedenotingthetypeofthegopherresource.If
theentirepathisomittedfromthegopherURL,thetypedefaultsto1.
Theselectorcorrespondstothepathofaresourceonthegopherserver.Itmaybe
omitted,inwhichcasethetop-levelindexofthegopherserverisretrieved.
Ifthegopherresourceisactuallyagophersearchengine,thesearchcomponent
providesthestringforwhichtosearch.Thesearchstringmustbeprecededbyan
encodedhorizontaltab(%09).
Ifthegopherserversupportsgopher+resources,thegopherpluscomponent
suppliesthenecessaryinformationtolocatethatresource.Theexactcontentof
thiscomponentvariesbasedupontheresourcesonthegopherserver.This
componentisprecededbyanencodedhorizontaltab(%09).Ifyouwanttoinclude
thegopherpluscomponentbutomitthesearchcomponent,youmuststillsupplyboth
encodedtabswithintheURL.
6.3.CreatingHyperlinks
UsetheHTML/XHTML<a>tagtocreatelinkstootherdocumentsandtoname
anchorsforfragmentindentifierswithindocuments.
6.3.1.The<a>Tag
Youwillusethe<a>tagmostcommonlywithitshrefattributetocreatea
hypertextlink,orhyperlink,toanotherplaceinthesamedocumentortoanother
document.Inthesecases,thecurrentdocumentisthesourceofthelink;the
valueofthehrefattribute,aURL,isthetarget.[*]
[*]Youmayrunacrossthetermsheadandtail,whichreferencethetargetandsourceofahyperlink.Thisnaming
schemeassumesthatthereferenceddocument(thehead)hasmanytailsthatareembeddedinmanyreferencing
documentsthroughouttheWeb.Wefindthisnamingconventionconfusingandsticktotheconceptofsourceandtarget
documentsthroughoutthisbook.
Theotherwayyoucanusethe<a>tagiswiththenameattribute,tomarka
hyperlinktarget,orfragmentidentifier,inadocument.Thismethod,although
partoftheHTML4andXHTMLstandards,isslowlysuccumbingtotheidattribute,
whichletsyoumarknearlyanyelement,includingparagraphs,divisions,forms,
andsoon,asahyperlinktarget.
<a>
Function Definesanchorswithinatextflow
Attributes
accesskey,charset,class,coords,dir,HRef,hreflang,id,lang,name,onBlur,onClick,
onDblClick,onFocus,onKeyDown,onKeyPress,onKeyUp,onMouseDown,onMouseMove,
onMouseOut,onMouseOver,onMouseUp,rel,rev,shape,style,tabindex,target,title,type
Endtag </a>;neveromitted
Contains a_content
Usedin text
Thestandardsletyouuseboththenameandhrefattributeswithinasingle<a>tag,
definingalinktoanotherdocumentandafragmentidentifierwithinthecurrent
document.Werecommendagainstthisbecauseitoverloadsasingletagwith
multiplefunctionsandsomebrowsersmaynotbeabletohandleit.Instead,use
two<a>tagswhensuchaneedarises.Yoursourcewillbeeasiertounderstand
andmodifyandwillworkbetteracrossawiderrangeofbrowsers.
6.3.1.1.Allowedcontent
Betweenthe<a>taganditsrequiredendtag,youmayputonlyregulartext,
inlineelements,linebreaks,andimages.Thebrowserrendersallofthese
elementsnormally,butwiththeadditionofsomespecialeffectstoindicatethat
theyarehyperlinkstootherdocuments.Forinstance,thepopulargraphical
browserstypicallyunderlineandcolorthetextanddrawacoloredborderaround
imagesthatareenclosedby<a>tags.
6.3.1.2.Thehrefattribute
UsethehrefattributetospecifytheURLofthetargetofahyperlink.Itsvalueis
anyvaliddocumentURL,absoluteorrelative,includingafragmentidentifierora
JavaScriptcodefragment.Iftheuserselectsthecontentsofthe<a>tag,the
browserwillattempttoretrieveanddisplaythedocumentindicatedbytheURL
specifiedbythehrefattributeorexecutethelistofJavaScriptexpressions,
methods,andfunctions.[ReferencingDocuments:TheURL,6.2]
Asimple<a>tagthatreferencesanotherdocumentmightbe:
The<ahref="http:growing_season.html">growing
season</a>forkumquatsintheNortheast.
whichappearsinthebrowserdisplayshowninFigure6-1.
Figure6-1.HyperlinktoanotherHTMLdocument
Noticethatthebrowserspeciallyrendersthephrase"growingseason",lettingthe
userknowthatitisalinktoanotherdocument.Usersusuallyhavetheoptionto
settheirowntextcolorforthelinkandhavethecolorchangewhenalinkis
taken;blueinitiallyandthenredafterithasbeenselectedatleastonce,for
instance.Morecomplexanchorsmightincludeimages:
<ul>
<li><ahref="pruning_tips.html">
<imgsrc="pics/new.gif"align=center>
Newpruningtips!</a>
<p>
<li><ahref="xhistory.html">
<imgsrc="pics/new2.gif"align=center>
Kumquatsthroughouthistory</a>
</ul>
MostgraphicalbrowserssuchasInternetExplorer,butnotOperaforsomereason,
placeaspecialborderaroundimagesthatarepartofananchor,asshownin
Figure6-2.Removethathyperlinkborderwiththeborder=0attributeandvalue
withinthe<img>tagfortheimage.[Theborderattribute,5.2.6.8]
Figure6-2.InternetExplorerputsaspecialborderaroundan
imagethatisinsideananchor
6.3.1.3.Thenameandidattributes
Usethenameandidattributeswiththe<a>tagtocreateafragmentidentifier
withinadocument.Oncecreated,thefragmentidentifierbecomesapotential
targetofalink.
PriortoHTML4.0,theonlywaytocreateafragmentidentifierwastousethename
attributewiththe<a>tag.WiththeadventoftheidattributeinHTML4.0,andits
abilitytobeusedwithalmostanytag,anyHTMLorXHTMLelementcanbea
fragmentidentifier.The<a>tagretainsthenameattributeforhistoricpurposesand
honorstheidattributeaswell.Theseattributescanbeusedinterchangeably,with
idbeingthemore"modern"versionofthenameattribute.Bothnameandidcanbe
specifiedinconjunctionwiththehrefattribute,allowingasingle<a>tobebotha
hyperlinkandafragmentidentifier.
AneasywaytothinkofafragmentidentifierisastheHTMLanalogofthegoto
statementlabelcommoninmanyprogramminglanguages.Thenameattribute
withinthe<a>tagortheidattributewithinthe<a>orothertagsplacesalabel
withinadocument.Whenthatlabelisusedinalinktothatdocument,itisthe
equivalentoftellingthebrowsertogotothatlabel.
Thevalueoftheidornameattributeisacharacterstring,enclosedinquotation
marks.Thestringmustbeginwithaletter,followedbyletters,numbers,hyphens,
underscores,colons,andperiods.Thevaluemustbeauniquelabel,notreusedin
anyothernameoridattributeinthesamedocument,althoughitcanbereusedin
differentdocuments.
Herearesomenameandidexamples:
<h2><aname="Pruning">PruningYourKumquatTree</a></h2>
<h2id="Pruning">PruningYourKumquatTree</h2>
Noticethatwesettheanchorinasectionheaderofapresumablylarge
document.It'sapracticeweencourageyoutofollowforallmajorsectionsofyour
workforeasierreferenceandfuturesmartprocessing,suchasautomated
extractionoftopics.
Thefollowinglink,whentakenbytheuser:
<ahref="growing_guide.html#Pruning">
jumpsdirectlytothesectionofthedocumentwenamedintheprevious
examples.
Browsersdon'tdisplaythecontentsoftheanchor<a>tagwiththenameorid
attributeinanyspecialway.Technically,youdonothavetoputanydocument
contentwithinthe<a>tagwiththenameattributebecauseitsimplymarksa
locationinthedocument.Inpractice,though,somebrowsersignorethetag
unlesssomedocumentcontentawordorphrase,evenanimageisbetweenthe<a>
and</a>tags.Forthisreason,it'sprobablyagoodideatohaveatleastone
displayableelementinthebodyofany<a>tag.
6.3.1.4.Theeventattributes
Anumberofeventhandlersarebuiltintomodernbrowsers.Thesehandlerswatch
forcertainconditionsanduseractions,suchasaclickofthemouseorwhenan
imagefinishesloadingintothebrowserwindow.Withclient-sideJavaScript,you
mayincludeselectedeventhandlersasattributesofcertaintagsandexecuteone
ormoreJavaScriptcommandsandfunctionswhentheeventoccurs.
Withtheanchor(<a>)tag,youmayassociateJavaScriptcodewithanumberof
mouse-andkeyboard-relatedevents.Thevalueoftheeventhandlerisenclosedin
quotationmarksoneorasequenceofsemicolon-separatedJavaScriptexpressions,
methods,andfunctionreferencesthatthebrowserexecuteswhentheevent
occurs.[JavaScriptEventHandlers,12.3.3]
Apopular,albeitsimple,useoftheonMouseOvereventwithahyperlinkistoprintan
expandeddescriptionofthetag'sdestinationintheJavaScript-awarebrowser's
statusbox(Figure6-3).Normally,thebrowserdisplaysthefrequentlycryptic
destinationURLtherewhenevertheuserpassesthemousepointeroveran<a>
tag'scontents:
<ahref="http://www.ora.com/kumquats/homecooking/recipes.html#quat5"
onMouseOver="status='Ayummyrecipeforkumquatsoup.';returntrue;">
<imgsrc="pics/bowl.gif"border=0>
</a>
Figure6-3.UseJavaScripttodisplayamessageinthebrowser's
statusbox
Wearguethatthecontentsofthetagitselfshouldexplainthelink,but
sometimeswindowspaceistightandanexpandedexplanationishelpful,suchas
whenthelinkisinatableofcontents.
SeeChapter12formoreaboutJavaScript.
6.3.1.5.Therelandrevattributes
Theoptionalrelandrevattributesforthe<a>tagexpressaformalrelationshipand
directionbetweensourceandtargetdocuments.Therelattributespecifiesthe
relationshipfromthesourcedocumenttothetarget,andtherevattribute
specifiestherelationshipfromthetargettothesource.Bothattributescanbe
placedinasingle<a>tag,andthebrowsermayusethemtospeciallyalterthe
appearanceoftheanchorcontentortoautomaticallyconstructdocument
navigationmenus.Othertoolsalsomayusetheseattributestobuildspeciallink
collections,tablesofcontents,andindexes.
Thevalueofeithertherelorrevattributeisaspace-separatedlistof
relationships.Theactualrelationshipnamesandtheirmeaningsareuptoyou:
theyarenotformallyaddressedbytheHTMLorXHTMLstandards.Forexample,a
documentthatispartofasequenceofdocumentsmightincludeitsrelationshipin
alink:
<ahref="part-14.html"rel=nextrev=prev>
Therelationshipfromthesourcetothetargetisthatofmovingtothenext
document;thereverserelationshipisthatofmovingtothepreviousdocument.
Thesedocumentrelationshipsarealsousedinthe<link>taginthedocument
<head>.The<link>tagestablishestherelationshipwithoutactuallycreatingalink
tothetargetdocument;the<a>tagcreatesthelinkandimbuesitwiththe
relationshipattributes.[<link>,6.7.2]
Commonlyuseddocumentrelationshipsinclude:
next
Linkstothenextdocumentinacollection
prev
Linkstothepreviousdocumentinacollection
head
Linkstothetop-leveldocumentinacollection
toc
Linkstoacollection'stableofcontents
parent
Linkstothedocumentabovethesource
child
Linkstothedocumentbelowthesource
index
Linkstotheindexforthisdocument
glossary
Linkstotheglossaryforthisdocument
Fewbrowserstakeadvantageoftheseattributestomodifythelinkappearance.
However,theseattributesareagreatwaytodocumentlinksyoucreate,andwe
recommendthatyoutakethetimetoinsertthemwheneverpossible.
6.3.1.6.Thestyleandclassattributes
Usethestyleandclassattributesforthe<a>tagtocontrolthedisplaystyleforthe
contentenclosedbythetagandtoformatthecontentaccordingtoapredefined
classofthe<a>tag.[InlineStyles:ThestyleAttribute,8.1.1][StyleClasses,8.3]
6.3.1.7.Thelanganddirattributes
Likealmostallothertags,the<a>tagacceptsthelanganddirattributes,denoting
thelanguageusedforthecontentwithinthe<a>tagandthedirectioninwhich
thatlanguageisrendered.[Thedirattribute,3.6.1.1][Thelangattribute,
3.6.1.2]
6.3.1.8.Thetargetattribute
Thetargetattributeletsyouspecifywheretodisplaythecontentsofaselected
hyperlink.Commonlyusedinconjunctionwithframesormultiplebrowser
windows,thevalueofthisattributeisthenameoftheframeorwindowinwhich
thereferenceddocumentshouldbeloaded.Ifthenamedframeorwindowexists,
thedocumentisloadedinthatframeorwindow.Ifnot,anewwindowiscreated
andgiventhespecifiedname,andthedocumentisloadedinthatnewwindow.
Formoreinformation,includingalistofspecialtargetnames,seesection11.7.
6.3.1.9.Thetitleattribute
Thetitleattributeletsyouspecifyatitleforthedocumenttowhichyouare
linking.Thevalueoftheattributeisanystring,enclosedinquotationmarks.The
browsermightuseitwhendisplayingthelink,perhapsflashingthetitlewhenthe
mousepassesoverthelink.Thebrowsermightalsousethetitleattributewhen
addingthislinktoauser'sbookmarksorfavorites.
Thetitleattributeisespeciallyusefulforreferencinganotherwiseunlabeled
resource,suchasanimageoranon-HTMLdocument.Forexample,thebrowser
mightincludethefollowingtitleonthisotherwisewordlessimagedisplaypage:
<ahref="pics/kumquat.gif"
title="AphotographoftheNobleFruit">
Ideally,thevaluespecifiedshouldmatchthetitleofthereferenceddocument,but
it'snotrequired.
6.3.1.10.Thecharset,hreflang,andtypeattributes
AccordingtotheHTML4andXHTMLstandards,thecharsetattributespecifiesthe
characterencodingusedinthedocumentthatisthedestinationofthelink.The
valueofthisattributemustbethenameofastandardcharacterset:"euc-jp,"for
example.Thedefaultvalueis"ISO-8859-1."
TheHReflangattributemaybespecifiedonlywhenthehrefattributeisused.Like
thelangattribute,itsvalueisanInternationalOrganizationforStandardization
(ISO)standardtwo-characterlanguagecode.Unlikethelangattribute,theHReflang
attributedoesnotaddressthelanguageusedbythecontentsofthetag.Instead,
itspecifiesthelanguageusedinthedocumentreferencedbythehrefattribute.
[Thelangattribute,3.6.1.2]
Thetypeattributespecifiesthecontenttypeoftheresourcereferencedbythe<a>
tag.ItsvalueisanyMultipurposeInternetMailExtension(MIME)encodingtype.
Forexample,youmightinformthebrowserthatyouarelinkingtoaplainASCII
documentwith:
<ahref="readme.txt"type="text/plain">
Thebrowsermightusethisinformationwhendisplayingthereferenceddocument,
ormightevenpresentthelinkdifferentlybaseduponthecontenttype.
6.3.1.11.Thecoordsandshapeattributes
TwomoreattributesaredefinedintheHTMLandXHTMLstandardsforthe<a>tag
butarenotsupportedbythecurrentlypopularbrowsers.Liketheattributesofthe
samenamesforthe<area>tag,thecoordsandshapeattributesdefinearegionof
influenceforthe<a>tag.Youshouldusetheseattributeswiththe<a>tagonly
whenthattagispartofthecontentofa<map>tag,asdescribedlaterinthis
chapter.[<map>,6.5.3][Thecoordsattribute,6.5.4.2][Theshapeattribute,
6.5.4.7]
6.3.1.12.Theaccesskeyandtabindexattributes
Traditionally,usersofgraphicalbrowsersselectandexecuteahyperlinkby
pointingandclickingthemousedeviceontheregionofthebrowserdisplay
definedbytheanchor.Whatislesswellknownisthatyoumaychoosea
hyperlink,amongotherobjectsinthebrowserwindow,bypressingtheTabkey
andthenactivatethatlinkbypressingtheEnterkey.Withthetabindexattribute,
youmayreorderthesequenceinwhichthebrowserstepsthroughtoeachobject
whentheuserpressestheTabkey.Thevalueofthisattributeisaninteger
greaterthan0.Thebrowserstartswiththeobjectwhosetabindex=1andmoves
throughtheotherobjectsinincreasingtabindexorder.
Withtheaccesskeyattribute,youmayselectanalternative"hotkey"that,when
pressed,activatesthespecificlink.Thevalueofthisattributeisasinglecharacter
thatispressedinconjunctionwithanAltor"meta"key,dependingonthe
browserandcomputingplatform.Ideally,thischaractershouldappearinthe
contentofthe<a>tag;ifso,thebrowsermaychoosetodisplaythecharacter
differentlytoindicatethatitisahotkey.
SeeanexpandeddescriptionforbothoftheseattributesinChapter9.
6.3.2.LinkingtoOtherDocuments
Sayyoumakeahyperlinktoanotherdocumentwiththe<a>taganditshref
attribute,whichdefinestheURLofthetargetdocument.Thecontentsofthe<a>
tagarepresentedtotheuserinsomedistinctivemannertoindicatethelinkis
available.
Whencreatingalinktoanotherdocument,youshouldconsideraddingthetitle,
rel,andrevattributestothe<a>tag.Theyhelpdocumentthelinkyouarecreating
andallowthebrowsertoembellishthedisplayanchorcontents.
6.3.3.LinkingWithinaDocument
Creatingalinkwithinthesamedocumentortoaspecificfragmentofanother
documentisatwo-stepprocess.Thefirststepistomakethetargetfragment;the
secondistocreatethelinktothefragment.
Usethe<a>tagwithitsnameattributetoidentifyafragment.Here'sasample
fragmentidentifier:
<h3><aname="Section_7">Section7</a></h3>
Alternatively,usetheidattributeandembedthehyperlinktargetdirectlyina
definingtag,suchasaheader:[*]
[*]Weprefertheidway,althoughnotallbrowserssupportit,yet.
<h3id="Section_7">Section7</h3>
Ahyperlinktothefragmentisan<a>tagwiththeHRefattribute,inwhichthe
attribute'svaluethetargetURLendswiththefragment'sname,precededbythe
poundsign(#).Areferencetothepreviousexample'sfragmentidentifier,then,
mightlooklikethis:
See<ahref="index.html#Section_7">Section7</a>
forfurtherdetails.
Byfar,themostcommonuseoffragmentidentifiersisincreatingatableof
contentsforalengthydocument.Beginbydividingyourdocumentintoseveral
logicalsections,usingappropriateheadersandconsistentformatting.Atthestart
ofeachsection,addafragmentidentifierforthatsection,typicallyaspartofthe
sectiontitle.Finally,makealistoflinkstothosefragmentidentifiersatthe
beginningofyourdocument.
Oursampledocumentextollingthelifeandwondersofthemightykumquat,for
example,isquitelongandinvolved,includingmanysectionsandsubsectionsof
interest.Itisadocumenttobereadandreadagain.Inordertomakeiteasyfor
kumquatloverseverywheretofindtheirsectionofinterestquickly,we've
includedfragmentidentifiersforeachmajorsectionandplacedanorderedlistof
linksahot-linkedtableofcontents,asitwereatthebeginningofeachKumquat
Lover'sdocument,asampleofwhichfollows,alongwithsamplefragment
identifiersthatappearinthesamedocument.Theellipsessymbol(...)meansthat
thereareinterveningsegmentsofcontent,ofcourse:
...
<h3>TableofContents</h3>
<ol>
<li><ahref="#soil_prep">SoilPreparation</a>
<li><ahref="#dig_hole">DiggingtheHole</a>
<li><ahref="#planting">PlantingtheTree</a>
</ol>
...
<h3id=soil_prep>SoilPreparation</h3>
...
<h3id=dig_hole>DiggingtheHole</h3>
...
<h3id=planting>PlantingtheTree</h3>
...
Thekumquatlovercantherebyclickthedesiredlinkinthetableofcontentsand
jumpdirectlytothesectionofinterest,withoutlotsoftediousscrolling.
NoticealsothatthisexampleusesrelativeURLsagoodideaifyoueverintendto
moveorrenamethedocumentwithoutbreakingallthehyperlinks.
6.4.CreatingEffectiveLinks
Adocumentbecomeshypertextwhenyoutossinafewlinksinthesamewaythat
waterbecomessoupwhenyouthrowinafewvegetables.Technically,you'vemet
thegoal,buttheoutcomemaynotbeverytasty.
Insertinganchorsintoyourdocumentsissomethingofanart,requiringgood
writingskills,HTML/XHTMLprowess,andanarchitecturalsenseofyour
documentsandtheirrelationshipstoothersontheWeb.Effectivelinksflow
seamlesslyintoadocument,quietlysupplyingadditionalbrowsingopportunitiesto
thereaderwithoutdisturbingthecurrentdocument.Poorlydesignedlinksscream
out,interrupttheflowofthesourcedocument,andgenerallyannoythereader.
Whilethereareasmanylinkingstylesasthereareauthors,hereareafewofthe
morepopularwaystolinkyourdocuments.Alldotwothings:theygivethe
readerquickaccesstorelatedinformation,andtheytellthereaderhowthelinkis
relatedtothecurrentcontents.
6.4.1.ListsofLinks
Perhapsthemostcommonwaytopresenthyperlinksisinorderedorunordered
listsinthestyleofatableofcontentsorlistofresources.
Twoschoolsofstyleexist.Oneputstheentirelistitemintothesourceanchor;
theotherabbreviatestheitemandputsashorthandphraseinthesourceanchor.
Intheformer,makesureyoukeeptheanchorcontentshortandsweet;inthe
latter,useadirectwritingstylethatmakesiteasytoembedthelink.
Ifyourlistoflinksbecomesoverlylong,considerorganizingitintoseveral
sublistsgroupedbytopic.Readerscanthenscanthetopics(setoff,perhaps,as
<h3>headers)fortheappropriatelistandthenscanthatlistforthedesired
document.
Thealternativeliststyleismuchmoredescriptive,butalsowordier,soyouhave
tobecarefulthatitdoesn'tendupcluttered:
<p>
Kumquat-relateddocumentsinclude:
<ul>
<li>Aconciseguideto<ahref="kumquat_farming.html">
profitablekumquatfarming</a>,
includingavarietyofbusinessplans,listsoffruit
packingcompanies,andfarmingsupplycompanies.
<li>101differentwaysto<ahref="kumquat_uses">
useakumquat</a>,includingstewedkumquatsandkumquatpie!
<li>Thekumquatisahardytree,buteventhegreenestof
thumbscanuseafew<ahref="news:alt.kumquat_growers">
growingtips</a>toincrease
theiryield.
<li>Thebusinessofkumquatsisanexpandingone,as
shownbythis10yearoverviewofthe
<ahref="http://www.oreilly.com/kumquat_report/">
kumquatindustry</a>.
</ul>
ItsometimesgetshardtoreadasourceHTMLdocument,anditwillbecomeeven
moretediouswithXHTML.Imaginetheclutterifwe'dusedanchorswithfragment
identifiersforeachsubtopicinthelist-itemexplanations.Nonetheless,itlooks
pristineandeasilynavigablewhendisplayedbyabrowsersuchasOpera,as
showninFigure6-4.
Figure6-4.Wordybuteffectivelydescriptivelinklist
Thismoredescriptivestyleofpresentingalinklisttrieshardtodrawreadersinto
thelinkeddocumentbygivingafullertasteofwhattheycanexpecttofind.
Becauseeachlistelementislongerandrequiresmorescanningbythereader,
youshouldusethisstylesparinglyanddramaticallylimitthenumberoflinks.
Usethebriefliststylewhenpresentinglargenumbersoflinkstoawell-informed
audience.Thesecond,moredescriptivestyleisbettersuitedtoasmallernumber
oflinksforwhichyourreadershipislesswell-versedinthetopicathand.
6.4.2.InlineReferences
Ifyouaren'tcollectinglinksintolists,you'reprobablysprinklingthemthroughout
yourdocument.So-calledinlinelinksaremoreinkeepingwiththetruespiritof
hypertextbecausetheyenablereaderstomarktheircurrentplaceinthe
document,visittherelatedtopicinmoredepthorfindabetterexplanation,and
thencomebacktotheoriginalandcontinuereading.That'sverypersonalized
informationprocessing.
Thebiggestmistakenoviceauthorsmake,however,istooverloadtheir
documentswithlinksandtreatthemasthoughtheyarepanicbuttonsdemanding
tobepressed.Youmayhaveseenthisstyleoflinking;HTMLpageswiththeword
hereallovertheplace,likethepanic-riddenexampleinFigure6-5(wecan't
bringourselvestoshowyouthesourceforthistravesty).
Figure6-5.Linksshouldnotwaveandyell,likefirst-graders,
"Here!Me!Me!"
Aslinks,phrasessuchas"clickhere"and"alsoavailable"arecontent-freeand
annoying.Theymakethepersonwhoisscanningthepageforanimportantlink
readallthesurroundingtexttoactuallyfindthereference.
Thebetter,morerefinedstyleforaninlinelinkistomakeeveryonecontaina
nounornoun/verbphraserelatingtothetopicathand.Comparehowkumquat
farmingandindustrynewsreferencesaretreatedinFigure6-6tothe"Here!Me!
Me!"exampleinFigure6-5.
Figure6-6.Kinder,gentlerinlinelinksworkbest
AquickscanofFigure6-6immediatelyyieldsusefullinksto"kumquatfarming
methods"and"kumquatindustry'spasttenyears."Thereisnoneedtoreadthe
surroundingtexttounderstandwherethelinkwilltakeyou.Indeed,the
immediatelysurroundingcontentinourexample,asformostinlinelinks,serves
onlyassyntacticsugarinsupportoftheembeddedlinks.
Embeddinglinksintothegeneraldiscourseofadocumenttakesmoreeffortthan
creatinglinklists.Youhavetoactuallyunderstandthecontentofthecurrent
documentaswellasthetargetdocuments,beabletoexpressthatrelationshipin
justafewwords,andthenintelligentlyincorporatethatlinkatsomekeyplacein
thesourcedocument.Hopefullythiskeyplaceiswhereyoumightexpecttheuser
tobereadytointerruptherreadingandaskaquestionorrequestmore
information.Tomakemattersevenmoredifficult,particularlyforthetraditional
techwriter,thisformofauthor-readerconversationismosteffectivewhen
presentedinactivevoice(he,she,oritdoessomethingtoanobjectversusthe
objecthavingsomethingdonetoit).Theeffortexpendedisworthwhile,resulting
inmoreinformative,easilyreaddocuments.Remember,you'llwritethedocument
once,butitwillbereadthousands,ifnotmillions,oftimes.Pleaseyourreaders,
please.
6.4.3.LinkingDosandDon'ts
Herearesomehintsforcreatinglinks:
Keepthelinkcontentasconciseaspossible
Longlinksorhugeinlinegraphiciconsforlinksarevisuallydisruptiveand
potentiallyconfusing.
Neverplacetwolinksimmediatelyadjacenttooneanother
Mostbrowsersmakeitdifficulttotellwhereonelinkstopsandthenextlink
starts.Separatethemwithregulartextorlinebreaks.
Beconsistent
Ifyouareusinginlinereferences,makeallofyourlinksinlinereferences.If
youchoosetouselistsoflinks,sticktoeithertheshortorthelongform;try
nottomixstylesinasingledocument.
Tryreadingyourdocumentwithallthenonanchortextremoved
Ifsomelinkssuddenlymakenosense,rewritethemsothattheystandon
theirown.(Manypeoplescandocumentslookingonlyforlinks;the
surroundingtextbecomeslittlemorethanagraybackgroundtothemore
visuallycompellinglinks.)
6.4.4.UsingImagesandLinks
Ithasbecomefashionabletouseimagesandiconsinsteadofwordsforlink
contents.Forinstance,insteadofthewordnext,youmightuseaniconofalittle
pointinghand.Alinktothehomepageisnotcompletewithoutapictureofalittle
house.Linkstosearchingtoolsmustnowcontainapictureofamagnifyingglass,
aquestionmark,orbinoculars.Andallthoseflashing,GIF-animatedlittle
advertisements!
Resistfallingpreytothe"MountEverestsyndrome"ofinsertingimagessimply
becauseyoucan.Again,it'samatterofcontext.Ifyouoryourdocument's
readerscan'ttellataglancewhatrelationshipalinkhaswiththecurrent
document,you'vefailed.Usecuteimagesforlinkssparingly,consistently,and
onlyinwaysthathelpreadersscanyourdocumentforimportantinformationand
leads.Also,beevermindfulthatyourpagesmaybereadbysomeonefromnearly
anywhereonEarth(perhapsbeyond,even)andthatimagesdonottranslate
consistentlyacrossculturalboundaries.(Everhearwhatthe"OK"handsign
commonintheUnitedStatesmeanstoaJapaneseperson?)
Creatingconsistenticonographyforacollectionofpagesisadauntingtaskthat
youreallyshouldperformwiththeassistanceofsomeoneformallyschooledin
visualdesign.Trustus,thekindofmindthatproducesniftycodeandwrites
XHTMLwellisrarelysuitedtocreatingbeautiful,compellingimagery.Findagood
visualdesigner;yourpagesandreaderswillbenefitimmeasurably.
6.5.Mouse-SensitiveImages
Normally,animageplacedwithinananchorsimplybecomespartoftheanchor
content.Thebrowsermayaltertheimageinsomespecialway(usuallywitha
specialborder)toalertthereaderthatitisahyperlink,butusersclicktheimage
inthesamewaytheyclickatextualhyperlink.
TheHTMLandXHTMLstandardsprovideafeaturethatletsyouembedmany
differentlinksinsidethesameimage.Clickingdifferentareasoftheimagecauses
thebrowsertolinktodifferenttargetdocuments.Suchmouse-sensitiveimages,
knownasimagemaps,openupavarietyofcreativelinkingstyles.
Therearetwowaystocreateimagemaps,knownasserver-sideandclient-side
imagemaps.Theformer,enabledbytheismapattributeforthe<img>tag,requires
accesstoaserverandrelatedimage-mapprocessingapplications.Thelatteris
createdwiththeusemapattributeforthe<img>tag,alongwithcorresponding<map>
and<area>tags.
Translationofthemousepositionintheimagetoalinktoanotherdocument
happensontheuser'smachine,soclient-sideimagemapsdon'trequireaspecial
serverconnectionandcanevenbeimplementedinnon-Webenvironments,such
asonalocalharddriveorinaCD-ROM-baseddocumentcollection.Any
HTML/XHTMLcanimplementaclient-side(usemap)imagemap.[<map>,6.5.3]
[<area>,6.5.4][<img>,5.2.6]
6.5.1.Server-SideImageMaps
Youaddanimagetoananchorsimplybyplacingan<img>tagwithinthebodyof
the<a>tag.Makethatembeddedimageintoamouse-sensitiveonebyaddingthe
ismapattributetothe<img>tag.Thisspecial<img>attributetellsthebrowserthat
theimageisaspecialmapcontainingmorethanonelink.(Theismapattributeis
ignoredbythebrowserifthe<img>tagisnotwithinan<a>tag.)
Whentheuserclickssomeplacewithintheimage,thebrowserpassesthe
coordinatesofthemousepointeralongwiththeURLspecifiedinthe<a>tagtothe
documentserver.Theserverusesthemouse-pointercoordinatestodetermine
whichdocumenttodeliverbacktothebrowser.
Whenismapisused,thehrefattributeofthecontaining<a>tagmustcontainthe
URLofaserverapplicationor,forsomeHTTPservers,arelatedmapfilethat
containsthecoordinateandlinkinginformation.IftheURLissimplythatofa
conventionaldocument,errorsmayresult,andthedesireddocumentprobably
willnotberetrieved.
Thecoordinatesofthemousepositionarescreenpixelscountedfromtheupper-
leftcorneroftheimage,beginningwith(0,0).Thebrowseraddsthemouse
coordinates,precededbyaquestionmark,totheendoftheURL.
Forexample,ifauserclicks43pixelsoverand15pixelsdownfromtheupper-left
corneroftheimagedisplayedfromthefollowinglink:
<ahref="/cgi-bin/imagemap/toolbar.map">
<imgismapsrc="pics/toolbar.gif">
</a>
thebrowsersendsthefollowingsearchparameterstotheHTTPserver:
/cgi-bin/imagemap/toolbar.map?43,15
Intheexample,toolbar.mapisaspecialimage-mapfilelocatedinsidethecgi-
bin/imagemapdirectoryandcontainingcoordinatesandlinks.Aspecialimage-
mapprocessusesthatfiletomatchthepassedcoordinates(43,15inour
example)andreturntheselectedhyperlinkdocument.
6.5.1.1.Server-sideconsiderations
Withmouse-sensitive,ismap-enabledimagemaps,thebrowserisrequiredtopass
alongonlytheURLandmousecoordinatestotheserver.Theserverconvertsthe
coordinatesintoaspecificdocument.Theconversionprocessdiffersamong
serversandisnotdefinedbytheHTMLorXHTMLstandard.
Youneedtoconsultwithyourwebserveradministratorsandperhapsevenread
yourserver'sdocumentationtodeterminehowtocreateandprogramaserver-
sideimagemap.Mostserverscomewithsomesoftwareutility,typicallylocatedin
acgi-bin/imagemapdirectory,tohandleimagemaps.Andmostoftheseuseatext
filecontainingtheimage-mapregionsandrelatedhyperlinksthatisreferencedby
yourimage-mapURLtoprocesstheimage-mapquery.
Here'sanexampleimage-mapfiledescribingthesensitiveregionsinourexample
image:
#Imagemapfile=toolbar.map
defaultdflt.html
circ100,30,50link1.html
rect180,120,290,500link2.html
poly80,80,90,72,160,90link3.html
Eachsensitiveregionoftheimagemapisdescribedbyageometricshapeand
definingcoordinatesinpixels,suchasthecirclewithitscenterpointandradius,
therectangle'supper-leftandlower-rightedgecoordinates,andthelociofa
polygon.Allcoordinatesarerelativetotheupper-leftcorneroftheimage(0,0).
EachshapehasarelatedURL.
Animage-mapprocessingapplicationtypicallytestseachshapeintheorderin
whichitappearsintheimagefileandreturnsthedocumentspecifiedbythe
correspondingURLtothebrowseriftheuser'smouseX,Ycoordinatesfallwithin
theboundariesofthatshape.Thatmeansit'sOKtooverlapshapes;justbeaware
whichtakesprecedence.Also,theentireimageneednotbecoveredwith
sensitiveregions:ifthepassedcoordinatesdon'tfallwithinaspecifiedshape,the
defaultdocumentgetssentbacktothebrowser.
Thisisjustoneexampleofhowanimagemapmaybeprocessedandthe
accessoryfilesrequiredforthatprocess.Pleasehuddlewithyourwebmasterand
servermanualstodiscoverhowtoimplementaserver-sideimagemapforyour
owndocumentsandsystem.
6.5.2.Client-SideImageMaps
Theobviousdownsidetoserver-sideimagemapsisthattheyrequireaserver.
ThatmeansyouneedaccesstotherequiredHTTPserverorits/cgi-bindirectory,
eitherofwhichisrarelyavailabletoanyoneotherthanownersorsystem
administrators.Andserver-sideimagemapslimitportabilitybecausenotall
image-mapprocessingapplicationsarethesame.
Server-sideimagemapsalsomeandelaysfortheuserwhilebrowsingbecause
thebrowsermustgettheserver'sattentiontoprocesstheimagecoordinates.This
istrueevenifthere'snoactiontotake,suchaswhentheuserclicksonasection
oftheimagethatisn'thyperlinkedanddoesn'tleadanywhere.
Client-sideimagemapssufferfromnoneofthesedifficulties.Enabledbytheusemap
attributeforthe<img>taganddefinedbyspecial<map>and<area>extensiontags,
client-sideimagemapsletauthorsincludeintheirdocumentscoordinatesand
linksthatdescribethesensitiveregionsofanimage.Thebrowserontheclient
computertranslatesthecoordinatesofthemousepositionwithintheimageinto
anaction,suchasloadinganddisplayinganotherdocument.Andspecial
JavaScript-enabledattributesprovideawealthofspecialeffectsforclient-side
imagemaps.[JavaScriptEventHandlers,12.3.3]
Tocreateaclient-sideimagemap,includetheusemapattributeaspartofthe<img>
tag.[*]ItsvalueistheURLofa<map>segmentinanHTMLdocumentthatcontains
themapcoordinatesandrelatedlinkURLs.ThedocumentintheURLidentifies
theHTMLorXHTMLdocumentcontainingthemap;thefragmentidentifierinthe
URLidentifiesthemapitself.Mostoften,themapisinthesamedocumentasthe
image,andtheURLcanbereducedtothefragmentidentifier:apoundsign(#)
followedbythemapname.
[*]Alternatively,accordingtotheHTML4standard,youmayreferenceaclient-sideimagemapbyincludingtheusemap
attributewiththe<object>andform<input>tags.SeeChapter12fordetails.
Forexample,thefollowingsourcefragmenttellsthebrowserthatthemap.gif
imageisaclient-sideimagemapandthatitsmouse-sensitivecoordinatesand
relatedlinkURLsarefoundinthemapfragmentofthecurrentdocument:
<imgsrc="pics/map.gif"usemap="#map">
6.5.3.The<map>Tag
Forclient-sideimagemapstowork,youmustprovideasetofcoordinatesand
URLsthatdefinethemouse-sensitiveregionsofaclient-sideimagemapandthe
hyperlinktotakeforeachregionthattheusermayclickorotherwiseselect.[ ]
Includethosecoordinatesandlinksasvaluesofattributesinconventional<a>tags
orspecial<area>tags;thecollectionof<area>specificationsor<a>tagsisenclosed
withinthe<map>taganditsendtag,</map>.The<map>segmentmayappear
anywhereinthebodyofthedocument.
[ ]TheTabkeyalsostepsthroughthehyperlinksinadocument,includingclient-sideimagemaps.Selectachosen
hyperlinkwiththeEnterkey.
<map>
Function Enclosesclient-sideimage-map(usemap)specifications
Attributes class,dir,id,lang,name,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </map>;neveromitted
Contains map_content
Usedin body_content
Morespecifically,the<map>tagmaycontaineitherasequenceof<area>tagsor
conventionalHTML/XHTMLcontentincluding<a>tags.Youcannotmixandmatch
<area>tagswithconventionalcontent.Browsersmaydisplayconventionalcontent
withinthe<map>tag;<area>tagcontentswillnot.Ifyouareconcernedabout
compatibilitywitholderbrowsers,useonly<map>tagscontaining<area>tags.
Ifyoudoplace<a>tagswithina<map>tag,theymustincludetheshapeandcoords
attributesthatdefinearegionwithintheobjectsthatreferencethe<map>tag.
6.5.3.1.Thenameattribute
Thevalueofthenameattributeinthe<map>tagisthenameusedbytheusemap
attributeinan<img>or<object>tagtolocatetheimage-mapspecification.The
namemustbeuniqueandnotusedbyanother<map>inthedocument,butmore
thanoneimagemapmayreferencethesame<map>specifications.[Theismapand
usemapattributes,5.2.6.14]
6.5.3.2.Theclass,id,style,andtitleattributes
Thestylesheetdisplay-relatedstyleandclassattributesforthe<map>tagareuseful
onlywhenthe<map>tagcontainsconventionalcontent,inwhichcasetheyapplyto
thecontentofthetag.[InlineStyles:ThestyleAttribute,8.1.1][StyleClasses,
8.3]
Theidandtitleattributes,ontheotherhand,arestraightforward.Theyare
standardwaystorespectivelylabelthetagforlaterreferencebyahyperlinkor
programortotitlethesectionforlaterreview.[Theidattribute,4.1.1.4][The
titleattribute,4.1.1.5]
6.5.3.3.Theeventattributes
ThevariouseventattributesallowyoutoassignJavaScripthandlerstoevents
thatmayoccurwithintheconfinesofthemap.[JavaScriptEventHandlers,
12.3.3]
6.5.4.The<area>Tag
Thegutsofaclient-sideimagemaparethe<area>tagswithinthemapsegment.
These<area>tagsdefineeachmouse-sensitiveregionandtheactionthebrowser
shouldtakeiftheuserselectsitinanassociatedclient-sideimagemap.
Theregiondefinedbyan<area>tagactsjustlikeanyotherhyperlink:whenthe
usermovesthemousepointerovertheregionoftheimage,thepointericon
changes,typicallyintoahand,andthebrowsermaydisplaytheURLofthe
relatedhyperlinkinthestatusboxatthebottomofthebrowserwindow.[*]
Regionsoftheclient-sideimagemapnotdefinedinatleastone<area>tagarenot
mousesensitive.
[*]Thatis,unlessyouactivateaJavaScripteventhandlerthatwritesthecontentsofthestatusbox.SeetheonMouse
eventhandlersinsection6.3.1.4.
<area>
Function Definescoordinatesandlinksforaregiononaclient-sideimagemap
Attributes
accesskey,alt,class,coords,dir,href,id,lang,nohref,notab,onBlur,onClick,
onDblClick,onFocus,onKeyDown,onKeyPress,onKeyUp,onMouseDown,onMouseMove,
onMouseOut,onMouseUp,shape,style,tabindex,taborder ,target ,title,type
Endtag NoneinHTML;</area>or<area.../>inXHTML
Contains Nothing
Usedin map_content
6.5.4.1.Thealtattribute
Likeitscousinforthe<img>tag,thealtattributeforthe<area>tagattachesatext
labeltotheimage,exceptinthiscasethelabelisassociatedwithaparticular
areaoftheimage.Thepopularbrowsersdisplaythislabeltotheuserwhenthe
mousepassesoverthearea,andnongraphicalbrowsersmayuseittopresentthe
client-sideimagemapasalistoflinksidentifiedbythealtlabels.
6.5.4.2.Thecoordsattribute
Therequiredcoordsattributeofthe<area>tagdefinescoordinatesofamouse-
sensitiveregioninaclient-sideimagemap.Thenumberofcoordinatesandtheir
meaningsdependupontheregion'sshapeasdeterminedbytheshapeattribute,
discussedlaterinthischapter.Youmaydefinehyperlinkregionsasrectangles,
circles,andpolygonswithinaclient-sideimagemap.
Theappropriatevaluesforeachshapeinclude:
circleorcirc
coords="x,y,r",wherexandydefinethepositionofthecenterofthecircle(0,0
istheupper-leftcorneroftheimage)andrisitsradiusinpixels.
polygonorpoly
coords="x1,y1,x2,y2,x3,y3,...",whereeachpairofX,Ycoordinatesdefinesa
vertexofthepolygon,with0,0beingtheupper-leftcorneroftheimage.At
leastthreepairsofcoordinatesarerequiredtodefineatriangle;higher-order
polygonsrequirealargernumberofvertices.Thepolygonisautomatically
closed,soitisnotnecessarytorepeatthefirstcoordinateattheendofthe
listtoclosetheregion.
rectangleorrect
coords="x1,y1,x2,y2",wherethefirstcoordinatepairisonecornerofthe
rectangleandtheotherpairisthecornerdiagonallyopposite,with0,0being
theupper-leftcorneroftheimage.Notethatarectangleisjustashortened
wayofspecifyingapolygonwithfourvertices.
Forexample,thefollowingXHTMLfragmentdefinesasinglemouse-sensitive
regioninthelower-rightquarterofa100x100-pixelimageandanothercircular
regionsmackinthemiddle:
<mapname="map1">
<areashape="rect"coords="75,75,99,99"nohref="nohref"/>
<areashape="circ"coords="50,50,25"nohref="nohref"/>
</map>
Ifthecoordinatesinone<area>tagoverlapwithanotherregion,thefirst<area>tag
takesprecedence.Thebrowsersignorecoordinatesthatextendbeyondthe
boundariesoftheimage.
6.5.4.3.Thehrefattribute
Likethehrefattributefortheanchor(<a>)tag,thehrefattributeforthe<area>tag
definestheURLofthedesiredlinkifitsregionintheassociatedimagemapis
clicked.ThevalueoftheHRefattributeisanyvalidURL,relativeorabsolute,
includingJavaScriptcode.
Forexample,thebrowserwillloadanddisplaythelink4.htmldocumentiftheuser
clicksinthelower-rightquarterofa100x100-pixelimage,asdefinedbythe
firstimage-map<area>taginthefollowingHTMLexample:
<mapname="map">
<areacoords="75,75,99,99"href="link4.html">
<areacoords="0,0,25,25"href="javascript:window.alert('Oooh,tickles!');">
</map>
Thesecond<area>tagintheexampleusesajavascriptURL,which,whentheuser
clicksintheupper-leftquadrantoftheimagemap,executesaJavaScriptalert
methodthatdisplaysthesillymessageinadialogbox.
6.5.4.4.Thenohrefattribute
Thenohrefattributeforthe<area>tagdefinesamouse-sensitiveregioninaclient-
sideimagemapforwhichnoactionistaken,eventhoughtheusermayselectit.
Youmustincludeeitheranhreforanohrefattributeforeach<area>tag.
6.5.4.5.Thenotab,taborder,andtabindexattributes
Asanalternativetothemouse,ausermaychooseadocument"hotspot,"suchas
ahyperlinkembeddedinanimagemap,bypressingtheTabkey.Oncetheuser
choosesthehotspot,heactivatesthehyperlinkbypressingtheEnterkey.By
default,thebrowserstepstoeachhotspotintheorderinwhichtheyappearin
thedocument.Youcannowchangethatdefaultorderwithwhatwasoriginally
introducedbyInternetExplorerwiththetaborderattributeandisnowstandardized
asthetabindexattribute.Thevalueoftheattributeisanintegerindicatingthe
positionofthisareaintheoveralltabsequenceforthedocument.
SupportedbyInternetExploreronlyandnotpartoftheHTML4andXHTML
standards,notabareasgetpassedoverastheuserpressestheTabkeytomove
thecursoraroundthedocument.Otherwise,thisareawillbepartofthetabbing
sequence.Theattributeisuseful,ofcourse,incombinationwiththenohref
attribute.
InternetExplorerversion4supportedthenotabandtaborderattributes.Versions5
andlatersupporttabindex,too,sousethestandardratherthantheextension
attributes.
6.5.4.6.Theeventattributes
Thesamemouse-relatedJavaScripteventhandlersthatworkfortheanchor(<a>)
tagalsoworkwithclient-sideimage-maphyperlinks.Thevalueoftheevent
handlerisenclosedinquotationmarksoneorasequenceofsemicolon-separated
JavaScriptexpressions,methods,andfunctionreferencesthatthebrowser
executeswhentheeventoccurs.[JavaScriptEventHandlers,12.3.3]
Forexample,apopular,albeitsimple,useoftheonMouseOvereventistoprinta
moredescriptiveexplanationinthebrowser'sstatusboxwhenevertheuser
passesthemousepointeroveraregionoftheimagemap:
<areahref="http://www.oreilly.com/kumquats/homecooking/recipes.html#quat5"
onMouseOver="self.status='Arecipeforkumquatsoup.';returntrue">
Weshouldpointoutthatthecurrentversionsofthepopularbrowsers
automaticallydisplaythealtattribute'sstringvalue,ostensiblyaccomplishingthe
sametask.Sowerecommendthatyouincludethealtattributeandvalueinlieu
ofhackingJavaScript.And,incontextwithatext-basedhyperlink,wearguethat
thecontentsofthetagitselfshouldexplainthelink.Butimagescanbedeceptive,
soweurgeyoutotakeadvantageofboththealtattributeandeventhandlersto
providetextdescriptionswithyourimagemaps.
6.5.4.7.Theshapeattribute
Usetheshapeattributetodefinetheshapeofanimagemap'smouse-sensitive
region:acircle(circorcircle),polygon(polyorpolygon),orrectangle(rector
rectangle).
Thevalueoftheshapeattributeaffectshowthebrowserinterpretsthevalueofthe
coordsattribute.Ifyoudon'tincludeashapeattribute,thevaluedefaultisassumed.
Accordingtothestandard,defaultmeansthattheareacoverstheentireimage.In
practice,thebrowsersdefaulttoarectangularareaandexpecttofindfourcoords
values.Ifyoudon'tspecifyashapeanddon'tincludefourcoordinateswiththe
tag,thebrowsersignoretheareaaltogether.
Infact,onlythemostrecentversionsofthepopularbrowsersrecognizetheshape
valuedefaulttoprovideacatchallareaforclicksthatfalloutsidealltheother
definedhotspots.Becauseareasareina"first-come,first-served"orderinthe
<map>tag,youshouldplacethedefaultarealast.Otherwise,itcoversupanyand
allareasthatfollowinyourimagemap.
Thebrowsersarelaxintheirimplementationoftheshapenames.Netscape4,for
example,doesn'trecognize"rectangle"butdoesrecognize"rect"forarectangular
shape.Forthisreason,werecommendthatyouusetheabbreviatednames.
6.5.4.8.Thetargetattribute
Thetargetattributegivesyouawaytocontrolwherethecontentsoftheselected
hyperlinkintheimagemapgetdisplayed.Theattributeiscommonlyusedin
conjunctionwithframesormultiplebrowserwindows,anditsthevalueisthe
nameoftheframeorwindowinwhichthereferenceddocumentshouldbeloaded.
Ifthenamedframeorwindowexists,thedocumentisloadedinthatframeor
window.Ifnot,anewwindowiscreatedandgiventhespecifiedname,andthe
documentisloadedinthatnewwindow.Formoreinformation,includingalistof
specialtargetnames,seesection11.7.
6.5.4.9.Thetitleattribute
Thetitleattributeletsyouspecifyatitleforthedocumenttowhichtheimage
map'sarealinks.Thevalueoftheattributeisanystring,enclosedinquotes.The
browsermightusethetitlewhendisplayingthelink,perhapsflashingthetitle
whenthemousepassesoverthearea.Thebrowsermightalsousethetitle
attributewhenaddingthislinktoauser'sbookmarksorfavorites.
Thetitleattributeisespeciallyusefulforreferencinganotherwiseunlabeled
resource,suchasanimageoranon-HTMLdocument.Ideally,thevaluespecified
shouldmatchthetitleofthereferenceddocument,butthisisn'trequired.
6.5.4.10.Theclass,dir,id,lang,andstyleattributes
Theclassandstyleattributesallowyoutosupplydisplaypropertiesandclass
namestocontroltheappearanceofthearea,althoughtheirvalueseemslimited
forthistag.Theidattributeallowsyoutocreateanamefortheareathatmight
bereferencedbyahyperlink.[Theidattribute,4.1.1.4][InlineStyles:Thestyle
Attribute,8.1.1][StyleClasses,8.3]
Thelanganddirattributesdefinethelanguageusedforthisareaandthedirection
inwhichtextisrendered.Again,theiruseisnotapparentwiththistag.[Thedir
attribute,3.6.1.1][Thelangattribute,3.6.1.2]
6.5.5.AClient-SideImage-MapExample
ThefollowingexampleHTMLfragmentdrawstogetherthevariouscomponentsof
aclient-sideimagemapdiscussedearlierinthissection.Itincludesthe<img>tag
withtheimagereferenceandausemapattributewithanamethatpointstoa<map>
thatdefinesfourmouse-sensitiveregions(threeplusadefault)andrelatedlinks:
<body>
...
<imgsrc="pics/map.gif"usemap="#map1"border=0>
...
<mapname="map1">
<areashape=rectcoords="0,20,40,100"
href="k_juice.html"
onMouseOver="self.status='Howtopreparekumquatjuice.'
;returntrue">
<areashape=rectcoords="50,50,80,100"
href="k_soup.html"
onMouseOver="self.status='Arecipeforheartykumquatsoup.'
;returntrue">
<areashape=rectcoords="90,50,140,100"
href="k_fruit.html"
onMouseOver="self.status='Careandhandlingofthenativekumquat.'
;returntrue">
<areashape=default
href="javascript:window.alert('Choosethecuporoneofthebowls.')"
onMouseOver="self.status='Selectthecuporabowlformoreinformation.'
;returntrue">
</map>
SeeFigure6-7fortheresults.
Figure6-7.Asimpleclient-sideimagemapwithJavaScript-
enabledmouseevents
6.5.6.HandlingOtherBrowsers
Unlikeitsserver-sideismapcounterpart,theclient-sideimage-maptagwith
attributes(<imgusemap>)doesn'tneedtobeincludedinan<a>tag.Butitmaybeso
thatyoucangracefullyhandlebrowsersthatareunabletoprocessclient-side
imagemaps.
Forexample,theancientMosaicandearlyversionsofNetscapesimplyloada
documentnamedmain.htmliftheuserclicksthemap.gifimagereferencedinthe
followingsourcefragment.Morerecentbrowsers,ontheotherhand,dividethe
imageintomouse-sensitiveregions,asdefinedintheassociated<map>,andlinkto
aparticularnameanchorwithinthesamemain.htmldocumentiftheuserselects
theimage-mapregion:
<ahref="main.html">
<imgsrc="pics/map.gif"ismapusemap="#map1">
</a>
...
<mapname="map1">
<areacoords="0,0,49,49"href="main.html#link1">
<areacoords="50,0,99,49"href="main.html#link2">
<areacoords="0,50,49,99"href="main.html#link3">
<areacoords="50,50,99,99"href="main.html#link4">
</map>
Tomakeanimagemapbackwardcompatiblewithallimage-map-capable
browsers,youmayalsoincludeclient-sideandserver-sideprocessingforthe
sameimagemap.Capablebrowserswillhonorthefasterclient-sideprocessing;
allotherbrowserswillignoretheusemapattributeinthe<img>tagandrelyuponthe
referencedserverprocesstohandleuserselectionsinthetraditionalway.For
example:
<ahref="/cgi-bin/images/map.proc">
<imgsrc="pics/map2.gif"usemap="#map2"ismap>
</a>
...
<mapname="map2">
<areacoords="0,0,49,49"href="link1.html">
<areacoords="50,0,99,49"href="link2.html">
<areacoords="0,50,49,99"href="link3.html">
<areacoords="50,50,99,99"href="link4.html">
</map>
6.5.7.EffectiveUseofMouse-SensitiveImages
SomeofthemostvisuallycompellingpagesontheWebhavemouse-andhot-
key-sensitiveimages:mapswithregionsthat(whenclickedorselectedwiththe
TabandEnterkeys)lead,forexample,tomoreinformationaboutacountryor
townorresultinmoredetailaboutthelocationandwhotocontactataregional
branchofabusiness.We'veseenanimageofafashionmodelwhosevarious
clothingpartsleadtotheirrespectivecatalogentries,completewithdetailed
descriptionsandpricesforordering.
Thevisualnatureofthese"hyperactive"pictures,coupledwiththeneedforan
effectiveinterface,meansthatyoushouldstronglyconsiderhavinganartist,a
user-interfacedesigner,andevenahuman-factorsexpertevaluateyourimagery.
Attheveryleast,engageinabitofusertestingtomakesurepeopleknowwhat
regionoftheimagetoselecttomovetothedesireddocument.Makesurethe
sensitiveareasoftheimageindicatethistotheuserusingaconsistentvisual
mechanism.Considerusingborders,dropshadows,orcolorchangestoindicate
thoseareasthattheusercanselect.
Finally,alwaysrememberthatthedecisiontousemouse-sensitiveimagesisan
explicitdecisiontoexcludetext-basedandimage-restrictedbrowsersfromyour
pages.ThisincludesbrowsersconnectingtotheInternetviaslowmodem
connections.Forthesepeople,downloadingyourbeautifulimagesissimplytoo
expensive.Tokeepfromdisenfranchisingagrowingpopulation,makesureany
pagethathasamouse-sensitiveimagehasatext-onlyequivalenteasily
accessiblefromalinkontheimage-enabledversion.Somethoughtfulwebmasters
evenprovideseparatepagesforuserspreferringfullgraphicsversusmostlytext.
6.6.CreatingSearchableDocuments
AnotherextensibleformofanHTMLlinkthatdoesnotusethe<a>tagisonethat
causestheservertosearchadatabaseforadocumentthatcontainsauser-
specifiedkeywordorwords.AnHTMLdocumentthatcontainssuchalinkisknown
asasearchabledocument.
6.6.1.The<isindex>Tag(Deprecated)
BeforeitwasdeprecatedinboththeHTML4andXHTMLstandards,authorsused
tousethe<isindex>tagtopasskeywordsalongwithasearchengine'sURLtothe
server.Theserverthenmatchedthekeywordsagainstadatabaseoftermsto
selectthenextdocumentfordisplay.Today'sauthorsmostlyuseformstopass
informationtotheserverandsupportingprograms.SeeChapter9fordetails.
<isindex>
Function Indicatesthatadocumentcanbesearched
Attributes action ,class,dir,id,lang,prompt,style,title
Endtag NoneinHTML;</isindex>or<isindex.../>inXHTML
Contains Nothing
Usedin head_content
Whenabrowserencountersthe<isindex>tag,itaddsastandardsearchinterface
tothedocument(renderedbyInternetExplorerinFigure6-8):
<html>
<head>
<title>KumquatAdviceDatabase</title>
<basehref="cgi-bin/quat-query">
<isindex>
</head>
<body>
<h3>KumquatAdviceDatabase</h3>
<p>
Searchthisdatabasetolearnmoreaboutkumquats!
</body>
</html>
Figure6-8.Asearchabledocument
Theusertypesalistofspace-separatedkeywordsintothefieldprovided.When
theuserpressestheEnterkey,thebrowserautomaticallyappendsthequerylist
totheendofaURLandpassestheinformationtotheserverforfurther
processing.
WhiletheHTMLandXHTMLstandardsallowthedeprecated<isindex>tagtobe
placedonlyinthedocumentheader,mostbrowsersletthetagappearanywhere
inthedocumentandinsertthesearchfieldinthecontentflowwherethe<isindex>
tagappears.Thisconvenientextensionletsyouaddinstructionsandotheruseful
elementsbeforepresentingtheuserwiththeactualsearchfield.
6.6.1.1.Thepromptattribute
Thebrowserprovidesaleadingpromptjustaboveortotheleftoftheuser-entry
field.InternetExplorer'sdefaultprompthasevenchangedovertheyears.Version
5,forexample,used"Thisisasearchableindex.Entersearchkeywords:".Figure
6-8showsthenewonewithversion6'sprompt.Thatdefaultpromptisnotthe
bestforalloccasions,soitispossibletochangeitwiththepromptattribute.
Whenaddedtothe<isindex>tag,thevalueofthepromptattributeisthestringof
textthatprecedesthekeywordentryfieldthebrowserplacesinthedocument.
Forexample,compareFigure6-8withFigure6-9,inwhichweaddedthe
followingprompttotheprevioussourceexample:
<isindexprompt="Tolearnmoreaboutkumquats,enterakeyword:">
Figure6-9.Thepromptattributecreatescustompromptsin
searchabledocuments
Olderbrowsersignorethepromptattribute,butthereislittlereasonnottoinclude
abetterpromptstringforyourmoreup-to-datereadership.
6.6.1.2.ThequeryURL
Besidesthe<isindex>tagintheheaderofasearchabledocument,theother
importantelementofthisspecialtagisthequeryURL.Bydefault,itistheURLof
thesourcedocumentitselfnotgoodifyourdocumentcan'thandlethequery.
Rather,mostauthorsusethe<base>attributetopointtoadifferentURLforthe
search.[<base>,6.7.1]
ThebrowserappendsaquestionmarktothequeryURL,followedbythespecified
searchparameters.Nonprintablecharactersareappropriatelyencoded;multiple
parametersareseparatedbyplussigns(+).
Inthepreviousexample,ifausertyped"insectcontrol"inthesearchfield,the
browserwouldretrievetheURL:
cgi-bin/quat-query?insect+control
6.6.1.3.Theactionattribute
ForInternetExploreronly,youcanspecifythequeryURLfortheindexwiththe
actionattribute.TheeffectisexactlyasthoughyouhadusedtheHRefattribute
withthe<base>tag:thebrowserlinkstothespecifiedURLwiththesearch
parametersappendedtotheURL.
Whiletheactionattributeprovidesthedesirablefeatureofdivorcingthe
document'sbaseURLfromthesearchindexURL,itwillcauseyoursearchestofail
iftheuserisnotusingInternetExplorer.Forthisreason,wedonotrecommend
thatyouusetheactionattributetospecifythequeryURLforthesearch.
6.6.1.4.Theclass,dir,id,lang,style,andtitleattributes
Theclassandstyleattributesallowyoutosupplydisplaypropertiesandclass
namestocontroltheappearanceofthetag,althoughtheirvalueseemslimited
for<isindex>.Theidandtitleattributesallowyoutocreateanameandtitlefor
thetag;thenamemightbereferencedbyahyperlink.[Theidattribute,4.1.1.4]
[InlineStyles:ThestyleAttribute,8.1.1][StyleClasses,8.3]
Thedirandlangattributesdefinethelanguageusedforthistagandthedirection
inwhichtextisrendered.Again,theiruseisnotapparentwith<isindex>.[Thedir
attribute,3.6.1.1][Thelangattribute,3.6.1.2]
6.6.1.5.Serverdependencies
Likeimagemaps,searchabledocumentsrequiresupportfromtheservertomake
thingswork.HowtheserverinterpretsthequeryURLanditsparametersisnot
definedbytheHTMLorXHTMLstandards.
Youshouldconsultyourserver'sdocumentationtodeterminehowyoucanreceive
andusethesearchparameterstolocatethedesireddocument.Typically,the
serverbreakstheparametersoutofthequeryURLandpassesthemtoaprogram
designatedbytheURL.
6.7.Relationships
Veryfewdocumentsstandalone.Instead,adocumentisusuallypartofa
collectionofdocuments,eachconnectedbyoneorseveralofthehypertext
strandswedescribeinthischapter.Onedocumentmaybeapartofseveral
collections,linkingtosomedocumentsandbeinglinkedtobyothers.Readers
moveamongthedocumentfamiliesastheyfollowthelinksthatinterestthem.
Whenyoulinktwodocuments,youestablishanexplicitrelationshipbetween
them.Conscientiousauthorsusetherelattributeofthe<a>tagtoindicatethe
natureofthelink.Inaddition,twoothertagsmaybeusedwithinadocumentto
furtherclarifythelocationofadocumentwithinadocumentfamilyandits
relationshiptotheotherdocumentsinthatfamily.Thesetags,<base>and<link>,
areplacedwithinthebodyofthe<head>tag.[<head>,3.7.1]
6.7.1.The<base>HeaderElement
Aswepreviouslyexplained,URLswithinadocumentcanbeeitherabsolute(with
everyelementoftheURLexplicitlyprovidedbytheauthor)orrelative(with
certainelementsoftheURLomittedandsuppliedbythebrowser).Normally,the
browserfillsintheblanksofarelativeURLbydrawingthemissingpiecesfrom
theURLofthecurrentdocument.Youcanchangethatwiththe<base>tag.
<base>
Function DefinesthebaseURLforotheranchorsinthedocument
Attributes href,target
Endtag NoneinHTML;</base>or<base.../>inXHTML
Contains Nothing
Usedin head_content
The<base>tagshouldappearonlyinthedocumentheader,notinitsbody
contents.ThebrowserthereafterusesthespecifiedbaseURL,notthecurrent
document'sURL,toresolveallrelativeURLs,includingthosefoundin<a>,<img>,
<link>,and<form>tags.ItalsodefinestheURLthatwillbeusedtoresolvequeries
insearchabledocumentscontainingthe<isindex>tag.[ReferencingDocuments:
TheURL,6.2]
6.7.1.1.Thehrefattribute
TheHRefattributemusthaveavalidURLasitsvalue,whichthebrowserthenuses
todefinetheabsoluteURLagainstwhichrelativeURLsarebasedwithinthe
document.
Forexample,the<base>taginthisXHTMLdocumenthead:
<head>
<basehref="http://www.kumquat.com/"/>
</head>
...
tellsthebrowserthatanyrelativeURLswithinthisdocumentarerelativetothe
top-leveldocumentdirectoryonwww.kumquat.com,regardlessoftheaddressand
directoryofthemachinefromwhichtheuserretrievedthecurrentdocument.
Contrarytowhatyoumayexpect,youcanmakethebaseURLrelative,not
absolute.Thebrowsershould(butdoesn'talways)formanabsolutebaseURLout
ofthisrelativeURLbyfillinginthemissingpieceswiththeURLofthedocument
itself.Thispropertycanbeusedtogoodadvantage.Forinstance,inthisnext
HTMLexample:
<head>
<basehref="/info/">
</head>
...
thebrowsermakesthe<base>URLintoonerelativetotheserver's/infodirectory,
whichprobablyisnotthesamedirectoryofthecurrentdocument.Imagineifyou
hadtoreaddresseverylinkinyourdocumentwiththatcommondirectory.Not
onlydoesthe<base>taghelpyoushortenthoseURLsinyourdocumentthathave
acommonroot,butitalsoletsyouconstrainthedirectoryfromwhichrelative
referencesareretrievedwithoutbindingthedocumenttoaspecificserver.
6.7.1.2.Thetargetattribute
Whenworkingwithdocumentsinsideframes,thetargetattributewiththe<a>tag
ensuresthatareferencedURLgetsloadedintothecorrectframe.Similarly,the
targetattributeforthe<base>tagletsyouestablishthedefaultnameofoneofthe
framesorwindowsinwhichthebrowseristodisplayredirectedhyperlinked
documents.[AnOverviewofFrames,11.1]
Ifyouhavenootherdefaulttargetforyourhyperlinkswithinyourframes,you
maywanttoconsiderusing<basetarget=_top>.Thisensuresthatlinksthatarenot
specificallytargetedtoaframeorwindowwillloadinthetop-levelbrowser
window.Thiseliminatestheembarrassingandcommonerrorofhavingreferences
topagesonothersitesappearwithinaframeonyourpages,insteadofwithin
theirownpages.AminorbitofHTML,tobesure,butitmakeslifemucheasierfor
yourreaders.
6.7.1.3.Using<base>
Themostimportantreasonforusing<base>istoensurethatanyrelativeURLs
withinthedocumentwillresolveintocorrectdocumentaddresses,evenifthe
documentsthemselvesaremovedorrenamed.Thisisparticularlyimportantwhen
creatingadocumentcollection.Byplacingthecorrect<base>tagineach
document,youcanmovetheentirecollectionbetweendirectoriesandeven
serverswithoutbreakingallofthelinkswithinthedocuments.Youalsoneedto
usethe<base>tagforasearchabledocument(<isindex>)ifyouwantuserqueries
posedtoaURLdifferentfromthatofthehostdocument.
Adocumentthatcontainsboththe<isindex>tagandotherrelativeURLsmayhave
problemsiftherelativeURLsarenotrelativetothedesiredindex-processingURL.
Becausethisisusuallythecase,don'tuserelativeURLsinsearchabledocuments
thatusethe<base>tagtospecifythequeryURLforthedocument.
6.7.2.The<link>HeaderElement
Usethe<link>tagtodefinetherelationshipbetweenthecurrentdocumentand
anotherinawebcollection.
The<link>tagbelongsinthe<head>contentandnowhereelse.Usetheattributes
ofthe<link>taglikethoseofthe<a>tag,buttheireffectsserveonlytodocument
therelationshipbetweendocuments.The<link>taghasnocontent,andonly
XHTMLsupportstheclosing</link>tag.
<link>
Function Definesarelationshipbetweenthisdocumentandanotherdocument
Attributes
charset,class,dir,href,hreflang,id,lang,media,onClick,onDblClick,onKeyDown,
onKeyPress,onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,rel,
rev,style,target,title,type
Endtag NoneinHTML;</link>or<link.../>inXHTML
Contains Nothing
Usedin head_content
6.7.2.1.Thehrefattribute
Aswithitsothertagapplications,theHRefattributespecifiestheURLofthetarget
<link>tag.Itisarequiredattribute,anditsvalueisanyvaliddocumentURL.The
specifieddocumentisassumedtohavearelationshiptothecurrentdocument.
6.7.2.2.Therelandrevattributes
Therelandrevattributesexpresstherelationshipbetweenthesourceandtarget
documents.Therelattributespecifiestherelationshipfromthesourcedocument
tothetarget;therevattributespecifiestherelationshipfromthetargetdocument
tothesourcedocument.Bothattributescanbeincludedinasingle<link>tag.
Thevalueofeitherattributeisaspace-separatedlistofrelationships.Theactual
relationshipnamesarenotspecifiedbytheHTMLstandard,althoughsomehave
comeintocommonusage.Forexample,adocumentthatispartofasequenceof
documentsmightuse:
<linkhref="part-14.html"rel=nextrev=prev>
whenreferencingthenextdocumentintheseries.Therelationshipfromthe
sourcetothetargetisthatofmovingtothenextdocument;thereverse
relationshipisthatofmovingtothepreviousdocument.
6.7.2.3.Thetitleattribute
Thetitleattributeletsyouspecifythetitleofthedocumenttowhichyouare
linking.Thisattributeisusefulwhenreferencingaresourcethatdoesnothavea
title,suchasanimageoranon-HTMLdocument.Inthiscase,thebrowsermight
usethe<link>titlewhendisplayingthereferenceddocument.Forexample:
<linkhref="pics/kumquat.gif"
title="AphotographoftheNobleFruit">
tellsthebrowsertousetheindicatedtitlewhendisplayingthereferencedimage.
Thevalueoftheattributeisanarbitrarycharacterstring,enclosedinquotation
marks.
6.7.2.4.Thetypeattribute
ThetypeattributeprovidestheMIMEcontenttypeofthelinkeddocument.
Supportedbyallthepopularbrowsers,theHTML4andXHTMLstandardtype
attributecanbeusedwithanylinkeddocument.Itisoftenusedtodefinethetype
ofalinkedstylesheet.Inthiscontext,thevalueofthetypeattributeisusually
text/css.Forexample:
<linkhref="styles/classic.css"rel=stylesheettype="text/css">
createsalinktoanexternalstylesheetwithinthe<head>ofadocument.See
Chapter8fordetails.
6.7.2.5.Howbrowsersmightuse<link>
Althoughthestandardsdonotrequirebrowserstodoanythingwiththe
informationprovidedbythe<link>tag,it'snothardtoenvisionhowthis
informationmightbeusedtoenhancethepresentationofadocument.
Asasimpleexample,supposeyouconsistentlyprovide<link>tagsforeachofyour
documentsthatdefinenext,prev,andparentlinks.Abrowsercouldusethis
informationtoplaceatthetoporbottomofeachdocumentastandardtoolbar
containingbuttonsthatwouldjumptotheappropriaterelateddocument.By
relegatingthetaskofprovidingsimplenavigationallinkstothebrowser,youare
freetoconcentrateonthemoreimportantcontentofyourdocument.
Asamorecomplexexample,supposethatabrowserexpectstofinda<link>tag
definingaglossaryforthecurrentdocumentandthatthisglossarydocumentis
itselfasearchabledocument.Wheneverareaderclickedonawordorphrasein
thedocument,thebrowsercouldautomaticallysearchtheglossaryforthe
definitionoftheselectedphrase,presentingtheresultinasmallpop-upwindow.
AstheWebevolves,expecttoseemoreandmoreusesofthe<link>tagtodefine
documentrelationshipsexplicitly.
6.7.2.6.Other<link>attributes
TheHTML4andXHTMLstandardsalsoincludetheubiquitouscollectionof
attributesrelatedtostylesheetsanduserevents,andlanguageforthe<link>tag.
Youcanrefertothecorrespondingsectiondescribingtheseattributesforthe<a>
tagforacompletedescriptionoftheirusage.[<a>,6.3.1]
Becauseyouputthe<link>taginthe<head>section,whosecontentsarenot
displayed,itmayseemthattheseattributesareuseless.Itisentirelypossible
thatsomefuturebrowsermayfindsomewaytodisplaythe<link>informationto
theuser,possiblyasanavigationbarorasetofhot-listselections.Inthosecases,
thedisplayandrenderinginformationwouldproveuseful.Currently,nobrowser
providesthesecapabilities.
6.8.SupportingDocumentAutomation
Twoadditionalheadertagshavetheprimaryfunctionsofsupportingdocument
automationandinteractingwiththewebserveritselfandwithdocument-
generationtools.
6.8.1.The<meta>HeaderElement
Giventherichsetofheadertagsfordefiningadocumentanditsrelationshipwith
othersthatgounusedbymostauthors,you'dthinkwe'dallbesatisfied.Butno,
there'salwayssomeonewithspecialneeds.Theseauthorswanttobeabletogive
evenmoreinformationabouttheirpreciousdocumentsinformationthatbrowsers,
readersofthesource,ordocument-indexingtoolsmightuse.The<meta>tagisfor
thoseofyouwhoneedtogobeyondthebeyond.
<meta>
Function Suppliesadditionalinformationaboutadocument
Attributes charset ,content,dir,http_equiv,lang,name,scheme
Endtag NoneinHTML;</meta>or<meta.../>inXHTML
Contains Nothing
Usedin head_content
The<meta>tagbelongsinthedocumentheaderandhasnocontent.Instead,
attributesofthetagdefinename/valuepairsthatassociatethedocument.In
certaincases,thewebserverservingthedocumentusesthesevaluestofurther
definethedocumentcontenttypetothebrowser.
6.8.1.1.Thenameattribute
Thenameattributesuppliesthenameofthename/valuepairdefinedbythe<meta>
tag.NeithertheHTMLnortheXHTMLstandardspecifiesanypredefined<meta>
names.Ingeneral,youarefreetouseanynamethatmakessensetoyouand
otherreadersofyoursourcedocument.
Onecommonlyusednameiskeywords,whichdefinesasetofkeywordsforthe
document.WhenencounteredbyanyofthepopularsearchenginesontheWeb,
thesekeywordsmaybeusedtocategorizethedocument.Ifyouwantyour
documentstobeindexedbyasearchengine,considerputtingthiskindoftagin
the<head>ofeachdocument:
<metaname="keywords"content="kumquats,cooking,peeling,eating">
Ifthenameattributeisnotprovided,thenameofthename/valuepairistaken
fromthehttp-equivattribute.
6.8.1.2.Thecontentattribute
Thecontentattributeprovidesthevalueofthename/valuepair.Itcanbeanyvalid
string(enclosedinquotesifitcontainsspaces).Itshouldalwaysbespecifiedin
conjunctionwitheitheranameoranhttp-equivattribute.
Asanexample,youmightplacetheauthor'snameinadocumentwith:
<metaname="Authors"content="ChuckMusciano&BillKennedy">
6.8.1.3.Thehttp-equivattribute
Thehttp-equivattributesuppliesanameforthename/valuepairandinstructsthe
servertoincludethename/valuepairintheMIMEdocumentheaderthatis
passedtothebrowserbeforesendingtheactualdocument.
Whenaserversendsadocumenttoabrowser,itfirstsendsanumberof
name/valuepairs.Whilesomeserversmightsendanumberofthesepairs,all
serverssendatleastone:
content-type:text/html
ThistellsthebrowsertoexpecttoreceiveanHTMLdocument.
Whenyouusethe<meta>tagwiththehttp-equivattribute,theserverwilladdyour
name/valuepairstothecontentheaderitsendstothebrowser.Forexample,
adding:
<metahttp-equiv="charset"content="iso-8859-1">
<metahttp-equiv="expires"content="31Dec99">
causestheheadersenttothebrowsertocontain:
content-type:text/html
charset:iso-8859-1
expires:31Dec99
Ofcourse,addingtheseadditionalheaderfieldsmakessenseonlyifyourbrowser
acceptsthefieldsandusestheminsomeappropriatemanner.
6.8.1.4.Thecharsetattribute
InternetExplorerversions5andearlierprovidedexplicitsupportforacharset
attributeinthe<meta>tag.Setthevalueoftheattributetothenameofthe
charactersettobeusedforthedocument.Thisisnottherecommendedwayto
defineadocument'scharacterset.Rather,werecommendalwaysusingthehttp-
equivandcontentattributestodefinethecharacterset.
6.8.1.5.Theschemeattribute
Thisattributespecifiestheschemetobeusedtointerprettheproperty'svalue.
Thisschemeshouldbedefinedwithintheprofilespecifiedbytheprofileattribute
ofthe<head>tag.[<head>,3.7.1]
6.8.2.The<nextid>HeaderElement(Archaic)
ThistagisnotdefinedintheHTML4andXHTMLstandardsandshouldnotbe
used.Wedescribeithereforhistoricalreasons.
<nextid>
Function Definesthenextvaliddocumententityidentifier
Attributes n
Endtag None
Contains Nothing
Usedin head_content
Theideabehindthe<nextid>tagistoprovidesomewayofautomaticallyindexing
fragmentidentifiers.
6.8.2.1.Thenattribute
Thenattributespecifiesthenameofthenextgeneratedfragmentidentifier.Itis
typicallyanalphabeticstringfollowedbyatwo-digitnumber.Atypical<nextid>tag
mightlooklikethis:
<html>
<head>
<nextidn=DOC54>
</head>
...
Anautomaticdocumentgeneratormightusethenextidinformationtosuccessively
namefragmentidentifiersDOC54,DOC55,andsoforth,withinthisdocument.
Chapter7.FormattedLists
MakinginformationmoreaccessibleisthesinglemostimportantqualityofHTML
anditsprogeny,XHTML.Thelanguages'excellentcollectionoftextstyleand
formattingtoolshelpyouorganizeyourinformationintodocumentsreaderscan
quicklyunderstand,scan,andextract,possiblywithautomatedbrowseragents.
Beyondembellishingyourtextwithspecializedtexttags,HTMLandXHTML
providearichsetoftoolsthathelpyouorganizecontentintoformattedlists.
There'snothingmagicalormysteriousaboutlists.Infact,thebeautyoflistsis
theirsimplicity.They'rebasedoncommonlistparadigmsweencountereveryday,
suchasunorderedgrocerylists,orderedinstructionlists,anddictionary-like
definitionlists.Allarefamiliar,comfortablewaysoforganizingcontent.All
providepowerfulmeansforquicklyunderstanding,scanning,andextracting
pertinentinformationfromyourwebdocuments.
7.1.UnorderedLists
Likealaundryorshoppinglist,anunorderedlistisacollectionofrelateditems
thathavenospecialorderorsequence.Themostcommonunorderedlistyou'll
findontheWebisacollectionofhyperlinkstootherdocuments.Somecommon
topic,suchas"RelatedKumquatLovers'Sites,"alliestheitemsinanunordered
list,buttheyhavenoorderamongthemselves.
7.1.1.The<ul>Tag
The<ul>tagsignalstothebrowserthatthefollowingcontent,betweenitandthe
</ul>endtag,isanunorderedlistofitems.Inside,aleading<li>tagidentifies
eachitemintheunorderedlist.Otherwise,nearlyanythingHTML/XHTML-wise
goes,includingotherlists,text,andmultimediaelements.
<ul>
Function Definesanunorderedlist
Attributes
class,compact,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,
onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,
title,type
Endtag </ul>;neveromitted
Contains list_content
Usedin block
Typically,thebrowseraddsaleadingbulletcharacterandformatseachunordered
listitemonanewline,indentedsomewhatfromtheleftmarginofthedocument.
Theactualrenderingofunorderedlists,althoughsimilarforthepopularbrowsers
(seeFigure7-1),isnotdictatedbythestandards,soyoushouldn'tgetbentoutof
shapetryingtoattainexactpositioningoftheelements.
HereisanexampleXHTMLunorderedlist,asshowninFigure7-1:
PopularKumquatrecipes:
<ul>
<li>PickledKumquats</li>
<li>'Quatsand'Kraut(aholidayfavorite!)</li>
<li>'Quatshakes</li>
</ul>
Therearesomanymoretopleaseeverypalate!
Figure7-1.Asimpleunorderedlist
TrickyHTMLauthorssometimesusenestedunorderedlists,withandwithout<li>-
taggeditems,totakeadvantageoftheautomatic,successiveindenting.Youcan
producesomefairlyslicktextsegmentsthatway.Justdon'tdependonitforall
browsers,includingfutureones.Rather,it'sbesttousetheborderpropertywitha
styledefinitionintheparagraph(<p>)ordivision(<div>)tagtoindentnonlist
sectionsofyourdocument(seeChapter8).
7.1.1.1.Thetypeattribute
Thegraphicalbrowsersautomaticallybulleteach<li>-taggediteminanunordered
list.NetscapeandFirefoxuseadiamondlikethatshowninFigure7-1,whereas
InternetExplorerandOperauseasolidcircle,forexample.Browsersthatsupport
HTML3.2andlaterversions,including4.0and4.01,aswellasXHTML1.0,let
youusethetypeattributetospecifywhichbulletsymbolyou'dratherhave
precedeitemsinanunorderedlist.Thisattributemayhavethevalueofdisc,
circle,orsquare.Alltheitemswithinthatlistthereafterusethespecifiedbullet
symbol,unlessanindividualitemoverridesthelistbullettype,asdescribedlater
inthischapter.
WiththeadventofstandardCascadingStyleSheets(CSS),theWorldWideWeb
Consortium(W3C)hasdeprecatedthetypeattributeinHTML4andinXHTML.
Expectittodisappear.
7.1.1.2.Compactunorderedlists
Ifyoulikewide-openspaces,you'llhatetheoptionalcompactattributeforthe<ul>
tag.Ittellsthebrowsertosqueezetheunorderedlistintoanevensmaller,more
compacttextblock.Typically,thebrowserreducesthelinespacingbetweenlist
items;italsomayreducetheindentationbetweenlistitems,ifitdoesanythingat
allwithindentation(usuallyitdoesn't).
Somebrowsersignorethecompactattribute,soyoushouldn'tdependonits
formattingattributes.Also,theattributeisdeprecatedintheHTML4andXHTML
standards,soithasn'tlongtolive.
7.1.1.3.Thestyleandclassattributes
ThestyleandclassattributesbringCSS-baseddisplaycontroltolists,providingfar
morecomprehensivecontrolthanyouwouldgetthroughindividualattributeslike
type.Combinethestyleattributewiththe<ul>tag,forinstance,toassignyourown
bulleticonimage,insteadofusingthecommoncircle,disc,orsquare.Theclass
attributeletsyouapplythestyleofapredefinedclassofthe<ul>tagtothe
contentsoftheunorderedlist.Thevalueoftheclassattributeisthenameofa
styledefinedinsomedocument-levelorexternallydefinedstylesheet.Formore
information,seeChapter8.[InlineStyles:ThestyleAttribute,8.1.1][Style
Classes,8.3]
7.1.1.4.Thelanganddirattributes
Thelangattributeletsyouspecifythelanguageusedwithinalist,anddirletsyou
advisethebrowserinwhichdirectionthetextshouldbedisplayed.Thevalueof
thelangattributeisanyoftheInternationalOrganizationforStandardization
(ISO)standardtwo-characterlanguageabbreviations,includinganoptional
languagemodifier.Forexample,addinglang=en-UKtellsthebrowserthatthelistis
inEnglish("en")asspokenandwrittenintheUnitedKingdom("UK").
Presumably,thebrowsermaymakelayoutortypographicdecisionsbasedupon
yourlanguagechoice.[Thelangattribute,3.6.1.2]
Thedirattributetellsthebrowserinwhichdirectiontodisplaythelist
contentsfromlefttoright(dir=ltr),likeEnglishandFrench,orfromrighttoleft
(dir=rtl),aswithHebrewandChinese.[Thedirattribute,3.6.1.1]
7.1.1.5.Theidandtitleattributes
Usetheidattributetospeciallylabeltheunorderedlist.Anacceptablevalueis
anyquote-enclosedstringthatuniquelyidentifiesthelistandcanlaterbeusedto
unambiguouslyreferencethelistinahyperlinktarget,forautomatedsearches,as
astylesheetselector,andforahostofotherapplications.[Theidattribute,
4.1.1.4]
Youalsocanusetheoptionaltitleattributeandquote-enclosedstringvalueto
identifythelist.Unlikeanidattribute,atitledoesnothavetobeunique.[The
titleattribute,4.1.1.5]
7.1.1.6.Theeventattributes
Themanyuser-relatedeventsthatmayhappeninandaroundalist,suchas
whenauserclicksordouble-clickswithinitsdisplayspace,arerecognizedby
currentbrowsers.Withtherespectiveonattributeandvalue,youmayreactto
thoseeventsbydisplayingauserdialogboxoractivatingsomemultimediaevent.
[JavaScriptEventHandlers,12.3.3]
7.2.OrderedLists
Useanorderedlistwhenthesequenceofthelistitemsisimportant.Alistof
instructionsisagoodexample,asaretablesofcontentsandlistsofdocument
footnotesorendnotes.
7.2.1.The<ol>Tag
Thetypicalbrowserformatsthecontentsofanorderedlistjustlikeanunordered
list,exceptthattheitemsarenumberedratherthanbulleted.Thenumbering
startsatoneandisincrementedbyoneforeachsuccessiveorderedlistelement
taggedwith<li>.[<li>,7.3]
<ol>
Function Definesanorderedlist
Attributes
class,compact,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,start,style,title,
type
Endtag </ol>;neveromitted
Contains list_content
Usedin block
HTML3.2introducedanumberoffeaturesthatprovideawidevarietyofordered
lists.Youcanchangethestartvalueofthelistandselectfromfivedifferent
numberingstyles.
HereisasampleXHTMLorderedlist:
<h3>PickledKumquats</h3>
Here'saneasywaytomakeadeliciousbatchofpickled'quats:
<ol>
<li>Rinse50poundsoffreshkumquats</li>
<li>Bringeightgallonswhitevinegartorollingboil</li>
<li>Addkumquatsgradually,keepingvinegarboiling</li>
<li>Boilforonehour,oruntilkumquatsaretender</li>
<li>Placeinsealedjarsandenjoy!</li>
</ol>
OperarenderstheexampleasshowninFigure7-2.
Figure7-2.Anorderedlist
7.2.1.1.Thestartattribute
Normally,browsersautomaticallynumberorderedlistitemsbeginningwiththe
Arabicnumeral1.Thestartattributeforthe<ol>tagletsyouchangethat
beginningvalue.Tostartnumberingalistat5,forexample:
<olstart=5>
<li>Thisisitemnumber5.</li>
<li>Thisisnumber6!</li>
<li>Andsoforth...</li>
</ol>
7.2.1.2.Thetypeattribute
Bydefault,browsersnumberorderedlistitemswithasequenceofArabic
numerals.Besidesbeingabletostartthesequenceatsomenumberotherthan1,
youcanusethetypeattributewiththe<ol>tagtochangethenumberingstyle
itself.TheattributemayhaveavalueofAfornumberingwithcapitalletters,afor
numberingwithlowercaseletters,IforcapitalRomannumerals,iforlowercase
Romannumerals,or1forcommonArabicnumerals.SeeTable7-1.
Table7-1.HTMLtypevaluesfornumberingorderedlists
Typevalue Generatedstyle Samplesequence
A Capitalletters A,B,C,D
a Lowercaseletters a,b,c,d
I CapitalRomannumerals I,II,III,IV
i LowercaseRomannumerals i,ii,iii,iv
1 Arabicnumerals 1,2,3,4
Thestartandtypeattributesworkintandem.Thestartattributesetsthestarting
valueoftheitemcounter(aninteger)atthebeginningofanorderedlist.Thetype
attributesetstheactualnumberingstyle.Forexample,thefollowingorderedlist
startsnumberingitemsat8,butbecausethestyleofnumberingissettoi,the
firstnumberisthelowercaseRomannumeral"viii."Subsequentitemsare
numberedwiththesamestyle,andeachvalueisincrementedby1,asshownin
thisHTMLexample,andrenderedasshowninFigure7-3:[*]
[*]Noticethatwedon'tincludethe</li>endtagintheHTMLexamplebutdoinalltheXHTMLones.Someendtagsare
optionalwithHTMLbutmustbeincludedinallXHTMLdocuments.
<olstart=8type="i">
<li>ThisistheRomannumber8.
<li>Thenumeralsincrementby1.
<li>Andsoforth...
</ol>
Figure7-3.Thestartandtypeattributesworkintandem
Thetypeandvalueofindividualitemsinalistcanbedifferentfromthoseofthe
listasawhole,describedinsection7.3.1laterinthischapter.Asmentioned
earlier,thestartandtypeattributesaredeprecatedinHTML4andXHTML.
Considerusingstylesheetsinstead.
7.2.1.3.Compactorderedlists
Likethe<ul>tag,the<ol>taghasanoptionalcompactattributethatisdeprecatedin
theHTML4andXHTMLstandards.Unlessyouabsolutelyneedtouseit,don't.
7.2.1.4.Theclass,dir,id,lang,event,style,andtitleattributes
Theseattributesareapplicablewithorderedlists,too;theireffectsareidenticalto
thoseforunorderedlists.[Theclassandstyleattributes,4.1.1.6][Thelangand
dirattributes,6.3.1.7][Theidandtitleattributes,7.1.1.5][Theeventattributes,
6.3.1.4]
7.3.The<li>Tag
Itshouldbequiteobvioustoyoubynowthatthe<li>tagdefinesaniteminalist.
It'stheuniversaltagforlistitemsinordered(<ol>)andunordered(<ul>)lists,as
wediscussedearlier,andfordirectories(<dir>)andmenus(<menu>),whichwe
discussindetaillaterinthischapter.
Becausetheendofalistelementcanalwaysbeinferredbythesurrounding
documentstructure,mostauthorsomittheending</li>tagsfortheirHTMLlist
elements.Thatmakessensebecauseitbecomeseasiertoadd,delete,andmove
elementsaroundwithinalist.However,XHTMLrequirestheendtag,soit'sbest
togetusedtoincludingitinyourdocuments.
Althoughuniversalinmeaning,therearesomedifferencesandrestrictionstothe
useofthe<li>tagforeachlisttype.Inunorderedandorderedlists,nearly
anythingcanfollowthe<li>tag,includingotherlistsandmultipleparagraphs.
Typically,ifithandlesindentationatall,thebrowsersuccessivelyindentsnested
listitems,andthecontentinthoseitemsisjustifiedtotheinnermostindented
margin.
<li>
Function Definesanitemwithinanordered,unordered,directory,ormenulist
Attributes
class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title,type,
value
Endtag </li>;oftenomittedinHTML
Contains flow
Usedin list_content
Directoryandmenulistsareanothermatter.Theyarelistsofshortitems,likea
singlewordorsimpletextblurbandnothingelse.Consequently,<li>itemswithin
<dir>and<menu>tagsmaynotcontainotherlistsorotherblockelements,including
paragraphs,preformattedblocks,orforms.
Cleandocuments,fullycompliantwiththeHTMLandXHTMLstandards,shouldnot
containanytextorotherdocumentiteminsidetheunordered,ordered,directory,
ormenuliststhatisnotcontainedwithinan<li>tag.Mostbrowserstolerate
violationstothisrule,butyoucan'tholdthebrowserresponsibleforcompliant
renderingofexceptionalcases,either.
7.3.1.ChangingtheStyleandSequenceofIndividualList
Items
Justasyoucanchangethebulletornumberingstyleforalloftheitemsinan
unorderedororderedlist,youcanchangethestyleforindividualitemswithin
thoselists.Withorderedlists,youalsocanchangethevalueoftheitemnumber.
Asyou'llsee,thecombinationsofchangingstyleandnumberingcanleadtoa
varietyofusefulliststructures,particularlywhenincludedwithnestedlists.Do
note,however,thatthestandardshavedeprecatedtheseattributesindeference
totheirCSScounterparts.
7.3.1.1.Thetypeattribute
Acceptablevaluesforthetypeattributeinthe<li>tagarethesameasthevalues
fortheappropriatelisttype:itemswithinunorderedlistsmayhavetheirtypeset
tocircle,square,ordisc,anditemsinanorderedlistmayhavetheirtypesettoany
ofthevaluesshownpreviouslyinTable7-1.
Becareful.Withearlierbrowsers,suchasNetscapeNavigatorandInternet
Explorerversions4andearlier,achangeinthebulletornumberingtypeinone
listitemsimilarlyaffectedsubsequentitemsinthelist.NotsoforHTML4-
compliantbrowsers,includingNetscapeversion6,InternetExplorerversions5
andlater,Firefox,andOpera!Thetypeattribute'seffectsareacuteandlimitedto
onlythecurrent<li>tag.Subsequentitemsreverttothedefaulttype;eachmust
containthespecifiedtype.
Thetypeattributechangesthedisplaystyleoftheindividuallistitem'sleading
number,andonlythatitem,butnotthevalueofthenumber,whichpersistently
incrementsbyone.Figure7-4showstheeffectthatchangingthetypeforan
individualiteminanorderedlisthasonsubsequentitems,asrenderedfromthe
followingXHTMLsource:
<ol>
<litype=A>Changingthenumberingtype</li>
<litype=I>UppercaseRomannumerals</li>
<litype=i>LowercaseRomannumerals</li>
<litype=1>Plainol'numbers</li>
<litype=a>Doesn'taltertheorder.</li>
<li><--But,althoughnumberingcontinuessequentially,</li>
<li>typesdon'tpersist.See?Ishould'vebeena"g"!</li>
</ol>
Figure7-4.Changingthenumberingstyleforeachiteminan
orderedlist
Youcanusethestylesheet-relatedstyleandclassattributestoaffectindividual
typechangesinorderedandunorderedliststhatmayormaynotaffect
subsequentlistitems.SeeChapter8fordetails(particularlysection8.4.8.5).
7.3.1.2.Thevalueattribute
Thevalueattributechangesthenumbersofaspecificlistitemandallofthelist
itemsthatfollowit.Becausetheorderedlististheonlytypewithsequentially
numbereditems,thevalueattributeisvalidonlywhenusedwithinan<li>tag
insideanorderedlist.
Tochangethecurrentandsubsequentnumbersattachedtoeachiteminan
orderedlist,simplysetthevalueattributetoaninteger.Thefollowingsourceuses
thevalueattributetojumpthenumberingonitemsinanXHTMLorderedlist,and
getsrenderedbymodernbrowsersasshowninFigure7-5:
<ol>
<li>Itemnumber1</li>
<li>Andthesecond</li>
<livalue=9>Jumptonumber9</li>
<li>Andcontinuewith10...</li>
</ol>
Figure7-5.Thevalueattributeletsyouchangeindividualitem
numbersinanorderedlist
7.3.1.3.Thestyleandclassattributes
Thestyleattributeforthe<li>tagcreatesaninlinestylefortheelements
enclosedbythetag,overridinganyotherstyleruleineffect.Theclassattribute
letsyouformatthecontentaccordingtoapredefinedclassofthe<li>tag;its
valueisthenameofthatclass.[InlineStyles:ThestyleAttribute,8.1.1][Style
Classes,8.3]
7.3.1.4.Theclass,dir,id,lang,event,style,andtitleattributes
Youcanapplytheseattributestoindividuallistitems;theyhavesimilareffects
fororderedandunorderedlists.[Theclassandstyleattributes,4.1.1.6][Thelang
anddirattributes,6.3.1.7][Theidandtitleattributes,7.1.1.5][Theevent
attributes,6.3.1.4]
7.4.NestingLists
Exceptwhenplacedinsidedirectoriesormenus,listsnestedinsideotherlistsare
fine.Youcanembedmenuanddirectorylistswithinotherlists.Indentsforeach
nestedlistarecumulative,sodonotnestliststoodeeply;thelistcontentscould
quicklyturnintoathinribbonoftextflushagainsttherightedgeofthebrowser
documentwindow.
7.4.1.NestedUnorderedLists
Theitemsineachnestedunorderedlistmaybeprecededbyadifferentbullet
characteratthediscretionofthebrowser.Forexample,InternetExplorerdisplays
analternatingseriesofhollow,solidcircular,andsquarebulletsforthevarious
nestsinthefollowingsourcefragment,asshowninFigure7-6:
<ul>
<li>MorningKumquatDelicacies
<ul>
<li>HotDishes
<ul>
<li>Kumquatomelet</li>
<li>Kumquatwaffles
<ul>
<li>Countrystyle</li>
<li>Belgian</li>
</ul>
</li>
</ul>
</li>
<li>ColdDishes
<ul>
<li>Kumquatsandcornflakes</li>
<li>PickledKumquats</li>
<li>DicedKumquats</li>
</ul>
</li>
</ul>
</li>
</ul>
Figure7-6.Bulletschangefornestedunorderedlistitems
Youcanchangethebulletstyleforeachunorderedlistandevenforindividuallist
items,buttherepertoireofbulletsislimited,typicallyasimplesoliddiscforlevel-
oneitems,anopencircleforleveltwo,andasolidsquareforsubsequentlevels.
7.4.2.NestedOrderedLists
Bydefault,browsersnumbertheitemsinorderedlistsbeginningwiththeArabic
numeral1,nestedornot.Itwouldbegreatifthestandardsnumberednested
orderedlistsinsomerational,consecutivemanner;e.g.,theitemsinthesecond
nestofthethirdmainorderedlistmightbesuccessivelynumbered"3.2.1,"
"3.2.2,""3.2.3,"andsoon.
Withthetypeandvalueattributes,however,youdohavealotmorelatitudeinhow
youcreatenestedorderedlists.Anexcellentexampleisthetraditionalstylefor
outlining,whichusesthemanydifferentwaysofnumberingitemsofferedbythe
typeattribute(seeFigure7-7):
<oltype="A">
<li>AHistoryofKumquats
<oltype="1">
<li>EarlyHistory
<oltype="a">
<li>TheFossilRecord</li>
<li>Kumquats:TheMissingLink?</li>
</ol>
</li>
<li>MayanUseofKumquats</li>
<li>KumquatsintheNewWorld</li>
</ol>
</li>
<li>FutureUseofKumquats</li>
</ol>
Figure7-7.Thetypeattributeletsyoudotraditionaloutlining
withorderedlists
7.5.DefinitionLists
HTMLandXHTMLalsosupportaliststyleentirelydifferentfromtheorderedand
unorderedlistswe'vediscussedsofar:definitionlists.Liketheentriesyoufindin
adictionaryorencyclopedia,completewithtext,pictures,andothermultimedia
elements,thedefinitionlististheidealwaytopresentaglossary,listofterms,or
othername/valuelist.
7.5.1.The<dl>Tag
Thedefinitionlistisenclosedbythe<dl>and</dl>tags.Withinthetags,eachitem
inadefinitionlistiscomposedoftwoparts:aterm,followedbyitsdefinitionor
explanation.Insteadof<li>,eachitemnameina<dl>listismarkedwiththe<dt>
tag,followedbytheitem'sdefinitionorexplanationmarkedbythe<dd>tag.
<dl>
Function Definesadefinitionlist
Attributes class,compact,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title,type
Endtag </dl>;neveromitted
Contains dl_content
Usedin block
Unlessyouchangethedisplayattributeswithstylesheetrules,browserstypically
rendertheitemortermnameattheleftmarginandrenderthedefinitionor
explanationbelowitandindented.Ifthedefinitiontermsareveryshort(typically
lessthanthreecharacters),thebrowsermaychoosetoplacethefirstportionof
thedefinitiononthesamelineastheterm.SeehowthefollowingsourceXHTML
definitionlistgetsdisplayedinFigure7-8:
Figure7-8.Adefinitionlistexample
<h3>CommonKumquatParasites</h3>
<dl>
<dt>Leafmites</dt>
<dd>TheleafmitewillravagetheKumquattree,strippingit
ofanyandallvegetation.</dd>
<dt>Trunkdropsy</dt>
<dd>Thismicroscopiclarvaeofthecommonopossum
chiggerwillconsumethestructuralelementsofthe
treetrunk,causingittocollapseinward.</dd>
</dl>
Aswithotherlisttypes,youcanaddmorespacebetweenthedefinitionlistitems
byinsertingparagraph<p>tagsattheendoftheircontentorbydefininga
spaciousstylefortherespectivetags.
7.5.1.1.Morecompactdefinitionlists
The<dl>tagsupportsthecompactattribute,advisingthebrowsertomakethelist
presentationassmallaspossible.Fewbrowsers,ifany,honorthisattribute,andit
hasbeendeprecatedinHTML4andXHTML.
7.5.1.2.Theclass,dir,id,lang,style,title,andeventattributes
Themanyotherattributesforthe<dl>tagshouldbequitefamiliarbynow.The
styleandclassattributesletyoucontrolthedisplaystyle,theidandtitletag
attributesletyouuniquelylabelitscontents,thelanganddirattributesletyou
specifyitsnativelanguageandthedirectioninwhichthetextwillberendered,
andthemanyon-eventattributesletyoureacttouser-initiatedmouseand
keyboardactionsonthecontents.Notallareimplementedbythecurrently
popularbrowsersforthistagorformanyothers.[Thedirattribute,3.6.1.1][The
langattribute,3.6.1.2][Theidattribute,4.1.1.4][Thetitleattribute,4.1.1.5]
[InlineStyles:ThestyleAttribute,8.1.1][StyleClasses,8.3][JavaScriptEvent
Handlers,12.3.3]
7.5.2.The<dt>Tag
The<dt>tagdefinesthetermcomponentofadefinitionlist.Itisvalidonlywhen
usedwithinadefinition(<dl>)listprecedingthetermoritem,beforethe<dd>tag
andtheterm'sdefinitionorexplanation.
Traditionally,thedefinitiontermthatfollowsthe<dt>tagisshortandsweetoneor
afewwords.Technically,itcanbeanylength.Ifthedefinitiontermislong,the
browsermayexercisetheoptionofextendingtheitembeyondthedisplaywindow
orwrappingitontothenextline,wherethedefinitionbegins.
Becausetheendofthe<dt>tagimmediatelyprecedesthestartofthematching
<dd>tag,itisunambiguous,sothe</dt>endtagisnotrequiredinHTML
documents.
<dt>
Function Definesadefinitionlistterm
Attributes class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </dt>;maybeomittedinHTML
Contains text
Usedin dl_content
However,theXHTMLstandardinsiststhatitbepresent,sogetusedtoincludingit
inyourdocuments.
7.5.2.1.Formattingtextwith<dt>
Inpractice,browsersareeithertoolenientortoodumbtoenforcetherules,so
sometrickyHTMLauthorsmisusethe<dt>tagtoshifttheleftmarginrightand
left,respectively,forfancytextdisplays.(Remember,tabcharactersandleading
spacesusuallydon'tworkwithregulartext.)Wedon'tcondoneviolatingthe
HTML,andcertainlynottheXHTMLstandard,andwecautionyouonceagain
abouttricked-updocuments.Usestylesheetsinstead.
7.5.2.2.Theclass,dir,id,lang,style,title,andeventattributes
The<dt>tagsupportsthestandardHTML4/XHTMLtagattributes.Thestyleand
classattributesletyoucontrolthedisplaystyle,theidandtitletagattributeslet
youuniquelylabelitscontents,thelanganddirattributesletyouspecifyits
nativelanguageandthedirectioninwhichthetextwillberendered,andthe
manyon-eventattributesletyoureacttouser-initiatedmouseandkeyboard
actionsonthecontents.Notallareimplementedbythecurrentlypopular
browsersforthistagorformanyothers.[Thedirattribute,3.6.1.1][Thelang
attribute,3.6.1.2][Theidattribute,4.1.1.4][Thetitleattribute,4.1.1.5][Inline
Styles:ThestyleAttribute,8.1.1][StyleClasses,8.3][JavaScriptEventHandlers,
12.3.3]
7.5.3.The<dd>Tag
The<dd>tagmarksthestartofthedefinitionportionofaniteminadefinitionlist.
AccordingtotheHTMLandXHTMLstandards,<dd>belongsonlyinsideadefinition
(<dl>)list,immediatelyfollowingthe<dt>tagandtermandprecedingthe
definitionorexplanation.
<dd>
Function Definesadefinitionlistterm
Attributes class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </dd>;maybeomittedinHTML
Contains flow
Usedin dl_content
Thecontentthatfollowsthe<dd>tagmaybeanyHTMLorXHTMLconstruct,
includingotherlists,blocktext,andmultimediaelements.Althoughtreatingit
otherwiseidenticallyasconventionalcontent,browserstypicallyindentdefinition
list(<dd>)definitions.Becausethestartofanothertermanddefinition(<dt>)orthe
requiredendtagofthedefinition(</dl>)unambiguouslyterminatesthepreceding
definition,the</dd>endtagisnotneeded,anditsabsencemakesyoursourcetext
morereadable.However,onceagain,XHTMLinsiststhattheendtagappearin
yourdocuments,soyoumayaswellgetusedtoadding</dd>toyourdocuments.
7.5.3.1.Theclass,dir,id,lang,style,title,andeventattributes
The<dt>tagsupportsthestandardtagattributes.Thestyleandclassattributeslet
youcontrolthedisplaystyle,theidandtitletagattributesletyouuniquelylabel
itscontents,thelanganddirattributesletyouspecifyitsnativelanguageandthe
directioninwhichthetextwillberendered,andthemanyon-eventattributeslet
youreacttouser-initiatedmouseandkeyboardactionsonthecontents.Notall
areimplementedbythecurrentlypopularbrowsersforthistagorformany
others.[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2][Theidattribute,
4.1.1.4][Thetitleattribute,4.1.1.5][InlineStyles:ThestyleAttribute,8.1.1]
[StyleClasses,8.3][JavaScriptEventHandlers,12.3.3]
7.6.AppropriateListUsage
Ingeneral,useunorderedlistsfor:
Linkcollections
Short,nonsequencedgroupsoftext
Emphasizingthehighpointsofapresentation
Ingeneral,useorderedlistsfor:
Tablesofcontents
Instructionsequences
Setsofsequentialsectionsoftext
Assigningnumberstoshortphrasesthatcanbereferencedelsewhere
Ingeneral,usedefinitionlistsfor:
Glossaries
Custombullets(maketheitemafterthe<dt>taganicon-sizebulletimage)
Anylistofname/valuepairs
7.7.DirectoryLists
Thedirectorylistisaspecializedformofunorderedlist.Ithasbeendeprecatedin
theHTML4andXHTMLstandards.Wedon'trecommendthatyouuseitatall.
[<ul>,7.1.1]
7.7.1.The<dir>Tag(Deprecated)
ThedesignersofHTMLoriginallydedicatedthe<dir>tagfordisplayinglistsoffiles.
Assuch,thebrowser,ifittreats<dir>and<ul>differentlyatall(mostdon't),
expectsthevariouslistelementstobequiteshort,possiblynolongerthan20or
socharacters.Somebrowsersdisplaytheelementsinamulticolumnformatand
maynotusealeadingbullet.
<dir>
Function Definesadirectorylist
Attributes class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </dir>;neveromitted
Contains list_content
Usedin block
Aswithanunorderedlist,youdefinedirectorylistitemswiththe<li>tag.When
usedwithinadirectorylist,however,the<li>tagmaynotcontainanyblock
element,includingparagraphs,otherlists,preformattedtext,orforms.
Thefollowingexampleputsthedirectorytagtoitstraditionaltaskofpresentinga
listoffilenames:
Thedistributiontapehasthefollowingfilesonit:
<dir>
<li><code>README</code></li>
<li><code>Makefile</code></li>
<li><code>main.c</code></li>
<li><code>config.h</code></li>
<li><code>util.c</code></li>
</dir>
Noticethatweusedthe<code>tagtoensurethatthefilenameswouldberendered
inanappropriatemanner(seeFigure7-9).
Figure7-9.Anexample<dir>list
7.7.1.1.The<dir>attributes
Theattributesforthe<dir>tagareidenticaltothosefor<ul>,withthesame
effects.
7.8.MenuLists
Themenulistisyetanotherspecializedformoftheunorderedlist.Like<dir>,itis
deprecatedintheHTML4andXHTMLstandards,sowedon'trecommendusingit.
[<ul>,7.1.1]
7.8.1.The<menu>Tag(Deprecated)
The<menu>tagdisplaysalistofshortchoicestothereader,suchasamenuoflinks
tootherdocuments.Thebrowsermayuseaspecial(typicallymorecompact)
representationofitemsinamenulistcomparedwiththegeneralunorderedlist,
orevenusesomesortofgraphicalpull-downmenutoimplementthemenulist.If
thelistitemsareshortenough,thebrowsermayevendisplaythemina
multicolumnformatandmaynotprecedeeachlistitemwithabullet.
Likeanunorderedlist,definethemenulistitemswiththe<li>tag.Whenused
withinamenulist,however,the<li>tagmaynotcontainanyblockelements,
includingparagraphs,otherlists,preformattedtext,orforms.
Comparethefollowingsourcetextanddisplay(Figure7-10)withthedirectory
(Figure7-9)andunordered(Figure7-1)listdisplayspresentedearlierinthe
chapter:
Somepopularkumquatrecipesinclude:
<menu>
<li>PickledKumquats</li>
<li>'Quatsand'Kraut(aholidayfavorite!)</li>
<li>'Quatshakes</li>
</menu>
Therearemanymoretopleaseeverypalate!
Figure7-10.Sample<menu>list
<menu>
Function Definesamenulist
Attributes class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </menu>;neveromitted
Contains list_content
Usedin block
Chapter8.CascadingStyleSheets
Stylesheetsarethewaypublishingprofessionalsmanagetheoverall"look"of
theirpublicationsbackgrounds,fonts,colors,andsoonfromasinglepagetohuge
collectionsofdocuments.Mostdesktoppublishingsoftwaresupportsstylesheets,
asdopopularwordprocessors,sousingstylesheetsforHTMLdocumentsis
obvious.
Forthemostpart,HTMLfocusesoncontentoverstyle.Authorsareencouragedto
worryaboutprovidinghigh-qualityinformationandleaveittothebrowserto
worryaboutpresentation.Westronglyurgeyoutoadoptthisphilosophyinyour
documentsdon'tmistakestyleforsubstance.
However,presentationisforthebenefitofthereader,andeventheoriginal
designersofHTMLunderstandtheinterplaybetweenstyleandreadabilityfor
example,throughthephysicalstyleandheadertags.Stylesheetsextendthat
presentationwithseveraladditionaleffects,includingcolors,awiderselectionof
fonts,andevensoundssothatuserscanbetterdistinguishelementsofyour
document.Butmostimportantly,stylesheetsletyoucontrolthepresentation
attributesforallthetagsinadocumentforasingledocumentoracollectionof
manydocumentsfromasinglemaster.
Inearly1996,theWorldWideWebConsortium(W3C)puttogetheradraft
proposaldefiningCascadingStyleSheets(CSS)forHTML.Thisdraftproposal
quicklymaturedintoarecommendedstandard.Inmid-1998,theW3Cextended
theoriginalspecificationtocreateCSS2,whichincludespresentationstandards
foravarietyofmediabesidesthefamiliaronscreenbrowser,alongwithseveral
otherenhancements.
TheW3Ccontinuestoworkonaminorversionupgrade(version2.1)andadraft
ofCSS3,butthesearenotimminent.Indeed,nocurrentbrowserorwebagent
fullycomplieswiththeCSS2standard.However,becausewerealizethateventual
compliancewiththeW3Cstandardislikely,we'llcoverallthecomponentsofthe
CSS2standardinthischapter.Asalways,we'lldenoteclearlywhatisreal,whatis
proposed,andwhatisactuallysupported.[*]
[*]Inthefallof2000,workbeganonCSS3.AsCSS3isstillunderconstructionandbrowsershavenotyetevenbecome
fullycompliantwithCSS2,wefocusonCSS2throughoutthischapter.
8.1.TheElementsofStyles
Atthesimplestlevel,astyleisnothingmorethanarulethebrowserfollowsto
renderaparticularHTMLorXHTMLtag'scontents.[*]Eachtaghasanumberof
stylepropertiesassociatedwithit,whosevaluesdefinehowthattagisrendered
bythebrowser.Aruledefinesaspecificvalueforoneormorepropertiesofatag.
Forexample,mosttagscanhaveacolorproperty,thevalueofwhichdefinesthe
colorinwhichthemodernGUIbrowsershoulddisplaythecontentsofthetag.
Otherpropertiesincludefonts,linespacing,margins,borders,soundvolume,and
voice,whichwedescribeindetaillaterinthischapter.
[*]Weexplicitlyavoidedthetermdisplayherebecauseitconnotesvisualpresentation,whereastheCSS2standard
workshardtosuggestmanydifferentwaysofpresentingthetaggedcontentsofadocument.
Therearethreewaystoattachastyletoatag:inline,onthedocumentlevel,or
throughtheuseofanexternalstylesheet.Youmayuseoneormorestylesheets
foryourdocuments.Thebrowsereithermergesthestyledefinitionsfromeach
styleorredefinesthestylecharacteristicforatag'scontents.Stylesfromthese
varioussourcesareappliedtoyourdocument,combininganddefiningstyle
propertiesthatcascadefromexternalstylesheetsthroughlocaldocumentstyles,
andendingwithinlinestyles.Thiscascadeofpropertiesandstylerulesgivesrise
tothestandard'sname:CascadingStyleSheets.
Wecoverthesyntacticbasicsofthethreestylesheettechniqueshere.Wedelve
moredeeplyintotheappropriateuseofinline,document-level,andexternal
stylesheetsattheendofthischapter.
8.1.1.InlineStyles:ThestyleAttribute
Theinlinestyleisthesimplestwaytoattachastyletoatagjustincludeastyle
attributewiththetagalongwithalistofpropertiesandtheirvalues.Thebrowser
usesthosestylepropertiesandvaluestorenderthecontentsofthattag.
Forinstance,thefollowingstyletellsthebrowsertodisplaythelevel-1header
text,"I'msobluuuuoooo!",notonlyinthe<h1>tagstyle,butalsocoloredblueand
italicized:
<h1style="color:blue;font-style:italic">I'msobluuuuoooo!</h1>
Inlinestylescanbedifficulttomaintain,becausetheyaddmorecontentstotheir
tags'definitions,makingthemhardertoread.Also,becausetheyhaveonlya
localeffect,theymustbesprinkledthroughoutyourdocument.Usetheinline
styleattributesparinglyandonlyinthoserarecircumstanceswhenyoucannot
achievethesameeffectsotherwise.
8.1.2.Document-LevelStylesheets
Therealpowerofstylesheetsbecomesmoreevidentwhenyouplacealistof
presentationrulesatthebeginningofyourHTMLorXHTMLdocument.Placed
withinthe<head>andenclosedwithintheirown<style>and</style>tags,
document-levelstylesheetsaffectallthesametagswithinthatdocument,except
fortagsthatcontainoverridinginlinestyleattributes.[*]
[*]XHTML-baseddocument-levelstylesheetsarespeciallyenclosedinCDATAsectionsofyourdocuments.Seesection
16.3.7inChapter16fordetails.
<style>
Function Definesadocument-levelstylesheet
Attributes dir,lang,media,title,type
Endtag </style>;rarelyomittedinHTML
Contains styles
Usedin head_content
Everythingbetweenthe<style>and</style>tagsisconsideredpartofthestyle
rulesthatthebrowseristoapplywhenrenderingthedocument.Actually,the
contentsofthe<style>tagarenotHTMLorXHTMLandarenotboundbythe
normalrulesformarkupcontent.The<style>tag,ineffect,letsyouinsertforeign
contentintoyourdocumentthatthebrowserusestoformatyourtags.
Forexample,astyles-consciousbrowserdisplaysthecontentsofall<h1>tagsas
blue,italictextinanHTMLdocumentthathasthefollowingdocument-level
stylesheetdefinitioninitshead:
<head>
<title>AllTrueBlue</title>
<styletype="text/css">
<!--
/*makealllevel-1headersblueinitalics*/
h1{color:blue;font-style:italic}
-->
</style>
</head>
<body>
<h1>I'msobluuuuoooo!</h1>
...
<h1>Iamba-loooooo,tooooo!</h1>
8.1.2.1.Thetypeattribute
OthertypesofstylesheetsareavailableforHTML/XHTMLbesidesCSS.Likethe
JavaScriptstylesheetswedescribeinChapter12,theyarenotwellsupported,if
atall,bythepopularbrowsers,sowedon'tspendalotoftimeontheminthis
book.Nonetheless,thebrowserneedsawaytodistinguishwhichstylesheetyou
useinyourdocument.Usethetypeattributewithinthe<style>tagforthat.All
cascadingstylesheetsareofthetypetext/css;JavaScriptstylesheetsusethetype
text/javascript.Youmayomitthetypeattributeandhopethebrowserfiguresout
thekindsofstylesyouareusing,butwesuggestyoualwaysincludethetype
attribute,sothereisnoopportunityforconfusion.[JavaScriptStylesheets
(Antiquated),12.4]
8.1.2.2.Themediaattribute
HTMLandXHTMLdocumentscanwindupinthestrangestplacesthesedays,such
asoncellularphones.Tohelpthebrowserfigureoutthebestwaytorenderyour
documents,includethemediaattributewithinthe<style>tag.Thevalueofthis
attributeisthedocument'sintendedmedium,althoughitdoesn'tpreclude
renderingbyothermedia.Thedefaultvalueisscreen(computerdisplay).Other
valuesincludetty(textonly),tv(television),projection(theaters),handheld(PDAs
andcellphones),print(inkonpaper),braille(tactiledevices),embossed(Braille
printers),aural(audio;speechsynthesis,forinstance),andall(manydifferent
typesofmedia).
Ifyouwanttoexplicitlylistseveraltypesofmedia,insteadofspecifyingall,usea
quote-enclosed,comma-separatedlistofmediatypesasthevalueofthemedia
attribute.Forexample:
<styletype="text/css"media="screen,print">
tellsthebrowserthatyourdocumentcontainsCSSbothforprintingandfor
computerdisplays.
Becarefulspecifyingmedia,becausethebrowsercannotapplythestylesyou
defineunlessthedocumentisbeingrenderedononeofyourspecifiedmedia.
Thus,thebrowserwouldnotapplyourexamplesetofstylesdesignedfor
media="screen,print"iftheuseris,forinstance,connectedtotheWebwitha
handheldcomputer.
Howdoyoucreatedifferentstyledefinitionsfordifferentmediawithoutcreating
multiplecopiesofyourdocument?TheCSS2standardletsyoudefinemedia-
specificstylesheetsthroughitsextensiontothe@importat-ruleandthroughthe
@mediaat-rule,whichwedescribeinsection8.1.5laterinthischapter.
8.1.2.3.Thedir,lang,andtitleattributes
AswithanyHTML/XHTMLelement,youcanassociateadescriptivetitlewiththe
<!--<DEFANGED_STYLE>tagandspecifythelanguageandtext-renderingdirectionwith
thetitle,lang,anddirattributes.[Thedirattribute,3.6.1.1][Thelangattribute,
3.6.1.2][Theidattribute,4.1.1.4]
8.1.3.Style-FreeBrowsers
Certainlyyounoticedthat,intheprecedingdocument-levelstylesheetexample,
weenclosedthecontentsofthe<style>taginsideanHTMLcomment(<!--)tag.
Older,style-freebrowsersignorethe<style>tag,butthenblithelygoontodisplay
itscontents.CurrentbrowsersexpectstylerulestoappearwithinanHTML
commentandprocessthemaccordingly,whereasolderbrowsersappropriately
ignoretheunrecognized<style>tagandgoontotreatthecommenttagandits
interveningtextnormally.Thatworks.
Theorderofthetagsisveryimportant.Here'stheapproach,whichyoumayhave
noticedinourdocument-levelstyleexample:
<style>
<!--
h1{color:blue;font-style:italic}
-->
</style>
Usea<style>tag,followedbyanHTMLcomment,thenfollowedbythedocument-
levelstylerule(s).Finally,inorder,closethecommentandthe</style>tag.
XHTMLdocumentsrequireaslightlydifferentapproach.Inthosedocuments,we
enclosedocument-levelstylesinaCDATAsectionratherthananHTMLcomment
tag.Seesection16.3.7fordetails.
Also,astheydoforotherattributestheydon'trecognize,thestyle-freebrowsers
ignoreinlinestyleattributesandtheirvalues,sotherearenodetrimentaleffects
inthatregardforyourdocumentdisplays.
8.1.4.ExternalStylesheets
Youcanalsoplacestyledefinitionsintoaseparatedocument(atextfilewiththe
MultipurposeInternetMailExtension,orMIME,typeoftext/css)andimportthis
externalstylesheetintoyourdocument.Usethesamestylesheetforother
documentsinyourcollection,too,evenentirecollectionsofdocuments,to
achieveaconsistentlookandfeel.Becauseanexternalstylesheetisaseparate
fileandthebrowserloadsitoverthenetwork,youcanstoreitanywhere,reuseit
often,andevenuseothers'stylesheets.
Forexample,supposewecreateafilenamedgen_styles.csscontainingthe
followingstylerule:
h1{color:blue;font-style:italic}
Foreachandeveryoneofthedocumentsinourcollections,wecantellthe
browsertoreadthecontentsofthegen_styles.cssfile,whichinturncolorsallthe
<h1>tagcontentsblueandrendersthetextinitalic.Ofcourse,thatistrueonlyif
theuser'smachineiscapableofthesestyletricks,she'susingastyles-conscious
browser,andthestyleisn'toverriddenbyadocument-levelorinlinestyle
definition.
Youcanloadexternalstylesheetsintoyourdocumentintwodifferentways:by
linkingthemorbyimportingthem.
8.1.4.1.Linkedexternalstylesheets
Onewaytoloadanexternalstylesheetistousethe<link>tagwithinthe<head>of
yourdocument:
<head>
<title>Stylelinked</title>
<linkrel=stylesheettype="text/css"
href="http://www.kumquats.com/styles/gen_styles.css"
title="Theblues">
</head>
<body>
<h1>I'msobluuuuoooo!</h1>
...
<h1>Iamba-loooooo,tooooo!</h1>
Recallthatthe<link>tagcreatesarelationshipbetweenthecurrentdocumentand
someotherdocumentontheWeb.Inthisexample,wetellthebrowserthatthe
documentnamedinthehrefattributeisacascadingstylesheet(css),asindicated
bythetypeattribute.Referencinganexternalstylesheetin<link>requiresthat
youincludethehrefandtypeattributes.Wealsotellthebrowserexplicitly,albeit
optionally,thatthefile'srelationshiptoourdocumentisthatitisastylesheet,and
weprovideatitlemakingitavailableforlaterreferencebythebrowser.[The
<link>HeaderElement,6.7.2]
Thestylesheet-specifying<link>taganditsrequiredhrefandtypeattributesmust
appearinthe<head>ofadocument.TheURLofthestylesheetmaybeabsoluteor
relativetothedocument'sbaseURL.
8.1.4.2.Importedexternalstylesheets
Thesecondtechniqueforloadinganexternalstylesheetimportsthefilewitha
specialcommand(a.k.a.at-rule)withinthe<style>tag:
<head>
<title>Importedstylesheet</title>
<styletype="text/css">
<!--
@import
url(http://www.kumquats.com/styles/gen_styles.css);
@import"http://www.kumquats.com/styles/spec_styles.css";
body{background:url(backgrounds/marble.gif)}
-->
</style>
</head>
The@importat-ruleexpectsasingleURLforthenetworkpathtotheexternal
stylesheet.Asshowninthisexample,theURLmaybeeitherastringenclosedin
doublequotesandendingwithasemicolonorthecontentsoftheurlkeyword,
enclosedinparentheses,withatrailingsemicolon.TheURLmaybeabsoluteor
relativetothedocument'sbaseURL.
The@importat-rulemustappearbeforeanyconventionalstylerules,eitherinthe
<style>tagorinanexternalstylesheet.Otherwise,thestandardinsiststhatthe
browserignoretheerrant@import.Byfirstimportingallthevariousstylesheets,
thenprocessingdocument-levelstylerules,theCSS2standardcascades:thelast
onestandingwins.[URLpropertyvalues,8.4.1.4]
The@importat-rulecanappearinadocument-levelstyledefinitionorevenin
anotherexternalstylesheet,lettingyoucreatenestedstylesheets.
8.1.5.Media-SpecificStyles
Besidesthemediaattributeforthe<style>tag,theCSS2standardhastwoother
featuresthatletyouapplydifferentstylesheets,dependingontheagentordevice
thatrendersyourdocument.Thisway,forinstance,youcanhaveonestyleor
wholestylesheettakeeffectwhenyourdocumentgetsrenderedonacomputer
screenandanothersetofstylesforwhenthecontentsgetpunchedoutona
Brailleprinter.AndwhataboutthosecellphonesthataccesstheWeb?
Likethemediaattributeforthe<style>tagthataffectstheentirestylesheet,you
canspecifywhethertheuser'sdocumentprocessorloadsandusesanimported
stylesheet.Dothatbyaddingamedia-typekeywordoraseriesofcomma-
separatedkeywordstotheendofthe@importat-rule.Forinstance,thefollowing
exampleletstheuseragentdecidewhethertoimportandusethespeech-
synthesisstylesheetoracommonPCdisplayandprintstylesheet,ifitisableto
renderthespecifiedmediatypes:
@importurl(http://www.kumquats.com/styles/visual_styles.css)screen,print;
@import"http://www.kumquats.com/styles/speech_styles.css"aural;
The@importCSS2mediatypesarethesameasthoseforthe<style>tag'smedia
attribute,includingall,aural,braille,embossed,handheld,print,projection,screen,
tty,andtv.
AnotherCSS2waytoselectmediaisthroughtheexplicit@mediaat-rule,whichlets
youincludemedia-specificruleswithinthesamestylesheet,eitheratthe
documentlevelorinanexternalstylesheet.Atthedocumentlevel,aswith
@import,the@mediaat-rulemustappearwithinthecontentsofthe<style>tag.The
at-rulesmaynotappearwithinanotherrule.Unlike@import,@mediamayappear
subsequenttootherstylerules,anditsstyle-rulecontentsoverridepreviousrules
accordingtothecascadingstandard.
Thecontentsof@mediaincludeoneormorecomma-separatedmedia-type
keywordsfollowedbyacurlybrace({})-enclosedsetofstylerules.Forexample:
body{background:white}
@mediatv,projection{
body{background:yellow}
}
Theyellowattributetothe@mediaat-rulecausesthebody'sbackgroundcolorto
displayyellow,ratherthanthedefaultwhitesetinthegeneralstylerule,when
thedocumentisrenderedonatelevisionorprojectionscreen(asspecifiedbythe
tvandprojectionattributes).
8.1.6.LinkedVersusImportedStylesheets
Atfirstglance,itmayappearthatlinkedandimportedstylesheetsareequivalent,
usingdifferentsyntaxforthesamefunctionality.Thisistrueifyouusejustone
<link>taginyourdocument.However,specialCSS2-standardrulescomeintoplay
ifyouincludetwoormore<link>tagswithinasingledocument.
Withone<link>tag,thebrowsershouldloadthestylesinthereferenced
stylesheetandformatthedocumentaccordingly,withanydocument-leveland
inlinestylesoverridingtheexternaldefinitions.Withtwoormore<link>tags,the
browsershouldpresenttheuserwithalistofallthelinkedstylesheets.Theuser
thenselectsoneofthelinkedsheets,whichthebrowserloadsandusestoformat
thedocument;theotherlinkedstylesheetsgetignored.
Ontheotherhand,thestyles-consciousbrowsermerges,asopposedto
separating,multiple@importedstylesheetstoformasinglesetofstylerulesfor
yourdocument.Thelastimportedstylesheettakesprecedenceifthereare
duplicatedefinitionsamongthestylesheets.Hence,iftheexternalgen_styles.css
stylesheetspecificationfirsttellsthebrowsertomake<h1>contentsblueand
italic,andthenalaterspec_styles.csstellsthebrowsertomake<h1>textred,the
<h1>tagcontentsappearredanditalic.Andifwelaterdefineanothercolorsay,
yellowfor<h1>tagsinadocument-levelstyledefinition,the<h1>tagsareallyellow
anditalic.Cascadingeffects.See?
Inpractice,thepopularbrowserstreatlinkedstylesheetsjustlikeimportedones
bycascadingtheireffects.Thebrowsersdonotcurrentlyletyouchoosefrom
amonglinkedchoices.Importedstylesoverridelinkedexternalstyles,justasthe
document-levelandinlinestylesoverrideexternalstyledefinitions.Tobringthis
alltogether,considerthisexample:
<html>
<head>
<linkrel=stylesheethref=sheet1.csstype=text/css>
<linkrel=stylesheethref=sheet2.csstype=text/css>
<style>
<!--
@importurl(sheet3.css);
@importurl(sheet4.css);
-->
</style>
</head>
UsingtheCSS2model,thebrowsershouldprompttheusertochoosesheet1.css
orsheet2.css.Itshouldthenloadtheselectedsheet,followedbysheet3.cssand
sheet4.css.Duplicatestylesdefinedinsheet3.cssorsheet4.css,andinanyinline
styles,overridestylesdefinedintheselectedsheet.Inpractice,thepopular
browserscascadethestylesheetrulesasdefinedintheexampleordersheet1
throughsheet4.
8.1.7.LimitationsofCurrentBrowsers
Allthepopularbrowserssupportthe<link>tagtoapplyanexternalstylesheettoa
document.Nonesupportsmultiple,user-selectable<link>stylesheets,asproposed
bytheCSS2standard.Instead,theytreatthe<link>stylesheetsastheydo@import
ordocument-levelstyles,bycascadingtherules.
Netscapeversion6,butnotearlierversions,InternetExplorerversions5and
later,aswellasallversionsofOperaandFirefox,honorthe@importandthe@media
at-rules,forbothdocument-levelandexternalsheets,allowingsheetstobe
nested.
Achievingmedia-specificstylesthroughexternalstylesheetswithearlierNetscape
browsersishopeless.Assume,therefore,thatmostpeoplewhohaveNetscape
version4willrenderyourdocumentsonacommonPCscreen,somakescreenthe
default.Thenembedallothermedia-specificstyles,suchasthoseforprintor
Braille,within@mediaat-rulessothatCSS-compliantagentsproperlyselectstyles
basedontherenderingmedium.
Anotheralternativeistocreatemedia-specific<style>tagswithineachdocument.
Run,donotwalk,awayfromthatidea.
8.1.8.StyleComments
Commentsarewelcomeinsidethe<style>tagandinexternalstylesheets,but
treatthemdifferentlythanHTMLcomments:stylesheetsaren'tHTML.Rather,
enclosestylecommentsbetween/*and*/markers,aswedidintheexamplein
section8.1.2,earlierinthischapter.(ThoseofyouwhoarefamiliarwiththeC
programminglanguagewillrecognizethesecommentmarkings.)Usethis
commentsyntaxforbothdocument-levelandexternalstylesheets.Comments
cannotbenested.
Werecommenddocumentingyourstyleswheneverpossible,especiallyinexternal
stylesheets.Wheneverthepossibilityexiststhatotherauthorsmayuseyour
styles,commentsmakeitmucheasiertounderstandyourstyles.
8.1.9.StylePrecedence
Youmayimportmultipleexternalstylesheetsandcombinethemwithdocument-
levelandinlinestyleeffectsinmanydifferentways.Theireffectscascade(hence
thename,ofcourse).Youmayspecifythefonttypeforourexample<h1>tag,for
instance,inanexternalstyledefinition,whereasitscolormaycomefroma
document-levelstylesheet.
Stylesheeteffectsarenotcumulative,however:ofthemanystylesthatmay
definedifferentvaluesforthesamepropertycolorsforthecontentsofour
exampletag,forinstancetheonethattakesprecedencecanbefoundbyfollowing
theserules,listedhereinorder:
Sortbyorigin
Astyle-defined"closer"toatagtakesprecedenceoveramore"distant"style;
aninlinestyletakesprecedenceoveradocument-levelstyle,whichtakes
precedenceovertheeffectsofanexternalstyle.
Ifmorethanoneapplicablestyleexists,sortbyclass
Apropertydefinedasaclassofatag(seesection8.3,laterinthischapter)
takesprecedenceoverapropertydefinedforthetagingeneral.
Ifmultiplestylesstillexist,sortbyspecificity
Thepropertiesforamorespecificcontextualstyle(seesection8.2.3,laterin
thischapter)takeprecedenceoverpropertiesdefinedforalessspecific
context.
Ifmultiplestylesstillexist,sortbyorder
Thepropertyspecifiedlatesttakesprecedence.
Therelationshipbetweenstylepropertiesandconventionaltagattributesis
almostimpossibletopredict.Forinstance,stylesheet-dictatedbackgroundand
foregroundcolorswhetherdefinedexternally,atthedocumentlevel,or
inlineoverridethevariouscolorattributesthatmayappearwithinatag.Butthe
alignattributeofaninlineimageusuallytakesprecedenceoverastyle-dictated
alignment.
Myriadstyleandtagpresentation-attributecombinationsexist.Youneedacrystal
balltopredictwhichcombinationwinsandwhichlosestheprecedencebattle.The
rulesofredundancyandstyle-versus-attributeprecedenceareelucidatedinthe
W3CCSS2standard,butnoclearpatternofprecedenceisimplementedinthe
styles-consciousbrowsers.Thisisparticularlyunfortunatebecausetherewillbe
anextendedperiod,perhapsseveralmoreyears,inwhichusersmayormaynot
usestyles-consciousbrowsers.Authorsmustimplementbothstylesandnonstyle
presentationcontrolstoachievethesameeffects.
Nonetheless,ourrecommendationistorunasfastasyoucanfromone-shot,
inline,localizedkindsofpresentationeffectssuchasthoseaffordedbythe<font>
tagandcolorattribute.Theyhaveservedtheirtemporarypurpose;it'snowtime
tobringconsistency(withoutthepain!)backintoyourdocumentpresentation.
Usestyles.
8.2.StyleSyntax
Thesyntaxofastyleits"rule,"asyoumayhavegleanedfromourprevious
examplesisverystraightforward.
8.2.1.TheBasics
Astyleruleismadeupofatleasttwobasicparts:aselector,whichisthenameof
theHTMLorXHTMLmarkupelement(tagname)thatthestyleruleaffects,
followedbyacurlybrace({})-enclosed,semicolon-separatedlistofoneormore
styleproperty:valuepairs:
selector{property1:value1;property2:value1;...}
Forinstance,wemightdefinethecolorpropertyforthecontentsofallthelevel-1
headerelementsofourdocumenttobethevaluegreen:
h1{color:green}
Inthisexample,H1istheselector,whichisalsothenameofthelevel-1header
element,coloristhestyleproperty,andgreenisthevalue.
Mostpropertiesrequireatleastonevalue,butmayhavetwoormorevalues.
Comma-separatedvaluestypicallyindicateaseriesofoptionsasacceptedbythe
property,ofwhichthefirstvalidvalueappliestotheproperty,whereasspace-
separatedvalueseachapplyseparatelytotheproperty.Thelastvalidvaluemay
overrideapreviousvalue:
selector{property3:value1value2value3}
selector{property4:value1,value2,value3}
Forinstance,thefollowingdisplaybackgroundwillbeblack,notwhiteorgray,
eventhoughyouspecifybothwhiteandblackvaluesintherule:
body{background:whiteblack}
Currentstyles-consciousbrowsersignorelettercaseinanyelementofastyle
rule.Hence,h1andh1arethesameselector,andCOLOR,color,ColOR,andcOLorare
equivalentproperties.Atonetime,conventiondictatedthatHTMLauthorswrite
selectornamesinuppercasecharacters,suchash1,P,andSTRONG.Thisconvention
isstillcommonandisusedintheW3C'sownCSS2document.
However,currentstandardsdictate,particularlyforXML-compliantdocuments,
thatelementnamesbeidenticaltotheirrespectiveDocumentTypeDefinitions
(DTDs).WithXHTML,forinstance,allelementnamesarelowercase(e.g.,h1,p,
andstrong),sotheirrespectiveCSS2selectorsmustbeinlowercase.Weabideby
thelatterconvention.
Anyvalidelementname(atagnameminusitsenclosing<and>charactersand
attributes)canbeaselector.Youmayincludemorethanonetagnameinthelist
ofselectors,asweexplaininthefollowingsections.
8.2.2.MultipleSelectors
Whenseparatedbycommas,alltheelementsnamedintheselectorlistare
affectedbythepropertyvaluesinthestylerule.Thismakeslifeeasyforauthors.
Forinstance:
h1,h2,h3,h4,h5,h6{text-align:center}
doesexactlythesamethingas:
h1{text-align:center}
h2{text-align:center}
h3{text-align:center}h4{text-align:center}
h5{text-align:center}
h6{text-align:center}
Bothstylestellthebrowsertocenterthecontentsofheaderlevels1through6.
Formostauthors,thefirstversioniseasiertotype,understand,andmodify.And
ittakeslesstimeandfewerresourcestotransmitacrossanetwork,thoughthe
effectistrivial.Definestylesinthemannerthatismostcomfortableforyou.You
don'thavetousemultipleselectors.
8.2.3.ContextualSelectors
Normally,thestyles-consciousbrowserappliesdocument-levelorimportedstyles
toatag'scontentswherevertheyappearinyourdocument,withoutregardto
context.However,theCSS2standarddefinesawaytohaveastyleappliedonly
whenatagoccurswithinacertaincontextwithinadocument,suchaswhenitis
nestedwithinothertags.
Tocreateacontextualselector,listthetagsintheorderinwhichtheyshouldbe
nestedinyourdocument,outermosttagfirst.Then,whenthebrowserencounters
thatnestingorder,thestylepropertiesareappliedtothelasttaginthelist.
Forexample,here'showyoumightusecontextualstylestocreateaclassic
outline,completewithuppercaseRomannumeralsfortheouterlevel,capital
lettersforthenextlevel,Arabicnumeralsforthenext,andlowercaselettersfor
theinnermostlevel:
olli{list-style:upper-roman}
ololli{list-style:upper-alpha}
olololli{list-style:decimal}
ololololli{list-style:lower-alpha}
Accordingtotheexamplestylesheet,whenthestyles-consciousbrowser
encountersthe<li>tagnestedwithinone<ol>tag,itusestheupper-romanvaluefor
thelist-stylepropertyofthe<li>tag.Whenitseesan<li>tagnestedwithintwo
<ol>tags,thebrowserusestheupper-alphaliststyle.Nestan<li>tagwithinthree
andfour<ol>tags,andyou'llseethedecimalandlower-alphaliststyles,respectively.
CompareFigure8-1,displayedfromtheprecedingexample,withusingthe<ol>
tag'stypeattributetoachievesimilareffects,asshowninFigure7-7inChapter7.
Figure8-1.Nestedorderedliststyles
Similarly,youmayimposeaspecificstyleontagsrelatedonlybycontext.For
instance,thiscontextualstyledefinitioncolorstheemphasis(<em>)tag'scontents
redonlywhenitappearsinsidealevel-1headertag(<h1>),notelsewhereinthe
document:
h1em{color:red}
Ifthereispotentialambiguitybetweentwocontextualstyles,themorespecific
contextprevails.
Likeindividualtags,youmayhaveseveralcontextualselectorsmixedwith
individualselectors,separatedbycommas,sharingthesamelistofstyle
declarations.Forexample:
h1em,pstrong,address{color:red}
meansyou'llseeredwheneverthe<em>tagappearswithinan<h1>tag,whenthe
<strong>tagappearswithina<p>tag,andforthecontentsofthe<address>tag.
Thenestingneednotbeexacttomatchtherule.Forexample,ifyounestthe
<strong>tagwithina<ul>tagwithina<p>tag,you'llstillmatchtheruleforpstrong
thatwedefinedearlier.Ifaparticularnestingmatchesseveralstylerules,the
mostspecificruleisused.Forexample,ifyoudefinedtwocontextualselectors:
pstrong{color:red}
pulstrong{color:blue}
andyouusethesequence<p><ul><strong>inyourdocument,thesecond,more
specificruleapplies,coloringthecontentsofthe<strong>tagblue.
8.2.4.Universal,Child,andAdjacentSelectors
TheCSS2standarddefinesadditionalpatternsforselectorsbesidescommasand
spaces,asillustratedinthefollowingexamples:
*{color:purple;font:ZapfDingBats}
ol>li{font-size:200%;font-style:italic}
h1+h2{margin-top:+4mm}
Inthefirstexample,theuniversalasteriskselectorappliesthestyletoall
elementsofyourdocumentsothatanytextgetsdisplayedinZapfDingbat
characters.[*]Thesecondexampleselectsaparticularchild/parentrelationship;in
thiscase,itemsinanorderedlist.Thethirdexampleillustratestheadjacent
selectortype,whichselectsforonetagimmediatelyfollowinganotherinyour
document.Inthiscase,thespecialselectoraddsverticalspacetoinstancesin
whichyourdocumenthasalevel-2headerimmediatelyfollowingalevel-1
header.
[*]Assuming,ofcourse,thatthestyleisnotoverriddenbyasubsequentrule.
8.2.5.AttributeSelectors
ItispossibletoattachastyletoonlythoseHTML/XHTMLelementsthathave
specificattributes.Youdothisbylistingthedesiredattributesinsquarebrackets
([])nexttotheelementname,beforethestyledefinition:
div[align]{font-style:italic}
div[align=left]{font-style:italic}
div[title~="bibliography"]{font-size:smaller}
div[lang|="en"]{color:green}
Thefirstexampleisthesimplest:ititalicizesthesubsequenttextcontentsofonly
those<div>tagsthatcontainthealignattribute,regardlessofthevalueassigned
totheattribute.Thesecondexampleisabitpickier;itmatchesonly<div>tags
whosealignattributesaresettoleft.
Thethirdexamplematchesany<div>tagwhosetitleattributecontainstheword
bibliography,specificallydelimitedbyoneormorespaces.Partialwordmatchesdo
notcount;ifyouuseddiv[title~="a"],youwouldmatchonly<div>tagswhosetitle
attributescontainedasingle"a"delimitedbyspaces(oratthebeginningorend
ofthetitle).
Thefinalexamplematchesany<div>tagwhoselangattributeissettoahyphen-
separatedlistofwords,beginningwith"en."Thisexamplematchesattributes
suchaslang=en,lang=en-us,andlang=en-uk.
Youmaycombinetheuniversalselectorwithattributeselectorstomatchany
elementwithaspecificattribute.Forexample:
*[class=comment]{display:none}
wouldhidealltheelementsinyourdocumentwhoseclassattributesaresetto
comment.
Netscape,Firefox,Opera,andothermodernbrowserssupportattributeselectors;
forunknownreasons,InternetExplorerdoesnot.
8.2.6.Pseudoelements
Someelementalrelationshipsinyourdocumentsyoucannotexplicitlytag.The
drop-capisacommonprintstyle,buthowdoyouselectthefirstletterina
paragraph?Thereareways,butyouhavetoidentifyeachinstanceseparately.
Thereisnotagforthefirstlineinaparagraph.Andsometimesyoumightwant
thebrowsertoautomaticallygeneratecontent,suchastoaddtheprefix"Item#"
andautomaticallynumbereachiteminanorderedlist.
CSS2introducesfournewpseudoelementsthatletyoudefinespecial
relationshipsandstylesfortheirdisplay(:first-line,:first-letter,:before,and
:after).Declareeachasacolon-separatedsuffixofastandardmarkupelement.
Forexample:
p:first-line{font-size:200%;font-style:italic}
meansthatthebrowsershoulddisplaythefirstlineofeachparagraphitalicized
andtwiceaslargeastherestofthetext.Similarly:
p:first-letter{font-size:200%;float:left}
tellsthebrowsertomakethefirstletterofaparagraphtwiceaslargeasthe
remainingtextandtofloatthelettertotheleft,allowingthefirsttwolinesofthe
paragraphtofloataroundthelargerinitialletter(seeFigure8-2).[*]
[*]Thepropertiesyoucanspecifyforthe:first-letterand:first-linepseudoelementsarefont,color,
background,text-decoration,vertical-align,text-transform,line-height,andclear.Andin
addition,the:first-letterpseudoelementacceptsthemarginproperties,paddingproperties,borderproperties,
andfloat.The:first-linepseudoelementalsoacceptstheword-spacingandletter-spacingproperties.
Figure8-2.Usethefirst-letterpseudoelementtoselectthefirst
letteroftextwithinatag'scontent
The:beforeand:afterpseudoelementsletyouidentifywhereinyourdocument
youinsertgeneratedcontentsuchaslistnumbersandspeciallead-inheaders.
Hence,thesepseudoelementsgohandinhandwiththeCSS2contentandcounter
properties.Towhetyourappetite,considerthisexample:
ul{counter-reset:item;list-style:none}
ulli:before{content:"Item#"counters(item,".")"";
counter-increment:item}
...
<ul>
<li>Thisisitemnumber1.</li>
<ul>
<li>Thisissub-itemnumber1.1.</li>
</ul>
<li>Thisisitemnumber2.</li>
<ul>
<li>Thisissub-item2.1.</li>
<li>Thisissub-item2.2.</li>
...andsoon
Allthepopularbrowserssupportthepseudoelements,generatingeffectssuchas
thatshowninFigure8-2.However,InternetExplorerdoesnotsupportthecontent
propertyandNetscapedoesn'tsupportcounters.Soonlythenewcomers,Firefox
andOpera,properlydisplaytheprogressivelynumberedunorderedlistitems,
definedbytheforegoingexampleandshowninFigure8-3.
Figure8-3.Stylecounterscombinewithpseudoelementsto
createoutline-linenumbering
8.3.StyleClasses
CSS2allowsyoutodefineseveraldifferentstylesforthesameelementby
namingaclassforeachstyleatthedocumentlevelorinanexternalstylesheet.
Laterinadocument,youexplicitlyselectwhichstyletoapplybyincludingthe
styles-relatedclassattributewiththerelatednamevalueintherespectivetag.
8.3.1.RegularClasses
Forexample,inatechnicalpaper,youmightwanttodefineoneparagraphstyle
fortheabstract,anotherforequations,andathirdforcenteredquotations.
Differentiatetheseparagraphsbydefiningeachasadifferentstyleclass:
<styletype="text/css">
<!--
p.abstract{font-style:italic;
margin-left:0.5cm;
margin-right:0.5cm}
p.equation{font-family:Symbol;
text-align:center}
h1,p.centered{text-align:center;
margin-left:0.5cm;
margin-right:0.5cm}
-->
</style>
Noticefirstintheexamplethatdefiningaclassissimplyamatterofappendinga
period-separatedclassnameasasuffixtothetagnameastheselectorinastyle
rule.UnliketheXHTML-compliantselector,whichisthenameofthestandardtag
andmustbeinlowercase,theclassnamecanbeanysequenceofletters,
numbers,andhyphens,butitmustbeginwithaletter.[*]Careful,though:case
doesmatter,soabstractisnotthesameasAbsTRact.Classes,likeselectors,maybe
includedwithotherselectors,separatedbycommas,asinthethirdexample.The
onlyrestrictiononclassesisthattheycannotbenested;forexample,
p.equation.centeredisnotvalid.
[*]DuetoitssupportofJavaScriptstylesheets,Netscape4cannothandleclassnamesthathappentomatchJavaScript
keywords.Theclassabstract,forinstance,generatesanerrorinNetscape4.
Accordingly,thefirstruleintheexamplecreatesaclassofparagraphstyles
namedabstractwhosetextisitalicandindentedfromtheleftandrightmarginsby
0.5centimeters.Similarly,thesecondparagraphstyleclass,equation,instructsthe
browsertocenterthetextandtousetheSymboltypefacetodisplaythetext.The
laststylerulecreatesastylewithcenteredtextand0.5-centimetermargins,
applyingthisstyletoalllevel-1headersaswellascreatingaclassofthe<p>tag
namedcenteredwiththatstyle.
Touseaparticularclassofatag,youaddtheclassattributetothetag,asinthis
example(Figure8-4):
<pclass=abstract>
Thisistheabstractparagraph.Seehowthemarginsareindented?
</p>
<h3>Theequationparagraphfollows</h3>
<pclass=equation>
a=b+1
</p>
<pclass=centered>
Thisparagraph'stextshouldbecentered.
</p>
Figure8-4.Useclassestodistinguishdifferentstylesforthe
sametag
Foreachparagraph,thevalueoftheclassattributeisthenameoftheclasstobe
usedforthattag.
8.3.2.GenericClasses
Youalsomaydefineaclasswithoutassociatingitwithaparticulartagandapply
thatclassselectivelythroughyourdocumentsforavarietyoftags.Forexample:
.italic{font-style:italic}
createsagenericclassnameditalic.Touseit,simplyincludeitsnamewiththe
classattribute.Forinstance,<pclass=italic>and<h1class=italic>createanitalic
paragraphandlevel-1header,respectively.
Genericclassesarequitehandyandmakeiteasytoapplyaparticularstyletoa
broadrangeoftags.AllthepopularbrowserssupportCSS2genericclasses.
8.3.3.IDClasses
AlmostallHTMLtagsaccepttheidattribute,whichassignsauniqueidentifierto
anelementwithinthedocument.BesidesbeingthetargetofaURLoridentifiedin
anautomateddocument-processingtool,theidattributecanalsospecifyastyle
rulefortheelement.
Tocreateastyleclassthatthestyles-consciousbrowserappliestoonlythose
portionsofyourdocumentexplicitlytaggedwiththeidattribute,followthesame
syntaxasforstyleclasses,exceptwitha#characterbeforetheclassname
insteadofaperiod.Forexample:
<style>
<!--
#yellow{color:yellow}
h1#blue{color:blue}
-->
</style>
Withinyourdocument,usethatsameidnametoapplythestyle,suchas<h1
id=blue>tocreateablueheading.Or,asintheexample,useid=yellowelsewherein
thedocumenttoturnatag'scontentsyellow.Youcanmixandmatchbothclass
andidattributes,givingyoualimitedabilitytoapplytwoindependentstylerules
toasingleelement.
Thereisadramaticdrawbacktousingstyleclassesthisway:theHTMLand
XHTMLstandardsdictatethatthevalueoftheidattributebeuniqueforeach
instanceinwhichit'susedwithinthedocument.Yethere,wehavetousethe
samevaluetoapplythestyleclassmorethanonce.
Eventhoughcurrentbrowsersletyougetawaywithit,westronglydiscourage
creatingandusingtheidkindsofstyleclasses.Sticktothestandardstyleclass
conventiontocreatecorrect,robustdocuments.
8.3.4.Pseudoclasses
Inadditiontoconventionalstyleclasses,theCSS2standarddefines
pseudoclasses,whichallowyoutodefinethedisplaystyleforcertaintagstates,
suchaschangingthedisplaystylewhenauserselectsahyperlink.Youcreate
pseudoclassesasyoudoregularclasses,butwithtwonotabledifferences:they
areattachedtothetagnamewithacolonratherthanaperiod,andtheyhave
predefinednames,notarbitraryonesyoumaygivethem.Thereareseven
pseudoclasses,threeofwhichareexplicitlyassociatedwiththe<a>tag.
8.3.4.1.Hyperlinkpseudoclasses
CSS2-compliantbrowsersdistinguishthreespecialstatesforthehyperlinks
createdbythe<a>tag:notyetvisited,currentlybeingvisited,andalreadyvisited.
Thebrowsermaychangetheappearanceofthetag'scontentstoindicateits
state,suchaswithunderliningorcolor.Throughpseudoclasses,youmaycontrol
howthesestatesgetdisplayedbydefiningstylesfora:link(notvisited),a:active
(beingvisited),anda:visited.
The:linkpseudoclasscontrolstheappearanceoflinksthatarenotselectedbythe
userandhavenotyetbeenvisited.The:activepseudoclassdefinesthe
appearanceoflinksthatarecurrentlyselectedbytheuserandarebeing
processedbythebrowser.The:visitedpseudoclassdefinesthoselinksthatthe
userhasalreadyvisited.
Tocompletelydefineallthreestatesofthe<a>tag,youmightwrite:
a:link{color:blue}
a:active{color:red;font-weight:bold}
a:visited{color:green}
Inthisexample,thestyles-consciousbrowserrendersunvisitedlinksinblue.
Whentheuserselectsalink,thebrowserchangesitscolortoredandmakesit
bold.Oncevisited,thelinkrevertstogreen.
8.3.4.2.Interactionpseudoclasses
TheCSS2standarddefinestwonewpseudoclassesthat,alongwith:active,relate
touseractionsandadvisetheinteractiveagent,suchasabrowser,howtodisplay
theaffectedelementastheuserinteractswiththeelement.Inotherwords,these
twopseudoclasseshoverandfocusaredynamic.
Forinstance,whenyoudragthemouseoverahyperlinkinyourdocument,the
browsermaychangethemouse-pointericon.Hoveringcanbeassociatedwitha
stylethatappearsonlywhilethemouseisovertheelement.Forexample,ifyou
addthe:hoverpseudoclasstoourexamplelistofhyperlinkstylerules:
a:hover{color:yellow}
thetextassociatedwithunvisitedlinksnormallyappearsblue,butturnsyellow
whenyoupointtoitwiththemouse,redafteryouclickthelinkandwhileyouare
visitingit,andgreenafteryou'redonevisitingthehyperlink.
Similarly,the:focuspseudoclassletsyouchangethestyleforanelementwhenit
becomestheobjectofattention.Anelementmaybeunderfocuswhenyoutabto
it,clickonit,or,dependingonthebrowser,advancethecursortoit.Regardlessof
howthefocusgottotheelement,thestylerulesassociatedwiththefocus
pseudoclassareappliedonlywhiletheelementhasthefocus.
8.3.4.3.Nestingandlanguagepseudoclasses
TheCSS2:first-childpseudoclassletsyouspecifyhowanelementmaybe
renderedwhenitisthefirstinstance,orchild,ofthecontainingelement.For
instance,thefollowingrulegetsappliedtoaparagraphwhenitisthefirst
elementofadivision;therecanbenointerveningelements(noticethespecial
greater-thanbracketsyntaxrelatingthefirstchildwithitsparentelement):
div>p:first-child{font-style:italic}
Accordingly,thefirstparagraphinthefollowingHTMLfragmentwouldbe
renderedinitalicsbyaCSS2-compliantbrowserbecauseitisthefirstchild
elementofitsdivision.Conversely,thesecondparagraphcomesafteralevel-2
header,whichisthefirstchildoftheseconddivision.So,thatsecondparagraphin
theexamplegetsrenderedinplaintext,becauseitisnotthefirstchildofits
division(Figure8-5):
<div>
<p>
Igettobeinitalicsbecausemyparagraphisthefirstchildofthedivision.
</p>
</div>
<div>
<h2>NewDivision</h2>
<p>
I'minplaintextbecausemyparagraphisasecondchildofthedivision.
Figure8-5.Thefirst-childpseudoclassinaction
Finally,theCSS2standarddefinesanewpseudoclassthatletsyouselectan
elementbasedonitslanguage.Forinstance,youmightincludethelang=fr
attributeina<div>tagtoinstructthebrowserthatthedivisioncontainsFrench
languagetext.Thebrowsermayspeciallytreatthetext.Or,youmayimposea
specificstylewiththepseudoclass:lang.Forexample:
div:lang(it){font-family:Roman}
saysthattextindivisionsofadocumentthatcontaintheItalianlanguageshould
usetheRomanfontfamily.Appropriate,don'tyouthink?Noticethatyouspecify
thelanguageinparenthesesimmediatelyafterthelangkeyword.Usethesame
two-letterInternationalOrganizationforStandardization(ISO)standardcodefor
thepseudoclass:langasyoudoforthelangattribute.[Thelangattribute,3.6.1.2]
8.3.4.4.Browsersupportofpseudoclasses
Noneofthepopularbrowserssupportsthe:langor:focuspseudoclassyet.Allthe
currentpopularbrowserssupportthe:link,:active,:hover,and:visited
pseudoclassesforthehyperlinktag(<a>),aswellas:first-child.Eventhoughyou
mayuse:activeforotherelements,noneofthebrowsersyetsupportsapplications
beyondthe<a>tag.
8.3.5.MixingClasses
Mixpseudoclasseswithregularclassesbyappendingthepseudoclassnametothe
selector'sclassname.Forexample,herearesomerulesthatdefineplain,normal,
andfancyanchors:
a.plain:link,a.plain:active,a.plain:visited{color:blue}
a:link{color:blue}
a:visited{color:green}
a:active{color:red}
a.fancy:link{font-style:italic}
a.fancy:visited{font-style:normal}
a.fancy:active{font-weight:bold;font-size:150%}
Theplainversionof<a>isalwaysblue,nomatterwhatthestateofthelinkis.
Accordingly,normallinksstartoutblue,turnredwhenactive,andconvertto
greenwhenvisited.Thefancylinkinheritsthecolorschemeofthenormal<a>tag,
butitalicizesthetextforunvisitedlinks,convertsbacktonormaltextafterbeing
visited,andactuallygrows50percentinsizeandbecomesboldwhenactive.
Awordofwarningaboutthatlastpropertyofthefancyclass:specifyingafont-size
changeforatransientdisplaypropertyresultsinlotsofbrowserredisplayactivity
whentheuserclicksthelink.Giventhatsomebrowsersrunonslowmachines,
thismaynotbevisuallyrefreshingforyourreaders.Givenalsothatimplementing
thatsortofdisplaychangeissomethingofapain,itisunlikelythatmost
browserswillsupportradicalappearancechangesin<a>tagpseudoclasses.
8.3.6.ClassInheritance
Classesinheritthestylepropertiesoftheirgenericbasetags.Forinstance,allthe
propertiesoftheplain<p>tagapplytoaspeciallydefinedparagraphclass,except
wheretheclassoverridesaparticularproperty.
Classescannotinheritfromotherclasses,onlyfromtheunclassedversionsofthe
tagstheyrepresent.Ingeneral,therefore,youshouldputasmanycommon
stylesaspossibleintotheruleforthebasicversionofatagandcreateclasses
onlyforthosepropertiesthatareuniquetothatclass.Thismakesmaintenance
andsharingofyourstyleclasseseasier,especiallyforlargedocumentcollections.
8.4.StyleProperties
AttheheartoftheCSS2standardarethemanypropertiesthatletyoucontrol
howthestyles-consciousbrowserpresentsyourdocumentstotheuser.The
standardcollectsthesepropertiesintosixgroups:fonts,colorsandbackgrounds,
text,boxesandlayout,lists,andtagclassification.We'llstickwiththattaxonomy
andprefacethewholeshebangwithadiscussionofpropertyvaluesand
inheritancebeforedivingintothepropertiesthemselves.
You'llfindasummaryofthestylepropertiesinAppendixC.
8.4.1.PropertyValues
Mostpropertiessetavaluetosomecharacteristicofyourdocumentforrendering
bythebrowserthesizeofthecharactersinafontorthecoloroflevel-2headers,
forexample.Aswediscussedearlier,whendescribingthesyntaxofstyles,you
givevaluetoaCSS2propertybyfollowingtheproperty'skeywordwithacolon(:)
andoneormorespace-orcomma-separatednumbersorvalue-relatedkeywords.
Forexample:
color:blue
font-family:Helvetica,Univers,sans-serif
colorandfont-familyarethepropertiesinthesetwostyleexamples;blueandthe
variouscomma-separatedfontnamesaretheirvalues,respectively.
Thereareeightkindsofpropertyvalues:keywords,lengthvalues,percentage
values,URLs,colors,angles,time,andfrequencies.
8.4.1.1.Keywordpropertyvalues
Apropertymayhaveakeywordvaluethatexpressesactionordimension.For
instance,theeffectsofunderlineandline-throughareobviouspropertyvalues.And
youexpresspropertydimensionswithsuchkeywordsassmallandxx-large.Some
keywordsareevenrelational:bolder,forinstance,isanacceptablevalueforthe
font-weightproperty.Keywordvaluesarenotcasesensitive:Underline,UNDERLINE,and
underlineareallacceptablekeywordvalues.
8.4.1.2.Lengthpropertyvalues
So-calledlengthvalues(atermtakenfromtheCSS2standard)explicitlysetthe
sizeofaproperty.Theyarenumbers,somewithdecimals,too.Lengthvaluesmay
havealeading+or-signtoindicatethatthevalueistobeaddedtoor
subtractedfromthecurrentvalueoftheproperty.Lengthvaluesmustbefollowed
immediatelybyatwo-letterunitabbreviation,withnointerveningspaces.
Therearethreekindsoflength-valueunits:relative,pixels,andabsolute.
Relativeunitsspecifyasizethatisrelativetothesizeofsomeotherpropertyof
thecontent.Currently,thereareonlytworelativeunits:em,whichisthewidthof
thelowercaseletter"m"inthecurrentfont;andx-height,abbreviatedex,which
istheheightoftheletter"x"inthecurrentfont.
Pixelsarethetinydotsofcoloredlightthatmakeuptheonscreentextand
imagesonacomputermonitororTVimage.Thepixelsunit,abbreviatedpx,is
equaltotheminutesizeof1pixel,soyoumayexpressthesizeofsome
propertiesbyhowmanypixelsacrossordowntheyrun.
Absolutepropertyvalueunitsaremorefamiliartousall.Theyincludeinches(in),
centimeters(cm),millimeters(mm),points(pt;1/72ofaninch),andpicas(pc;12
points).
Allofthefollowingarevalidlengthvalues,althoughthecurrentstyles-conscious
browsersdonotrecognizeallunits:
1in
1.5cm
+0.25mm
-3pt
-2.5pc
+100em
-2.75ex
250px
8.4.1.3.Percentagepropertyvalues
Similartotherelativelengthpropertyvaluetype,apercentagevaluedescribesa
proportionrelativetosomeotheraspectofthecontent.Ithasanoptionalsign,
meaningitmaybeaddedtoorsubtractedfromthecurrentvalueforthat
property,andoptionaldecimalportiontoitsnumericvalue.Percentagevalues
havethepercentsign(%)suffix.Forexample:
line-height:120%
computestheseparationbetweenlinestobe120percentofthecurrentline
height(usuallyrelativetothetextfontheight).Notethatthisvalueisnot
dynamic:changesmadetothefontheightaftertherulehasbeenprocessedby
thebrowserdonotaffectthecomputedlineheight.
8.4.1.4.URLpropertyvalues
Somepropertiesalsoaccept,ifnotexpect,aURLvalue.ThesyntaxforaCSS2
URLpropertyvalueisdifferentfromthatinHTML/XHTML:
url(service://server.com/pathname)
WithCSS2properties,thekeywordurlisrequired,asaretheopeningandclosing
parentheses.Donotleaveanyspacesbetweenurlandtheopeningparenthesis.
TheurlvaluemaycontaineitheranabsoluteorarelativeURL.However,theURL
isrelativetothestylesheet'sURL,notnecessarilythedocument'sbaseURL.This
meansthatifyouuseaurlvalueinadocument-levelorinlinestyle,theURLis
relativetotheHTMLdocumentcontainingthestyledocument.Otherwise,theURL
isrelativetothe@importedor<link>edexternalstylesheet'sURL.
8.4.1.5.Colorpropertyvalues
Colorvaluesspecifycolorsinaproperty(surprised?).Youcanspecifyacolorasa
colornameorahexadecimalRGBtriple,asforcommonHTML/XHTMLattributes,
orasadecimalRGBtripleuniquetostyleproperties.Bothcolornamesand
hexadecimalRGBtriplenotationaredescribedinAppendixG.
WithCSS2,too,youmayassignjustonehexadecimaldigitinsteadoftwotothe
red,green,andblue(RGB)componentsofacolor.Thatdigitissimplydoubledto
createaconventionalsix-digittriple.Thus,thecolor#78Cisequivalentto#7788CC.
Ingeneral,three-digitcolorvaluesarehandyonlyforsimplecolors.
ThedecimalRGBtriplenotationisunique:
rgb(red,green,blue)
Thered,green,andblueintensityvaluesaredecimalintegersintherange0to255,
orintegerpercentages.Aswithaurlvalue,donotleaveanyspacesbetweenrgb
andtheopeningparenthesis.
Forexample,indecimalRGBconvention,thecolorwhiteisrgb(255,255,255)or
rgb(100%,100%,100%),andamediumyellowisrgb(127,127,0)orrgb(50%,50%,0%).
8.4.1.6.Angle,time,andfrequencypropertyvalues
Afewpropertiesrequireavaluethatexpressesanangle,suchastheheadingofa
compass.Thesepropertiestakeanumericvaluefollowedbytheunitsdeg
(degrees),grad(gradations),orrad(radians).Similarly,expresstimevaluesas
numbersfollowedbyeitherms(milliseconds)ors(seconds)units.
Finally,frequencyvaluesarenumbersfollowedbyHz(hertz)orkHz(1kilohertz=
1000Hz).Interestingly,thereisnocorrespondingMHzorGHzunits,because
frequenciesinCSS2refertoaudio,notTV,FMradio,Bluetoothwireless
networking,orotherelectromagneticwaves.
8.4.2.PropertyInheritance
Inlieuofaspecificruleforaparticularelement,propertiesandtheirvaluesfor
tagswithintagsareinheritedfromtheparenttag.Thus,settingapropertyforthe
<body>tageffectivelyappliesthatpropertytoeverytaginthebodyofyour
document,exceptforthosethatspecificallyoverrideit.So,tomakeallthetextin
yourdocumentblue,youneedonlywrite:
body{color:blue}
insteadofcreatingaruleforeverytagyouuseinyourdocument.
Thisinheritanceextendstoanylevel.Ifyoulatercreateda<div>tagwithtext
styledbyadifferentcolor,thestyles-consciousbrowserwoulddisplayallthetext
contentsofthat<div>tagandallitsenclosedtagsinthatnewcolor.Whenthe
<div>tagends,thecolorrevertstothatofthecontaining<body>tag.
Inmanyofthefollowingpropertydescriptions,werefertothetagcontainingthe
currenttagastheparentelementofthattag.
8.4.3.FontProperties
TheloudestcomplaintthatwehearaboutHTMLanditsprogeny,XHTML,isthat
theylackfontstylesandcharacteristicsthateventhesimplestoftexteditors
implement.Thevarious<font>attributesaddresspartoftheproblem,buttheyare
tedioustouse,becauseeachtextfontchangerequiresadifferent<font>tag.
Stylesheetssimplifyallthat,ofcourse.TheCSS2standardprovidessevenfont
propertiesthatmodifytheappearanceoftextcontainedwithintheaffectedtag:
font-family,font-size,font-size-adjust,font-style,font-variant,font-stretch,andfont-
weight.Inaddition,thereisauniversalfontpropertyinwhichyoucandeclareall
thefontvalues.
Pleasebeawarethatstylesheetscannotovercomelimitationsoftheuser's
display/document-renderingsystem,andthebrowsercannotconjureeffectsifthe
fontsitusesdonotprovidethemeans.
8.4.3.1.Thefont-familyproperty
Thefont-familypropertyacceptsacomma-separatedlistoffontnames.The
browserusesthefirstfontnamedinthelistthatalsoisinstalledandavailablefor
displayontheclientmachinefortextdisplay.
Font-namevaluesareforspecificfontstyles,suchasHelveticaandCourier,orfor
agenericfontstyle,asdefinedbytheCSS2standard:serif,sans-serif,cursive,
fantasy,andmonospace.Thebrowserdefineswhichfontitactuallyusesforeach
genericfont.Forinstance,Courieristhemostpopularchoiceforamonospaced
font.
Becausefontsvarywildlyamongbrowsers,youshouldusuallyprovideseveral
choiceswhenspecifyingafontstyle,endingwithasuitablegenericfont.For
example:
h1{font-family:Helvetica,Univers,sans-serif}
causesthebrowsertolookforanduseHelvetica,andthenUnivers.Ifneitherfont
isavailablefortheclientdisplay,thebrowserusesthegenericsans-seriftypeface.
EnclosefontnamesthatcontainspacesNewCenturySchoolbook,forexamplein
quotationmarks.Forinstance:
p{font-family:Times,"NewCenturySchoolbook",Palatino,serif}
Withinlinestyles,thatextrasetofdoublequotationmarkscausesproblems.The
solutionistousesinglequotationmarksinaninlinestyle:
<pstyle="font-family:Times,'NewCenturySchoolbook',Palatino,serif">
Inpractice,youdon'thavetousequotationmarks,becausefont-namevaluesare
commaseparated,sothebrowsernormallyignoresthespaces.Hence,bothofthe
followingarelegal:
p{font-family:Times,NewCenturySchoolbook,Palatino,serif}
<pstyle="font-family:Times,NewCenturySchoolbook,Palatino,serif">
Nonetheless,werecommendthatyouusequotationmarks.It'sagoodhabitto
getinto,anditmakesthingsthatmuchlessambiguous.
8.4.3.2.Thefont-sizeproperty
Thefont-sizepropertyletsyouprescribeabsoluteorrelativelengthvalues,
percentages,andkeywordstodefinethefontsize.Forexample:
p{font-size:12pt}
p{font-size:120%}
p{font-size:+2pt}
p{font-size:medium}
p{font-size:larger}
Thefirstruleisprobablythemostused,becauseitisthemostfamiliar:itsetsthe
fontsizefortextenclosedinyourdocument'sparagraph(s)toaspecificnumber
ofpoints(12inthisexample).Thesecondexamplerulesetsthefontsizetobe
20percentlargerthantheparentelement'sfontsize.Thethirdincreasesthe
font'snormalsizeby2points.
Thefourthexampleselectsapredefinedfontsizesetbythebrowser,identifiedby
themediumkeyword.Validabsolute-sizekeywordsarexx-small,x-small,small,medium,
large,x-large,andxx-large;theseusuallycorrespondtothesevenfontsizesused
withthesizeattributeofthe<font>tag.
Thelastfont-sizeruleselectsthenextsizelargerthanthefontassociatedwiththe
parentelement.Thus,ifthesizewerenormallymedium,itwouldbechangedto
large.Youcanalsospecifysmaller,withtheexpectedresults.
Noneofthecurrentbrowsershandlesincrementedordecrementedfontsizes
correctly.Rather,theyignorethedecrementsignandsizealtogether,and
misinterprettheincrementedsizevalueasanabsolutesize.Forinstance,inthe
middleexampleinthissection,thefontsizewouldendupas2points,not2
pointslargerthanthenormalsize.
8.4.3.3.Thefont-stretchproperty
Inadditiontodifferentsizes,fontfamiliessometimescontaincondensedand
expandedversions,inwhichthecharactersaresqueezedorstretched,
respectively.Usethefont-stretchpropertytochoosemorecompressedor
stretched-outcharactersfromyourfont.
Usethepropertyvalueofnormaltoselectthenormal-sizeversionofthefont.The
relativevalueswiderandnarrowerselectthenext-widerornext-narrowervariantof
thefont'scharacters,respectively,butnotwiderornarrowerthanthemost
("ultra")expandedorcontractedoneinthefamily.
Theremainingfont-stretchpropertyvalueschoosespecificvariantsfromthefont
family.Startingfromthemostcondensedandendingwiththemostexpanded,the
valuesareultra-condensed,extra-condensed,condensed,semi-condensed,semi-expanded,
expanded,extra-expanded,andultra-expanded.
Thefont-stretchproperty,ofcourse,assumesthatyourdisplayfontssupport
stretchablefonts.Evenso,thecurrentlypopularbrowsersignorethisproperty.
8.4.3.4.Thefont-size-adjustproperty
Withouttoomanydetails,thelegibilityanddisplaysizeofafontdepend
principallyonitsaspectratio:theratioofitsrenderedsizetoitsx-height,which
isameasureofthefont'slowercaseglyphheight.Fontswithaspectratios
approaching1.0tendtobemorelegibleatsmallersizesthanfontswithaspect
ratiosapproaching0.
Also,becauseofaspectratios,theactualdisplaysizeofonefontmayappear
smallerorlargerthananotherfontatthesamesize.So,whenonefontisnot
availableforrendering,thesubstitutedfontmaydistortthepresentation.
Thefont-size-adjustpropertyletsyoureadjustthesubstitutedfont'saspectratioso
thatitbetterfitsthedisplay.Usethepropertyvalueofnonetoignoretheaspect
ratio.Otherwise,includeyourdesiredaspectratio(adecimalvaluelessthan
one),typicallytheaspectratioforyourfirst-choicedisplayfont.Thestyles-
consciousbrowsercomputesanddisplaysthesubstitutedfontatasizeadjustedto
yourspecifiedaspectratio:
s=(n/a)*fs
wheresisthenew,computerfontsizefordisplayofthesubstitutedfont,
calculatedasthefont-size-adjustvaluendividedbythesubstitutedfont'saspect
ratioatimesthecurrentfontsizefs.
Forexample,let'simaginethatyourfirst-choicefontisTimesNewRoman,which
hasanaspectratioof0.45.Ifit'snotavailable,thebrowsermaythensubstitute
ComicSansMS,whichhasanaspectratioof0.54.Sothatthesubstitution
maintainsnearlyequivalentsizingforthefontdisplaysay,atan18-pxfont
sizewiththefont-size-adjustpropertysetto0.45,theCSS2-compliantbrowser
woulddisplayorprintthetextwiththesubstitutedComicSansMSfontatthe
smallersizeof(0.45/0.54x18px)=15px.
Unfortunately,wecan'tshowyouhowthepopularbrowserswoulddothisbecause
theydon'tsupportit.
8.4.3.5.Thefont-styleproperty
Usethefont-stylepropertytoslanttext.Thedefaultstyleisnormalandmaybe
changedtoitalicoroblique.Forexample:
h2{font-style:italic}
makesalllevel-2headertextitalic.Netscape4supportedonlytheitalicvaluefor
font-style;allcurrentbrowserssupportbothvalues,althoughitisusuallydifficult
todistinguishitalicfromoblique.
8.4.3.6.Thefont-variantproperty
Usethefont-variantpropertytodisplaytextinsmallcapitals.Thedefaultvaluefor
thispropertyisnormal,indicatingtheconventionalversionofthefont.Otherwise,
givethepropertythevaluesmall-capstoselectaversionofthefontinwhichthe
lowercaselettershavebeenreplacedwithsmallcapitalletters.
Allthecurrentbrowserssupportthisproperty.InternetExplorerversions4and5
incorrectlydisplayedsmall-capsasalluppercaseletters.
8.4.3.7.Thefont-weightproperty
Thefont-weightpropertycontrolstheweightorboldnessofthelettering.The
defaultvalueofthispropertyisnormal.Youmayspecifyboldtoobtainabold
versionofafontorusetherelativebolderandlightervaluestoobtainaversionof
thefontthatisbolderorlighterthantheparentelement'sfont.
Tospecifyvaryinglevelsoflightnessorboldness,setthevaluetoamultipleof
100,betweenthevalues100(lightest)and900(boldest).Thevalue400isequalto
thenormalversionofthefont,and700isthesameasspecifyingbold.
Thecurrentbrowsersfullysupportthisproperty.
8.4.3.8.Thefontproperty
Moreoftenthannot,you'llfindyourselfspecifyingmorethanonefont-related
propertyatatimeforatag'stextcontentdisplay.Acompletefontspecification
cangetsomewhatunwieldy.Forexample:
p{font-family:Times,Garamond,serif;
font-weight:bold;
font-size:12pt;
line-height:14pt}
Tomitigatethistroublesomeandpotentiallyunreadablecollection,usethe
comprehensivefontpropertyandgroupalltheattributesintoonesetof
declarations:
p{font:bold12pt/14ptTimes,Garamond,serif}
Thegroupingandorderingoffontattributesisimportantwithinthefontproperty.
Thefontstyle,weight,andvariantattributesmustbespecifiedfirst,followedby
thefontsizeandthelineheightseparatedbyaslashcharacter,andendingwith
thelistoffontfamilies.Ofalltheproperties,thesizeandfamilyarerequired;the
othersmaybeomitted.
Hereareafewmoreexamplefontstylerules:
em{font:italic14ptTimes}
h1{font:24pt/48ptsans-serif}
code{font:12ptCourier,monospace}
Thefirstexampletellsthestyles-consciousbrowsertoemphasize<em>textusinga
14-pointitalicTimesface.Thesecondrulehas<h1>textdisplayedintheboldest
24-pointsans-seriffontavailable,withanextra24pointsofspacebetweenthe
linesoftext.Finally,textwithina<code>tagissetin12-pointCourierorthe
browser-definedmonospacedfont.
Weleaveittoyourimaginationtoconjureupexamplesoftheabusesyoucould
fosterwithfontstyles.PerhapsarecentissueofWiredmagazine,notoriousfor
avant-gardefontsandotherprint-relatedabuses,wouldbehelpfulinthatregard.
8.4.4.FontSelectionandSynthesis
TheoriginalCSSstandard,CSS1,hadasimplisticfont-matchingalgorithm:if
yourspecifiedfontdoesnotexistinthelocalclient'sfontcollection,substitutea
genericfont.Ofcourse,theresultsareoftenlessthanpleasingtotheeyeandcan
wreakhavocwiththedisplay.Moreover,thereareoftenmoresuitablefont
substitutesthangenericones.TheCSS2standardsignificantlyextendstheCSS1
font-matchingmodelandincludesanewat-rulethatletsauthorsdefine,
download,andusenewfontsintheirdocuments.
8.4.4.1.CSS2font-matchingsteps
TheCSS2font-matchingalgorithmhasfoursteps.Thefirststepissimplytouse
thespecifiedfontwhenitisfoundontheuser'smachine;thiscouldbeoneof
severalfontfamiliesspecifiedinthestylesheetrule,parsedintheirorderof
appearance.
Thesecondstep,takenwhennoneofthefontsspecifiedintheruleexistsonthe
user'smachine,hasthebrowserattempttofindaclosematchamongsimilarlocal
fonts.Forexample,arequestforHelveticamightwindupusingArial,asimilar
sans-seriffont.
ThethirdstepintheCSS2font-matchingalgorithmhasthebrowsertryto
synthesizeafont,takingalocalfontandchangingittomatchthespecifiedone.
Forexample,arequestfor72-pointHelveticamightbesatisfiedbytakingthe
local12-pointArialfontandscalingituptomatchthedesiredsize.
Failingallthreeprevioussteps,thebrowsermaytakeafourthstepanddownload
thedesiredfont,providedtheauthorhassuppliedsuitableexternalfont
definitions.Theseexternalfontdefinitionsarecreatedwiththe@font-faceat-rule,
whosegeneralsyntaxis:
@font-face{
descriptor:value;
...
descriptor:value
}
Each@font-faceat-ruledefinesanewfonttothebrowser.Subsequentrequestsfor
fontsmaybesatisfiedbythesenewfonts.Thebrowserusesthevarious
descriptorvaluestoensurethatthefontsuppliedmatchesthefontrequested.
8.4.4.2.Basicfontdescriptors
Thebasicfontdescriptorsthatyouuseinthe@font-faceat-rulecorrespondtothe
CSS2fontpropertiesandacceptthesamevaluesasthoseproperties.Accordingly,
usethefont-family,font-style,font-variant,font-weight,font-stretch,andfont-size
descriptorsandtheirassociatedvaluestodefineanewfonttothebrowser.For
example:
@font-face{
font-family:"KumquatSans";
font-style:normal,italic;
src:url("http://www.kumquat.com/foundry/kumquat-sans")
}
definesafontnamedKumquatSansthatisavailablefordownloadfrom
www.kumquat.com.Withinthatdownloadablefont,boththenormalandtheitalic
versionsofKumquatSansareavailable.Becauseweprovidenootherfont
descriptors,thebrowserassumesthatallotherfontproperties(weight,variant,
etc.)canbesatisfiedwithinthisfont.
Ingeneral,omittingafontdescriptorletsthebrowsermatchanyvalueprovided
forthatdescriptor.Byprovidingoneormorevaluesforafontdescriptor,youare
restrictingthebrowsertomatchonlythosevaluesinlaterfontrequests.Hence,
youshouldbeasspecificaspossiblewhendefiningafontthisway,tobetter
ensurethatthebrowsermakesgoodmatcheslater.Forexample,ifafontdoes
notcontainanitalicversionandyoufailtotellthebrowser,itmayusean
incorrectfontwhenattemptingtofulfillarequestforanitalicstyleofthatfont.
8.4.4.3.Thesrcdescriptor
Thesrcdescriptorinthe@font-faceat-ruletellsthebrowserwheretoretrievethe
font.Fordownloadablefonts,thevalueofthisdescriptorisitsdocumentURL,
expressedinCSS2syntaxwiththeurlkeyword.Toreferencelocallyinstalled
fontsonesstoredontheuser'smachinewithsrc,usethekeywordlocalratherthan
urlandsupplythelocalnameofthefont.
Thesrcdescriptor'svaluemayalsobealistoflocations,separatedbycommas.In
ourpreviousexample,wecouldhaveused:
src:url("http://www.kumquat.com/foundry/kumquat-sans"),local("LucidaSans")
whichasksthebrowsertodownloadanduseKumquatSansfrom
www.kumquat.comand,ifthatfails,tolookforalocallyinstalledcopyofLucida
Sans.
Youcanevenprovidehintstothebrowser.CSS2isdecidedlynonpartisanwhenit
comestotheformatofthefontfile.Recognizingthatanumberofdifferentfont
formatsexist,thestandardletsyouuseanyformatyouwant,presumingthatthe
browsercanmakesenseofit.Toprovideaformathint,usethekeywordformat
followedbyoneormoreformatnames,suchas:
src:url("http://www.kumquat.com/foundry/kumquat-sans")format("type-1"),
local("LucidaSans")format("truetype","intellitype")
Inthiscase,theexternalfontisinType1format,andthelocalflavorsofLucida
SansareavailableinbothTrueTypeandIntellifontformats.Otherrecognizedfont
formatsincludetruedoc-pfr,opentype,embedded-opentype,truetype,truetype-gx,and
speedo.
8.4.4.4.Advancedfontdescriptors
Inadditiontothestandardfontdescriptors,CSS2supportsanumberofmore
esotericonesthatfurtherrefinethedefinedfont.Typicalpagedesignersdonot
havemuchneedforthesedescriptors,butmorediscriminatingtypographersmay
findthemuseful.
Theunicode-rangedescriptoracceptsacomma-separatedlistofUnicodevalues,
eachbeginningwithU+followedbyahexadecimalvalue.Youcanspecifyrangesof
valuesbyaddingadashandanotherhexadecimalvalue;thequestionmark
matchesanyvalueinthatposition.
Thepurposeoftheunicode-rangedescriptoristodefineexactlywhichcharacter
glyphsaredefinedinthefont.Ifcharactersusedinyourdocumentarenot
available,thebrowserdoesnotdownloadandusethefont.Forexample,avalue
ofU+2A70indicatesthatthefontcontainstheglyphatthatpositioninthefont.
UsingU+2A7?representscharactersintherange2A70to2A7F,andU+2A70-2A9F
definesabroaderrange.Forthemostpart,thisdescriptorisusedtorestrictthe
useofspecialsymbolfontstojustthosesymbolsdefinedinthefont.
Theunits-per-emdescriptoracceptsasinglenumericvaluedefiningthesizeofthe
font'semarea.Thisvalueisimportantifyouspecifythevaluesofother
descriptorsusingemunits.
Thepanose-1descriptoracceptsexactly10integervalues,separatedbyspaces,
correspondingtothePanose-1characterizationofthisfont.Definingtheactual
Panose-1valuesiswellbeyondthescopeofthisbook;interestedauthorsshould
refertoappropriatedocumentationforthePanose-1systemformoreinformation.
Thestemvandstemhdescriptorsdefinethethickness,inems,oftheverticaland
horizontalstrokesofthefont.Similarly,thecap-heightandx-heightdescriptors
definetheheightoftheupper-andlowercaseglyphsinthefont.Finally,theascent
anddescentdescriptorsdefinethefont'smaximumheightanddepth.Ifyouuse
anyofthesedescriptors,youmustalsospecifytheunits-per-emdescriptor.
Theslopedescriptordefinestheslopeoftheverticalstrokeofthefont.Thisis
importantformatchingitalicandobliqueversionsofafont.
Thebaseline,centerline,mathline,andtoplinedescriptorsdefinetheconventional
baseline,centerbaseline,mathematicalbaseline,andtopbaselineofthefont.All
acceptanumericvalueexpressedinems.Allrequirethatyouspecifytheunits-
per-emdescriptor,too.
Thebboxdescriptoracceptsexactlytwocoordinate(X,Y)pairs,specifyingthe
lower-leftandupper-rightcornersofthefont'sboundingbox.Thebboxdescriptor
isimportantifthebrowserchoosestosynthesizeafontbasedonthisfont.By
specifyingthesizeoftheboundingbox,youensurethatthesynthesizedfont
occupiesthesamespaceasthedesiredone.
Thewidthsdescriptoracceptsacomma-separatedlistofUnicoderanges,followed
byspace-separatedvalueswhichdefinethewidthsofthecharactersinthe
indicatedrange.Ifyousupplyonevalueforarange,allthecharactersinthat
rangehavethesamewidth.Multiplevaluesareassignedtosuccessivecharacters
inarange.Likethebboxdescriptor,thewidthsdescriptorisusedtoensuregood
fidelitybetweenasynthesizedfontanditsrequestedcounterpart.
Finally,theoptionaldefinitions-srcdescriptorprovidestheURLofafilethat
containsallofthedescriptorsforafont.Thisishandyifyouneedtodefineafont
ingreatdetail.Insteadofincludingthelengthydescriptorsineachdocumentor
stylesheetthatusesthefont,youdefinethedescriptorsonceinaseparatefile
andreferencethatfileusingthedefinitions-srcdescriptor.
8.4.5.ColorandBackgroundProperties
Everyelementinyourdocumenthasaforegroundandabackgroundcolor.In
somecases,thebackgroundisnotonecolor,butacolorfulimage.Thecolorand
backgroundstylepropertiescontrolthesecolorsandimages.
ThechildrenofanHTML/XHTMLelementnormallyinherittheforegroundcolorof
theirparent.Forinstance,ifyoumake<body>textred,thestyles-conscious
browseralsodisplaysheaderandparagraphtextinred.
Backgroundpropertiesbehavedifferently,howevertheyarenotinherited.Instead,
eachelementhasadefaultbackgroundthatistransparent,allowingtheparent's
backgroundtoshowthrough.Thus,settingthebackgroundimageofthe<body>tag
doesnotcausethatimagetobereloadedforeveryelementwithinthebodytag.
Instead,thebrowserloadstheimageonceanddisplaysitbehindtherestofthe
document,servingasthebackgroundforallelementsthatdonotthemselves
haveanexplicitbackgroundcolororimage.
Allthecurrentpopularbrowserssupportthefollowingbackgroundandcolor
properties.
8.4.5.1.Thebackground-colorproperty
Thebackground-colorpropertycontrolsthe(youguessedit!)backgroundcolorofan
element.Setittoacolorvalueortothekeywordtransparent(thedefaultvalue).
Theeffectsshouldbeobvious.
Whileyoumayhavebecomeaccustomedtosettingthebackgroundcolorofan
entiredocumentthroughthespecialattributesforthe<body>tag,youcanapply
thebackground-colorstylepropertytoanyelement.Forexample,tosetthe
backgroundcolorofoneiteminabulletedlist,youcoulduse:
<listyle="background-color:blue">
Similarly,youcouldgiveallthetableheadercellsinadocumentasnapshot
negativeeffectwith:
th{background-color:black;color:white}
Ifyoureallywantyouremphasizedtexttostandout,paintitsbackgroundred:
em{background-color:red}
8.4.5.2.Thebackground-imageproperty
Thebackground-imagepropertyputsanimagebehindthecontentsofanelement.Its
valueiseitheraURLorthekeywordnone(thedefaultvalue).
Aswithbackgroundcolors,youcanplaceabackgroundimagebehindtheentire
documentorbehindselectedelementsofadocument.Withthisstyleproperty,
effectssuchasplacinganimagebehindatableorselectedtextarenowsimple:
<tablestyle="background-image:url(backgrounds/woodgrain.gif)">
li.marble{background-image:url(backgrounds/marble.gif)}
Thefirstexampleusesaninlinestyletoplaceawoodgrainfinishbehindatable.
Theseconddefinesalist-itemclassthatplacesamarblebackgroundbehind<li>
tagsthatusetheclass=marbleattribute.Forexample,thisXHTMLsnippet:
<h2>Here'swhat'sfordinnertonight:</h2>
<ul>
<liclass="marble">LiverwithOnions</li>
<liclass="marble">MashedPotatoesandGravy</li>
<liclass="marble">GreenBeans</li>
<liclass="marble">ChoiceofMilk,Tea,orCoffee</li>
</ul>
<h2>Andfordessert:</h2>
<ul>
<li>CreamedQuatsinMilk(YUM!YUM!)</li>
</ul>
producesaresultlikethatinFigure8-6.
Figure8-6.Placingabackgroundimagebehindanelement
Iftheimageislargerthanthecontainingelement,itisclippedtothearea
occupiedbytheelement.Iftheimageissmaller,itisrepeatedtotilethearea
occupiedbytheelement,asdictatedbythevalueofthebackground-repeatattribute.
Youcontrolthestartingpositionoftheimagewithintheelementwiththe
background-positionproperty.Thebackground-attachmentpropertymanagesthescrolling
behavioroftheimage.
Whileitmayseemthatabackgroundcolorandabackgroundimagearemutually
exclusive,youshouldusuallydefineabackgroundcolorevenifyouareusinga
backgroundimage.Thatway,iftheimageisunavailableforexample,whenthe
userdoesn'tautomaticallydownloadimagesthebrowserdisplaysthebackground
colorinstead.Inaddition,ifthebackgroundimagehastransparentareas,the
backgroundcolorisusedtofillinthoseareas.
8.4.5.3.Thebackground-attachmentproperty
Ifyouspecifyabackgroundimageforanelement,usethebackground-attachment
propertytocontrolhowthatimageisattachedtothebrowser'sdisplaywindow.
Withthedefaultvaluescroll,thebrowsermovesthebackgroundimagewiththe
elementastheuserscrollsthroughthedocument.Avalueoffixedpreventsthe
imagefrommoving.
8.4.5.4.Thebackground-positionproperty
Bydefault,thestyles-consciousbrowserbeginsrenderingabackgroundimage
startingintheupper-leftcorneroftheallotteddisplayarea.Withthebackground-
positionproperty,youcanoffsetthestartingpositionofthebackgroundimageby
anabsolute(length)orrelative(percentageorkeyword)offset.Theresulting,
potentially"cropped,"imagefillstheareafromthatoffsetstartingpoint.
Youmayspecifyoneortwovaluesforthebackground-positionproperty.Ifyouusea
singlevalue,itappliestoboththeverticalandhorizontalpositions.Withtwo
values,thefirstisthehorizontaloffsetandthesecondistheverticaloffset.
Lengthvalues(withtheirappropriateunits;seesection8.4.1.2,earlierinthis
chapter)indicateanabsolutedistancefromtheupper-leftcorneroftheelement
behindwhichyoudisplaythebackgroundimage.Negativelengthvalues
effectivelycropthecorrespondingtopandleftsidesoftheimagewithinthe
allottedviewport,justasanimagethatistoobigforthebrowser'swindowgets
croppedonthebottomandrightsides.
Forexample:
table{background-image:url(backgrounds/marble.gif);
background-position:10px20px}
offsetsthemarblebackground10pixelstotherightand20pixelsdownfromthe
upper-leftcornerofany<table>elementinyourdocument.
Percentagevaluesareabittrickierbutsomewhateasiertouse.Measuredfrom0
percentto100percentfromlefttorightandtoptobottom,thecenterofthe
element'scontentdisplayspaceisat50%,50%.Similarly,thepositionone-third
ofthewayacrosstheareaandtwo-thirdsofthewaydownisat33%,66%.So,to
offsetthebackgroundforourexampledinnermenutothecenteroftheelement's
contentdisplayspace,weuse:[*]
[*]Interestingly,thispropertyworkedasadvertisedwithInternetExplorerversions4and5butisbrokeninversion6,asit
iswithotherpopularbrowsers:theoffsetworksonlyifyousetthebackground-repeatproperty.
background-position:50%
Whyuseanumberwhenasinglewordwilldo?Youcanusethekeywordsleft,
center,andright,aswellastop,center,andbottom,for0%,50%,and100%,respectively.
Tocenteranimageinthetag'scontentarea,use:
background-position:center
Youcanmixandmatchlengthandpercentagevalues,[ ]too,sothat:
[ ]Thatis,ifthebrowsersupportsthevalueunits.Sofar,InternetExplorerandNetscapesupportonlyameager
repertoireoflengthunitspixelsandpercents.
background-position:1cm50%
placestheimageonecentimetertotherightofthetag'sleftedge,centered
verticallyinthetag'sarea.
Notethatwithrelativeoffsets,theimagemovesrelativetothetag'scontents
whentheuserresizesthebrowserdisplaywindowbecausethespaceallottedto
thecontentalsogetsresized.Bycontrast,theimagestaysinthesameplace
relativetotheelement'scontentsifyouuseabsoluteoffsetvalues.
Finally,onemightalsoexpectthattherepeatingbackground(bydefault;seethe
followingsection,8.4.5.5)wouldtiledownandtotherightoftheoffset.Notso.
Currentbrowsers"wrap"theimagearoundtofilltheelement'sallotteddisplay
space.Forexample,lookcloselyatFigure8-7andnoticethetilingeffectsforan
offsetversusnonoffsetbackgroundimagedisplayedfromthefollowingexample
stylefragments:
<styletype=css/text>
<!--
pre{background-image:url(backgrounds/vert.gif)}
pre.offset{background-image:url(backgrounds/vert.gif);background-position:-20px
-20px}
-->
</style>
...
Thefollowingbackgroundimageisoffsetby-20pixelsleftandup:
<preclass=offset>
</pre>
<p>
Thisbackgroundimageisnotoffset:
<pre>
</pre>
Figure8-7.Background-offsetwithtiling
8.4.5.5.Thebackground-repeatproperty
Normally,thebrowsertilesabackgroundimagetofilltheallottedspace,
repeatingtheimagebothhorizontallyandvertically.Usethebackground-repeat
propertytoalterthisrepeat(defaultvalue)behavior.Tohavetheimagerepeat
horizontallybutnotvertically,usethevaluerepeat-x.Foronlyverticalrepetition,
userepeat-y.Tosuppresstilingaltogether,useno-repeat.
Acommonuseofthispropertyistoplaceawatermarkorlogointhebackground
ofapagewithoutrepeatingtheimageoverandover.Forinstance,thiscode
placesthewatermarkimageinthebackgroundatthecenterofthepage:
body{background-image:url(backgrounds/watermark.gif);
background-position:centercenter;
background-repeat:no-repeat
}
Apopulartrickistocreateaverticalribbondowntherighthandsideofthepage:
body{background-image:url(backgrounds/ribbon.gif);
background-position:topright;
background-repeat:repeat-y
}
8.4.5.6.Thebackgroundproperty
Likethevariousfontproperties,themanybackgroundCSS2propertiescanget
cumbersometowriteandhardtoreadlater.So,likethefontproperty,thereis
alsoageneralbackgroundproperty.
Thebackgroundpropertyacceptsvaluesfromanyandallofthebackground-color,
background-image,background-attachment,background-repeat,andbackground-position
properties,inanyorder.Ifyoudonotspecifyvaluesforsomeoftheproperties,
thosepropertiesareexplicitlysettotheirdefaultvalues.Thus:
background:red
setsthebackground-colorpropertytoredandresetstheotherbackground
propertiestotheirdefaultvalues.Amorecomplexexample:
background:url(backgrounds/marble.gif)bluerepeat-yfixedcenter
setsallthebackgroundimageandcolorpropertiesatonce,resultinginamarble
imageontopofabluebackground(blueshowingthroughanytransparentareas).
Theimagerepeatsvertically,startingfromthecenterofthecontentdisplayarea,
anddoesnotscrollwhentheuserscrollsthedisplay.Noticethatweincludejusta
singlepositionvalue(center),andthebrowserusesitforboththeverticaland
horizontalpositions.
8.4.5.7.Thecolorproperty
Thecolorpropertysetstheforegroundcolorforatag'scontentsthecolorofthe
textlettering,forinstance.Itsvalueiseitherthenameofacolor,ahexadecimal
RGBtriple,oradecimalRGBtriple,asoutlinedearlierinsection8.4.1.5.The
followingareallvalidpropertydeclarations:
color:mauve
color:#ff7bd5
color:rgb(255,125,213)
color:rgb(100%,49%,84%)
Generally,you'llusethecolorpropertywithtext,butyoumayalsomodify
nontextualcontentofatag.Forinstance,thefollowingexampleproducesagreen
horizontalrule:
hr{color:green}
Ifyoudon'tspecifyacolorforanelement,itinheritsthecolorofitsparent
element.
8.4.6.TextProperties
Cascadingstylesheetsmakeadistinctionbetweenfontproperties,whichcontrol
thesize,style,andappearanceoftext,andtextproperties,whichcontrolhow
textisalignedandpresentedtotheuser.
8.4.6.1.Theletter-spacingproperty
Theletter-spacingpropertyputsadditionalspacebetweentextlettersastheyare
displayedbythebrowser.Setthepropertywitheitheralengthvalueorthe
defaultkeywordnormal,indicatingthatthebrowsershouldusenormalletter
spacing.Forexample:
blockquote{letter-spacing:2px}
putsanadditionaltwopixelsbetweenadjacentletterswithinthe<blockquote>tag.
Figure8-8illustrateswhathappenswhenyouputfivepixelsbetweencharacters.
Figure8-8.Theletter-spacingpropertyletsyoustretchtext
Allthepopularbrowserssupportthisproperty.
8.4.6.2.Theline-heightproperty
Usetheline-heightpropertytodefinetheminimumspacingbetweenlinesofa
tag'stextcontent.Normally,browserssingle-spacetextlinesthetopofthenext
lineisjustafewpointsbelowthelastline.Byaddingtothatlineheight,you
increasetheamountofspacebetweenlines.
Theline-heightvaluecanbeanabsoluteorarelativelength,apercentage,a
scalingfactor,orthekeywordnormal.Forexample:
p{line-height:14pt}
p{line-height:120%}
p{line-height:2.0}
Thefirstexamplesetsthelineheighttoexactly14pointsbetweenbaselinesof
adjacentlinesoftext.Thesecondcomputesthelineheightto120percentofthe
fontsize.Thelastexampleusesascalingfactortosetthelineheighttotwiceas
largeasthefontsize,creatingdouble-spacedtext.Thevaluenormal,thedefault,is
usuallyequaltoascalingfactorof1.0to1.2.
Keepinmindthatabsoluteandpercentagevaluesforline-heightcomputetheline
heightbasedonthevalueofthefont-sizeproperty.Childrenoftheelementinherit
thecomputedpropertyvalue.Subsequentchangestofont-sizebyeitherthe
parentorthechildelementsdonotchangethecomputedlineheight.
Scalingfactors,ontheotherhand,defertheline-heightcomputationuntilthe
browseractuallydisplaysthetext.Hence,varyingfontsizesaffectlineheight
locally.Ingeneral,itisbesttouseascalingfactorfortheline-heightpropertyso
thatthelineheightchangesautomaticallyasthefontsizechanges.
Althoughitisusuallyconsideredseparatefromfontproperties,youmayinclude
thistext-relatedline-heightproperty'svalueaspartoftheshorthandnotationof
thefontproperty.[Thefontproperty,8.4.3.8]
8.4.6.3.Thetext-alignproperty
Textjustifiedwithrespecttothepagemarginsisarudimentaryfeatureofnearly
alltextprocessors.Thetext-alignpropertybringsthatcapabilitytoHTMLforany
block-leveltag.(TheW3CstandardspeoplepreferthatyouuseCSS2text-align
stylesratherthantheexplicitalignattributeforblock-leveltagssuchas<div>and
<p>.)Useoneoffourvalues:left,right,center,orjustify.Thedefaultvalueis,of
course,left.[*]
[*]Forleft-to-rightlocales.Inright-to-leftlocales,thedefaultisright.
Forexample:
div{text-align:right}
tellsthestyles-consciousbrowsertoalignallthetextinside<div>tagsagainstthe
rightmargin.Thejustifyvaluetellsthebrowsertoalignthetexttoboththeleft
andrightmargins,spreadingthelettersandwordsinthemiddletofit.
Allthepopularbrowserscurrentlysupporttheleft,right,andcenteralignments,
butnotjustify.
8.4.6.4.Thetext-decorationproperty
Thetext-decorationpropertyproducestextembellishments,someofwhicharealso
availablewiththeoriginalphysicalstyletags.Itsvalueisoneormoreofthe
keywordsunderline,overline,line-through,andblink.Thevaluenoneisthedefault,
whichtellsthestyles-consciousbrowsertopresenttextnormally.
Thetext-decorationpropertyishandyfordefiningdifferentlinkappearances:
a:visited,a:link,a:active{text-decoration:underlineoverline}
Thisputslinesaboveandbelowthelinksinyourdocument.
Thistextpropertyisnotinherited,andnontextualelementsarenotaffectedby
thetext-decorationproperty.
Interestingly,allthepopularbrowserssupportthetext-decorationproperty,but
onlyInternetExplorerhasthegoodtastenottosupportitsblinkvalue.
8.4.6.5.Thetext-indentproperty
Althoughlesscommontoday,itisstillstandardpracticetoindentthefirstlineof
aparagraphoftext.[*]Andsometextblocks,suchasdefinitions,typically"out-
dent"thefirstline,creatingwhatiscalledahangingindent.
[*]Butnot,obviously,inthisbook.
TheCSS2text-indentpropertyletsyouapplythesefeaturestoanyblocktagand
therebycontroltheamountofindentationofthefirstlineoftheblock.Uselength
andpercentagevalues:negativevaluescreatethehangingindent,and
percentagevaluescomputetheindentationasapercentageoftheparent
element'swidth.Thedefaultvalueis0.
Toindentalltheparagraphsinyourdocument,forexample,youcoulduse:
p{text-indent:3em}
Thelengthunitemscalestheindentasthefontoftheparagraphchangesinsize
ondifferentbrowsers.
Hangingindentsareabittrickier,becauseyouhavetowatchoutfortheelement
borders.Negativeindentationdoesnotshifttheleftmarginofthetext;itsimply
shiftsthefirstlineoftheelementleft,possiblyintothemargin,border,orpadding
oftheparentelement.Forthisreason,hangingindentsworkasexpectedonlyif
youalsoshifttheleftmarginoftheelementtotherightbyanamountequaltoor
greaterthanthesizeofthehangingindent.Forexample:
p.wrong{text-indent:-3em}
p.hang{text-indent:-3em;margin-left:3em}
p.large{text-indent:-3em;margin-left:6em}
createsthreeparagraphstyles.Thefirstcreatesahangingindentthatextends
intotheleftmargin,thesecondcreatesaconventionalhangingindent,andthe
thirdcreatesaparagraphwhosebodyisindentedmorethanthehangingindent.
Figure8-9showsallthreestylesinuse.
Figure8-9.Theeffectsoftext-indentandmargin-leftona
paragraph
Allthepopularbrowserssupportthetext-indentproperty.
8.4.6.6.Thetext-shadowproperty
Thetext-shadowpropertyletsyougiveyourtextathree-dimensionalappearance
throughthetime-honoreduseofshadowing.Valuesforthepropertyincludea
requiredoffsetandoptionalblurradiusandcolor.Thepropertymayincludemore
thanonesetofvalues,separatedwithcommas,toachieveastackofshadows,
witheachsubsequentsetofvalueslayeredontopofthepreviousonebutalways
beneaththeoriginaltext.
Theproperty'srequiredoffsetiscomposedoftwolengthvalues:thefirstspecifies
thehorizontaloffset,andthesecondspecifiestheverticaloffset.Positivevalues
placetheshadowtotherightandbelowtherespectivelengthdistancefromthe
text.Negativevaluesmovetheshadowleftandup,respectively.
Theoptionalblurradiusisalsoalengthvaluethatspecifiestheboundariesfor
blurring,aneffectthatdependsontherenderingagent.Theothershadowvalue
iscolor.This,ofcourse,maybeanRGBtripleorcolorname,asforother
properties,andspecifiestheshadowcolor.Ifyoudon'tspecifythisvalue,text-
shadowusesthecolorvalueofthecolorproperty.Forexample:
h1{text-shadow;10px10px2pxyellow}
p:first-letter{text-shadow:-5px-5pxpurple,10px10pxorange}
Thefirsttext-shadowexampleputsa2-pixelblurred-yellowshadowbehind,10
pixelsbelow,and10pixelstotherightoflevel-1headersinyourdocument.The
secondexampleputstwoshadowsbehindthefirstletterofeachparagraph.The
purpleshadowsits5pixelsaboveand5pixelstotheleftofthatfirstletter.The
othershadow,likeinthefirstexample(althoughorangeinthiscase),goes10
pixelstotherightand10pixelsbelowthefirstletterofeachparagraph.
Unfortunately,wecan'tshowyouanyoftheseeffects,becausenoneofthe
popularbrowserssupportsthisproperty.
8.4.6.7.Thetext-transformproperty
Thetext-TRansformpropertyletsyouautomaticallyconvertportionsorallofyour
document'stextintouppercaseorlowercaselettering.Acceptablevaluesare
capitalize,uppercase,lowercase,andnone.
capitalizerendersthefirstletterofeachwordinthetextintouppercase,evenif
thesourcedocument'stextisinlowercase.Theuppercaseandlowercasevalues
respectivelyrenderallthetextinthecorrespondingcase.none,ofcourse,cancels
anytransformations.Forexample:
h1{text-transform:uppercase}
formatsallthelettersinlevel-1headers,presumablytitles,inuppercasetext,
whereas:
h2{text-transform:capitalize}
makessurethateachwordinlevel-2headersbeginswithacapitalletter,a
conventionthatmightbeappropriateforsectionheads,forinstance.
Notethatwhileuppercaseandlowercaseaffecttheentiretext,capitalizeaffectsonly
thefirstletterofeachwordinthetext.Consequently,transformingtheword
"htMl"withcapitalizegenerates"HtMl."
Allthepopularbrowserssupportthetext-TRansformproperty.
8.4.6.8.Thevertical-alignproperty
Thevertical-alignpropertycontrolstherelativepositionofanelementwith
respecttothelinecontainingtheelement.Validvaluesforthispropertyinclude:
baseline
Alignthebaselineoftheelementwiththebaselineofthecontainingelement.
middle
Alignthemiddleoftheelementwiththemiddle(usuallythex-height)ofthe
containingelement.
sub
Subscripttheelement.
super
Superscripttheelement.
text-top
Alignthetopoftheelementwiththetopofthefontoftheparentelement.
text-bottom
Alignthebottomoftheelementwiththebottomofthefontoftheparent
element.
top
Alignthetopoftheelementwiththetopofthetallestelementinthecurrent
line.
bottom
Alignthebottomoftheelementwiththebottomofthelowestelementinthe
currentline.
Inaddition,apercentagevalueindicatesapositionrelativetothecurrent
baselinesothatapositionof50%putstheelementhalfwayupthelineheight
abovethebaseline.Apositionvalueof-100%putstheelementanentireline
heightbelowthebaselineofthecurrentline.
Allthepopularbrowsersagreeonwheretoplaceimagesrelativetoalineoftext
forbaseline(defaultandthesameasnovertical-alignspecification),middle(butnot
center),super(butnotsub),text-top,text-bottom,top(sameastext-top;butnot
bottom),andforbothplusandminuspercentageoffsetvalues.Figure8-10shows
youhowInternetExplorertreatsthevariousvertical-alignvalues.
Figure8-10.InternetExplorer'streatmentofthevertical
alignmentpropertyvalues
Forthedifferences,FirefoxtreatscenterlikeInternetExploreranddifferentfrom
middle(Figure8-10),whereasNetscapetreatscenteridenticaltomiddle,butOpera
doesn'trecognizethevalueatall.Withsub,it'sNetscape'sturntoagreewith
Firefoxandplacethebottomofthesubscriptedimageatthebottomofthe
characterdescender,whereasOperaplacesthebottomoftheimageperceptively
belowthebaseline,butunlikeInternetExplorer,notsolowastobejustabove
thenextlineoftext.
Withthebottomvalue,it'sOpera'sturntoagreewithInternetExplorer,aligningthe
bottomoftheimagewiththebottomofthelinejustabovethenextlineoftext,
whereasFirefoxandNetscapeplacethebottomoftheimageatthebottomofthe
characterdescender.Clearasmud?PerhapsFigures8-11through8-13willhelp
youtovisualizethedifferenceswhenalsocomparedwithFigure8-10.
Figure8-11.Firefox'srenderingofselectedvertical-alignvalues
Figure8-12.Opera'srenderingofselectedvertical-alignvalues
Figure8-13.Netscape'srenderingofselectedvertical-align
values
8.4.6.9.Theword-spacingproperty
Usetheword-spacingpropertytoaddspacebetweenwordswithinatag.Youcan
specifyalengthvalue,orusethekeywordnormaltoreverttonormalword
spacing.Forexample:
h3{word-spacing:25px}
placesanadditional25pixelsofspacebetweenwordsinthe<h3>tag.
Allthecurrentlypopularbrowserssupporttheword-spacingproperty.
8.4.7.BoxProperties
TheCSS2modelassumesthatHTMLandXHTMLelementsalwaysfitwithin
rectangularboxes.Usingthepropertiesdefinedinthissection,youcancontrol
thesize,appearance,andpositionoftheboxescontainingtheelementsinyour
documents.
8.4.7.1.TheCSS2formattingmodel
Eachelementinadocumentfitsintoarectangularspaceorbox.TheCSS2
authorscallthisboxthecorecontentareaandsurrounditwiththreemore
boxes:thepadding,theborder,andthemargin.Figure8-14showstheseboxes
anddefinessomeusefulterminology.
Figure8-14.TheCSS2formattingmodelandterminology
Thetop,bottom,left-outer,andright-outeredgesboundthecontentareaofan
elementandallofitspadding,border,andmarginspaces.Theinner-top,inner-
bottom,left-inner,andright-inneredgesdefinethesidesofthecorecontentarea.
Theextraspacearoundtheelementistheareabetweentheinnerandouter
edges,includingthepadding,border,andmargin.Abrowsermayomitanyandall
oftheseextraspacesforanyelement,andformany,theinnerandouteredges
arethesame.
Whenelementsareverticallyadjacent,thebottommarginoftheupperelements
andthetopmarginofthelowerelementsoverlapsothatthetotalspacebetween
theelementsisthegreateroftheadjacentmargins.Forexample,ifone
paragraphhasabottommarginof1inch,andthenextparagraphhasatop
marginof0.5inches,thegreaterofthetwomargins,1inch,isplacedbetween
thetwoparagraphs.Thispracticeisknownasmargincollapsingandgenerally
resultsinbetterdocumentappearance.
Horizontallyadjacentelementsdonothaveoverlappingmargins.Instead,the
CSS2modeladdstogetheradjacenthorizontalmargins.Forexample,ifa
paragraphhasaleftmarginof1inchandisadjacenttoanelementwitharight
marginof0.5inches,thetotalspacebetweenthetwois1.5inches.Thisrulealso
appliestonestedelementssothataparagraphwithinadivisionhasaleftmargin
equaltothesumofthedivision'sleftmarginandtheparagraph'sleftmargin.
AsshowninFigure8-14,thetotalwidthofanelementisequaltothesumof
sevenitems:theleftandrightmargins,theleftandrightborders,theleftand
rightpadding,andtheelement'scontentitself.Thesumofthesesevenitems
mustequalthewidthofthecontainingelement.Ofthesesevenitems,onlythree
(theelement'swidthanditsleftandrightmargins)canbegiventhevalueauto,
indicatingthatthebrowsercancomputeavalueforthatproperty.Whenthis
becomesnecessary,thebrowserfollowstheserules:
Ifnoneofthesepropertiesissettoautoandthetotalwidthislessthanthe
widthoftheparentelement,themargin-rightpropertyissettoautoandmade
largeenoughtomakethetotalwidthequaltothewidthoftheparent
element.
Ifexactlyonepropertyissettoauto,thatpropertyismadelargeenoughto
makethetotalwidthequaltothewidthoftheparentelement.
Ifwidth,margin-left,andmargin-rightaresettoauto,theCSS2-compliant
browsersetsbothmargin-leftandmargin-rightto0andsetswidthlargeenough
tomakethetotalequaltothewidthoftheparentelement.
Ifboththeleftandrightmarginsaresettoauto,theyarealwayssettoequal
values,centeringtheelementwithinitsparent.
Therearespecialrulesforfloatingelements.Afloatingelement(suchasan
imagewithalign=leftspecified)doesnothaveitsmarginscollapsedwiththe
marginsofcontainingorprecedingelements,unlessthefloatingelementhas
negativemargins.Figure8-15showshowthefollowingbitofHTMLmightbe
rendered:
<body>
<p>
<imgalign=leftsrc="pics/img.gif">
Somesampletext...
</body>
Figure8-15.Handlingthemarginsoffloatingelements
Thebrowsermovestheimage,includingitsmargins,asfaraspossibletotheleft
andtowardthetopoftheparagraphwithoutoverlappingtheleftandtopmargins
oftheparagraphorthedocumentbody.Theleftmarginsoftheparagraphandthe
containingbodyareadded,andtheirtopmarginsarecollapsed.
8.4.7.2.Theborderproperties
Thebordersurroundinganelementhasacolor,athickness,andastyle.Youcan
usevariouspropertiestocontrolthesethreeaspectsoftheborderoneachofthe
foursidesofanelement.Shorthandpropertiesmakeiteasytodefinethesame
color,thickness,andstylefortheentireborder,ifdesired.Borderpropertiesare
notinherited;youmustexplicitlysetthemforeachelementthathasaborder.
8.4.7.3.Theborder-colorproperty
Usetheborder-colorpropertytosetthebordercolor.Ifthispropertyisnot
specified,thebrowserdrawstheborderusingthevalueoftheelement'scolor
property.
Theborder-colorpropertyacceptsfromonetofourcolorvalues.Thenumberof
valuesdetermineshowtheyareappliedtotheborders(summarizedinTable8-1).
Ifyouincludejustonepropertyvalue,allfoursidesoftheborderaresettothe
specifiedcolor.Twovaluessetthetopandbottomborderstothefirstvalueand
theleftandrightborderstothesecondvalue.Withthreevalues,thefirstisthe
topborder,thesecondsetstherightandleftborders,andthethirdcolorvalueis
forthebottomborder.Fourvaluesspecifycolorsforthetop,right,bottom,and
leftborders,inthatorder.
Table8-1.Orderofeffectsformultipleborder,margin,andpaddingpropertyvalues
Numberofvalues Affectedborder(s),margin(s),orpadding
1 Allitemshavethesamevalue.
2 Thefirstvaluesetstopandbottom;thesecondvaluesetsleftandright.
3 Thefirstvaluesetstop;thesecondsetsbothleftandright;thethirdvaluesetsbottom.
4 Thefirstvaluesetstop;thesecondsetsright;thethirdsetsbottom;thefourthvaluesetsleft.
8.4.7.4.Theborder-widthproperty
Theborder-widthpropertyletsyouchangethewidthoftheborder.Liketheborder-
colorproperty,itacceptsfromonetofourvaluesthatareappliedtothevarious
bordersinasimilarmanner(refertoTable8-1).
Besidesaspecificlengthvalue,youmayalsospecifythewidthofaborderasone
ofthekeywordsthin,medium,orthick.Thedefaultvalue,ifthewidthisnot
explicitlyset,ismedium.Sometypicalborderwidthsare:
border:1px
border:thinthickmedium
border:thick2mm
Thefirstexamplesetsallfourborderstoexactly1pixel.Thesecondmakesthe
topborderthin,therightandleftbordersthick,andthebottombordermedium.The
lastexamplemakesthetopandbottombordersthickandtherightandleft
borders2millimeterswide.
Ifyouareuncomfortabledefiningallfourborderswithoneproperty,youcanuse
theindividualborder-top-width,border-bottom-width,border-left-width,andborder-right-
widthpropertiestodefinethethicknessofeachborder.Eachpropertyacceptsjust
onevalue;thedefaultismedium.
Allthecurrentlypopularbrowserssupportthisproperty.
8.4.7.5.Theborder-styleproperty
AccordingtotheCSS2model,youmayapplyanumberofembellishmentstoyour
HTMLelementborders.
Theborder-stylepropertyvaluesincludenone(default),dotted,dashed,solid,double,
groove,ridge,inset,andoutset.Theborder-style-consciousbrowserappliesoneto
fourvaluesforthepropertytoeachborder,inthesameorderasfortheborder
colorsandwidths,asdescribedinTable8-1.
Thebrowserdrawsdotted,dashed,solid,anddoublebordersasflatlinesontopof
thetag'sbackground.Thegroove,ridge,inset,andoutsetvaluescreatethree-
dimensionalborders:thegrooveisanincisedline,theridgeisanembossedline,
theinsetbordermakestheentiretagareaappearsetintothedocument,andthe
outsetbordermakestheentiretagareaappearraisedabovethedocument.The
effectofthethree-dimensionalnatureoftheselastfourstylesonthetag's
backgroundimageisundefinedandleftuptothebrowser.Netscapesupports
three-dimensionaleffects.
Allthecurrentlypopularbrowserssupporttheborderstyles.Anexampleisshown
inFigure8-16.
Figure8-16.Theborder-stylepropertynicelyframesimages
8.4.7.6.Bordersinshorthand
Specifyingacomplexbordercangettedious,sotheCSS2standardprovidesfive
shorthandpropertiesthatacceptanyorallofthewidth,color,andstylevaluesfor
oneoralloftheborderedges.Theborder-top,border-bottom,border-left,andborder-
rightpropertiesaffecttheirrespectiveborders'sides;thecomprehensiveborder
propertycontrolsallfoursidesofthebordersimultaneously.Forexample:
border-top:thicksolidblue
border-left:1exinset
border-bottom:bluedashed
border:reddouble2px
Thefirstpropertymakesthetopborderathick,solid,blueline.Thesecondsets
theleftbordertouseaninseteffectthatisasthickasthex-heightofthe
element'sfont,whileleavingthecolorthesameastheelement'scolor.Thethird
propertycreatesabluedashedlineatthebottomoftheelement,usingthe
defaultmediumthickness.Finally,thelastpropertymakesallfourbordersared
doubleline,2pixelsthick.
Thatlastpropertyraisestwoissues.First,youcannotsupplymultiplevaluesto
theborderpropertytoselectivelyaffectcertainborders,asyoucanwiththe
individualborder-color,border-width,andborder-styleproperties.Theborderproperty
alwaysaffectsallfourbordersaroundanelement.
Second,abitofreflectionshouldrevealthatitisnotpossibletocreateadouble-
lineborderjust2pixelsthick.Incaseslikethis,thebrowserisfreetoadjustthe
thicknesstorendertheborderproperly.
Whileweusuallythinkofborderssurroundingblockelementssuchasimages,
tables,andtextflows,youalsocanapplyborderstoinlinetags.Thisletsyouput
aboxaroundawordorphrasewithinatextflow.Theimplementationofborders
oninlinetagsthatspanmultiplelinesisundefinedandlefttothebrowser.
Allofthecurrentlypopularbrowserssupporttheborderstyles.
8.4.7.7.Theclearproperty
Likeitscousinattributeforthe<br>tag,theclearpropertytellsthebrowser
whethertoplaceatag'scontentsadjacenttoa"floating"elementoronthefirst
linebelowit.Textflowsaroundfloatingelementssuchasimagesandtableswith
analign=leftoralign=rightattributeoranyHTML/XHTMLelementwithitsfloat
propertysettoanythingbutnone.[<br>,4.6.1][Thefloatproperty,8.4.7.9]
Thevalueoftheclearpropertycanbenone,left,right,orboth.Avalueofnone,the
default,meansthatthebrowseractsnormallyandplacesthetag'scontents
adjacenttofloatingelementsoneitherside,ifthereisroomtodoso.Thevalue
leftpreventscontentsfrombeingplacedadjacenttoafloatingelementonitsleft;
rightpreventsplacementontherightsideofafloatingelement;andbothprevents
thetag'scontentsfromappearingadjacenttoanyfloatingelement.
Theeffectofthisstyleisthesameasprecedingthetagwitha<br>tagwithits
clearattributeset.Hence:
h1{clear:left}
hasthesameeffectasprecedingevery<h1>tagwith<brclear=left>.
8.4.7.8.Theclipproperty
Normally,thecontentofanelementiscompletelyvisiblewithinthedisplayspace
oftheelement.Theclippropertydefinesaviewingwindowwithinanelement's
displayspace,lettingyouhideunwantedelementsandfocusattentiononsome
areaoraspectofthecontent.
Thedefaultvalueoftheclippropertyisauto,meaningthattheviewingwindow
matchestheboxoftheelement.Instead,youmayspecifyashapethatcreatesa
distinctviewingwindowintotheelement'sdisplayarea.Currently,theonlyshape
supportedbyCSS2[*]isarectangle,denotedbytherectkeyword.Forexample:
[*]Presumably,futureversionsofthestandardwillexpandtoincludeothershapes.
p{overflow:hidden;
clip:rect(15px,-10px,5px,10px)}
Thefourvaluesdefinethetop,right,bottom,andleftedgesoftheclipping
rectangle.Eachvalueisanoffsetrelativetotheboxedgesdefinedforthe
element.So,inthisexample,thetopoftheclippingareais15pixelsbelowthe
topoftheelement'sbox,therightedgeis10pixelstotherightofthebox,the
bottomis5pixelsabovethebottomofthebox,andtheleftedgeis10pixelsto
therightoftheleftsideofthebox.
Notethattheclippropertytakeseffectonlywhentheoverflowpropertyofan
elementissettosomevalueotherthanvisible.Whenoverflowissettovisible,no
clippingoccursandtheclippropertyisignored.
Thepopularbrowsersdon'tyetsupporttheclipproperty.
8.4.7.9.Thefloatproperty
Thefloatpropertydesignatesatag'sdisplayspaceasafloatingelementand
causestexttoflowarounditinaspecifiedmanner.Itisgenerallyanalogousto
thealignattributeforimagesandtables,butyoucanapplyittoanyelement,
includingtext.[Thealignattribute(deprecated),10.2.1.1]
Thefloatpropertyacceptsoneofthreevalues:left,right,ornone(thedefault).
Usingnonedisablesthefloatproperty.Theothersworkliketheiralignattribute-
valuecounterparts,tellingthebrowsertoplacethecontenttoeithersideofthe
flowandallowothercontenttoberenderednexttoit.
Accordingly,thebrowserplacesatag'scontents(includingitsmargins,padding,
andborders)specifiedwithfloat:leftagainsttheleftmarginofthecurrenttext
flow,andsubsequentcontentflowstoitsright,downandbelowthetag's
contents.Thefloat:rightpairputsthetagcontentsagainsttherightedgeofthe
flowandflowsothercontentonitsleft,downandbelowthetag'scontents.
Althoughthefloatpropertyismostcommonlyusedwithtablesandimages,itis
perfectlyacceptabletoapplyittoatextelement.Forexample,thefollowing
createsa"run-in"header,withthetextflowingaroundtheheadertext,asshown
inFigure8-17:
h2{float:left;
text-align:center;
margin-right:10px}
Figure8-17.Usethefloatpropertywithtextblockstocreate
run-inheaders
Allthepopularbrowserssupportthisproperty.
8.4.7.10.Theheightproperty
Asyoumightsuspect,theheightpropertycontrolstheheightoftheassociated
tag'sdisplayregion.You'llfinditmostoftenusedwithimagesandtables,butyou
canuseittocontroltheheightofotherdocumentelementsaswell.
Thevalueoftheheightpropertyiseitheralengthvalueorthekeywordauto(the
default).Usingautoimpliesthattheaffectedtaghasaninitialheightthatshould
beusedwhendisplayingthetag.Otherwise,theheightofthetagissettothe
desiredheight.Ifanabsolutevalueisused,theheightissettothatlengthvalue.
Forexample:
img{height:100px}
tellsthebrowsertodisplaytheimagereferencedbythe<img>tagscaledsothatit
is100pixelstall.Ifyouusearelativevalue,thebasesizetowhichitisrelativeis
browserandtagdependent.
Whenscalingelementstoaspecificheight,youcanpreservetheaspectratioof
theobjectbyalsosettingthewidthpropertyofthetagtoauto.Thus:
img{height:100px;width:auto}
ensuresthattheimagesarealways100pixelstall,withanappropriatelyscaled
width.[Thewidthproperty,8.4.7.16]
Ifyouwanttoconstraintheheightofanelementtoarangeratherthanaspecific
value,usethemin-heightandmax-heightproperties.Thesepropertiesacceptvalues
liketheheightpropertyandestablisharangefortheheightoftheelement.The
browserthenadjuststheheightoftheelementtofallwithinthedesiredrange.
Allofthepopularbrowsersfullysupporttheheightproperty,butnoneofthe
browsersyetsupportsthemin-heightandmax-heightproperties.
8.4.7.11.Themarginproperties
Liketheborderproperties,thevariousmarginpropertiesletyoucontrolthe
marginspacearoundanelement,justoutsideofitsborder(seeFigure8-14).
Marginsarealwaystransparent,allowingthebackgroundcolororimageofthe
containingelementtoshowthrough.Asaresult,youcanspecifyonlythesizeof
amargin;ithasnocolororrenderedstyle.
Themargin-left,margin-right,margin-top,andmargin-bottompropertiesallaccepta
lengthorpercentagevalueindicatingtheamountofspacetoreservearoundthe
element.Inaddition,thekeywordautotellsthestyles-consciousbrowsertorevert
tothemarginsitnormallywouldplacearoundanelement.Percentagevaluesare
computedasapercentageofthecontainingelement'swidth.Thedefaultmargin,
ifnotspecified,is0.
Theseareallvalidmarginsettings:
body{margin-left:1in;margin-top:0.5in;margin-right:1in}
p{margin-left:-0.5cm}
img{margin-left:10%}
Thefirstexamplecreates1-inchmarginsdowntherightandleftedgesofthe
entiredocumentanda0.5-inchmarginacrossthetopofthedocument.The
secondexampleshiftstheleftedgeofthe<p>tag0.5centimetersleft,intotheleft
margin.Thelastexamplecreatesamargintotheleftofthe<img>tagequalto10
percentoftheparentelement'swidth.
Asyoucantheshorthandborderproperty,youcanusetheshorthandmargin
propertytodefineallfourmargins,usingfromonetofourvalues,whichaffect
themarginsintheorderdescribedinTable8-1.Usingthisnotation,our<body>
marginsinthepreviousexamplecouldalsohavebeenspecifiedas:
body{margin:0.5in1in}
Themargin-leftandmargin-rightpropertiesinteractwiththewidthpropertyto
determinethetotalwidthofanelement,asdescribedearlierinsection8.4.7.1.
Allthepopularbrowserssupportthemarginpropertiesandvalues.
8.4.7.12.Thepaddingproperties
Likethemarginproperties,thevariouspaddingpropertiesletyoucontrolthe
paddingspacearoundanelement,betweentheelement'scontentareaandits
border(seeFigure8-14,earlierinthechapter).
Paddingalwaysisrenderedusingthebackgroundcolororimageoftheelement.
Asaresult,youcanspecifyonlythesizeofthepadding;ithasnocoloror
renderedstyle.
Thepadding-left,padding-right,padding-top,andpadding-bottompropertiesallaccepta
lengthorpercentagevalueindicatingtheamountofspacethestyles-conscious
browsershouldreservearoundtheelement.Percentagevaluesarecomputedasa
percentageofthecontainingelement'swidth.Paddingcanneverbenegative.The
defaultpaddingis0.
Thesearevalidpaddingsettings:
p{padding-left:0.5cm}
img{padding-left:10%}
Thefirstexamplecreates0.5centimetersofpaddingbetweenthecontentsofthe
<p>taganditsleftborder.Thesecondexamplecreatespaddingtotheleftofthe
<img>tagequalto10percentoftheparentelement'swidth.
Liketheshorthandmarginandborderproperties,youcanusetheshorthandpadding
propertytodefineallfourpaddingamounts,usingfromonetofourvaluesto
affectthepaddingsidesasdescribedinTable8-1.InternetExplorerdoesnot
supportthepaddingproperty,butalltheotherpopularbrowsersdo.
8.4.7.13.Theoverflowproperty
Theoverflowpropertytellsthebrowserhowtohandlecontentthatoverflowsthe
displayareaofanelement.Thedefaultvalueofthisproperty,visible,tellsthe
browsertorenderallcontent,makingitvisibleevenifitfallsoutsideofthe
element'sdisplayarea.
Erringonthesideofcaution,youmostoftenwantthebrowsertodisplayallof
yourdocument'scontents.Butinrarecases,elementsmayoverlap,creatingan
uglydisplay.Topreventsuchmishaps,settheoverflowpropertytoeitherhidden,
scroll,orauto.
Thehiddenvalueforcesthebrowsertohideallcontentthatoverflowsitsallotted
space,makingitinvisibletotheuser.Thevaluescrollcreatesscrollbarsforthe
element,whichviewersmayusetoseethehiddencontent.However,scrollbars
areaddedtotheelementevenifthecontentdoesnotoverflow.
Addingpermanentscrollbarsensuresthatthescrollbarsdonotcomeandgoas
thecontentoftheelementchangesinsizeinadynamicdocument.Thedownside
tothisistheclutteranddistractionsthatscrollbarscreate.Avoidallthiswiththe
autovaluefortheoverflowproperty.Whenonauto,scrollbarsappearonlywhen
theyareneeded.Iftheelement'scontentchangessothatitisnotclipped,the
scrollbarsareremovedfromtheelement.
Noneofthecurrentlypopularbrowserssupportstheoverflowproperty.
8.4.7.14.Thepositionproperties
Withoutintervention,thebrowserflowsdocumentelementstogether,positioned
sequentiallythroughthedisplay.Youcanchangethisstandardbehaviorwiththe
CSS2positionproperty,inconjunctionwiththetop,bottom,left,andright
properties.
Ifthepositionpropertyissettostatic,conventionalHTML/XHTMLlayoutand
positioningrulesapply,withtheleftandtopedgesoftheelement'sbox
determinedbythebrowser.Toshiftanelementwithrespecttoitscontainingflow,
setthepositionpropertytorelative.Inthiscase,thetop,bottom,left,andright
propertiesareusedtocomputetheboxpositionrelativetoitsnormalpositionin
theflow.Subsequentelementsarenotaffectedbythispositionchangeandare
placedintheflowasthoughthiselementhadnotbeenshifted.
Settingthepositionpropertytoabsoluteremovestheelementfromthecontaining
flow,allowingsubsequentelementstomoveupaccordingly.Thepositionofthe
elementisthencomputedrelativetothecontainingblock,usingthetop,bottom,
left,andrightproperties.Thistypeofpositioningallowsanelementtobeplaced
inafixedpositionwithrespecttoitscontainingelementbuttomoveasthat
containingelementmoves.
Finally,settingthepositionpropertytofixedpositionsanelementwithrespectto
thewindoworpageinwhichitisdisplayed.Likeabsolutepositioning,theelement
isremovedfromthecontainingflow,withotherelementsshiftingaccordingly.The
top,bottom,left,andrightpropertiesareusedtosettheelement'spositionwith
respecttothecontainingwindoworpage.Notethatforcontinuousmedia(such
asascrollingbrowserdisplay),theelementisdisplayedonceatthedesired
position.Forprintedmedia,theelementisprintedoneachpageatthedesired
position.Youmightusedfixedpositioningtoplaceheadersandfootersatthetop
andbottomofthebrowserwindoworatthetopandbottomofeachprintedpage.
Thetop,bottom,left,andrightpropertieseachacceptalengthorpercentage
value.Whenthepositionattributeissettorelative,thepercentageisbasedonthe
sizeoftheelement'sbox.Whenpositionissettoabsoluteorfixed,thepercentage
isbasedonthesizeofthecontainingelement'sbox.Whenlengthvaluesare
used,theyspecifyoffsetsfromthecorrespondingedgeoftheelement'scontaining
box.Forexample,topositionanelementsuchthatitsbottomis1centimeter
abovethebottomofthebrowserwindow(oreachprintedpage),youwouldset
thepositionpropertytofixedandthebottompropertyto1cm.
8.4.7.15.Thevisibilityproperty
Thevisibilitypropertydetermineswhetherthecontentsofanelementarevisible
inthedisplay.Thespacesetasidefortheelementisstillcreatedandaffectsthe
layoutofthedocument,butthecontentoftheelementmaybemadeinvisible
withinthatspace.
Thedefaultvalueforthisproperty,visible,causestheelement'scontenttobe
displayed.Settingthispropertytohiddenmakesthecontentinvisiblewithout
removingtheelement'sdisplaybox,alteringthelayoutofthedocument.Note
thatyoucanremoveanelement'scontentanddisplayboxfromthedocumentby
settingthedisplaypropertytonone.
Thispropertyisoftenusedindynamicdocuments,wherechangingitsvaluefor
anelementremovesitscontentfromthedisplaywithoutreformattingthe
document.
Whenthispropertyisusedinconjunctionwithtablerows,rowgroups,columns,
andcolumngroups,youmayalsospecifythevaluecollapse.Usedinthiscontext,
thecollapsevalueremovestheassociatedrow(s)orcolumn(s)fromthetable
withoutotherwisereformattingorredrawingthetable.Withindynamic
documents,thisletsyouremoveelementsfromatablewithoutreformattingthe
entiretable.Usedoutsideofatable,thecollapsevaluehasthesameeffectasthe
hiddenvalue.
8.4.7.16.Thewidthproperty
Thewidthpropertyisthecompaniontotheheightpropertyandcontrolsthewidth
ofanassociatedtag.Specifically,itdefinesthewidthoftheelement'scontent
area,asshowninFigure8-8.You'llseeitmostoftenusedwithimagesandtables,
butyoucouldconceivablyuseittocontrolthewidthofotherelementsaswell.
Thevalueforthewidthpropertyiseitheralengthorpercentagevalue,orthe
keywordauto.Thevalueautoisthedefaultandimpliesthattheaffectedtaghasan
initialwidththatshouldbeusedwhendisplayingthetag.Ifalengthvalueis
used,thewidthissettothatvalue;percentagevaluescomputethewidthtobea
percentageofthewidthofthecontainingelement.Forexample:
img{width:100px}
displaystheimagereferencedbythe<img>tagscaledto100pixelswide.
Whenscalingelementstoaspecificwidth,theaspectratiooftheobjectis
preservediftheheightpropertyofthetagissettoauto.Thus:
img{width:100px;height:auto}
makesalltheimages100pixelswideandscalestheirheightsappropriately.[The
heightproperty,8.4.7.10]
Ifyouwanttoconstrainthewidthofanelementtoarangeratherthanaspecific
value,usethemin-widthandmax-widthproperties.Thesepropertiesacceptvalues
likethewidthpropertyandestablisharangeforthewidthoftheelement.The
browserthenadjuststhewidthoftheelementtofallwithinthedesiredrange.
Thewidthpropertyinteractswiththemargin-leftandmargin-rightpropertiesto
determinethetotalwidthofanelement,asdescribedearlierinsection8.4.7.1.
8.4.7.17.Thez-indexproperty
Inadditiontothexandypositionsofanelementwithinthebrowserwindowor
ontheprintedpage,eachelementhasavertical,orz,position.Elementswith
higherzpositionsare"closer"totheviewerandobscureelementsunderneath
them.
Zpositionsarenotabsolutethroughoutadocument.Instead,zpositionsare
relativetothecontainingelement.Forexample,two<div>elementswithina
documentmightbepositionedtolieontopofoneanother.Thefirst<div>might
haveazpositionof1,andthesecondmighthaveazpositionof2.Theentire
contentsofthesecond<div>aredisplayedover(orinfrontof)thefirst<div>.If
elementswithinthefirst<div>havezpositionsof3or4,theyarestilldisplayed
withintheircontaining<div>sanddonot"jumpout"infrontofthesecond<div>.
Youcontrolthezpositionofanelementwiththez-indexproperty.Thevalueofthe
z-indexpropertyisapositiveintegerthatsetsthezpositionoftheelementwith
respecttoitscontainingelement.Withthez-indexproperty,youcandynamically
alterthezpositionofanelementtomakeitvisible,orpositionatextelementin
frontofanimagetolabelitemsofinterest.
8.4.8.ListProperties
TheCSS2standardalsoletsyoucontroltheappearanceoflist
elementsspecifically,orderedandunorderedlists.Browsersformatlistitemsjust
likeanyotherblockitem,exceptthattheblockhassomesortofmarker
precedingthecontents.Forunorderedlists,themarkerisabulletofsomesort;
fornumberedlists,themarkerisanumericoralphabeticcharacterorsymbol.
TheCSS2listpropertiesletyoucontroltheappearanceandpositionofthe
markerassociatedwithalistitem.
8.4.8.1.Thelist-style-imageproperty
Thelist-style-imagepropertydefinestheimagethatthebrowserusestomarka
listitem.ThevalueofthispropertyistheURLofanimagefileorthekeyword
none.Thedefaultvalueisnone.
Theimageisthepreferredlistmarker.Ifitisavailable,thebrowserdisplaysitin
placeofanyotherdefinedmarker.Iftheimageisunavailable,oriftheuserhas
disabledimageloading,thebrowserusesthemarkerdefinedbythelist-style-type
property(seesection8.4.8.3,laterinthischapter).
HTML/XHTMLauthorsusethelist-style-imagepropertytodefinecustombulletsfor
theirunorderedlists.Whileyouconceivablycoulduseanyimageasabullet,we
recommendthatyoukeepyourmarkerGIForJPEGimagessmall,toensure
attractivelyrenderedlists.
Forexample,byplacingthedesiredbulletimageinthefilemybullet.gifonyour
server,youcouldusethatimage:
li{list-style-image:url(pics/mybullet.gif);list-style-type:square}
Inthiscase,thebrowserusestheimageifitisabletosuccessfullydownload
mybullet.gif.Otherwise,thebrowserusesaconventionalsquarebullet.
Allthepopularbrowserssupportthelist-style-imageproperty,asshowninFigure
8-18.
Figure8-18.Thelist-style-imagepropertyletsyouuseyourown
bullets
8.4.8.2.Thelist-style-positionproperty
Therearetwowaystopositionthemarkerassociatedwithalistitem:insidethe
blockassociatedwiththeitemoroutsidetheblock.Accordingly,thelist-style-
positionpropertyacceptsoneoftwovalues:insideoroutside.
Thedefaultvalueisoutside,meaningthattheitemmarkerhangstotheleftofthe
item,likethis:
•Thisisabulleted
list
withan"outside"marker
Thevalueinsidecausesthemarkertobedrawnwiththelistitemflowingaround
it,muchlikeafloatingimage:
•Thisisabulletedlist
withan"inside"marker
Noticethatthesecondlineoftextisnotindentedbutinsteadlinesupwiththe
leftedgeofthemarker.
Thecurrentversionsofthepopularbrowsersfullysupportthelist-style-position
property.
8.4.8.3.Thelist-style-typeproperty
Thelist-style-typepropertyservesdoubledutyinasense,determininghowa
styles-consciousbrowserrendersbothorderedandunorderedlistitems.The
propertyhasthesameeffectasthetypeattributeonalistitem.[Thetype
attribute,6.7.2.4]
Whenappliedtoitemswithinanunorderedlist,thelist-style-typepropertyuses
oneoffourvaluesdisc,circle,square,ornoneandmarkstheunorderedlistitems
withacorrespondingdingbat.Thedefaultvalueofalevel-1listitemisdisc,
althoughbrowserschangethatdefaultdependingonthenestinglevelofthelist.
Whenappliedtoitemswithinanorderedlist,thelist-style-typepropertyusesone
ofsixvaluesdecimal,lower-roman,upper-roman,lower-alpha,upper-alpha,or
nonecorrespondingtotheitemnumbersexpressedasdecimalvalues,lowercase
Romannumerals,uppercaseRomannumerals,lowercaseletters,uppercase
letters,orwithnostyle,respectively.Mostbrowsersusedecimalnumberingas
thedefault.
Thepopularbrowserssupportlist-style-typeaswellasthelist-styleproperty
describedinthenextsection.
8.4.8.4.Thelist-styleproperty
Thelist-stylepropertyistheshorthandversionforalltheotherlist-style
properties.Itacceptsanyorallofthevaluesallowedforthelist-style-type,list-
style-position,andlist-style-imageproperties,inanyorderandwithvalues
appropriateforthetypeoflisttheyaretoaffect.Thesearevalidlist-style
properties:
li{list-style:disc}
li{list-style:lower-romaninside}
li{list-style:url(http://www.kumquat.com/images/tiny-quat.gif)square}
Thefirstexamplecreateslistitemsthatuseadiscasthebulletimage.The
secondcausesnumberedlistitemstouselowercaseRomannumerals,drawn
insidethelistitem'sblock.Inthelastexample,thestyles-consciousbrowseruses
asquareasthebulletimageifthereferencedimageisunavailable.
8.4.8.5.Usinglistpropertieseffectively
Althoughyoucanapplylistpropertiestoanyelement,theyaffectonlythe
appearanceofelementswhosedisplaypropertyissettolist-item.Normally,the
onlytagwiththispropertyisthe<li>tag.
However,thisshouldn'tdeteryoufromusingthesepropertieselsewhere,
particularlywiththe<ul>and<ol>tags.Becausethesepropertiesareinheritedby
elementswhoseparentshavethemset,modifyingalistpropertyforthe<ul>and
<ol>tagssubsequentlymodifiesitforallthe<li>tagscontainedwithinthatlist.
Thismakesitmucheasiertodefinelistswithaparticularappearance.
Forexample,supposeyouwanttocreatealiststylethatuseslowercaseRoman
numerals.Onewayistodefineaclassofthe<li>tagwiththeappropriatelist-
style-typedefined:
li.roman{list-style-type:lower-roman}
Withinyourlist,you'llneedtospecifyeachlistelementusingthatclass:
<ol>
<liclass=roman>Itemone
<liclass=roman>Itemtwo
<liclass=roman>Andsoforth
</ol>
Havingtorepeattheclassnameistediousanderror-prone.Abettersolutionisto
defineaclassofthe<ol>tag:
ol.roman{list-style-type:lower-roman}
Any<li>tagwithinthelistinheritsthepropertyanduseslowercaseRoman
numerals:
<olclass=roman>
<li>Itemone
<li>Itemtwo
<li>Andsoforth
</ol>
Thisismucheasiertounderstandandmanage.Ifyouwanttochangethe
numberingstylelater,youneedonlychangethe<ol>tagproperties,insteadof
findingandchangingeachinstanceofthe<li>taginthelist.
Youcanusethesepropertiesinamuchmoreglobalsense,too.Settingalist
propertyonthe<body>tagchangestheappearanceofalllistsinthedocument;
settingitona<div>tagchangesallthelistswithinthatdivision.
8.4.9.TableProperties
Forthemostpart,HTML/XHTMLbrowsersrendertablecontentusingthesame
propertiesthatcontroltherenderingofconventionaldocumentcontent.However,
afewspecialcircumstancesoccuronlywithintables.Togiveauthorsgreater
controlovertheseitems,CSS2hasaddedafewtable-specificproperties.The
popularbrowsersdonotyetsupportanyofthem.
8.4.9.1.Theborder-collapse,border-spacing,andempty-cellsproperties
Therearetwodivergentviewsregardingcellborderswithintables.Thefirstview
holdsthateachcellisanindependententitywithuniqueborders.Thesecond
viewholdsthatadjacentcellssharethebordersideandthatchangingaborderin
onecellshouldaffecttheneighboringcell.
Togivethemostcontroltoauthors,CSS2providestheborder-collapseproperty,
whichletsyouchoosethemodelthatsuitsyourstyle.Bydefault,thevalueofthis
propertyiscollapse,meaningadjacentcellssharetheirborderstyle.Alternatively,
youcansettheborder-collapsepropertytoseparate,whichenlargesthetablesothat
bordersarerenderedseparatelyanddistinctlyaroundeachcell.
Ifyouchoosetheseparatemodel,youcanalsousetheborder-spacingpropertytoset
thespacingbetweenadjacentborders.Thedefaultborderspacingis0,meaning
thatadjacentcellborderstoucheachother,althoughsomebrowsersmayusea
differentdefault.Byincreasingthisvalue,youcausethebrowsertoinsert
additionalspacebetweenborders,allowingthebackgroundcolororimageofthe
tabletoshowthrough.Ifyouspecifyjustonevalueforborder-spacing,itsetsthe
spacingforbothhorizontalandverticalborders.Ifyouprovidetwovalues,the
firstsetsthehorizontalspacingandtheseconddeterminestheverticalspacing.
Withintheseparatemodel,youcanalsocontrolhowbordersaredrawnaround
emptycells.Bydefault,bordersaredrawnaroundeverycellinatable,evenifit
hasnocontent.Youcanchangethisbyswitchingtheempty-cellspropertyfromits
defaultvalueofshowtothevaluehide.Whenthispropertyisset,emptycells
simplyshowthetablebackground.Ifawholerowofcellsisempty,thebrowser
removestherowfromthetableentirely.
8.4.9.2.Thecaption-sideproperty
Usethecaption-sidepropertyonlywiththe<caption>element.Itacceptsvaluesof
top(default),bottom,left,orright,andtellsthebrowserwheretoplacethecaption
adjacenttoitsassociatedtable.Thecaption-sidepropertyprovidesamore
consistentmethodofplacingthecaptionthanthebrowser-dependentand
standards-deprecatedalignattributeofthe<caption>tag.
Allofthepopularbrowsers,exceptInternetExplorer,supportcaption-side.
8.4.9.3.Thespeak-headerproperty
Anaudio-capablebrowsermightofferanumberofwaysforuserstonavigateby
hearingthecontentsofatable.Asimplisticapproachwouldhavethebrowser
readthetablecontentsinorder,fromtoptobottomandrighttoleft.Amore
sophisticatedaudiobrowserorganizesthetablecontentsaccordingtotheir
respectiveheadersandreadstheinformationinamorecomprehensiblemanner.
Toavoidconfusioninanycase,thebrowsermustprovidesomewaytotellthe
userwhichcellitisreading.
Thespeak-headerpropertyprovidestwowaysforabrowsertoidentifyacellor
collectionofcellsinthetable.Ifonce(thedefault)isspecified,thebrowserreads
thecontentsofaheadercellonlyoncebeforeproceedingtoreadthecontentsof
eachassociateddatacell.Thisway,ausermovingacrossarowofcellswould
heartherowheaderandcolumnheaderofthefirstcellintherow,butwould
hearthechangingcolumnheadersonlyasshemovedtosubsequentcellsinthe
row.
Ifyousetthespeak-headerpropertytoalways,thebrowserprefacesthereadingof
eachcell'scontentswithareadingofitsassociatedheader.Thismayprovemore
usefulwithcomplextablesorwheretheheadervaluesmakeiteasierto
understandthetablecontentsespeciallywhenatablecontainsonlynumbers.
Notethatheadersarespokenonlywhenthebrowserknowswhichheadercells
areassociatedwithwhichdatacells.Conscientiousauthorsalwaysusetheheader
attributewiththeirtablecells,tospecifytheheadercellsrelatedtoeachdatacell
intheirtables.
8.4.9.4.Thetable-layoutproperty
Tablelayoutisatoughtaskforanybrowser.Tocreateanattractivetable,the
browsermustfindthewidestcellineachcolumn,adjustthatcolumnto
accommodatethewidth,andthenadjusttheoveralltabletoaccommodateallof
itscolumns.Forlargetables,documentrenderingcanbenoticeablyslowedasthe
browsermakesseveralpassesoverthetable,tryingtogetthingsjustright.
Tohelpinthisprocess,usethetable-layoutproperty.Ifyousetthepropertyto
fixed,thebrowserdeterminescolumnwidthsbasedonthewidthsofcellsinthe
firstrowofthetable.Ifyouexplicitlysetthecolumnwidths,settingthetable's
table-layoutpropertytofixedmakesthetable-renderingprocessevenfaster,
enhancingthereaders'experienceastheyviewyourdocument.
Bydefault,thetable-layoutpropertyissettoauto,whichforcesthebrowsertouse
themoretime-consuming,multiple-passlayoutalgorithm,evenifyouspecifythe
widthsofyourcolumnsinthetable.Ifyourtablecontentisvariableandyou
cannotexplicitlysetthewidths,leavethetable-layoutpropertysettoauto.Ifyou
canfixyourcolumnwidthsandyourtablecontentisamenable,settable-layoutto
fixed.
8.4.10.ClassificationProperties
ClassificationpropertiesarethemostfundamentaloftheCSS2styleproperties.
Theydonotdirectlycontrolhowastyles-consciousbrowserrendersHTMLor
XHTMLelements.Instead,theytellthebrowserhowtoclassifyandhandle
varioustagsandtheircontentsastheyareencountered.
Forthemostpart,youshouldnotsetthesepropertiesonanelementunlessyou
aretryingtoachieveaspecificeffect.
8.4.10.1.Thedisplayproperty
EveryelementinanHTMLorXHTMLdocumentcanbeclassified,fordisplay
purposes,asablockitem,aninlineitem,oralistitem.Blockelements,like
headings,paragraphs,tables,andlists,areformattedasseparateblocksoftext,
separatefromtheirpreviousandfollowingblockitems.Inlineitems,likethe
physicalandcontent-basedstyletagsandhyperlinkanchors,arerenderedwithin
thecurrentlineoftextwithinacontainingblock.Listitems,specifically<li>-
taggedcontent,arerenderedlikeblockitems,withaprecedingbulletornumber
knownasamarker.
Thedisplaypropertyletsyouchangeanelement'sdisplaytypetoblock,inline,
list-item,ornone.Thefirstthreevalueschangetheelement'sclassification
accordingly;thevaluenoneturnsofftheelement,preventingitanditschildren
frombeingdisplayedinthedocument.
Conceivably,youcouldwreakallsortsofhavocbyswitchingelement
classifications,forcingparagraphstobedisplayedaslistitemsandconverting
hyperlinkstoblockelements.Inpractice,thisisjustpuerilemonkeybusiness,
andwedon'trecommendthatyouchangeelementclassificationswithoutavery
goodreasontodoso.
Allthepopularbrowserssupportthisproperty,butInternetExplorersupportsonly
theblockandnonevalues.
8.4.10.2.Thewhite-spaceproperty
Thewhite-spacepropertydefineshowthestyles-consciousbrowsertreats
whitespace(tabs,spaces,andcarriagereturns)withinablocktag.Thekeyword
valuenormalthedefaultcollapseswhitespacesothatoneormorespaces,tabs,and
carriagereturnsaretreatedasasinglespacebetweenwords.Thevaluepre
emulatesthe<pre>tag,inthatthebrowserretainsanddisplaysallspaces,tabs,
andcarriagereturns.Finally,thenowrapvaluetellsthebrowsertoignorecarriage
returnsandnotinsertautomaticlinebreaks;alllinebreakingmustbedonewith
explicit<br>tags.
Likethedisplayproperty,thewhite-spacepropertyisrarelyusedforgoodpurposes.
Don'tchangehowelementshandlewhitespacewithoutacompellingreasonfor
doingso.
InternetExploreronlysupportsthenowrapvalue,andtheotherpopularbrowsers
supportbothpreandnowrapvaluesforthewhite-spaceproperty.
8.4.11.GeneratedContentProperties
TheideaofgeneratedcontentisnotnewtoHTML.Eventheearliestbrowsers
automaticallyappendedappropriatebulletsornumberstoenhancethereadability
ofyourunorderedandorderedlistitems.Suchfeaturesarehardlyenough,
though,andauthorshavewishedforbettercontent-generationtoolsinHTML.
CSS2finallycomesthrough,givingauthorstheabilitytocreatearbitrarycontent,
numberedlists,andallsortsofelement-basedcontent.
ThefoundationoftheCSS2generated-contentmodelisthecontentandquotes
properties,alongwiththe:beforeand:afterpseudoelements.Youusetheformer
todefinethecontentyouneed,andusethelattertopositionthatcontentwith
respecttotheelementsinyourdocument.
8.4.11.1.The:beforeand:afterpseudoelements
Weintroducedyoutopseudoelementsearlierinthischapter,andyouevensaw
someinaction(refertoFigures8-2and8-3).The:beforeand:after
pseudoelementsoperatesimilarly.Appendeithertoastyle-elementselectorto
selectandspecifythecontentandpropertiesofgeneratedcontentinyour
document.Ingeneral,anycontentcreatedwithinthesepseudoelementsinherits
thedisplayattributesoftheparentelement,suchthatfonts,sizes,andcolors
appliedtoanelementarealsoappliedtoitsgeneratedcontent.Forexample:
p.note{color:blue}
p.note:before{content:"Note:"}
ThisstyleexampleinsertsthewordNote:beforeevery<pclass=note>element.The
insertedtextisrenderedinblue,liketherestoftheparagraph.Replacingitwith
thisstylewouldcolortheinsertedtextred,andtheremainderofthenotewould
beblue:
p.note:before{content:"Note:";color:red}
Anygeneratedcontent,beforeorafteranelement,isincludedintheboxofan
elementandaffectsitsformatting,flow,size,andlayout.
8.4.11.2.Thecontentproperty
Thecontentpropertyacceptsawidevarietyofvalues,rangingfromsimplestrings
toautomaticcounterreferences.Youcanincludeanynumberofthesevalues,
separatedbyspaces,inasinglecontentproperty.Thebrowserconcatenatesthe
valuestoformasinglevaluethatittheninsertsintothedocument.
Thesimplestofcontentvaluesisaquote-enclosedstring.Youmaynotinclude
HTMLorXHTMLmarkupinthestring.Rather,useescapesequencestogenerate
specialtext(e.g.,\A,whichgeneratesalinebreak).
CSS2escapesequencesarelikeHTML/XHTMLcharacterentities.Whereas
characterentitiesbeginwiththeampersand(&),followedbythenameordecimal
valueofacharacter(#suffixforthelatter),youcreatethesamecharactersfor
CSS2string-contentpropertyvaluesbyprecedingthehexadecimalequivalentof
thecharacterwithabackslash(\).Theescapesequence\Aisthesameasthe
characterentity
,which,ifyouconsultAppendixF,you'llfindistheline-feed
character.
ThecontentpropertyalsoacceptsURLvalues.Expressedinstyles,notHTML-like
fashion,theURLmaypointtoanyobjectacceptabletothebrowser,including
text,images,andsoundfiles.Forexample,toplaceadecorativesymbolnextto
eachequationinadocument,youmightuse:
p.equation:before{content:url("http://www.kumquat.com/decorative-symbol.jpg")}
Keepinmindthattheobjectshouldn'tcontainHTML/XHTMLmarkupbecausethe
browserinsertsitscontentsverbatimintothedocument.
Thecontentpropertyalsosupportsautomaticgenerationofcontextuallycorrect,
locale-specificquotationmarks.Youinsertthemusingtheopen-quoteandclose-quote
keywords.Thesekeywordsinserttheappropriatequotationmarkandincrement
ordecrement,respectively,thebrowser'snestedquotationcounter.Youcan
controltheappearanceofthequotationmarksusingthequotesproperty,described
shortly.Youmayalsousetheno-open-quoteandno-close-quotekeywords,which
incrementordecrementthenestingdepthwithoutinsertingaquotationmark.
Acleverfeatureofthecontentpropertyisitsabilitytohavethebrowserrender
thevalueofanyattributeofitsassociatedelement.Theattrvaluehasasingle
parameter,correspondingtothenameofanattribute.Ifthatattributeisdefined
fortheelement,itsvalueisinsertedintothedocument.TodisplaytheURLofan
imageaftertheimage,forinstance,youmightwrite:
img:after{content:"("attr(src)")"}
Iftheattributeisnotdefinedfortheelement,nocontentgetsinserted,although
theothervaluesforthecontentproperty(liketheparenthesesweincludedinthe
earlierexample)wouldstillbeinserted.
Oneofthemostpowerfulfeaturesofthecontentpropertyisitsabilitytocreate
numberedlists.Wecoverthisindetailintheupcomingsection,8.4.11.4.
Allthepopularbrowserssupportthe:beforeand:afterpseudoelements,but
InternetExplorerdoesnotsupportthecontentproperty.
8.4.11.3.Specifyingquotationmarks
Whileyouinsertquotationmarksusingtheopen-quoteandclose-quotevalueswith
thecontentproperty,youcontroltheactualcharactersusedforquotationmarks
withthequotesproperty.
Thevalueofthispropertyisoneormorepairsofstrings.Thefirstpairdefinesthe
openandclosequotationmarksfortheoutermostlevelofquotationsinyour
document.Thenextpairspecifiesthenextlevel,andsoforth.Ifthequotation
levelexceedsthesuppliedpairsofcharacters,thebrowserstartsoverwiththe
outermostpair.Notethatwhilemostlanguagesusesinglecharactersasquotation
marks,youcanspecifystringsofanylengthtobeusedasquotationmarks.
Youmayalsowanttospecifyalternativequotationmarksbasedonthelanguage
used.Youcanusethe:langpseudoelementtoassociatedifferentquotesproperties
withdifferentlanguages.Forexample:
q:lang(en){quotes:'"''"'"'""'"}
q:lang(no){quotes:" "" ""<"">"}
ensuresthatEnglishandNorwegiandocumentsusetheirrespectivequotation
marks.
8.4.11.4.Creatingcounters
YoucancreatesimplenumberedlistseasilyinHTMLandXHTMLwiththe<ol>
element.Morecomplexnumberedlists,especiallynestednumberedlists,are
impossiblewiththemarkuplanguages,though.Instead,CSS2providesthenotion
ofacounterwhosevaluecanbesetandchangedasthebrowserrendersyour
document.Insertthevalueofthecounterusingspecialfunctionsrecognizedby
thecontentproperty,andaltertheappearanceandformatofthecounterwith
otherCSS2properties.
EveryCSS2counterhasaname.Tocreateacounter,simplymentionitsnamein
thecounter-resetorcounter-incrementpropertiesassociatedwithanyelement.Ifan
instanceofthatnamedcounterdoesnotalreadyexistinthecurrentdocument
nestinglevel,theCSS2-consciousbrowserautomaticallycreatesit.Thereafter,set
orresetthevalueofthecounterasneeded.Forexample,supposewewanttouse
<h1>elementsaschapterheadings,with<h2>elementsassectionheadings.Both
chaptersandsectionsarenumbered,withsectionheadingsbeingresetwitheach
newchapter.Youcanachievethiswith:
h1:before{counter-increment:chapter;counter-reset:section}
h2:before{counter-increment:section}
WhentheCSS2-consciousbrowserencountersthefirst<h1>elementinthe
document,itcreatesboththechapterandsectioncountersandresetstheirvalues
to0.Atthesametime,andforeveryencounterthereafter,theCSS2-conscious
browserenactsthecounter-incrementpropertytosetthechaptercounterto1,
representingChapter1,then2,andsoon.As<h2>elementsareencountered
withinachapter,thesectioncountergetsincrementedaccordingtotheh2style
rule,numberingeachsectioninorder.Notice,too,thatthesectioncountergets
resetbytheh1rulesothatthesectioncounterrestartsforeachchapter.[*]
[*]Noteherethatthebrowserdoesn'tdisplaycountersunlessyouexplicitlytellitto.See"Usingcountersinyour
documents."
Boththecounter-resetandcounter-incrementpropertiesacceptlistsofcounternames,
lettingyouresetorincrementgroupsofcountersinoneproperty.Youcanalso
supplyanumericvalueafteracounternamesothatwithcounter-reset,the
countergetsinitializedtothatspecifiedvalue,andcounter-incrementaddsthevalue
tothecurrentcountervalue.Negativenumbersareallowed,too,sothatyoumay
countdown,ifdesired.
Forexample,ifwewantourdocumenttobeginwithChapter7andwewant
sectionnumberstoincreaseby2,wemightrewritethepreviousexampleas
follows:
body{counter-reset:chapter6}
h1:before{counter-increment:chapter;counter-reset:section}
h2:before{counter-increment:section2}
Noticehowwecreatedthechaptercounterintheearliestpossibleelementinour
document,usingavalueonelessthanthedesiredfirstvalue.Whenthebrowser
encountersthefirst<h1>element,itcreates,setsto6,andthenincrementsthe
chaptercounter.
Thescopeofacounternameisthenestinglevelinwhichitisdefined;itisnot
necessarilydocument-wide.Ifyouusethesamecounternameinachildelement,
thebrowsercreatesanewinstanceofthecounteratthatlevel.Inourexample,
allthe<h1>and<h2>elementsexistatthesamenestinglevel,sooneinstanceof
thechapterandsectioncountersservesthatwholelevel.Ifyounesteda<div>tagin
thatelement,whichinturncontained<h1>and<h2>elements,newinstancesof
bothcounterswouldbecreatedatthatnewlevel.
Thisnestingbehavioriscriticalfornestednumberedliststowork.Ifyouassociate
acounterwiththe<li>elementandthennestseveralorderedlists,eachlistlevel
hasitsowninstanceofthecounter,withseparatenumbersequencesateach
level.
8.4.11.5.Usingcountersinyourdocuments
Creatingcountersisoflittleuseifyoudon'tdisplaytheirvaluesinyour
documents.Thedisplayisnotautomatic.Toshowacounter,usethespecial
counter()andcounters()valuesinthecontentproperty.
Thecounter()valuerequiresthenameofacounterinsideitsparentheses,withan
optionalformatspecification.Thebrowserthendisplaysthevalueofthespecified
counterwithinthegeneratedcontentintheformatdesired.Theformatcanbe
anylistformatacceptedbythelist-style-typeproperty,asdescribedearlierin
section8.4.8.3.
Forexample,toactuallydisplaythenumbersofournumberedchaptersand
sections,weexpandourstylerulesforthe<h1>and<h2>elements:
h1:before{counter-increment:chapter;
counter-reset:section;
content:"Chapter"counter(chapter)":"}
h2:before{counter-increment:section;
content:"Section"counter(section)":"}
Then,whentheCSS2-consciousbrowserencountersthisinthedocument:
<h1>KumquatGrowers</h1>
itrendersitasshowninFigure8-19.TonumberourchaptersusingRoman
numerals,wewouldchangethepropertiesto:
h1:before{counter-increment:chapter;
counter-reset:section;
content:"Chapter"counter(chapter,upper-roman)":"}
h2:before{counter-increment:section;
content:"Section"counter(section,lower-roman)":"}
Thecounter()valueisthevalueofthecounteratthecurrentnestinglevel.To
accessallthevaluesofthesame-namedcounteratallnestinglevels,usethe
pluralcounters()valueinstead.Includethecounternameintheparenthesesand
aseparatorstring.Thebrowserputstheseparatorstringbetweeneachlistof
valuesforthecounterinthedisplay.Youmayalsosupplyaformattypetoswitch
fromthedefaultdecimalnumbering.
Figure8-19.UseCSS2counterstoautomaticallynumber
chaptersandsections
Thecounters()valueismostusefulwhencreatingnestednumberedlists.Consider
theseproperties:
ol{counter-reset:item}
li:before{counter-increment:item;
content:counters(item,".")}
Ifyounestseveral<ol>elementsinyourdocument,each<li>includesallthe
nestedvalues,separatedbyperiods.Thisshouldcreatethefamiliarnumbering
pattern[*]of1,1.1,1.1.1,andsoon,asthenestingincreases,aswe
demonstratedmuchearlierinthischapter(refertoFigure8-3).
[*]Surelyyou'venoticeditinthisbook!
Again,onlythenewcomersFirefoxandOperaproperlydisplaystyles-generated
countersandcontent.
8.4.11.6.Creatingmarkers
AccordingtotheCSS2standard,thebrowsershouldplacestyles-generated
contentbeforeoraftertheconventionalHTML/XHTMLcontentoftheaffected
element,anditshouldthereforebecomepartoftheelement'sflow.Thisisnot
acceptablefornumberedlists,wherethenumbershouldbedisplayedseparate
fromthecontentofeachnumbereditem.Todothis,addthedisplaypropertyto
yourgeneratedcontent,withthespecialvalueofmarker.Tomakeournested
numberedlistexamplecompletelycorrect,forinstance,weusetherules:
ul{counter-reset:item}
li:before{display:marker;
counter-increment:item;
content:counters(item,".")}
Thisway,thegeneratedcounternumbergetsrenderedtotheleftoftheelement's
actualcontent.Inasimilarfashion,youcanplacemarkersafteranelement.For
example,usethefollowingpropertiestocreatenumberedequationswithin
chapters(the<blockquote>elementdelineatestheequation):
h1:before{counter-increment:chapter;
counter-reset:equation}
blockquote:after{counter-increment:equation;
display:marker;
content:"("counter(chapter,upper-roman)"-"counter(equation)")"}
Whenrenderingamarker,thebrowserdetermineswheretoplacethemarker
contentinrelationtotheelement'sactualcontent.Youmodifythisbehaviorwith
themarker-offsetproperty.Itacceptsanumerical(length)valueequaltothe
distancebetweentheedgeofthemarkerandtheedgeoftheassociatedelement.
Forexample,toensurethatourequationnumbersgetshifted0.5inchesaway
fromtherelatedequation,wecoulduse:
h1:before{counter-increment:chapter;
counter-reset:equation}
blockquote:after{counter-increment:equation;
display:marker;
content:"("counter(chapter,upper-roman)"-"counter(equation)")";
marker-offset:0.5in}
8.4.12.AudioProperties
Fromitshumblebeginnings,HTMLhasbeenavisualmediumforcomputerdisplay
devices.Althoughincreasingattentionhasbeenpaidtoothermediaasthe
standardevolved,CSS2isthefirstrealefforttocomprehensivelyaddressusing
HTML/XHTMLdocumentsfornonvisualmedia.
Forexample,CSS2forecaststhatsomedaysomebrowserswillbeabletospeak
thetextualcontentofadocument,usingsomesortoftext-to-speechtechnology.
Suchabrowserwouldbeofenormoushelpforthevisuallyimpairedandwould
alsoallowwebbrowsingviathephoneandotherdeviceswhereavisualdisplayis
notreadilyavailableorusable.Imaginetheexcitementofdrivingdowntheroad
whileyourfavoritewebpagesarereadtoyou![*]
[*]Conversely,imaginetheannoyanceofsomeonehavingwebpagesreadtothemwhileyoutrytoenjoyaquietmealor
watchamovie.Weareconstantlyremindedthateveryadvanceintechnologyhasadarkside.
CSS2attemptstostandardizethesealternativerenderingsbydefininganumber
ofpropertiesthatcontroltheauralexperienceofaweblistener.Noneofthemis
currentlysupportedinanypopularbrowser,butweenvisionatimeinthenear
futurewhenyoumaybeabletotakeadvantageofsomeoralloftheseproperties.
8.4.12.1.Thevolumeproperty
Themostbasicauralpropertyisvolume.Itacceptsnumericlengthorpercentage
valuesalongwithafewkeywordscorrespondingtopresetvolumelevels.
Numericvaluesrangefrom0to100,with0correspondingtotheminimum
audibleleveland100beingthemaximumcomfortablelevel.Notethat0isnot
thesameassilent,astheminimumaudiblelevelinanenvironmentwithloud
backgroundnoise(likeafactoryfloor)maybequitehigh.
Percentagevaluescomputeanelement'svolumeasapercentageofthe
containingelement'svolume.Computedvalueslessthan0aresetto0;values
greaterthan100aresetto100.Thus,tomakeanelementtwiceasloudasits
parentelement,setthevolumepropertyto200%.Ifthevolumeoftheparent
elementis75,thechildelement'svolumegetssettothelimitof100.
Youalsomayspecifyakeywordvalueforthevolumeproperty.Here,silentactually
turnsthesoundoff.Thex-softvaluecorrespondstoavalueof0;softisthesame
asthenumericvolumeof25;mediumis50,loudis75,andx-loudcorrespondsto
100.
8.4.12.2.Speakingproperties
Threepropertiescontrolwhetherandhowtextisconvertedtospeech.Thefirstis
speak,whichturnsspeechonandoff.Bydefault,thevalueofspeakisnormal,
meaningthattextisconvertedtospeechusingstandard,locale-specificrulesfor
pronunciation,grammar,andinflection.Ifyousetspeaktonone,speechisturned
off.Youmightusethisfeaturetosuppressspeakingofsecondarycontentor
contentthatdoesnotreadilytranslatetoaudio,suchasatable.
Finally,youcansetthespeakpropertytospell-out,whichspellsouteachword.This
isusefulforacronymsandabbreviations.Forexample,using:
acronym{speak:spell-out}
ensuresthatacronymssuchasURLgettranslatedaurallyas"you-are-ell"andnot
as"earl."
Bydefault,thespeak-punctuationpropertyissettonone,causingpunctuationtobe
expressedaspausesandinflectioninthegeneratedspeech.Ifyougivethis
propertythecodevalue,punctuationisspokenliterally.Thismightbeusefulfor
aurallyreproducingprogrammingcodefragmentsorliteraltranscriptionsofsome
content.[*]
[*]Regrettably,thereisnovictor-borgemodeforthisproperty.PerhapsCSS3willaddressthisegregiousoversight.
Thespeak-numeralpropertydefaultstothevaluecontinuous,meaningthatnumerals
arepronouncedasasinglenumber.Accordingly,thenumber"1234"wouldbe
reproducedas"onethousandtwohundredthirty-four."Whensettodigits,the
numbersarepronounceddigitbydigit,suchas"one,two,three,four."
8.4.12.3.Voicecharacteristics
Tocreatearicherlisteningexperience,CSS2definesanumberofpropertiesthat
alterthespokencontent.Thisletsyouusedifferentvoicesfordifferentcontent,
speedupthespeech,andchangethepitchandstresslevelsinthespeech.
Thespeech-ratepropertyacceptsanumericlengthvaluethatdefinesthenumberof
wordsspokenperminute.Thedefaultvalueislocaledependentbecausedifferent
cultureshavedifferentnotionsofa"normal"rateofspeech.Insteadofaspecific
value,youmayuseanyofthekeywordsx-slow,slow,medium,fast,andx-fast,
correspondingto80,120,180,300,and500wordsperminute,respectively.The
fasterkeywordsetstherateto40wordsperminutefasterthanthecontaining
element,andslowersetstherateto40wordsperminuteslowerthanthe
containingelement.
Thevoice-familypropertyistheauralanalogofthefont-familyproperty.Avoice
familydefinesastyleandtypeofspeech.Suchdefinitionsarebrowserand
platformspecific,muchlikefonts.Itisassumedthatbrowserswilldefinegeneric
voicefamilies,suchas"male,""female,"and"child,"andmayalsoofferspecific
voicefamilieslike"televisionannouncer"or"bookauthor."Thevalueofthevoice-
familypropertyisacomma-separatedlistofthesevoicefamilynames;the
browsergoesdownthelistuntilitfindsavoicefamilythatitcanusetospeakthe
element'stext.
Thepitchpropertycontrolstheaveragepitch,withunitsinhertz(hz),ofthe
spokencontent.Thebasicpitchofavoiceisdefinedbythevoicefamily.Altering
thepitchletsyoucreateavariationofthebasicvoice,muchlikechangingthe
pointsizeofafont.Forexample,withachangeinpitch,the"bookauthor"might
bemadetosoundlikeachipmunk.[*]
[*]Assuming,ofcourse,thatshedoesn'talreadysoundlikeachipmunk.
Youcansetthepitchpropertytoanumericvaluesuchas120hzor210hz(the
averagepitchesoftypicalmaleandfemalevoices)ortooneofthekeywordsx-
low,low,medium,high,orx-high.Unlikeotherspeechpropertykeywords,thesedo
notcorrespondtospecificpitchfrequenciesbutinsteaddependonthebasepitch
ofthevoicefamily.Theonlyrequirementisthatthesekeywordscorrespondto
increasinglylowerorhigherpitches.
Whilethepitchpropertysetstheaveragepitch,thepitch-rangepropertydefines
howfarthepitchcanchangeasthebrowserreproducestextaurally.Thevalueof
thispropertyisanumericvaluerangingfrom0to100,withadefaultvalueof50.
Settingthepitch-rangeto0producesaflat,monotonicvoice;valuesover50
produceincreasinglyanimatedandexcited-soundingvoices.
Thestresspropertycontrolstheamountofinflectionthatisplacedonelementsin
thespokentext.Variouslanguageshavedifferingrulesforstressingsyllablesand
addinginflectionbasedongrammarandpronunciationrules.Thestressproperty
acceptsavalueintherangeof0to100,withthedefaultvalueof50
correspondingto"normal"stress.Usingavalueof0eliminatesinflectioninthe
spokencontent.Valuesover50increasinglyexaggeratetheinflectionofcertain
spokenelements.
Therichnesspropertycontrolsthequalityorfullnessofthevoice.Arichervoice
tendstofillaroomandcarriesfartherthanalessrich,orsmoother,voice.Like
pitchandstress,therichnesspropertyacceptsanumericvalueintherangeof0to
100,withadefaultvalueof50.Valuesapproaching0makethevoicesofter.
Valuesover50makethevoicefullerandmorebooming.
8.4.12.4.Pauseproperties
Likewhitespaceinaprinteddocument,insertpausesinspokencontenttooffset
andtherebydrawattentiontocontentaswellastocreateabetter-paced,more
understandablespokenpresentation.
Thepause-beforeandpause-afterpropertiesgeneratepausesjustbeforeorjustafter
anelement'sspokencontent.Thesepropertiesaccepteitheranabsolutetime
value(usingthesormsunit)orapercentagevalue.Withapercentagevalue,the
pauseisrelativetothelengthoftimerequiredtospeakasingleword.For
example,ifthespeechrateis120wordsperminute,oneword,onaverage,is
spokenevery0.5seconds.Apauseof100percent,therefore,wouldbe0.5
secondslong;a20percentpausewouldbe0.1secondslong,andsoon.
Thepausepropertysetsboththepause-beforeandpause-afterpropertiesatonce.Use
onevalueforpausetosetbothproperties;thefirstoftwovaluessetspause-before,
andthesecondsetsthepause-afterpropertyvalue.
8.4.12.5.Cueproperties
Cuepropertiesletyouinsertaudiblecuesbeforeorafteranelement.For
example,youmightprecedeeachchapterinabookwithamusicalcue,ordenote
theendofquotedtextwithanaudibletone.
Thecue-beforeandcue-afterpropertiestakeastheirvaluetheURLofasoundfile,
whichthebrowserloadsandplaysbeforeorafterthestyleddocumentelement,
respectively.Technically,thesoundcanbeofanyduration,butthepresumptionis
thataudiblecuesareshortandnonintrusive,enhancingtheaudioexperience
insteadofoverwhelmingit.
Usethecuepropertytosetboththecue-beforeandcue-afterpropertiesatonce.If
youprovideoneURLvalue,itsetsbothcuesounds;withtwovalues,thefirstsets
thecue-beforesoundandthesecondsetsthecue-aftersound.
8.4.12.6.Audiomixing
Tocreateamorepleasantlisteningexperience,youmaywanttoplaybackground
musicduringaspokenpassage.Theplay-duringpropertymeetsthisneed.Its
valuesaretheURLofthesoundfileandseveralkeywordsthatcontrolplayback.
Therepeatkeywordrepeatsthebackgroundaudiountilthespokencontentis
complete.Ifyoudon'tusethiskeyword,thebackgroundsoundplaysonce,evenif
itisshorterthanthespokencontent.Abackgroundsoundthatislongerthanthe
spokencontentendswhenthecontentends.
ThemixkeywordtellstheCSS2-consciousbrowsertomeldthebackgroundsound
withanyotherbackgroundsoundsthatmaybeplayingasdefinedbysomeparent
element.Ifyoudon'tusethiskeyword,child-elementbackgroundsoundsreplace
parent-elementbackgroundsounds,whichresumewhenthecurrentelementhas
finished.
InlieuofaURLrepresentingthebackgroundsound,youcanusethevaluenone.
Thisletsyousilenceallbackgroundsounds,suchasoneormoreplayingfrom
parentelements,whilethecurrentelementisbeingspoken.
8.4.12.7.Spatialpositioning
Whilearendereddocumentexistsonatwo-dimensionalpage,spokencontentcan
beplacedanywhereinthethree-dimensionalspacesurroundingthelistener.The
CSS2standarddefinestheazimuthandelevationpropertiessothatyoucanplace
spokencontentfromelementsindifferentplacesaroundthelistener.azimuth
relatestowhereandelevationtellshowfaraboveorbelowthesoundappearsto
thelistener.
Theazimuthpropertyacceptseitherananglevalueorkeywordsindicatinga
positionaroundthelistener.Thepositiondirectlyinfrontofthelistenerisdefined
tobe0degrees.Thelistener'srightisat90degrees,anddirectlybehindis180
degrees.Thelistener'sleftisat270degreesor,equivalently,-90degrees.
Positionkeywordsincludeabaseposition,possiblymodifiedbythebehindkeyword.
ThesekeywordscorrespondtotheangularpositionslistedinTable8-2.
Table8-2.Angularequivalentsforazimuthkeywords
Keyword Angularposition Angularpositionwhenusedwithbehind
left-side 270 270
far-left 300 240
left 320 220
center-left 340 200
center 0 180
center-right 20 160
right 40 140
far-right 60 120
right-side 90 90
Theleftwardskeywordsubtracts20degreesfromtheparentelement'sazimuth.
Similarly,rightwardsadds20degreestotheparentelement'sazimuth.Notethatthis
processcancontinueuntilyouworkyourwayaroundthelistener;thesevalues
addorsubtract20degreesnomatterwhattheazimuthoftheparentis.
Theelevationpropertyacceptsanangularvaluerangingfrom-90degreesto90
degrees,correspondingtofromdirectlybelowthelistenertodirectlyabovethe
listener.Zerodegreesisconsideredtobelevelwiththelistener'sears.Youcan
alsousethebelow,level,andabovekeywordsfor-90,0,and90degrees,
respectively.
Usethehigherkeywordtoincreasetheelevationby10degreesovertheparent
element'selevation;lowerchangestheelevationofthesoundto10degreesbelow
theparentelement'selevation.
8.4.13.PagedMedia
PrintinghasneverbeenHTML'sstrongsuit.Infact,theHTMLandXHTML
standardshaveintentionallyignoredprintingbecauseprintingassumespage
layout,andHTMLandXHTMLarenotlayouttools.
AuthorsusecascadingstylesheetstoformatandlayouttheirHTML/XHTML
documentcontents,soitisnotsurprisingthattheCSS2standardintroducessome
basicpaginationcontrolfeaturesthatletauthorshelpthebrowserfigureouthow
tobestprinttheirdocuments.Thesefeaturesfallintotwogroups:thosethat
defineaparticularpagelayoutandthosethatcontrolthepaginationofa
document.
8.4.13.1.Definingpages
Asanextensiontotheboxmodel,CSS2definesapagebox,aboxoffinite
dimensionsinwhichcontentisrendered.Thepageboxdoesnotnecessarily
correspondtoaphysicalsheetofpaper;theuseragentmapsoneormorepage
boxestosheetsofpaperduringtheprintingprocess.Manysmallpageboxesmay
fitonasinglesheet;largepageboxesmaybescaledtofitonasheetormaybe
brokenacrossseveralsheetsatthediscretionofthebrowser.
Duringtheprintingprocess,contentflowsintothepagebox,ispaginated
appropriately,andistransferredtoatargetsheetonahard-copyoutputdevice.
Thedimensionsofthepageboxmaydifferfromthebrowser'sdisplaywindow,so
theflowandrenderingofaprinteddocumentmaybecompletelydifferentfromits
onscreenrepresentation.Asalways,obtainingaspecificrenderedappearancefor
yourdocumentsisgenerallyimpossible.However,youcanusetheCSS2
paginationfeaturestohelpthebrowserprintyourdocumentinanattractive,
usefulmanner.
Youdefineapageboxusingthespecial@pageat-rule.Immediatelyfollowingthe
@pagekeywordisanoptionalnameforthepage,followedbyalistofproperties
separatedbysemicolonsandenclosedincurlybraces.Thesepropertiesdefinethe
size,margins,andappearanceofthepagebox.
Usethesizepropertytospecifythesizeofthepagebox.Thevalueofthis
propertyiseitheroneortwolengthvalues,oroneofthespecialkeywords
portrait,landscape,orauto.Ifyouprovideasinglelengthvalue,itcreatesasquare,
settingboththewidthandtheheightofthepagetothatvalue.Twolengthvalues
setthewidthandtheheightofthepage,respectively.Theportraitkeyword
specifiesthelocallyacceptedpagesizethatistallerthanitiswide(typically8x
11),andlandscapeusesalocallyacceptedpagesizethatiswiderthanitistall
(typically11x8inches).Finally,autocreatesapageboxthatisthesamesizeas
thetargetsheetofpaperonwhichthedocumentisprinted.
Ingeneral,youshouldusethespecialpagesizekeywordstoensurethatyour
documentprintswellinthelocalenvironment.Using:
@pagenormal{size:8.5in11in}
worksfineintheU.S.butmayfailinEuropeanlocales.Instead,use:
@pagenormal{size:portrait}
whichshouldselectan8.5"x11"pageintheU.S.andanA4sheetinEurope.[*]
[*]Thewordnormalintheruleisthepagename,ofcourse.
Usethemargin,margin-top,margin-bottom,margin-left,andmargin-rightproperties
withinthe@pageat-ruletosetmarginsforyourpage.Keepinmindthatthe
browsermaydefinemarginsforrenderingthepageboxwithinthetargetsheet,
soyourmarginsareinadditiontothosemargins.Thedefaultmarginsforthe
pageboxarenotdefinedandarebrowserdependent.
Finally,themarkspropertyisusedwithinthe@pageat-ruletocreatecropand
registrationmarksoutsidethepageboxonthetargetsheet.Bydefault,nomarks
areprinted.Youmayuseoneorbothofthecropandcrosskeywordstocreatecrop
marksandregistrationmarks,respectively,onthetargetprintpage.
8.4.13.2.Left,right,andfirstpages
Inmanyprintingapplications,authorswantdifferentpagelayoutsforthefirst
pageoftheirdocumentaswellasdifferingformatsforrightandleftpagesin
double-sideddocuments.CSS2accommodatesallofthesecasesusingthree
pseudoclassesattachedtothenameofapage.
The:firstpseudoclassappliesthepageformattothefirstpageinadocument.
Page-layoutattributesspecifiedinthe:firstpageoverridecorresponding
attributesinthegeneralpagelayout.Youcanusethe:firstpseudoclassin
conjunctionwithanamedpagelayout;theappropriatefirst-pagelayoutisapplied
ifthefirstpageofthedocumentisrenderedusingthenamedpage.
Inasimilarfashion,the:leftand:rightpseudoclassesdefineleftandrightpage
layoutsforyourdocument.Again,namedpagescanhaveleftandrightvariations.
Thebrowserautomaticallyappliesappropriateleftandrightlayoutstoeverypage
inthedocument,ifsuchlayoutsexist.
Youneednotspecifynamedpagestouseanyofthesepseudoclasses.Indeed,
mostdocumentsdonotdoso.Forexample,ifyouusethesesettings:
@page:first{margin-top:3in}
@page:left{margin-left:2in;margin-right:1in}
@page:right{margin-left:1in;margin-right:2in}
withoutfurtherintervention,thefirstpageofyourdocumentwillhavea3-inch
topmargin(andanappropriaterightandleftmargin,dependingonhowyour
localedefineswhetherthefirstpageofadocumentisontherightortheleft).
Subsequentpageswillalternatebetweenwideandnarrowinnerandouter
margins.
8.4.13.3.Usingnamedpages
Onceyoucreateanamedpagelayout,youcanuseitinyourdocumentbyadding
thepagepropertytoastylethatislaterappliedtoanelementinyourdocument.If
anelementhasapagelayoutthatisdifferentfromthatoftheprecedingor
containingelement,apagebreakisinsertedintothedocument,andformatting
resumesusingthenewpagelayout.Whenthescopeoftheelementends,the
pagelayoutrevertstothepreviouslayout,withappropriatepagebreaksas
needed.
Forexample,thisstylerendersallthetablesinyourdocumentonlandscape
pages:
@page{size:portrait}
@pagerotated{size:landscape}
table{page:rotated}
Whileprinting,ifthebrowserencountersa<table>elementinyourdocumentand
thecurrentpagelayoutisthedefaultportraitlayout,itstartsanewpageand
printsthetableonalandscapepage.Ifnontabularcontentfollowsthetable,the
browserinsertsanotherpagebreak,andtheflowresumesonthedefaultportrait-
sizepage.Severaltablesinarowwouldberenderedonasinglelandscapesheet,
iftheyallfit.
8.4.13.4.Controllingpagination
Unlessyouspecifyotherwise,pagebreaksoccuronlywhenthepageformat
changesorwhenthecontentoverflowsthecurrentpagebox.Tootherwiseforce
orsuppresspagebreaks,usethepage-break-before,page-break-after,andpage-break-
insideproperties.
Boththepage-break-beforeandpage-break-afterpropertiesaccepttheauto,always,
avoid,left,andrightkeywords.autoisthedefault;itletsthebrowsergenerate
pagebreaksasneeded.Thekeywordalwaysforcesapagebreakbeforeorafterthe
element,andavoidsuppressesapagebreakimmediatelybeforeorafterthe
element.Theleftandrightkeywordsforceoneortwopagebreakssothatthe
elementisrenderedonalefthandorrighthandpage.
Usingpaginationpropertiesisstraightforward.Supposeyourdocumenthaslevel-
1headersstartnewchapters,withsectionsdenotedbylevel-2headers.You'dlike
eachchaptertostartonanew,righthandpage,butyoudon'twantsection
headerstobesplitacrossapagebreakfromthesubsequentcontent.Accordingly,
youmightwriteyourCSS2printruleasfollows:
h1{page-break-before:right}
h2{page-break-after:avoid}
Useonlytheautoandavoidvalueswiththepage-break-insideproperty.autoallows
pagebreakswithintheelement(thedefaultbehavior),andavoidsuppressesthem.
Evenso,elementsthatarelargerthantheprintedpagegetbrokenup;thatis
whythekeywordisavoidandnotprevent.
Ifyoupreferthatyourtablesnotbebrokenacrosspagesifpossible,youwould
writethefollowingrule:
table{page-break-inside:avoid}
8.4.13.5.Controllingwidowsandorphans
Intypographiclingo,orphansarethoselinesofaparagraphstrandedatthe
bottomofapageduetoapagebreak,andwidowsarethoselinesremainingat
thetopofapagefollowingapagebreak.Generally,printedpagesdonotlook
attractivewithsinglelinesoftextstrandedatthetoporbottom.Mostprinterstry
toleaveatleasttwoormorelinesoftextatthetoporbottomofeachpage.
Ifyouwanttotakecontrolofthisbehavior,youcanapplythewidowsandorphans
propertiestoanelement.Thevalueofeachpropertyistheminimumnumberof
linesoftextthatcanbeleftatthetoporbottomofthepage,respectively.The
defaultis2,meaningthatthebrowsergeneratespagebreaksasneededto
ensurethatatleasttwolinesoftextfromtheelementappearatthetopor
bottomofeachpage.Yougenerallywanttoapplythispropertytoallofthe
elementsinyourdocument,toensureconsistentpaginationthroughout.
8.5.TaglessStyles:The<span>Tag
Uptonow,wehaveusedcascadingstylesheetstochangetheappearanceof
contentwithinadesignatedtag.Insomecases,however,youmaywanttoalter
theappearanceofonlyaportionofatag'scontentsusuallytext.Designatethese
specialsegmentswiththe<span>tag.
<span>
Function Delimitsanarbitraryamountoftext
Attributes class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </span>;neveromitted
Contains html_content
Usedin body_content
The<span>tagsimplydelimitsaportionofcontent(constrainedbynormaltag-
nestingrules,ofcourse).Browserstreatthe<span>tagasanotherphysicalor
content-basedstyletagtheonlydifferenceisthatthedefaultmeaningofthe<span>
tagistoleavethetextalone.
The<span>tagbecamepartofHTMLsothatyoucouldapplystyle,display,and
eventmanagementtoanarbitrarysectionofdocumentcontent.Defineastylefor
the<span>tagasyouwouldanyotherHTMLorXHTMLtag:
span{color:purple}
span.bigger{font-size:larger}
anduseitlikeanyotherHTMLorXHTMLtag:
Quatharvestprojectionsare<spanclass=bigger>biggerthanever</span>!
Similarly,applyaninlinestyletothe<span>tagtomodifytheappearanceofits
contents:
Quatharvestprojectionsare<spanstyle="font-size:larger">biggerthanever</span>!
Likeanyotherphysicalorcontent-basedstyletag,<span>tagscanbenestedand
maycontainothertags.
The<span>tagalsosupportsthemanycommontagattributes.Thestyleandclass
attributes,ofcourse,letyoucontrolthedisplaystyle;theidandtitletag
attributesletyouuniquelylabelitscontents;thedirandlangattributesletyou
specifyitsnativelanguage;andthemanyon-eventattributesletyoureactto
user-initiatedmouseandkeyboardactionsonthecontents.Notallare
implementedbythecurrentlypopularbrowsersforthistagorformanyothers.
[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2][Theidattribute,4.1.1.4]
[Thetitleattribute,4.1.1.5][InlineStyles:ThestyleAttribute,8.1.1][Style
Classes,8.3][JavaScriptEventHandlers,12.3.3]
8.6.ApplyingStylestoDocuments
Youshouldconsiderseveralissuesbefore,during,andafteryouusestylesinyour
webdocumentsanddocumentcollections.Thefirst,overarchingissueiswhether
tousethematall.Frankly,fewofthestyleeffectsareunique;youcanachieve
mostofthem,albeitlesseasilyandwithmuchlessconsistency,viathephysical
andcontent-basedstyletags(e.g.,<i>and<em>)andthevarioustagattributes
(e.g.,colorandbackground).
8.6.1.ToStyleorNottoStyle
WethinktheCSS2standardisawinner,notonlyoverJavaScript-basedstandards
butalsofortheconvenienceandeffectivenessofallofyourmarkupdocuments,
includingHTML,XHTML,andmostotherXML-compliantones.Mostbrowsersin
usetodaysupportCSS1andmanyofthefeaturesofCSS2.Thebenefitsareclear.
So,whywouldn'tyouusestyles?
AlthoughwestronglyurgeyoutolearnanduseCSS2stylesheetsforyour
documents,werealizethatcreatingstylesheetsisaninvestmentoftimeand
energythatpaysoffonlyinthelongrun.Designingastylesheetforaone-or
two-pagedocumentisprobablynottimeeffective,particularlyifyouwon'tbe
reusingthestylesheetforanyotherdocuments.Ingeneral,however,webelieve
thechoiceisnotifyoushoulduseCSS2stylesheets,butwhen.
8.6.2.WhichTypeofStylesheet,andWhen
Onceyouhavedecidedtousecascadingstylesheets(forpainorpleasure),the
nextquestioniswhichtypeofstylesheetinline,documentlevel,orexternalyou
shouldapply,andwhen.Eachhasitsprosandcons;eachisbestappliedunder
certaincircumstances.
8.6.2.1.Theprosandconsofexternalstyles
Becausestylesheetsprovideconsistencyinthepresentationofyourdocuments,
externalstylesheetsarethebestandeasiestwaytomanagestylesforyourentire
documentcollection.Simplyplacethedesiredstylerulesinastylesheet,and
applythosestylestothedesireddocuments.Becauseallofthedocumentsare
affectedbyasinglestylesheet,conversionoftheentirecollectiontoanewstyleis
assimpleaschangingasingleruleinthecorrespondingexternalstylesheet.
Evenincaseswheredocumentsmaydifferinstyle,itisoftenpossibletocollecta
fewbasicstylerulesinasinglesheetthatcanbesharedamongseveralotherwise
differentdocuments,including:
Backgroundcolor
Backgroundimage
Fontsizesandfaces
Margins
Textalignment
Anotherbenefitofexternalstylesheetsisthatotherwebauthorswhowantto
copyyourstylecaneasilyaccessthatsheetandmaketheirpageslooklikeyours.
Imitationbeingthesincerestformofflattery,youshouldnotbetroubledwhen
someoneelectstoemulatethelookandfeelofyourpages.Moretothepoint,you
can'tstopthemfromlinkingtoyourstylesheets,soyoumightaswelllearntolike
it.LikeconventionalHTMLdocuments,itisnotpossibletoencryptorotherwise
hideyourstylesheetssothatotherscannotviewandusethem.
Thebiggestproblemwithexternalstylesheetsisthattheymayincreasethe
amountoftimeneededtoaccessagivenwebpage.Notonlymustthebrowser
downloadthepageitself,butitmustalsodownloadthestylesheetbeforethepage
canbedisplayedtotheuser.Whilemoststylesheetsarerelativelysmall,their
existencecandefinitelybefeltwhenaccessingtheWeboveraslowconnection.
Withoutappropriatediscipline,externalstylesheetscanbecomelargeand
unwieldy.Whencreatingstylesheets,includeonlythosestylesthatarecommon
tothepagesusingthesheet.Ifasetofstylesisneededforonlyoneortwo
pages,youarebetteroffisolatingtheminaseparatesheetoraddingthemto
thosedocumentsusingdocument-levelstyles.Otherwise,youmayfindyourself
expendinganexorbitantamountofeffortcounteractingtheeffectsofexternal
stylesinmanyindividualdocuments.
8.6.2.2.Theprosandconsofdocument-levelstyles
Document-levelstylesaremostusefulwhencreatingcustomdocuments.Theylet
youoverrideoneormorerulesinyourexternallydefinedstyletocreateaslightly
differentdocument.
Youmightalsowanttousedocument-levelstylestoexperimentwithnewstyle
rulesbeforemovingthemtoyourstylesheets.Byaddingandchangingrulesusing
document-levelstyles,youeliminatetheriskofaddingabrokenstyletoyour
stylesheets,breakingtheappearanceofallthedocumentsthatusethatsheet.
Thebiggestproblemwithdocumentstylesisthatyoumaysuccumbtousingthem
inlieuofcreatingaformal,externalstylesheettomanageyourdocument
collection.Itiseasytosimplyaddrulestoeachdocument,cuttingandpastingas
youcreatenewdocuments.Unfortunately,managingacollectionofdocuments
withdocument-levelstylesistediousanderror-prone.Evenasimplechangecan
resultinhoursofeditingandpotentialmistakes.
Asaruleofthumb,anystylerulethatimpactsthreeormoredocumentsshould
bemovedtoastylesheetandappliedtothosedocumentsusingthe<link>tagor
@importat-rule.Adheringtothisruleasyoucreateyourdocumentfamiliespaysoff
inthelongrunwhenitistimetochangeyourstyles.
8.6.2.3.Theprosandconsofinlinestyles
Attheendofthecascade,inlinestylesoverridethemoregeneralstyles.Getinto
thehabitnowofusinginlinestylesrarelyandjustforthatpurpose.Youcannot
reuseinlinestyles,makingstylemanagementdifficult.Moreover,suchchanges
arespreadthroughoutyourdocuments,makingfindingandalteringinlinestyles
error-prone.(That'swhywemighteschewtag-andattribute-basedstylesinthe
firstplace,no?)
Anytimeyouuseaninlinestyle,thinklongandhardaboutwhetheryoumight
accomplishthesameeffectusingastyleclassdefinition.Forinstance,youare
betteroffdefining:
<styletype="text/css">
<!--
p.centered{text-align:center}
em.blue{color:blue}
-->
</style>
andlaterusing:
<pclass=centered>
<emclass=blue>
ratherthan:
<pstyle="text-align:center">
<emstyle="color:blue">
Yourstylesareeasiertofindandmanageandcaneasilybereusedthroughout
yourdocuments.
Chapter9.Forms
Forms,forms,forms,forms:wefill'emoutfornearlyeverything,fromthe
momentwe'reborn,'tilthemomentwedie.Prettymundane,really.Sowhat'sto
explainallthehooplaandexcitementoverHTMLforms?Simplythis:theymake
HTMLand,ofcourse,XHTMLtrulyinteractive.
Whenyouthinkaboutit,interactingwithawebpageisbasicallyalotofbutton
pushing:clickhere,clickthere,gohere,gotherethere'snorealinteractivity,and
it'scertainlynotpersonalized.Programssuchasapplets,servlets,JSPs,andASPs
provideextensiveuser-interactioncapabilitybutcanbedifficulttowrite.Forms,
ontheotherhand,areeasilymadeinHTML/XHTMLandmakeitpossibletocreate
documentsthatcollectandprocessuserinputandtoformulatepersonalized
replies.
Thispowerfulmechanismhasfar-reachingimplications,particularlyforelectronic
commerce.Itfinishesanonlinecatalogbygivingbuyersawaytoimmediately
orderproductsandservices.Itgivesnonprofitorganizationsawaytosignupnew
members.Itletsmarketresearcherscollectuserdata.Itgivesyouanautomated
waytointeractwithyourreaders.
Mulloverthewaysyoumightwanttointeractwithyourreaderswhilewetakea
lookatboththeclient-andserver-sidedetailsofcreatingforms.
9.1.FormFundamentals
Formsarecomposedofoneormoretext-inputboxes,clickablebuttons,multiple-
choicecheckboxes,andevenpull-downmenusandimagemaps,allplacedinside
the<form>tag.Youcanhavemorethanoneforminadocument,andwithineach
oneyoualsomayputregularbodycontent,includingtextandimages.Thetextis
particularlyusefulforprovidingformelementlabels,prompts,andinstructionsto
theusersonhowtofillouttheform.And,withinthevariousformelements,you
canuseJavaScripteventhandlersforavarietyofeffects,suchastestingand
verifyingformcontentsandcalculatingarunningsum.
Auserfillsoutthevariousfieldsintheform,thenclicksaspecialSubmitbutton
(or,sometimes,pressestheEnterkey)tosubmittheformtoaserver.The
browserpackagesuptheuser-suppliedvaluesandchoicesandsendsthemtoa
serverortoanemailaddress.[*]Theserverpassestheinformationalongtoa
supportingprogramorapplicationthatprocessestheinformationandcreatesa
reply,usuallyinHTML.Thereplysimplymaybeathankyou,oritmightprompt
theuseronhowtofillouttheformcorrectlyortosupplymissingfields.The
serversendsthereplytothebrowserclient,whichthenpresentsittotheuser.
Withemailedforms,theinformationissimplyputintosomeone'smailbox;there
isnonotificationoftheformbeingsent.
[*]Thepopularbrowsersmayalsoencrypttheinformation,securingitfromcreditcardthieves,forexample.However,
theencryptionfacilitymustbesupportedontheserveraswell:consultthewebserverdocumentationfordetails.
Theserver-side,data-processingaspectsofformsarenotpartoftheHTMLor
XHTMLstandard;theyaredefinedbytheserver'ssoftware.Whileacomplete
discussionofserver-sideformsprogrammingisbeyondthescopeofthisbook,
we'dberemissifwedidnotincludeatleastasimpleexampletogetyoustarted.
Tothatpurpose,we'veincludedattheendofthischapterafewskeletalprograms
thatillustratesomeofthecommonstylesofserver-sideformsprogramming.
Afinalcaveat:asisitswont,theWorldWideWebConsortium(W3C)hasbeen
workingonanXML-baseddefinitionofforms.Thisnewversionofforms,knownas
XForms,iscurrentlya"workingdocument,"subjecttoreviewandchangesas
needed.XFormsdiffersfromtheconventionalformsmodelinalmosteveryway:
theformsaredefineddifferently,dataisvalidateddifferently,andinformationis
transmittedtotheserverdifferently.Asyoumightimagine,XFormsisnot
currentlysupportedbyanybrowserorserver,althoughapreliminaryversionof
XFormsisavailablefortestingaspartoftheMozillaXFormsProject.Givenits
lackofgeneralsupport,dramaticdifferencesfromthecurrentmodel,andthelong
oddsthatXFormswillreplacethemillionsofformsalreadyinuse,itwouldbe
prematuretoaddressitinanydetailinthischapter.Instead,we'llcovertheforms
asdefinedinHTMLandXHTML,andleaveyouwithawarningthatanewforms
modelmaybecomingatsomepointinthefuture.
9.2.The<form>Tag
Placeaformanywhereinsidethebodyofadocument,withitselementsenclosed
bythe<form>taganditsrespectiveendtag(</form>).Youcan,andwerecommend
youoftendo,includeregularbodycontentinsideaformtospeciallylabeluser-
inputfieldsandtoprovidedirections.
<form>
Function Definesaform
Attributes
accept,action,charset,class,dir,enctype,id,lang,method,name,onClick,
onDblClick,onKeyDown,onKeyPress,onKeyUp,onMouseDown,onMouseMove,onMouseOut,
onMouseOver,onMouseUp,onReset,onSubmit,style,target,title
Endtag </form>;neveromitted
Contains form_content
Usedin block
Browsersflowthespecialformelementsintothecontainingparagraphsasthough
theyweresmallimagesembeddedintothetext.Therearen'tanyspeciallayout
rulesforformelements,soyouneedtouseotherelements,suchastablesand
stylesheets,tocontroltheplacementofelementswithinthetextflow.
Youmustdefineatleasttwospecialformattributes,whichprovidethenameof
theform'sprocessingserverandthemethodbywhichtheparametersaretobe
senttotheserver.Athird,optionalattributeletsyouchangehowtheparameters
getencodedforsecuretransmissionoverthenetwork.
9.2.1.TheactionAttribute
Therequiredactionattributeforthe<form>taggivestheURLoftheapplicationthat
istoreceiveandprocesstheform'sdata.Mostwebmasterskeeptheirforms-
processingapplicationsinaspecialdirectoryontheirwebserver,usuallynamed
cgi-bin,whichstandsforCommonGatewayInterface-binaries.[*]Keepingthese
specialforms-processingprogramsandapplicationsinonedirectorymakesit
easiertomanageandsecuretheserver.
[*]TheCommonGatewayInterface(CGI)definestheprotocolbywhichserversinteractwithprogramsthatprocess
formdata.
Atypical<form>tagwiththeactionattributelookslikethis:
<formaction="http://www.kumquat.com/cgi-bin/update">
...
</form>
TheexampleURLtellsthebrowsertocontactthewebservernamedwwwinthe
kumquat.comdomainandpassalongtheuser'sformvaluestotheapplicationnamed
updatelocatedinthecgi-bindirectory.
Ingeneral,ifyouseeaURLthatreferencesadocumentinadirectorynamedcgi-
bin,youcanbeprettysurethatthedocumentisactuallyanapplicationthat
dynamicallycreatesthedesiredpageeachtimeit'sinvoked.
9.2.2.TheenctypeAttribute
Thebrowserspeciallyencodestheform'sdatabeforepassingthatdatatothe
serversothatitdoesnotbecomescrambledorcorruptedduringthetransmission.
Itisuptotheservertoeitherdecodetheparametersorpassthem,stillencoded,
totheapplication.
ThestandardencodingformatistheInternetMediaTypeapplication/x-www-form-
urlencoded.Youcanchangethatencodingwiththeoptionalenctypeattributeinthe
<form>tag.Theonlyoptionalencodingformatscurrentlysupportedare
multipart/form-dataandtext/plain.
Themultipart/form-dataalternativeisrequiredforthoseformsthatcontainfile-
selectionfieldsforuploadbytheuser.Youshouldusethetext/plainformatin
conjunctionwithamailtoURLintheactionattributeforsendingformstoanemail
addressratherthanaserver.Unlessyourformsneedfile-selectionfieldsoryou
mustuseamailtoURLintheactionattribute,youprobablyshouldignorethis
attributeandsimplyrelyuponthebrowserandyourprocessingservertousethe
defaultencodingtype.[File-selectioncontrols,9.5.1.3]
9.2.2.1.Theapplication/x-www-form-urlencodedencoding
Thestandardencodingapplication/x-www-form-urlencodedconvertsanyspacesin
theformvaluesintoaplussign(+),nonalphanumericcharactersintoapercent
sign(%)followedbytwohexadecimaldigitsthataretheASCIIcodeofthe
character,andthelinebreaksinmultilineformdatainto%0D%0A.
Thestandardencodingalsoincludesanameforeachfieldintheform.(Afieldisa
discreteelementintheform,whosevaluecanbenearlyanythingfromasingle
numbertoseverallinesoftexttheuser'saddress,forexample.)Ifthereismore
thanonevalueinthefield,thevaluesareseparatedbyampersands.
Forexample,here'swhatthebrowsersendstotheserveraftertheuserfillsouta
formwithtwoinputfieldslabelednameandaddress;theformerfieldhasjustone
lineoftext,andthelatterfieldhasseverallinesofinput:
name=O'Reilly+Media&address=1005+Gravenstein+Highway+North%0D%0A
Sebastopol,%0D%0ACA+95472
We'vebrokenthevalueintotwolineshereforclarity,butinreality,thebrowser
sendsthedatainanunbrokenstring.ThenamefieldisO'ReillyMedia,andthevalue
oftheaddressfield,completewithembeddednewlinecharacters,is:
1005GravensteinHighwayNorth
Sebastopol,
CA95472
9.2.2.2.Themultipart/form-dataencoding
Themultipart/form-dataencodingencapsulatesthefieldsintheformasseveral
partsofasingleMultipurposeInternetMailExtension(MIME)-compatible
compounddocument.Eachfieldhasitsownsectionintheresultingfile,setoffby
astandarddelimiter.Withineachsection,oneormoreheaderlinesdefinethe
nameofthefield,followedbyoneormorelinescontainingthevalueofthefield.
Becausethevaluepartofeachsectioncancontainbinarydataorotherwise
unprintablecharacters,nocharacterconversionorencodingoccurswithinthe
transmitteddata.
Thisencodingformatisbynaturemoreverboseandlongerthanthe
application/x-www-form-urlencodedformat.Assuch,youcanuseitonlywhenthe
methodattributeofthe<form>tagissettopost,asdescribedinsection9.2.4,laterin
thischapter.Asimpleexamplemakesiteasytounderstandthisformat.Here's
ourpreviousexample,whentransmittedasmultipart/form-data:
------------------------------146931364513459
Content-Disposition:form-data;name="name"
O'ReillyMedia
------------------------------146931364513459
Content-Disposition:form-data;name="address"
1005GravensteinHighwayNorth
Sebastopol,
CA95472
------------------------------146931364513459--
Thefirstlineofthetransmissiondefinesthedelimiterthatappearsbeforeeach
sectionofthedocument.Italwaysconsistsof30dashesandalongrandom
numberthatdistinguishesitfromothertextthatmightappearinactualfield
values.
Thenextlinescontaintheheaderfieldsforthefirstsection.Thereisalwaysa
Content-Dispositionfieldindicatingthatthesectioncontainsformdataandproviding
thenameoftheformelementwhosevalueisinthissection.Youmayseeother
headerfields;inparticular,somefile-selectionfieldsincludeaContent-Typeheader
fieldthatindicatesthetypeofdatacontainedinthefilebeingtransmitted.
Aftertheheaders,thereisasingleblanklinefollowedbytheactualvalueofthe
fieldononeormorelines.Thesectionconcludeswitharepeatofthedelimiter
linethatstartedthetransmission.Anothersectionfollowsimmediately,andthe
patternrepeatsuntilalloftheformparametershavebeentransmitted.Theend
ofthetransmissionisindicatedbyanextratwodashesattheendofthelast
delimiterline.
Aswepointedoutearlier,usemultipart/form-dataencodingonlywhenyourform
containsafile-selectionfield.Here'sanexampleofhowthetransmissionofafile-
selectionfieldmightlook:
------------------------------146931364513459
Content-Disposition:form-data;name="thefile";filename="test"
Content-Type:text/plain
Firstlineofthefile
...
Lastlineofthefile
------------------------------146931364513459--
TheonlynotabledifferenceisthattheContent-Dispositionfieldcontainsanextra
element,filename,whichdefinesthenameofthefilebeingtransmitted.There
mightalsobeaContent-Typefieldtofurtherdescribethefile'scontents.
9.2.2.3.Thetext/plainencoding
Usethisencodingonlywhenyoudon'thaveaccesstoaforms-processingserver
andneedtosendtheforminformationbyemail(theform'sactionattributemust
beamailtoURL).Theconventionalencodingsaredesignedforcomputer
consumption;text/plainisdesignedwithpeopleinmind.
Inthisencoding,eachelementintheformisplacedonasingleline,withthe
nameandvalueseparatedbyanequalssign.Returningtoournameandaddress
example,theformdatawouldbereturnedas:
name=O'ReillyMedia
address=1005GravensteinHighwayNorth%0D%0ASebastopol,%0D%0ACA95472
Asyoucansee,theonlycharactersstillencodedinthisformarethecarriage-
returnandline-feedcharactersinmultilinetext-inputareas.Otherwise,theresult
iseasilyreadableandgenerallyparsablebysimpletools.
9.2.3.Theaccept-charsetAttribute
Theaccept-charsetattributewasintroducedintheHTML4.0standard.Itletsyou
specifyalistofcharactersetsthattheservermustsupporttoproperlyinterpret
theformdata.Thevalueofthisattributeisaquote-enclosedlistofoneormore
InternationalOrganizationforStandardization(ISO)charactersetnames.The
browsermaychoosetodisregardtheformorhandleitdifferentlyiftheacceptable
charactersetsdonotmatchthecharactersettheuserisusing.Thedefaultvalue
ofthisattributeisunknown,implyingthattheform'scharactersetisthesameas
thatofthedocumentcontainingtheform.
9.2.4.ThemethodAttribute
Thisattributeforthe<form>tagsetsthemethodbywhichthebrowsersendsthe
form'sdatatotheserverforprocessing.Therearetwoways:thePOSTmethod
andtheGETmethod.Ifmethodisnotspecified,GETisused.
WiththePOSTmethod,thebrowsersendsthedataintwosteps:thebrowserfirst
contactstheforms-processingserverspecifiedintheactionattributeandthen,
oncecontactismade,sendsthedatatotheserverinaseparatetransmission.
Ontheserverside,POST-styleapplicationsareexpectedtoreadtheparameters
fromastandardlocationoncetheybeginexecution.Onceread,theparameters
mustbedecodedbeforetheapplicationcanusetheformvalues.Yourparticular
serverdefinesexactlyhowyourPOST-styleapplicationscanexpecttoreceive
theirparameters.
TheGETmethod,ontheotherhand,contactstheforms-processingserverand
sendstheformdatainasingletransmissionstep:thebrowserappendsthedata
totheform'sactionURL,separatedbythequestionmarkcharacter.
Thecommonbrowserstransmittheforminformationbyeithermethod;some
serversreceivetheformdatabyonlyoneortheothermethod.Youindicate
whichofthetwomethodsPOSTorGETyourforms-processingserverhandleswith
themethodattributeinthe<form>tag.
Here'sthecompletetagincludingtheGETtransmissionmethodattributeforthe
previousformexample:
<formmethod=GET
action="http://www.kumquat.com/cgi-bin/update">
...
</form>
9.2.4.1.POSTorGET?
Whichoneshouldyouuseifyourforms-processingserversupportsboththePOST
andGETmethods?Herearesomerulesofthumb:
Forbestform-transmissionperformance,sendsmallformswithafewshort
fieldsviatheGETmethod.
Becausesomeserveroperatingsystemslimitthenumberandlengthof
command-lineargumentsthatcanbepassedtoanapplicationatonce,use
thePOSTmethodtosendformsthathavemanyfieldsorthathavelongtext
fields.
Ifyouareinexperiencedinwritingserver-sideforms-processingapplications,
chooseGET.TheextrastepsinvolvedinreadinganddecodingPOST-style
transmittedparameters,whilenottoodifficult,maybemorethanyouare
willingtotackle.
Ifsecurityisanissue,choosePOST.GETplacestheformparametersdirectly
intheapplicationURL,wheretheyeasilycanbecapturedbynetworksniffers
orextractedfromaserverlogfile.Iftheparameterscontainsensitive
informationlikecreditcardnumbers,youmaybecompromisingyourusers
withouttheirknowledge.WhilePOSTapplicationsarenotwithouttheir
securityholes,theycanatleasttakeadvantageofencryptionwhen
transmittingtheparametersasaseparatetransactionwiththeserver.
Ifyouwanttoinvoketheserver-sideapplicationoutsidetherealmofaform,
includingpassingitparameters,useGET,becauseitletsyouincludeform-like
parametersaspartofaURL.POST-styleapplications,ontheotherhand,
expectanextratransmissionfromthebrowseraftertheURLsomethingyou
can'tdoaspartofaconventional<a>tag.
9.2.4.2.Passingparametersexplicitly
Theforegoingbitofadvicewarrantssomeexplanation.Supposeyouhadasimple
formwithtwoelementsnamedxandy.Thebrowserencodesthemlikethis:
x=27&y=33
Ifmethod=GET,thebrowseralsoincludestheserver-side'sprocessingapplication's
URLasaprefix,likethis:
http://www.kumquat.com/cgi-bin/update?x=27&y=33
Thereisnothingtokeepyoufromcreatingaconventional<a>tagthatinvokesthe
formwithanyparametervalueyoudesire,likeso:
<ahref="http://www.kumquat.com/cgi-bin/update?x=19&y=104">
Theonlyhitchisthattheampersandthatseparatestheparametersisalsothe
character-entityinsertioncharacter.Whenplacedwithinthehrefattributeofthe
<a>tag,theampersandcausesthebrowsertoreplacethecharactersfollowingit
withacorrespondingcharacterentity.
Tokeepthisfromhappening,youmustreplacetheliteralampersandwithits
entityequivalent,either&or&(seeAppendixF).Withthissubstitution,our
exampleofthealternativeformreferencetotheserver-sideapplicationlookslike
this:
<ahref="http://www.kumquat.com/cgi-bin/update?x=19&y=104">
Becauseofthepotentialconfusionthatarisesfromhavingtoescapethe
ampersandsintheURL,serverimplementersareencouragedtoalsoacceptthe
semicolonasaparameterseparator.Youmightwanttocheckthedocumentation
toseewhetheryourserverhonorsthisconvention.
9.2.5.ThetargetAttribute
Itispossibletoredirecttheresultsofaformtoanotherwindoworframe.Simply
addthetargetattributetoyour<form>tagandprovidethenameofthewindowor
frametoreceivetheresults.
Likethetargetattributeusedinconjunctionwiththe<a>tag,youcanusea
numberofspecialnameswiththetargetattributeinthe<form>tagtocreateanew
windowortoreplacethecontentsofexistingwindowsandframes.[Thetarget
Attributeforthe<a>Tag,11.7.1]
9.2.6.Theid,name,andtitleAttributes
Theidattributeletsyouattachauniquestringlabeltoyourformforreferenceby
programs(applets)andhyperlinks.BeforeidwasintroducedinHTML4.0,
Netscapeusedthenameattributetoachievesimilareffects,althoughitcannotbe
usedinahyperlink.Tobecompatiblewiththebroadestrangeofbrowsers,we
recommendthatfornowyouincludebothnameandidwith<form>,ifneeded.Inthe
future,youshoulduseonlytheidattributeforthispurpose.
Thetitleattributedefinesaquote-enclosedstringvaluetolabeltheform.
However,ittitlesonlytheformsegment;itsvaluecannotbeusedinanapplet
referenceorhyperlink.[Theidattribute,4.1.1.4][Thetitleattribute,4.1.1.5]
9.2.7.Theclass,style,lang,anddirAttributes
Thestyleattributecreatesaninlinestylefortheelementsenclosedbytheform,
overridinganyotherstylerulesineffect.Theclassattributeletsyouformatthe
contentaccordingtoapredefinedclassofthe<form>tag;itsvalueisthenameof
thatclass.[InlineStyles:ThestyleAttribute,8.1.1][StyleClasses,8.3]
Theactualeffectsofstylewith<form>arehardtopredict,however.Ingeneral,
stylepropertiesaffectthebodycontenttext,inparticularthatyoumayincludeas
partoftheform'scontents,but<form>stylesdoaffectthedisplaycharacteristicsof
theformelements.
Forinstance,youmaycreateaspecialfontfaceandbackgroundcolorstylefor
theform.Theform'stextlabels,butnotthetextinsideatext-inputformelement,
appearinthespecifiedfontfaceandbackgroundcolor.Similarly,thetextlabels
youputbesideasetofradiobuttonsappearintheform-specifiedstyle,butthe
radiobuttonsthemselvesdonot.
Thelangattributeletsyouspecifythelanguageusedwithintheform,withits
valuebeinganyoftheISOstandardtwo-characterlanguageabbreviations,
includinganoptionallanguagemodifier.Forexample,addinglang=en-UKtellsthe
browserthatthelistisinEnglish("en")asspokenandwrittenintheUnited
Kingdom("UK").Presumably,thebrowsermaymakelayoutortypographic
decisionsbaseduponyourlanguagechoice.
Similarly,thedirattributetellsthebrowserinwhichdirectiontodisplaythelist
contentsfromlefttoright(dir=ltr),likeEnglishandFrench,orfromrighttoleft
(dir=rtl),aswithHebrewandChinese.
Thepopularbrowserssupportthedirandlangattributes,eventhoughno
behaviorsaredefinedforanyspecificlanguage.[Thedirattribute,3.6.1.1][The
langattribute,3.6.1.2]
9.2.8.TheEventAttributes
Asformostotherelementsinadocument,the<form>taghonorsthestandard
mouseandkeyboardevent-relatedattributesthecompliantbrowserwill
recognize.WedescribethemajorityoftheseattributesindetailinChapter12.
[JavaScriptEventHandlers,12.3.3]
Formshavetwospecialevent-relatedattributes:onSubmitandonReset.Thevalueof
eacheventattributeisenclosedinquotationmarksoneorasequenceof
semicolon-separatedJavaScriptexpressions,methods,andfunctionreferences.
WithonSubmit,thebrowserexecutesthesecommandsbeforeitactuallysubmitsthe
form'sdatatotheserverorsendsittoanemailaddress.
YoumayusetheonSubmiteventforavarietyofeffects.Themostpopularisfora
client-sideforms-verificationprogramthatscanstheformdataandpromptsthe
usertocompleteoneormoremissingelements.Anotherpopularandmuch
simpleruseistoinformuserswhenamailtoURLformisbeingprocessedvia
email.
TheonResetattributeisusedjustliketheonSubmitattribute,exceptthatthe
associatedprogramcodeisexecutedonlyiftheuserpressesaResetbuttoninthe
form.
9.3.ASimpleFormExample
Inamoment,we'llexamineeachofthemanyformcontrolsindetail.Let'sfirst
takeaquicklookatasimpleexample,toseehowformsareputtogether.This
HTMLform(showninFigure9-1)gathersbasicdemographicinformationabouta
user:
Figure9-1.Asimpleform
<formmethod=POSTaction="http://www.kumquat.com/demo">
Name:
<inputtype=textname=namesize=32maxlength=80>
<p>
Sex:
<inputtype=radioname=sexvalue="M">Male
<inputtype=radioname=sexvalue="F">Female
<p>
AnnualIncome:
<selectname=incomesize=1>
<option>Under$25,000
<option>$25,001to$50,000
<option>$50,001andhigher
</select>
<p>
<inputtype=submit>
</form>
Thefirstlineoftheexamplestartstheformandindicateswe'llbeusingthePOST
methodfordatatransmission.Theform'suser-inputcontrolsfollow,eachdefined
byan<input>tagandtypeattribute.Therearethreecontrolsinthesimple
example,eachcontainedwithinitsownparagraph.
Thefirstcontrolisaconventionaltext-entryfield,lettingtheusertypeupto80
charactersbutdisplayingonly32ofthematatime.Thenextoneisamultiple-
choiceoption,whichletstheuserselectonlyoneoftworadiobuttons.Thisis
followedbyapull-downmenuforchoosingoneofthreeoptions.Thefinalcontrol
isasimplesubmissionbutton,which,whenclickedbytheuser,setstheform's
processinginmotion.
9.4.UsingEmailtoCollectFormData
Itisincreasinglycommontofindauthorswhohavenoaccesstoawebserver
otherthantouploadtheirdocuments.Consequently,theyhavenoabilityto
createormanageCGIprograms.Infact,someInternetserviceproviders(ISPs),
particularlythosehostingspaceforhundredsoreventhousandsofsites,typically
disableCGIservicestolimittheirservers'processingloadandasasecurity
precaution.
Ifyouareworkingwithoneofthemanysiteswhereyoucannotgetaform
processedtosaveyourlife,allisnotlost:youcanuseamailtoURLasthevalue
oftheform'sactionattribute.Thelatestbrowsersautomaticallyemailthevarious
formparametersandvaluestotheaddresssuppliedintheURL.Therecipientof
themailcanthenprocesstheformandtakeactionaccordingly.
Bysubstitutingthefollowingforthe<form>taginourpreviousexample:
<formmethod=POSTaction="mailto:chuckandbill@oreilly.com"
enctype="text/plain"
onSubmit="window.alert('Thisformisbeingsentbyemail,even
thoughitmaynotappearthatanythinghashappened...')">
theformdatagetsemailedtochuckandbillwhensubmittedbytheuser,not
otherwiseprocessedbyaserver.Notice,too,thatwehaveasimpleJavaScript
alertmessagethatappearswhenthebrowsergetsreadytosendouttheform
data.Thealerttellstheusernottoexpectconfirmationthattheformdatawas
sent(seeFigure9-2).
Figure9-2.Awarningaboutamailtoformsubmission
Also,unlessdisabledbytheuserorifyouomitthemethod=POSTattribute,the
browsertypicallywarnsusersthattheyareabouttosendunencrypted
(text/plain)andtherebyunsecuredinformationoverthenetworkandgivesthem
theoptiontocancelthesubmission.Otherwise,theformissentviaemailwithout
incidentornotification.
Thebodyoftheresultingemailedformmessagelookssomethinglikethis:
name=BillKennedy
sex=M
income=Under$25,000
9.4.1.ProblemswithEmailForms
Ifyouchoosetouseeithermailtooraform-to-emailfacility,thereareseveral
problemsyoumayhavetodealwith:
Yourformswon'tworkonbrowsersthatdon'tsupportamailtoURLasaform
action.Allofthecurrentlypopularbrowsersdosupportmailtoforms.
Somebrowsers,includingsomeearlyversions(pre-version5)ofInternet
Explorer,donotproperlyplacetheformdataintotheemailmessagebodyand
mayevenopenanemaildialogbox,confusingtheuser.
AmailtoURLdoesn'tpresentuserswithaconfirmationpagetoassurethem
thattheirformshavebeenprocessed.Afterexecutingthemailtoform,the
userisleftlookingattheform,asthoughnothinghadhappened.(Aswedid
intheprecedingexample,useJavaScripttoovercomesomeofthisdilemma
withanonSubmitoronClickeventhandler.)
Yourdatamayarriveinaformthatisdifficult,ifnotimpossible,toread,
unlessyouuseareadableenctype,suchastext/plain.
Mostimportantly,youlosewhateversecurityprotectionstheservermayhave
providedwiththeform.
Thelastproblemdeservesadditionalexplanation.Somewebproviderssupport
securewebserversthatattachanencryptionkeytoyourwebpagewhensentto
theuser'sbrowser.Thepopularbrowsersusethatkeytoencryptanydatayour
documentmaysendbacktothatsameserver,includingtheuser'sformdata.
Becauseonlytheclient'sbrowserandtheserverknowthekey,onlythatserveris
abletodeciphertheinformationcomingbacktoitfromtheclientbrowser,
effectivelysecuringtheinformationfromnefariouseavesdroppersandhackers.
However,ifyouuseemailtoretrievetheformdata,theserverdecryptsitbefore
packagingtheforminformationintothebodyofanemailmessageandsendingit
toyou.Emailnormallyishighlysusceptibletoeavesdroppingandothertypesof
snooping.Itscontentsareveryinsecure.
So,please,ifyouuseanemailmethodtoretrievesensitiveformdata,suchas
creditcardsandpersonalinformation,beawareofthepotentialconsequences.
Anddon'tbefooledorfoolyouruserswitha"secure"serverwheninsecureemail
comesoutthebackend.
Inspiteofalltheseproblems,emailformspresentanattractivealternativetothe
webauthorconstrainedbyarestrictedserver.Ouradvice:useCGIscriptsifatall
possibleandfallbackonmailtoURLsifallelsefails.
9.5.The<input>Tag
Usethe<input>tagtodefineanyoneofanumberofcommonform"controls,"as
theyarecalledintheHTMLandXHTMLstandards,includingtextfields,multiple-
choicelists,clickableimages,andsubmissionbuttons.Althoughtherearemany
attributesforthe<input>tag,onlythenameattributeisrequiredforeachelement
(butnotforasubmissionorresetbutton;seethefollowingexplanation).Andas
wedescribeindetaillater,eachtypeofinputcontrolusesonlyasubsetofthe
allowedattributes.Additional<input>attributesmayberequiredbaseduponwhich
typeofformelementyouspecify.
Table9-1summarizesthevariousform<input>typesandattributes,requiredand
optional.
Table9-1.Requiredandsomecommonformelementattributes
Formtag
or
<input>
type
Attributes(x=required; =optional;blank=notsupported)
accept accesskey align alt border cols checked disabled maxlength multiple name notab onBlur onChange
button x
checkbox x
file x
hidden x
image
password x
radio x
reset
submit
text x
<button> x
<select> x
<textarea> x
<input>
Function Createsaninputelementwithinaform
Attributes
accept,accesskey,align,alt,border ,checked,class,dir,disabled,id,lang,
maxlength,name,notab ,onBlur,onChange,onClick,onDblClick,onFocus,onKeyDown,
onKeyPress,onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,
onSelect,size,src,tabindex,taborder ,title,type,usemap,value
Endtag NoneinHTML;</input>or<input.../>inXHTML
Contains Nothing
Usedin form_content
Youselectthetypeofcontroltoincludeintheformwiththe<input>tag'stype
attribute,andyounamethefield(usedduringtheformsubmissionprocesstothe
server;seeearlierdescription)withthenameattribute.Ifyoudonotspecifyit,the
typefielddefaultstoavalueoftext.Althoughthevalueofthenameattributeis
technicallyanarbitrarystring,werecommendthatyouuseanamewithout
embeddedspacesorpunctuation.Ifyousticktojustlettersandnumbers(butno
leadingdigits)andrepresentspaceswiththeunderscore(_)character,you'llhave
fewerproblems.Forexample,cost_in_dollarsandoverhead_percentagearegood
choicesforelementnames;$costandoverhead%mightcauseproblems.
Inaddition,noticethatthenameyougivetoaformcontrolisdirectlyassociated
withthedatathattheuserinputstothatcontrolandthatgetspassedtothe
forms-processingserver.Itisnotthesameasnordoesitsharethesame
namespacewiththenameattributeforahyperlinkfragmentoraframedocument.
9.5.1.TextFieldsinForms
TheHTMLandXHTMLstandardsletyouincludefourtypesoftext-entrycontrols
inyourforms:aconventionaltext-entryfield,amaskedfieldforsecuredata
entry,afieldthatnamesafiletobetransmittedaspartofyourformdata,anda
specialmultilinetext-entry<textarea>tag.Thefirstthreetypesare<input>-based
controls;thefourthisaseparatetagthatwedescribelaterinthischapter,in
section9.7.
9.5.1.1.Conventionaltextfields
Themostcommonforminputcontrolisthetext-entryfieldforusernames,
addresses,andotheruniquedata.Atext-entryfieldappearsinthebrowser
windowasanemptyboxononelineandacceptsasinglelineofuserinput.
Eventually,thatlineoftextbecomesthevalueofthecontrolwhentheuser
submitstheformtotheserver.Tocreateatext-entryfieldinsideaforminyour
documentyousetthetypeofthe<input>formelementtotext.Includeaname
attributeaswell;it'srequired.
Whatconstitutesalineoftextdiffersamongthevariousbrowsers.Fortunately,
HTMLandXHTMLgiveusaway,withthesizeandmaxlengthattributes,todictate
thewidth(inthenumberofcharacters)ofthetext-inputdisplaybox,andhow
manytotalcharacterstoacceptfromtheuser,respectively.Thevalueforeither
attributeisanintegerequaltothemaximumnumberofcharactersyou'llallow
theusertoseeandtypeinthefield.Ifmaxlengthexceedssize,thetextscrollsback
andforthwithinthetext-entrybox.Ifmaxlengthissmallerthansize,thereisextra
blankspaceinthetext-entryboxtomakeupthedifferencebetweenthetwo
attributes.
Thedefaultvalueforsizedependsonthebrowser,buttypicallyitis80characters;
thedefaultvalueformaxlengthisunlimited.Werecommendthatyousetthem
yourself.Adjustthesizeattributesothatthetext-entryboxdoesnotextend
beyondtherightmarginofatypicalbrowserwindow(about60characterswitha
veryshortprompt).Setmaxlengthtoareasonablenumberofcharacters;for
example,twoforstateabbreviations,12forphonenumbers,andsoon.
Atext-entryfieldisusuallyblankuntiltheusertypessomethingintoit.Youmay,
however,specifyaninitialdefaultvalueforthefieldwiththevalueattribute.The
usermaymodifythedefault,ofcourse.Iftheuserpressesaform'sResetbutton,
thevalueofthefieldisresettothisdefaultvalue.[Resetbuttons,9.5.4.2]
Allofthesearevalidtext-entryformcontrols:
<inputtype=textname=comments>
<inputtype=textname=zipcodesize=10maxlength=10>
<inputtype="text"name="address"size="30"maxlength="256"/>
<inputtype="text"name="rate"size="3"maxlength="3"value="100"/>
ThefirstexampleisHTMLandcreatesatext-entryfieldsettothebrowser's
defaultwidthandmaximumlength.Asweargued,thisisnotagoodidea,because
defaultsmayvaryamongbrowsers,andyourformlayoutissuretolookbadwith
someofthem.Rather,fixthewidthandmaximumnumberofacceptableinput
charactersaswedointhesecondexample:itletstheusertypeinupto10
charactersinsideaninputbox10characterswide.Itsvalueissenttotheserver
withthenamezipcodewhentheusersubmitstheform.
ThethirdexampleisXHTMLandtellsthebrowsertodisplayatext-inputbox30
characterswideintowhichtheusermaytypeupto256characters.Thebrowser
automaticallyscrollstextinsidetheinputboxtoexposetheextracharacters.
Thelasttext-inputcontrolisXHTML,too.Ittellsthebrowsertodisplayatextbox
threecharacterswide,intowhichtheusercantypeuptothreecharacters.Its
initialvalueissetto100.
Noticethatinthesecondandfourthexamplesitisimpliedthattheuserwillenter
certainkindsofdataapostalcodeoranumericrate,respectively.Exceptfor
limitinghowmany,neitherHTMLnorXHTMLprovideawayforyoutodictate
whatcharactersmaybetypedintoatext-inputfield.Forinstance,inthelast
examplefield,theusermaytype"ABC,"eventhoughyouintendthefield'svalue
tobeanumberlessthan1,000.Yourserver-sideapplicationorappletmusttrap
erroneousormistakeninput,checkforincompleteforms,andsendthe
appropriateerrormessagetotheuserwhenthingsaren'tright.Thatcanbea
tediousprocess,soweemphasizeagain:provideclearandpreciseinstructions
andprompts.Makesureyourformstelluserswhatkindsofinputyouexpectfrom
them,therebyreducingthenumberofmistakestheymaymakewhenfillingthem
out.
9.5.1.2.Maskedtextcontrols
LiketheLoneRangerandZorro,themaskisonthegoodguysinamaskedtext
field.Itbehavesjustlikeaconventionaltextcontrolinaform,exceptthatthe
user-typedcharactersdon'tappearonscreen.Rather,thebrowserobscuresthe
charactersinmaskedtexttokeepsuchthingsaspasswordsandothersensitive
codesawayfrompryingeyes.
Tocreateamaskedtextcontrol,setthevalueofthetypeattributetopassword.All
otherattributesandsemanticsoftheconventionaltextcontrolapplytothe
maskedone.Hence,youmustprovideaname,andyoumayspecifyasizeand
maxlengthforthefield,aswellasaninitialvalue(werecommendit).
Don'tbemisled:amaskedtextcontrolisnotallthatsecure.Thetyped-invalueis
onlyobscuredonscreen;thebrowsertransmitsitunencryptedwhentheformis
submittedtotheserver,unlessyouareusingawebserverrunningSecure
SocketsLayer(SSL)(httpsserver,forexample).So,whilepryingeyesmaynot
seethemonscreen,deviousbadguysmaystealtheinformationelectronically.
9.5.1.3.File-selectioncontrols
Asitsnameimplies,thefile-selectioncontrolletsauserselectafilestoredonthe
computerandsendittotheserverwhenshesubmitstheform.Createafile-
selectioncontrolinaformbysettingthevalueofthetypeattributetofile.Like
othertextcontrols,thesizeandmaxlengthofafile-selectionfieldshouldbesetto
appropriatevalues,withthebrowsercreatingafield20characterswide,ifnot
otherwisedirected.
Thebrowserpresentsthefile-selectionformcontroltotheuserlikeothertext
fields,accompaniedbyabuttonlabeledBrowsetoitsright.Userseithertypethe
pathnameofthefiledirectlyastextintothefieldor,withtheBrowseoption,
selectthepathnameofthefilefromasystem-specificdialogbox.
TheBrowsebuttonopensaplatform-specificfile-selectiondialogboxthatallows
userstoselectavalueforthefield.Inthiscase,theentirepathnameofthe
selectedfileisplacedintothefield,evenifthelengthofthatpathnameexceeds
thecontrol'sspecifiedmaxlength.
Usetheacceptattributetoconstrainthetypesoffilesthatthebrowserletsthe
userbrowse,eventhoughitdoesnotconstrainwhattheymaytypeinasthe
pathname.accept'svalueisacomma-separatedlistofMIMEencodings;users
browseandselectonlyfileswhosetypematchesoneofthoseinthelist.For
example,torestricttheselectiontoimages,youmightaddaccept="image/*"tothe
file-selection<input>tag.
Unlikeotherforminputcontrols,thefile-selectionfieldworkscorrectlyonlywith
aspecificformdataencodingandtransmissionmethod.Ifyouincludeoneor
morefile-selectionfieldsinyourform,youmustsettheenctypeattributeofthe
<form>tagtomultipart/form-dataandthe<form>tag'smethodattributetopost.
Otherwise,thefile-selectionfieldbehaveslikearegulartextfield,transmittingits
value(thatis,thefile'spathname)totheserverinsteadofthecontentsofthefile
itself.
Allofthisiseasierthanitmaysound.Forexample,hereisanHTMLformthat
collectsaperson'snameandfavoritefile:
<formenctype="multipart/form-data"method=post
action="cgi-bin/save_file">
Yourname:<inputtype=textsize=20name=the_name>
<p>
Yourfavoritefile:<inputtype=filesize=20name=fav_file>
</form>
Thedatatransmittedfromthebrowsertotheserverforthisexampleformhas
twoparts.Thefirstcontainsthevalueforthenamefield,andthesecondcontains
thenameandcontentsofthespecifiedfile:
-----------------------------6099238414674
Content-Disposition:form-data;name="the_name"
Onelineoftextfieldcontents
-----------------------------6099238414674
Content-Disposition:form-data;name="fav_file";filename="abc"
Firstlineoffile
...
Lastlineoffile
-----------------------------6099238414674--
Thebrowsersdon'tcheckthattheuserhasspecifiedavalidfile.Ifnofileis
specified,thefilenameportionoftheContent-Dispositionheaderisempty.Ifthefile
doesn'texist,itsnameappearsinthefilenamesubheader,butthereisnoContent-
Typeheaderorsubsequentlinesoffilecontent.Validfilesmaycontain
nonprintableorbinarydata;thereisnowaytorestrictuser-selectablefiletypes.
Inlightofthesepotentialproblems,theforms-processingapplicationonthe
servershouldberobustenoughtohandlemissingfiles,erroneousfiles,extremely
largefiles,andfileswithunusualorunexpectedformats.
9.5.2.Checkboxes
Thecheckboxformcontrolgivesusersawaytoselectordeselectanitemquickly
andeasilyinyourform.Checkboxesalsomaybegroupedtocreateasetof
choices,anyandallofwhichtheusermayselectordeselect.
Createindividualcheckboxesbysettingthetypeattributeforeach<input>tagto
checkbox.Includetherequirednameandvalueattributes.Onlythevaluesofthose
itemsselectedbytheuserappearinthesubmittedform.Theoptionalchecked
attribute(novalue)tellsthebrowsertodisplayaselected(checked)checkbox
andincludeitsvaluewhensubmittingtheformtotheserverunlesstheuser
deliberatelydeselects(unchecks)thebox.
Thevalueofthecheckedcheckboxsubmittedtotheserveristhetextstringyou
specifyintherequiredvalueattribute.Forexample,inXHTML:
<form>
Whatpetsdoyouown?
<p>
<inputtype="checkbox"name="pets"value="dog"/>Dog
<br/>
<inputtype="checkbox"checked="checked"name="pets"value="cat"/>Cat
<br/>
<inputtype="checkbox"name="pets"value="bird"/>Bird
<br/>
<inputtype="checkbox"name="pets"value="fish"/>Fish
</p>
</form>
createsacheckboxgroupasshowninFigure9-3.
Figure9-3.Acheckboxgroup
Althoughpartofthegroup,eachcheckboxcontrolappearsasaseparatechoice
onscreen.Notice,too,withallduerespecttodog,bird,andfishlovers,thatwe've
preselectedtheCatcheckboxwiththecheckedattributeinitstag.We'vealso
providedtextlabels;thesimilarvalueattributesdon'tappearinthebrowser's
windowbutarethevaluessubmittedwiththeirassociatednametotheserverif
theuserselectsthecheckbox.Also,youneedtouseparagraphorline-breaktags
tocontrolthelayoutofyourcheckboxgroup,asyoudoforotherformcontrols.
Intheexample,iftheuserselectsCatandFishandsubmitstheform,thevalues
includedintheparameterlistsenttotheserverwouldbe:
pets=cat
pets=fish
9.5.3.RadioButtons
Radiobuttonformcontrolsaresimilarinbehaviortocheckboxes,exceptthatthe
usercanselectonlyoneinthegroup.[*]Createaradiobuttonbysettingthetype
attributeofthe<input>tagtoradio.Aswithcheckboxcontrols,radiobuttonseach
requireanameandvalueattribute.Radiobuttonswiththesamenamearemembers
ofagroup.Oneofthemmaybecheckedbyincludingthecheckedattributewith
thatelement.Ifyoudon'tcheckoneinthegroup,thebrowserdoesit
automaticallyforyoubycheckingthefirstelementinthegroup.
[*]Someofusareoldenough,whilenotyetsenile,torecallwhenautomobileradioshadmechanicalpushbuttonsfor
selectingastation.Pushinginonebuttonpoppedoutthepreviouslydepressedone,implementingamechanicalone-of-
manychoicemechanism.
Youshouldgiveeachradiobuttonelementadifferentvaluesothattheforms-
processingservercansortthemoutafterformsubmission.
Here'sthepreviousexamplereworkedinHTMLsothatyougettochooseonlyone
animalasafavoritepet(seeFigure9-4):
Figure9-4.Radiobuttonsallowonlyoneselectionpergroup
<form>
Whichtypeofanimalisyourfavoritepet?
<p>
<inputtype=radioname=favoritevalue="dog">Dog
<inputtype=radiocheckedname=favoritevalue="cat">Cat
<inputtype=radioname=favoritevalue="bird">Bird
<inputtype=radioname=favoritevalue="fish">Fish
</form>
Asinthepreviousexamplewithcheckboxes,we'vetippedourhattowardfelines,
makingtheCatradiobuttonthedefaultchoice.Iftheuserselectsan
alternativeBird,forinstancethebrowserautomaticallydeselectsCatandselects
Bird.Whentheusersubmitstheformtotheserver,thebrowserincludesonlyone
valuewiththename"favorite"inthelistofformparameters;favorite=bird,ifthat
wasthelastchoice.
Oneofthecontrolsinagroupofradiobuttonsalwaysisselected,soitmakesno
sensetocreateasingleradiobutton.Instead,usegroupsoftwoormoreoptions,
suchasforOn/OffandYes/Notypesofformcontrols.
9.5.4.ActionButtons
Althoughtheterminologyispotentiallyconfusing,thereisanotherclassof
buttonsforforms.Unliketheradiobuttonsandcheckboxesdescribedpreviously,
thesespecialtypesofformcontrolsactimmediately,theireffectscannotbe
reversed,andtheyaffecttheentirecontentsoftheform,notjustthevalueofa
singlefield.These"action"buttons(forlackofabetterterm)includesubmit,
reset,regular,andimagebuttons.Whentheuserselectsthem,boththesubmit
andimagebuttonscausethebrowsertosubmitalloftheform'sparameterstothe
forms-processingserver.Aregularbuttondoesnotsubmittheformbutcanbe
usedtoinvokeanapplettomanipulateorvalidatetheform.Theresetbuttonacts
locallytoeraseanyuserinputandhavetheformreverttoitsoriginal(default)
contents.
Inthissection,wedescribetheactionbuttonsthatyoumaycreatewiththe
standardform<input>element.Inthenextsection,wedescribeindetailthenewer
<button>tagthatachievesidenticaleffectsandallowsyougreatercontroloverthe
presentationanddisplayofyourformbuttons.
9.5.4.1.Submissionbuttons
Thesubmitbutton(<inputtype=submit>)doeswhatitsnameimplies,settingin
motiontheform'ssubmissiontotheserverfromthebrowser.Youmayhavemore
thanonesubmitbuttoninaform.Youmayalsoincludenameandvalueattributes
withthesubmittypeofform<input>button.
Withthesimplestsubmitbutton(onewithoutanameorvalueattribute),the
browserdisplaysasmallrectangleorovalwiththedefaultlabel"Submit."
Otherwise,thebrowserlabelsthebuttonwiththetextyouincludewiththetag's
valueattribute.Ifyouprovideanameattribute,thebrowseraddsthevalueattribute
forthesubmitbuttontotheparameterlistandsendsitalongtotheserver.That's
good,becauseitgivesyouawaytoidentifywhichsubmitbuttoninaformthe
userselected,lettingyouprocessanyoneofseveraldifferentformswithasingle
forms-processingapplication.
Allofthefollowingarevalidsubmissionbuttons:
<inputtype=submit>
<inputtype=submitvalue="OrderKumquats">
<inputtype="submit"value="ShipOvernight"name="ship_style"/>
ThefirstoneisinHTMLandisalsothesimplest:thebrowserdisplaysabutton,
labeled"Submit,"whichactivatestheforms-processingsequencewhentheuser
clicksit.Itdoesnotaddanelementtotheparameterlistthatthebrowserpasses
totheforms-processingserverandapplication.
ThesecondexampleHTMLbuttonhasavalueattributethatmakesthedisplayed
button'slabel"OrderKumquats"but,likethefirstexample,doesnotincludethe
button'svalueintheform'sparameterlist.
Thelastexample,inXHTML,setsthebuttonlabelandmakesitpartoftheform's
parameterlist.Whentheuserclicksthissubmissionbutton,itaddstheparameter
ship_style="ShipOvernight"totheform'sparameterlist.
9.5.4.2.Resetbuttons
Theresettypeofform<input>buttonisnearlyself-explanatory:itletstheuser
reseteraseorsettosomedefaultvalueallelementsintheform.Unliketheother
buttons,aresetbuttondoesnotinitiateformprocessing.Instead,thebrowser
doestheworkofresettingtheformelements.Theserverneverknows(orcares,
forthatmatter)whetherorwhentheuserselectsaresetbutton.
Bydefault,thebrowserdisplaysaresetbuttonwiththelabel"Reset."Youcan
changethatbyspecifyingavalueattributewithyourownbuttonlabel.
Herearetwosampleresetbuttons:
<inputtype=reset>
<inputtype="reset"value="UseDefaults"/>
Thefirstone,inHTML,createsaresetbuttonthatisbydefaultlabeled"Reset"by
thebrowser.Thesecondexample,inXHTML,tellsthebrowsertolabelthereset
buttonwith"UseDefaults."Bothexamplesinitiatethesameresponseinthe
browserbyresettingtheformtoitsoriginalcontents.
9.5.4.3.Customimagebuttons
Theimagetypeofform<input>elementisaspecialsubmitbuttonmadeoutofa
picturethat,whenselectedbytheuser,tellsthebrowsertosubmittheformto
theserver.Uponsubmission,thebrowseralsoincludestheX,Ycoordinatesofthe
mousepointerwithintheimageintheform'sparameterlist,muchlikethe
mouse-sensitiveimagemapswediscussedinChapter6.
Imagebuttonsrequireansrcattributeand,asitsvalue,theURLoftheimagefile.
Youcanincludeanameattributeandadescriptivealtattributeforuseby
nongraphicalbrowsers.AlthoughitisdeprecatedinHTML4,youalsomayuse
aligntocontrolalignmentoftheimagewithinthecurrentlineoftext.Usethe
borderattributetocontrolthewidth,ifany,oftheframethatNetscapeandFirefox
putaroundtheformimage,muchliketheborderattributeforthe<img>tag.
(NeitherInternetExplorernorOperaputsbordersaroundform<input>images.)
Hereareacoupleofvalidimagebuttons:
<inputtype="image"src="pics/map.gif"name="map"/>
<inputtype=imagesrc="pics/xmap.gif"align=topname=map>
Thebrowserdisplaysthedesignatedimagewithintheform'scontentflow.The
secondbutton'simageisalignedwiththetopoftheadjacenttext,asspecifiedby
thealignattribute.NetscapeandFirefoxaddaborder,astheydowhenanimage
ispartofananchor(<a>)tag,tosignalthattheimageisaformbutton.
Whentheuserclickstheimage,thebrowsersendsthehorizontaloffset,inpixels,
ofthemousefromtheleftedgeoftheimageandtheverticaloffsetfromthetop
edgeoftheimagetotheserver.Thesevaluesareassignedthenameoftheimage
asspecifiedwiththenameattribute,followedby.xand.y,respectively.Thus,if
someoneclickedtheimagespecifiedinthefirstexample,thebrowserwouldsend
parametersnamedmap.xandmap.ytotheserver.
Imagebuttonsbehavemuchlikemouse-sensitiveimagemaps(usemap),andlike
theprogramsorclient-side<map>tagsthatprocessimagemaps,yourforms
processormayusetheX,Ymouse-pointerparameterstochooseaspecialcourse
ofaction.Youshoulduseanimagebuttonwhenyouneedtheadditionalform
informationtoprocesstheuser'srequest.Ifanimagemapoflinksisallyouneed,
useamouse-sensitiveimagemap.Mouse-sensitiveimagesalsohavetheadded
benefitofprovidingserver-sidesupportforautomaticdetectionofshapeselection
withintheimage,lettingyoudealwiththeimageasaselectablecollectionof
shapes.Formbuttonswithimagesrequireyoutowritecodethatdetermines
wheretheuserclickedontheimageandhowtheservercantranslatethis
positiontoanappropriateaction.
Oddly,theHTML4andXHTMLstandardsallowtheuseoftheusemapattributewith
animagebutton,butdonotexplainhowsuchausemightconflictwithnormal
serverprocessingoftheX,Ycoordinatesofthemouseposition.Werecommend
notmixingthetwo,usingmouse-sensitiveimagesoutsideofformsandimage
buttonswithinforms.
9.5.4.4.Pushbuttons
Usingthe<inputtype=button>tag(orthe<button>tag,describedlaterinthischapter,
insection9.6),youcreateabuttonthattheusermayclick,butthatdoesnot
submitorresettheform.Usethevalueattributetosetthelabelonthebutton.
Thenameattribute,ifincludedinthetag,causesthesuppliedvaluetobepassedto
theforms-processingscript.
Youmightwonderwhatvaluethebuttontypeprovides:littleornone,unlessyou
supplyoneormoreoftheon-eventattributesalongwithasnippetofJavaScriptto
beexecutedwhentheuserinteractswiththebutton.Thusempowered,these
buttonsprovideawayfortheusertoinitiateformcontentvalidation,update
fields,manipulatethedocument,andperformallotherkindsofclient-side
activity.[JavaScriptEventHandlers,12.3.3]
9.5.4.5.Multiplebuttonsinasingleform
Youcanhaveseveralbuttonsofthesameordifferenttypesinasingleform.Even
simpleformsoftenhavebothresetandsubmitbuttons,forexample.To
distinguishbetweenthem,makesureeachhasadifferentvalueattribute,which
thebrowserusesforthebuttonlabel.Dependingonthewayyouprogramthe
forms-processingapplication,youmightmakethenameofeachbuttondifferent,
butitisusuallyeasiertonameallsimilarlyactingbuttonsthesameandletthe
button-handlingsubroutinesortthemoutbyvalue.Forinstance(allinHTML):
<inputtype=submitname=editvalue="Add">
<inputtype=submitname=editvalue="Delete">
<inputtype=submitname=editvalue="Change">
<inputtype=submitname=editvalue="Cancel">
Whentheuserselectsoneoftheseexamplebuttons,aformparameternamed
editgetssenttotheserver.Thevalueofthisparameterisoneofthebutton
names.Theserver-sideapplicationtakesthevalueandbehavesaccordingly.
Becauseanimagebuttondoesn'thaveavalueattribute,theonlywayto
distinguishamongseveralimagebuttonsonasingleformistoensurethatthey
allhavedifferentnames.
9.5.5.HiddenFields
Thelasttypeofform<input>controlwedescribeinthischapterishiddenfrom
view.No,we'renottryingtoconcealanything;it'sawaytoembedinformation
intoyourformsthatthebrowserorusercannotignoreoralter.Thebrowser
automaticallyincludesthe<inputtype=hidden>tag'srequirednameandvalueattributes
inthesubmittedform'sparameterlist.Theseattributesservetolabeltheform
andcanbeinvaluablewhensortingoutdifferentformsorformversionsfroma
collectionofsubmittedandsavedforms.
Anotheruseforhiddenfieldsistomanageuser-serverinteractions.Forinstance,
ithelpstheservertoknowthatthecurrentformhascomefromapersonwho
madeasimilarrequestafewmomentsago.Normally,theserverdoesnotretain
thisinformation,andeachtransactionbetweentheserverandclientiscompletely
independentfromallothertransactions.
Forexample,thefirstformtheusersubmitsmighthaveaskedforsomebasic
information,suchastheuser'snameandwhereshelives.Basedonthatinitial
contact,theservermightcreateasecondformaskingmorespecificquestionsof
theuser.Becauseitistediousforuserstoreenterthesamebasicinformation
fromthefirstform,youcanprogramtheservertoputtheoriginallysubmitted
valuesbackintothesecondforminhiddenfields.Whenthesecondformcomes
back,alltheimportantinformationfrombothformsisthere,andthesecondform
canbematchedtothefirstone,ifnecessary.
Hiddenfieldsalsomaydirecttheservertowardsomespecificaction.Forexample,
youmightembedthefollowinghiddenfield:
<inputtype=hiddenname=actionvalue=change>
Then,ifyouhaveoneserver-sideapplicationthathandlestheprocessingof
severalforms,eachformmightcontainadifferentactioncodetohelpthatserver
applicationsortthemout.
9.6.The<button>Tag
Aswedescribedearlier,youcreateanactionbuttonwithstandardHTMLorXHTML
byincludingitstypevalueinthestandard<input>tag.Forinstance,the<input
type=submit>formcontrolcreatesabuttonthat,whenselectedbytheuser,tellsthe
browsertosendtheform'scontentstotheprocessingserverortoanemail
address(themailtooption).Display-wise,youdon'thaveanydirectcontrolover
whatthatsubmitbuttonlookslike,beyondchangingthedefaultlabel"Submit"to
someotherwordorshortphrase(e.g.,"Hitme"or"Outtahere!").
FirstintroducedintheHTML4.0standard,the<button>tagactsthesameas
<input>,butitgivesyoumorecontroloverhowthebrowserdisplaystheelement.
Inparticular,alloftheattributesyoumightusewiththe<inputtype=button>
elementareacceptablewiththe<button>tag.
<button>
Function Createsabuttonelementwithinaform
Attributes
accesskey,class,dir,disabled,id,lang,name,notab ,onBlur,onClick,onDblClick,
onFocus,onKeyDown,onKeyPress,onKeyUp,onMouseDown,onMouseMove,onMouseOut,
onMouseOver,onMouseUp,style,tabindex,taborder ,title,type,value
Endtag </button>;neveromitted
Contains button_content
Usedin form_content
9.6.1.The<button>Button
NeithertheHTML4northeXHTMLstandardisoverlyclearastowhatdisplay
enhancementstoaformthe<button>elementshouldprovide,otherthanto
suggestthatthecontentsshouldbe3Dandvisuallyappeartoreactlikeapush
buttonwhentheuserselectsit(i.e.,goinandbackoutwhenpressed).Allthe
popularbrowserssupport<button>.
The<button>controlprovidesforagreatervarietyandrichercontentsthanits
<input>analogs.Everythingbetweenthe<button>and</button>tagsbecomesthe
contentofthebutton,includinganyacceptablebodycontent,suchastextor
multimedia.Forinstance,youcouldincludeanimageandrelatedtextwithina
button,creatingattractivelabelediconsinyourbuttons.Theonlyverboten
elementisanimagemapbecauseitsmouse-andkeyboard-sensitiveactions
interferewiththeformbutton.
9.6.2.ThetypeAttribute
Usethetypeattributeforthe<button>tagtodefinethebutton'saction.Youshould
setitsvaluetosubmit,reset,orbutton.Likeits<input>analog,a<buttontype=submit>
formelement,whenselectedbytheuser,tellsthebrowsertopackageandsend
thecontentsoftheformtotheforms-processingserveroremailittothemailto
recipient.Usingtype=resetcreatesaconventionalresetbutton,andusing
type=buttoncreatesaconventionalpushbutton.
Forexample,Figure9-5showsthefollowingexclaim.gificoninsetona3Dbutton
thatpushesinandpopsbackoutwhentheuserclicksitwiththemouse.Indoing
so,thebrowsersubmitstheformtotheserver:
Figure9-5.Aform-submit<button>
<buttontype=submit>
Order<imgsrc="icons/exclaim.gif"align=middlealt="OrderNow">Now!
</button>
Noticethatyoucanexploittherichsetof<img>tagattributes,includingalignand
alt,forthis<button>styleofformcontrol.
Becausethe<button>tagissosimilartothe<inputtype=button>element,whyhaveit
atall?Theonlyreasonistoprovidefarrichercontentforbuttons.Ifyourbuttons
areconventionaltextbuttons,the<input>tagwillsuffice.Ifyouwanttocreate
fancy,mixed-contentbuttons,you'llneedtousethe<button>tag.
9.7.MultilineTextAreas
Theconventionalandhidden-texttypesforformsrestrictuserinputtoasingle
lineofcharacters.The<textarea>formtagsetsusersfree.
9.7.1.The<textarea>Tag
Aspartofaform,the<textarea>tagcreatesamultilinetext-entryareainthe
user'sbrowserdisplay.Init,theusermaytypeanearlyunlimitednumberoflines
oftext.Uponsubmissionoftheform,thebrowsercollectsallthelinesoftext,
eachseparatedby%0D%0A(carriagereturn/linefeed),andsendsthemtotheserver
asthevalueofthisformelement,usingthenamespecifiedbytherequiredname
attribute.
Youmayincludeplaintextinsidethe<textarea>taganditsendtag(</textarea>).
Thatdefaulttextmustbeplaintext,withnotagsorotherspecialelements.The
usermaymodifythecontentsandthebrowserusesthattextasthedefaultvalue
iftheuserpressesaresetbuttonfortheform.Hence,thetextcontentismost
oftenincludedforinstructionsandexamples:
Tellusaboutyourself:
<textareaname=addresscols=40rows=4>
YourNameHere
1234MyStreet
Anytown,StateZipcode
</textarea>
<textarea>
Function Createsamultilinetext-inputarea
Attributes
accesskey,class,cols,dir,disabled,id,lang,name,notab ,onBlur,onChange,
onClick,onDblClick,onFocus,onKeyDown,onKeyPress,onKeyUp,onMouseDown,onMouseMove,
onMouseOut,onMouseOver,onMouseUp,onSelect,readonly,rows,style,tabindex,taborder
,title,wrap
Endtag </textarea>;neveromitted
Contains plain_text
Usedin form_content
9.7.1.1.Therowsandcolsattributes
Amultilinetext-inputareastandsaloneonscreen:bodycontentflowsaboveand
below,butnotaroundit.Youcancontrolitsdimensions,however,bydefiningthe
colsandrowsattributesforthevisiblerectangularareasetasidebythebrowser
formultilineinput.Wesuggestyousettheseattributes.Thecommonbrowsers
haveahabitofsettingasidethesmallest,leastreadableregionpossiblefor
<textarea>input,andtheusercan'tresizeit.Bothattributesrequireintegervalues
fortherespectivedimension'ssizeincharacters.Thebrowserautomatically
scrollstextthatexceedseitherdimension.
9.7.1.2.Thewrapattribute
Normally,thebrowsersendsthetextthatyoutypeintothetextareatothe
serverexactlyastyped,withlinesbrokenonlywheretheuserpressedtheEnter
key.Becausethisisoftennottheactiontheuserdesired,youcanenableword
wrappingwithinthetextarea.Whentheusertypesalinethatislongerthanthe
widthofthetextarea,thebrowserautomaticallymovestheextratextdownto
thenextline,breakingthelineatthenearestpointbetweenwordsintheline.
Withthewrapattributesettovirtual,thetextiswrappedwithinthetextareafor
presentationtotheuser,butistransmittedtotheserverasthoughnowrapping
hadoccurredexceptwheretheuserpressedtheEnterkey.
Withthewrapattributesettophysical,thetextiswrappedwithinthetextareaand
istransmittedtotheserverasthoughtheuserhadactuallytypeditthatway.
Thisisthemostusefulwaytousewordwrapbecausethetextistransmitted
exactlyastheuserseesitinthetextarea.
Toobtainthedefaultaction,setthewrapattributetooff.
Asanexample,considerthefollowing60charactersoftextthatarebeingtyped
intoa40-character-widetextarea:
Wordwrappingisafeaturethatmakeslifeeasierforusers.
Withwrap=off,thetextareacontainsonelineandtheusermustscrolltotheright
toseeallofthetext.Onelineoftextistransmittedtotheserver.
Withwrap=virtual,thetextareacontainstwolinesoftext,brokenaftertheword
makes.Onlyonelineoftextistransmittedtotheserver:theentirelinewithno
embeddednewlinecharacters.
Withwrap=physical,thetextareacontainstwolinesoftext,brokenaftertheword
makes.Twolinesoftextaresenttotheserver,separatedbyanewlinecharacter
afterthewordmakes.
9.8.Multiple-ChoiceElements
Checkboxesandradiobuttonsgiveyoupowerfulmeansforcreatingmultiple-
choicequestionsandanswers,buttheycanleadtolongformsthataretediousto
writeandputafairamountofclutteronscreen.The<select>taggivesyoutwo
compactalternatives:pull-downmenusandscrollinglists.
9.8.1.The<select>Tag
Byplacingalistof<option>-taggeditemsinsidethe<select>tagofaform,you
magicallycreateapull-downmenuofchoices.Figure9-2,earlierinthischapter,
displaysa<select>pull-downmenu.
<select>
Function Createssingle-andmultiple-choicemenus
Attributes
class,dir,disabled,id,lang,multiple,name,notab ,onBlur,onChange,onClick,
onDblClick,onFocus,onKeyDown,onKeyPress,onKeyUp,onMouseDown,onMouseMove,
onMouseOut,onMouseOver,onMouseUp,size,style,tabindex,taborder ,title
Endtag </select>;neveromitted
Contains select_content
Usedin form_content
Aswithotherformtags,thenameattributeisrequiredandusedbythebrowser
whensubmittingthe<select>choicestotheserver.Unlikewithradiobuttons,no
itemispreselected,soiftheuserdoesn'tselectone,thebrowserdoesn'tsendany
valuetotheserverwiththesubmittedform.
Otherwise,thebrowsersubmitstheselecteditemwiththenameattributevalue
whensubmitting<select>formdatatotheserver.
9.8.1.1.Themultipleattribute
Toallowmorethanoneoptionselectionatatime,addthemultipleattributetothe
<select>tag.Thiscausesthe<select>elementtobehavelikean<inputtype=checkbox>
element.Whensubmitted,thebrowsercollectsthemultipleselections,separated
withcommas,intoasingleparameterlist,suchas:
pets=dog,cat,mouse
Ifyoudon'tincludethemultipleattribute,theusermayselectonlyoneoptionata
time,justlikeinagroupofradiobuttons.
9.8.1.2.Thesizeattribute
Thesizeattributedetermineshowmanyoptionsarevisibletotheuseratatime.
Thevalueofsizeshouldbeapositiveinteger.Thedefaultvalueis1.Whensize=1
withoutmultiple,thebrowsertypicallydisplaysthe<select>listasapop-upmenu.
Withsizevaluesgreaterthan1orwithmultiple,thebrowsertypicallydisplaysthe
<select>element'scontentsasascrollinglist.
InthefollowingXHTMLexample,we'veconvertedourpreviouscheckboxexample
intoascrolling,multiple-choicemenu.Noticethatthesizeattributetellsthe
browsertodisplaythreeoptionsatatime:[*]
[*]Noticethe</option>endtags.TheyarenotusuallyincludedinstandardHTMLdocumentsbutmustappearin
XHTML.
Whatpetsdoyouhave?
<selectname="pets"size="3"multiple="multiple">
<option>Dog</option>
<option>Cat</option>
<option>Bird</option>
<option>Fish</option>
</select>
TheresultisshowninFigure9-6.
Figure9-6.A<select>element,formattedwithsize=3
9.8.2.The<option>Tag
Usethe<option>tagtodefineeachitemwithina<select>formcontrol.Thebrowser
displaysthe<option>tag'scontentsasanelementwithinthe<select>tag'smenuor
scrollinglist,sothecontentsmustbeplaintextonly,withoutanyothersortof
markup.
<option>
Function Definesavailableoptionswithina<select>menu
Attributes
class,dir,disabled,id,label,lang,onClick,onDblClick,onKeyDown,onKeyPress,
onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,selected,style,
title,value
Endtag </option>;usuallyomittedinHTML
Contains plain_text
Usedin select_content
9.8.2.1.Thevalueattribute
Usethevalueattributetosetavalueforeachoptionthebrowsersendstothe
serveriftheuserselectsthatoption.Ifthevalueattributehasnotbeenspecified,
thevalueoftheoptionissettothecontentofthe<option>tag.Asanexample,
considertheseHTMLoptions:
<optionvalue=Dog>Dog
<option>Dog
Bothhavethesamevalue.Thefirstisexplicitlysetwithinthe<option>tag;the
seconddefaultstothecontentofthe<option>tagitself:"Dog".
9.8.2.2.Theselectedattribute
Bydefault,alloptionswithinamultiple-choice<select>tagareunselectedand
thereforenotincludedintheparameterslistwhentheclientsubmitstheformto
theserver.Includetheselectedattributeinsidethe<option>tagtopreselectoneor
moreoptions,whichtheusermaythendeselect.
TheHTMLversionoftheselectedattributehasnovalue;theXHTMLversionhas
thevalueselected="selected".Single-choice<select>tagspreselectthefirstoptionif
nooptionisexplicitlypreselected.
9.8.2.3.Thelabelattribute
Normally,thebrowsercreatesalabelfromthecontentsofthe<option>tagwhen
displayingittotheuser.Ifthelabelattributeissupplied,itsvalueisusedasthe
labelinstead.
9.8.3.The<optgroup>Tag
Menusofchoicesinformscanbequitelarge,makingthemdifficulttodisplayand
use.Inthesecases,itishelpfultogrouprelatedchoices,whichcanthenbe
presentedasasetofnested,cascadingmenustotheuser.IntroducedinHTML
4.0,the<optgroup>tagbringsthiscapabilitytoHTMLandXHTMLforms,albeitina
limitedway.
Youcanusethe<optgroup>tagonlywithina<select>tag,anditmaycontainonly
<option>tags.Thebrowsercreatessubmenusforeach<optgroup>tagwithinthe
main<select>menu.
Forexample,withHTMLyoumightuse<optgroup>topresentaformmenuofstates
organizedbyregion(Figure9-7):
Figure9-7.The<optgroup>taghelpsorganizeform<select>
menus
<selectname=state>
<optgrouplabel=Northeast>
<option>Maine
<option>NewHampshire
...
</optgroup>
<optgrouplabel=South>
<option>Florida
<option>Georgia
</optgroup>
...
</select>
LikethatshownforOperainFigure9-7,theotherpopularGUIbrowserssimilarly
indentthe<optgroup>itemswithinascrollingmenu,thoughtheothersitalicizeand
makethegroupheadersbold.
Thebiggestdrawbacktothe<optgroup>tagisthatitcannotbenested,limitingyou
toonelevelofsubmenus.Presumably,thisrestrictionwillbeliftedinafuture
versionofXHTML.
<optgroup>
Function Groupsrelated<option>elementswithina<select>menu
Attributes class,dir,disabled,id,label,lang,onClick,onDblClick,onKeyDown,onKeyPress,
onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </optgroup>;maybeomittedinHTML
Contains optgroup_content
Usedin select_content
9.8.3.1.Thelabelattribute
Usethelabelattributetodefinean<optgroup>submenutitletotheuser.Youshould
keepthelabelshortandtothepointtoensurethatthemenucanbedisplayed
easilyonalargevarietyofdisplays.
9.9.GeneralForm-ControlAttributes
Themanyform-controltagscontaincommonattributesthat,likemostothertags,
generallyservetolabel,setupthedisplay,extendthetextlanguage,andmake
thetagextensibleprogrammatically.
9.9.1.TheidandtitleAttributes
Theidattribute,asformostotherstandardtags,letsyouattachauniquestring
labeltotheformcontrolanditscontentsforreferencebyprograms(applets)and
hyperlinks.Thisnameisdistinctfromthenameassignedtoacontrolelement
withthenameattribute.Namesassignedwiththeidattributearenotpassedtothe
serverwhentheformisprocessed.
Thetitleattributeissimilartoidinthatitusesaquote-enclosedstringvalueto
labeltheformcontrol.However,ittitlesonlytheformsegment;youcannotuse
itsvalueinanappletreferenceorhyperlink.Browsersmayusethetitleaspop-
uphelpfortheuserorinnonvisualpresentationoftheform.[Theidattribute,
4.1.1.4][Thetitleattribute,4.1.1.5]
9.9.2.TheeventAttributes
Likemostotherelements,mostoftheformcontrolssupportanumberofuser
mouseandkeyboardevent-relatedattributesthattheHTML4/XHTML-compliant
browserrecognizesandletsyouspeciallyprocessusingJavaScriptoraJava
applet,forexample.WedescribethemajorityoftheseeventsindetailinChapter
12.
9.9.3.Thestyle,class,lang,anddirAttributes
Thestyleattributeforthevariousformcontrolscreatesaninlinestyleforthe
elementsenclosedbythetag,overridinganyotherstylerulesineffect.Theclass
attributeletsyouformatthecontentaccordingtoapredefinedclassofthe<form>
tag;itsvalueisthenameofthatclass.[InlineStyles:ThestyleAttribute,8.1.1]
[StyleClasses,8.3]
Thelangattributespecifiesthelanguageusedwithinacontrol,acceptingasits
valueanyoftheISOstandardtwo-characterlanguageabbreviations,includingan
optionallanguagemodifier.Forexample,addinglang=en-UKtellsthebrowserthat
thelistisinEnglish("en")asspokenandwrittenintheUnitedKingdom("UK").
Presumably,thebrowsermaymakelayoutortypographicdecisionsbasedupon
yourlanguagechoice.[Thelangattribute,3.6.1.2]
Similarly,thedirattributetellsthebrowserinwhichdirectiontodisplaythe
controlcontentseitherfromlefttoright(dir=ltr),likeEnglishandFrench,orfrom
righttoleft(dir=rtl),aswithHebrewandChinese.[Thedirattribute,3.6.1.1]
Thepopularbrowserssupportthedirandlangattributes,eventhoughthereare
nobehaviorsdefinedforanyspecificlanguage.
9.9.4.Thetabindex,taborder ,andnotab Attributes
Bydefault,allelements(excepthiddenelements)arepartoftheform'staborder.
AstheuserpressestheTabkey,thebrowsershiftstheinputfocusfromelement
toelementintheform.Formostbrowsers,thetabbingorderoftheelements
matchestheorderoftheelementswithinthe<form>tag.Withthetabindex
attribute,youcanchangetheorderandthepositionofthoseelementswithinthe
taborder.
Torepositionanelementwithinthetaborder,setthevalueoftheattributetothe
element'sdesiredpositioninthetaborder,withthefirstelementintheorder
beingnumberone.Ifyoureallywanttochangeaform'staborder,wesuggest
youincludethetabindexattributewitheveryelementintheform,withan
appropriatevalueforeachelement.Inthisway,you'llbesuretoplaceevery
elementexplicitlyinthetaborder,andtherewillbenosurpriseswhentheuser
tabsthroughtheform.
Thevalueofthetabindexattributeisapositiveintegerindicatingthepositionof
thetaggedcontentsintheoveralltabsequenceforthedocument.Thetabbing
orderbeginswithelementswithexplicittabindexvalues,startingfromthelowest
tothehighestnumbers.Same-valuedtagsgettab-selectedintheorderinwhich
theyappearinthedocument.Allotherselectabletags,suchasthevariousform
controlsandhyperlinks,arethelasttogettabbed,intheorderinwhichthey
appearinthedocument.Toexcludeanelementfromthetaborder,setthevalue
oftabindexto0.Theelementisskippedwhentheusertabsaroundtheform.
InternetExplorerintroducedtheconceptoftab-ordermanagementwithits
proprietarytaborderandnotabattributes.Thetaborderattributefunctionsexactly
likethetabindexattribute,andnotabisequivalenttotabindex=0.InternetExplorer
versions5andlaternowsupportthestandardtabindex,asdotheotherpopular
browsers.Consequently,westronglysuggestthatyouusethetabindexattribute
andnottaborder.
9.9.5.TheaccesskeyAttribute
Manyuserinterfacespromotetheideaofshortcutkeys:shortsequencesof
keystrokesthatgiveyouquickaccesstoanelementintheuserinterface.HTML4
andXHTMLprovidesupportforthiscapabilitywiththeaccesskeyattribute.The
valueoftheaccesskeyattributeisasinglecharacterthat,whenpressedin
conjunctionwithsomeotherspecialkey,causesfocustoshiftimmediatelytothe
associatedformelement.Thisspecialkeyvarieswitheachuserinterface:PC
userspresstheAltkey,whereasUnixkeyboarduserstypicallypresstheMeta
key.
Forexample,addingaccesskey="T"toa<textarea>elementwouldcausefocustoshift
tothattextareawhenaWindowsuserpressedAlt-T.Notethatthevalueofthe
accesskeyattributeisasinglecharacterandiscasesensitive(acapital"T"isnot
thesameasitslowercasecousin,forinstance).
Allthepopularbrowserssupporttheaccesskeyattribute.Becarefultotestyour
hot-keyoptions,however.Forinstance,whileAlt-fworkswithInternetExplorerto
jump-selectthetagwiththeaccesskey="f"attribute,inNetscapethiskey
combinationopenstheFilepull-downmenu.
Alsonotethattheaccesskeyoptionnotonlyjumpstobutalsoselectsthe
associatedformelement.So,forinstance,ifyouassociateanaccesskeywitha
radiobutton,bypressingtheaccess-keycombination,theuserdisplaynotonly
shiftsfocustothatradiobuttonbutalsoselectsit,asthoughtheuserhadclicked
themouseonthatelement.Thesamegoesforallactionformelements:jump
andselect.
9.9.6.ThedisabledandreadonlyAttributes
TheHTML4andXHTMLstandardsletyoudefinebutotherwisedisableaform
controlsimplybyinsertingthedisabledattributewithinthetag.Adisabledform
controlappearsinthedisplaybutcannotbeaccessedviatheTabkeyorotherwise
selectedwiththemouse.Itsparametersarenotpassedtotheserverwhenthe
usersubmitstheform.
Browserscanchangetheappearanceofdisabledelementsandalteranylabels
associatedwiththem.Thepopularbrowsersgrayoutdisabledradioandsubmit
buttons,asinthefollowingHTMLfragment(alsoshowninFigure9-8):
Figure9-8.Disabledformcontrolsturngray
<form>
Name:
<inputtype=textname=namesize=32maxlength=80readonly>
<p>
Sex:
<inputtype=radioname=sexvalue="M"disabled>Male
<inputtype=radioname=sexvalue="F"accesskey="z">Female
<p>
Income:
<selectname=incomesize=1disabled>
<option>Under$25,000
<option>$25,001to$50,000
<option>$50,001andhigher
</select>
<p>
<inputtype=submitdisabled>
</form>
Similarly,theusermaynotalteratext-related<input>or<textarea>formcontrol
thatyoudesignateasreadonlywiththeattribute.Theseelementsarestillpartof
thetaborderandmaybeselected,andthevalueofthecontrolgetssenttothe
serverwhentheusersubmitstheform.Theuserjustcan'talterthevalue.So,in
asense,aformcontrolrenderedreadonlyisthevisibleanalogofthe<input
type=hidden>control.
Whatisthepointofallthesehiddenandunchangeableformelements?
Automation.Byautomaticallygeneratingenabledanddisabledformelements,
youcantailortheformtotheuser.Forexample,iftheuserindicatesononeform
thatsheisfemale,asubsequentformmaycontainthatinformationinahidden
attribute,andcertainelementsintheformmaybedisplayedforfamiliaritywhile
certainelementsaredisabledtomaketheformeasiertonavigate.
9.10.LabelingandGroupingFormElements
Thecommontextandothercontentyoumayusetolabelandotherwiseexplaina
formarestatic.Otherthanbytheirvisualrelationshiptotheform'sinputareas,
theselabelsandinstructionsareunassociatedwiththeformcontrolsthatthey
serve.Becauseofthis,formsarenoteasilyunderstoodandnavigable,particularly
bypeoplewithimpairedvision.Tryit.Getasimplepersonal-informationform
onscreen,closeyoureyes,andfindtheplacetoenteryourname.
TheHTML4.0standardintroducedthreetagsthatmakenavigationofforms
easierforusers,particularlythosewithdisabilities.Theyincludeawaytogroup
andcaptionregionsoftheformandawaytoindividuallylabelformcontrols.All
aresupposedtogetspecialtreatmentbythebrowser,suchasbeingrenderedbya
speechsynthesizeraswellasspeciallydisplayed,andcanbeeasilyaccessedfrom
theuserkeyboardthatis,whenbrowsersbecomefullyHTML4/XHTMLcompliant.
9.10.1.The<label>Tag
Usethe<label>tagtodefinerelationshipsbetweenaformcontrol,suchasatext-
inputfield,andoneormoretextlabels.Accordingtothelateststandards,the
textinalabelistoreceivespecialtreatmentbythebrowser.Browsersmay
chooseaspecialdisplaystyleforthelabel(youcan,too,withstylesheets).And
whenselectedbytheuser,thebrowserautomaticallytransfersfocustoalabel's
associatedformcontrol.
<label>
Function Createsalabelforaformelement
Attributes
accesskey,class,dir,for,id,lang,onBlur,onClick,onDblClick,onFocus,onKeyDown,
onKeyPress,onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,
style,title
Endtag </label>;neveromitted
Contains label_contents
Usedin form_content
9.10.1.1.Implicitandexplicitassociations
Oneormorelabelsgetassociatedwithaformcontrolinoneoftwoways:
implicitly,byincludingtheformcontrolascontentsofthelabeltag,orexplicitly,
bynamingtheIDofthetargetformcontrolinthe<label>tag'sforattribute.
Forexample,inXHTML:
<labelfor="SSN">SocialSecurityNumber:</label>
<inputtype="text"name="SocSecNum"id="SSN"/>
<label>Dateofbirth:<inputtype="text"name="DofB"/></label>
Thefirstlabelexplicitlyrelatesthetext"SocialSecurityNumber:"withtheform's
SocialSecuritynumbertext-inputcontrol(SocSecNum),becauseitsforattribute's
valueisidenticaltothecontrol'sid,SSN.Thesecondlabel("Dateofbirth:")does
notrequireaforattribute,nordoesitsrelatedcontrolrequireanidattribute,
becausetheyareimplicitlyjoinedbyplacingthe<input>tagwithinthe<label>tag.
Becarefulnottoconfusethenameandidattributes.Theformercreatesanamefor
anelementthatthebrowsersendstotheserver-sideformsprocessor;idcreates
anamethat<label>tagsandURLscanuse.Notealsothatalthoughalabelmay
referenceonlyasingleformcontrol,severallabelsmayreferenceasinglecontrol.
Thus,youcansteeruserstoaparticularforminputregionfromseveralplacesin
adocument.
9.10.1.2.Otherlabelattributes
Labelsalsosharemanyofthegeneraldisplay,access,andevent-relatedtag
attributesdescribedearlierinsection9.9.InadditiontothestandardHTML4and
XHTMLeventattributes,labelsalsosupporttheonfocusandonblurattributes.
9.10.2.FormingaGroup
Beyondindividuallabels,youmaygroupasetofformcontrolsandlabelthe
groupwiththe<fieldset>and<legend>tags.Again,theHTML4andXHTML
standardsattempttomakeformsmorereadilyaccessiblebyusers,particularly
thosewithdisabilities.Groupingformcontrolsintoexplicitsectionsgivesyouthe
opportunitytospeciallydisplayandotherwisemanagetheformcontents.
9.10.2.1.The<fieldset>tag
The<fieldset>tagencapsulatesasectionofformcontents,creatingagroupof
relatedformfields.<fieldset>doesn'thaveanyrequiredoruniqueattributes.
<fieldset>
Function Groupsrelatedelementswithinaform
Attributes class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,onMouseDown,
onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </fieldset>;neveromitted
Contains form_content
Usedin form_content
Whenagroupofformelementsareplacedwithina<fieldset>tag,thebrowser
maydisplaytheminaspecialmanner.Thismightincludeaspecialborder,3D
effects,orevencreatingasubformtohandletheelements.
9.10.2.2.The<legend>tag
Usethe<legend>tagtocreatealabelforafieldsetinaform.Thetagmayappear
onlyinsidea<fieldset>.Aswith<label>,the<legend>contentsaretobespecially
treatedbytheHTML4/XHTML-compliantbrowser,transferringfocustoassociated
formelementswhenselectedandservingtoimproveaccessibilityofuserstoa
<fieldset>.
<legend>
Function Createsalegendforafieldsetwithinaform
Attributes accesskey,align,class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,
onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </legend>;maybeomittedinHTML
Contains legend_content
Usedin form_content
Inadditiontosupportingmanyoftheformelementattributesdescribedearlierin
section9.9,the<legend>tagacceptstheaccesskeyattributeandthealignattribute.
Thevalueofalignmaybetop,bottom,left,orright,instructingthebrowserwhere
thelegendshouldbeplacedwithrespecttothefieldset.
Bringingallthesetagstogether,hereareafieldsetandlegendcontainingafew
formelements,individuallylabeled:
<fieldset>
<legend>Personalinformation</legend>
<label>Name:<inputtype="text"/></label>
<label>Address:<inputtype="text"/></label>
<label>Phone:<inputtype="text"/></label>
</fieldset>
NoticeinFigure9-9howFirefoxneatlyputsaframearoundthefieldsetand
throughthelegendbutdoesn'totherwiseformatthefieldset'scontents.
Obviously,you'llneedtodosomeformat-tweakingyourself.
Figure9-9.Browsersfullyframeformfieldsets
9.11.CreatingEffectiveForms
Properlydone,aformcanprovideaneffectiveuserinterfaceforyourreaders.
Withsomeserver-sideprogrammingtricks,youcanuseformstopersonalizethe
documentsthatyoupresenttoreadersandtherebysignificantlyincreasethe
valueofyourpagesontheWeb.
9.11.1.BrowserConstraints
UnlikeotherGUIs,browserdisplaysarestatic.Theyhavelittleornocapabilityfor
real-timedatavalidation,forexample,orforupdatingthevaluesinaformbased
uponuserinput,givingusersnohelporguidance.[*]Consequently,poorly
designedwebformsaredifficulttofillout.
[*]Thisisnotentirelytrue.WhileneitherHTMLnorXHTMLprovidesfordatavalidationanduserguidance,itispossibleto
attachtoyourformelementsJavaorJavaScriptappletsthatdoaverynicejobofvalidatingformdata,updatingform
fieldsbaseduponuserinput,andguidingusersthroughyourforms.
Makesureyourformsassistusersasmuchaspossible.Forexample,adjustthe
sizeoftext-inputfieldstogivecluesonacceptableinput;five-character(ornine-
character)zipcodes,forinstance.Usecheckboxes,radiobuttons,andselection
listswheneverpossibletonarrowthelistofchoicestheusermustmake.
Makesureyoualsoadequatelydocumentyourforms.Explainhowtofillthem
out,supplyingexamplesforeachfield.Provideappropriatehyperlinksto
documentationthatdescribeseachfield,ifnecessary.
Whentheformissubmitted,makesurethattheserver-sideapplication
exhaustivelyvalidatestheuser'sdata.Ifanerrorisdiscovered,presenttheuser
withintelligenterrormessagesandpossiblecorrections.Oneofthemost
frustratingaspectsoffillingoutformsistohavetostartoverfromscratch
whenevertheserverdiscoversanerror.Toalleviatethisuglyredundancyand
burdenonyourreaders,considerspendingextratimeandresourcesonthe
serversidethatreturnstheuser'scompletedformwiththeerroneousfields
flaggedforchanges.
Whilethesesuggestionsrequiresignificanteffortonyourpart,theypayoffmany
timesoverbymakinglifeeasierforyourusers.Remember,youcreatetheform
justonce,butitmaybeusedthousandsorevenmillionsoftimesbyusers.
9.11.2.HandlingLimitedDisplays
AlthoughmostPCshavebeenupgradedtoprovideresolutionsignificantlybetter
thanthe600x480thatwascommonwhenwewrotethefirsteditionofthis
book,manydevices(WebTV,cellphoneswithbuilt-inbrowsers,PDAs)dictatethat
formdesignshouldbeconservative.Thebestcompromiseistoassumea
document-viewingwindowroughly75readablecharacterswideand30to50lines
tall.[*]Youshoulddesignyourforms(andallyourdocuments)sothattheyare
effectivewhenviewedthroughawindowofthissize.
[*]Somedevices,suchascellphones,havetinydisplays,assmallasfourlines.Abetterapproach,thoughbeyondthe
scopeofthisbook,istotailoryourdesigntothedevice,usingExtensibleStylesheetTransformations(XSLT).
Youshouldstructureyourformtoscrollnaturallyintotwoorthreelogical
sections.Theusercanfilloutthefirstsection,pagedown;filloutthesecond
section,pagedown;andsoforth.
Youshouldalsoavoidwideinputelements.Itisdifficultenoughtodealwitha
scrollingtextfieldortextareawithouthavingtoscrollthedocumentitself
horizontallytoseeadditionalportionsoftheinputelement.
9.11.3.User-InterfaceConsiderations
Whenyouelecttocreateaform,youimmediatelyassumeanotherrole:thatofa
user-interfacedesigner.Whileacompletediscussionofuser-interfacedesignis
beyondthescopeofthisbook,ithelpstounderstandafewbasicdesignrulesto
createeffective,attractiveforms.
Anyuserinterfaceisperceivedatseverallevelssimultaneously.Formsareno
different.Atthelowestlevel,yourbrainrecognizesshapeswithinthedocument,
attemptingtocategorizetheelementsoftheform.Atahigherlevel,youare
readingthetextguidesandprompts,tryingtodeterminewhatinputisrequiredof
you.Atthehighestlevel,youareseekingtoaccomplishagoalwiththeinterface
asyourtool.
Agoodformaccommodatesallthreeoftheseperceptiveneeds.Inputelements
shouldbeorganizedinlogicalgroupssothatyourbraincanprocesstheform
layoutinchunksofrelatedfields.Consistent,well-writtenpromptsandsupporting
textassistandleadtheusertoenterthecorrectinformation.Textpromptsalso
remindusersofthetaskathandandreinforcetheform'sgoal.
9.11.4.CreatingFormsThatFlow
Usersprocessformsinapredictableorder,oneelementafteranother,seekingto
findthenextelementastheyfinishthepreviousone.Toaccommodatethis
searchingprocess,youshoulddesignyourformssothatonefieldleadsnaturally
toanotherandrelatedfieldsaregroupedtogether.Similarly,groupsshouldlead
naturallytooneanotherandshouldbeformattedinaconsistentmanner.
Simplystringinganumberoffieldstogetherdoesnotconstituteaneffectiveform.
Youmustputyourselfintheplaceofyourusers,whoareusingtheformforthe
firsttime.Testyourformonunsuspectingfriendsandcolleaguesbeforeyou
releaseittothegeneralpublic.Isiteasytodeterminethepurposeoftheform?
Wheredoyoustartfillingthingsout?Cantheuserfindabuttontoclicktosubmit
theform?Isthereanopportunitytoconfirmdecisions?Doreadersunderstand
whatisexpectedofthemforeachfield?
Yourformsshouldleadtheusernaturallythroughtheprocessofsupplyingthe
necessarydatafortheapplication.Youwouldn'taskforastreetaddressbefore
askingfortheuser'sname;otherrulesmaydictatetheorderingofothergroups
ofinputelements.Toseewhetheryourformreallyworks,makesureyouviewit
onseveralbrowsersandhaveseveralpeoplefillitoutandcommentonits
effectiveness.
9.11.5.GoodForm,OldChap
Atfirstglance,thebasicruleofHTMLandXHTMLcontent,notstyleseemsindirect
oppositiontothebasicruleofgoodinterfacedesignprecise,consistentlayout.
Evenso,itispossibletousesomeelementstogreatlyimprovethelayoutand
readabilityofmostforms.
Traditionalpagelayoutusesagridofcolumnstoaligncommonelementswithina
page.Theresultingimpliedverticalandhorizontal"edges"ofadjacentelements
giveasenseoforderandorganizationtothepageandmakeiteasyfortheeyeto
scanandfollow.
HTMLandXHTMLmakeithard,butyoucanaccomplishthesamesortoflayout
foryourforms.Forexample,youcangrouprelatedelementsandseparategroups
withemptyparagraphsorhorizontalrules.
Verticalalignmentismoredifficult,butnotimpossible.Ingeneral,formsare
easiertouseifyouarrangetheinputelementsverticallyandalignedtoa
commonmargin.Onepopularformlayoutkeepstheleftedgeoftheinput
elementsaligned,withtheelementlabelsimmediatelytotheleftoftheelements.
Thisisdonebyusingtablestoplaceandaligneachformelementanditslabel.
HereisourpreviousHTMLformexample,withthelabelsplacedinthefirst
columnandthecorrespondingelementsinthesecond:
<formmethod=POSTaction="http://www.kumquat.com/demo">
<tableborder=0>
<trvalign=top>
<tdalign=right>Name:</td>
<tdalign=left><inputtype=textname=namesize=32maxlength=80>
</td>
</tr>
<trvalign=top>
<tdalign=right>Sex:</td>
<tdalign=left>
<inputtype=radioname=sexvalue="M">Male<br>
<inputtype=radioname=sexvalue="F">Female
</td>
</tr>
<trvalign=top>
<tdalign=right>Income:</td>
<tdalign=left>
<selectname=incomesize=1>
<option>Under$25,000
<option>$25,001to$50,000
<option>$50,001andhigher
</select>
</td>
</tr>
<trvalign=top>
<tdcolspan=2align=center>
<inputtype=submitvalue="SubmitQuery">
</td>
</tr>
</table>
</form>
Noticeintheresultingrenderedform,showninFigure9-10,thatthetablehas
placedeachinputelementinitsownrow.Thealignattributesinthetablecells
forcethelabelstotherightandtheelementstotheleft,creatingavertical
marginthroughtheform.Byspanningthecellinthelastrow,thesubmission
buttoniscenteredwithrespecttotheentireform.Ingeneral,usingtablesinthis
mannermakesformlayoutmucheasierandmoreconsistentthroughoutyour
documents.Ifyoufindthisexampleatalldifficult,seeChapter10,whichexplains
indetailallthegloriesoftables.
Figure9-10.Useaconsistentverticalmargintoalignform
elements
Youmayfindotherconsistentwaystolayoutyourforms.Thekeyistofinda
usefullayoutstylethatworkswellacrossmostbrowsersandstickwithit.Even
thoughHTMLandXHTMLhavelimitedtoolstocontrollayoutandpositioning,take
advantageofwhatisavailableinordertomakeyourformsmoreattractiveand
easiertouse.
9.12.FormsProgramming
Ifyoucreateforms,soonerorlateryou'llneedtocreatetheserver-side
applicationthatprocessesthem.Don'tpanic.Thereisnothingmagicaboutserver-
sideprogramming,norisitoverlydifficult.Withalittlepracticeandsome
perseverance,you'llbecrankingoutformsapplications.
Themostimportantadvicewecangiveaboutformsprogrammingiseasyto
remember:copyothers'work.Writingaformsapplicationfromscratchisfairly
hard;copyingafunctioningformsapplicationandmodifyingittosupportyour
formisfareasier.
Fortunately,servervendorsknowthis,andtheyusuallysupplysampleforms
applicationswiththeirserver.Rummageaboutforadirectorynamedcgi-src,and
youshoulddiscoveranumberofusefulexamplesyoucaneasilycopyandreuse.
Wecan'thopetoreplicatealltheusefulstuffthatcamewithyourserveror
provideacompletetreatiseonformsprogramming.Whatwecandoisoffera
simpleexampleofGETandPOSTapplications,givingyouafeelforthework
involvedandhopefullygettingyoumovingintherightdirection.
Beforewebegin,keepinmindthatnotallserversinvoketheseapplicationsinthe
samemanner.Ourexamplescoverthebroadclassofserversderivedfromthe
originalNationalCenterforSupercomputingApplications(NCSA)HTTPserver.
Theyalsoshouldworkwiththeverypopularandpublic-domainApacheserver.In
allcases,consultyourserverdocumentationforcompletedetails.Youwillfind
evenmoredetailedinformationinCGIProgrammingwithPerl,byScottGuelich,
GuntherBirznieks,andShishirGundavaram,andWebmasterinaNutshell,by
StephenSpainhourandRobertEckstein,bothpublishedbyO'Reilly.
OnealternativetoCGIprogrammingistheJavaservletmodel,coveredinJava
ServletProgramming,byJasonHunterwithWilliamCrawford(O'Reilly).Servlets
canbeusedtoprocessGETandPOSTformsubmissions,althoughtheyare
actuallymoregeneralobjects.Therearenoexamplesofservletsinthisbook.
9.12.1.ReturningResults
Beforewebegin,weneedtodiscusshowserver-sideapplicationsend.Allserver-
sideapplicationspasstheirresultsbacktotheserver(andontotheuser)by
writingthoseresultstotheapplication'sstandardoutputasaMIME-encodedfile.
Hence,thefirstlineoftheapplication'soutputmustbeaMIMEContent-Type
descriptor.IfyourapplicationreturnsanHTMLdocument,thefirstlineis:
Content-type:text/html
Thesecondlinemustbecompletelyempty.Yourapplicationcanreturnother
contenttypes,toojustincludethecorrectMIMEtype.AGIFimage,forexample,is
precededwith:
Content-type:image/gif
GenerictextthatisnottobeinterpretedasHTMLcanbereturnedwith:
Content-type:text/plain
Thisisoftenusefulforreturningtheoutputofothercommandsthatgenerate
plaintextratherthanHTML.
9.12.2.HandlingGETForms
WiththeGETmethod,thebrowserpassesformparametersaspartoftheURL
thatinvokestheserver-sideformsapplication.AtypicalinvocationofaGET-style
applicationmightuseaURLlikethis:
http://www.kumquat.com/cgi-bin/dump_get?name=bob&phone=555-1212
Whenthewww.kumquat.comserverprocessesthisURL,itinvokestheapplication
nameddump_getthatisstoredinthedirectorynamedcgi-bin.Everythingafter
thequestionmarkispassedtotheapplicationasparameters.
Thingsdivergeabitatthispoint,duetothenatureoftheGET-styleURL.While
formsplacename/valuepairsintheURL,itispossibletoinvokeaGET-style
applicationwithonlyvaluesintheURL.Thus,thefollowingisavalidinvocation
aswell,withparametersseparatedbyplussigns(+):
http://www.kumquat.com/cgi-bin/dump_get?bob+555-1212
Thisisacommoninvocationwhenthebrowserreferencestheapplicationviaa
searchabledocumentwiththe<isindex>tag.Theparameterstypedbytheuserinto
thedocument'stext-entryfieldgetpassedtotheserver-sideapplicationas
unnamedparametersseparatedbyplussigns.
IfyouinvokeyourGETapplicationwithnamedparameters,yourserverpasses
thoseparameterstotheapplicationinoneway;unnamedparametersarepassed
differently.
9.12.2.1.UsingnamedparameterswithGETapplications
NamedparametersarepassedtoGETapplicationsbycreatinganenvironment
variablenamedQUERY_STRINGandsettingitsvaluetotheentireportionoftheURL
followingthequestionmark.Usingourpreviousexample,thevalueofQUERY_STRING
wouldbesetto:
name=bob&phone=555-1212
Yourapplicationmustretrievethisvariableandextractfromittheparameter
name/valuepairs.Fortunately,mostserverscomewithasetofutilityroutines
thatperformthistaskforyou,soasimpleCprogramthatjustdumpsthe
parametersmightlooklikethis:
#include<stdio.h>
#include<stdlib.h>
#defineMAX_ENTRIES10000
typedefstruct{char*name;
char*val;
}entry;
char*makeword(char*line,charstop);
charx2c(char*what);
voidunescape_url(char*url);
voidplustospace(char*str);
main(intargc,char*argv[])
{entryentries[MAX_ENTRIES];
intnum_entries,i;
char*query_string;
/*GetthevalueoftheQUERY_STRINGenvironmentvariable*/
query_string=getenv("QUERY_STRING");
/*Extracttheparameters,buildingatableofentries*/
for(num_entries=0;query_string[0];num_entries++){
entries[num_entries].val=makeword(query_string,'&');
plustospace(entries[num_entries].val);
unescape_url(entries[num_entries].val);
entries[num_entries].name=
makeword(entries[num_entries].val,'=');
}
/*SpitouttheHTMLboilerplate*/
printf("Content-type:text/html\n");
printf("\n");
printf(<html>);
printf(<head>);
printf("<title>NamedParameterEcho</title>\n");
printf("</head>");
printf(<body>);
printf("Youenteredthefollowingparameters:\n");
printf("<ul>\n");
/*Echotheparametersbacktotheuser*/
for(i=0;i<num_entries;i++)
printf("<li>%s=%s\n",entries[i].name,
entries[i].val);
/*Andcloseoutwithmoreboilerplate*/
printf("</ul>\n");
printf("</body>\n");
printf("</html>\n");
}
Theexampleprogrambeginswithafewdeclarationsthatdefinetheutility
routinesthatscanthroughacharacterstringandextracttheparameternames
andvalues.[*]ThebodyoftheprogramobtainsthevalueoftheQUERY_STRING
environmentvariableusingthegetenv()systemcall,usestheutilityroutinesto
extracttheparametersfromthatvalue,andthengeneratesasimpleHTML
documentthatechoesthosevaluesbacktotheuser.
[*]Theseroutinesareusuallysuppliedbytheservervendor.TheyarenotpartofthestandardCorUnixlibrary.
Forrealapplications,youshouldinsertyouractualprocessingcodeafterthe
parameterextractionandbeforetheHTMLgeneration.Ofcourse,you'llalsoneed
tochangetheHTMLgenerationtomatchyourapplication'sfunctionality.
9.12.2.2.UsingunnamedparameterswithGETapplications
Unnamedparametersgetpassedtotheapplicationascommand-lineparameters.
Thismakeswritingtheserver-sideapplicationalmosttrivial.Hereisasimpleshell
scriptthatdumpstheparametervaluesbacktotheuser:
#!/bin/csh-f
#
#DumpunnamedGETparametersbacktotheuser
echo"Content-type:text/html"echo
echo'<html>'
echo'<head>'
echo'<title>UnnamedParameterEcho</title>'
echo'</head>'
echo'<body>'
echo'Youenteredthefollowingparameters:'
echo'<ul>'
foreachi($*)
echo'<li>'$i
end
echo'</ul>'
echo'</body>'
exit0
Again,wefollowthesamegeneralstyle:outputagenericdocumentheader,
includingtheMIMEContent-Type,followedbytheparametersandsomeclosing
boilerplate.Toconvertthistoarealapplication,replacetheforeachloopwith
commandsthatactuallydosomething.
9.12.3.HandlingPOSTForms
Forms-processingapplicationsthatacceptHTML/XHTMLPOST-styleparameters
expecttoreadencodedparametersfromtheirstandardinput.LikeGET-style
applicationswithnamedparameters,theycantakeadvantageoftheserver's
utilityroutinestoparsetheseparameters.
HereisaprogramthatechoesthePOST-styleparametersbacktotheuser:
#include<stdio.h>
#include<stdlib.h>
#defineMAX_ENTRIES10000
typedefstruct{char*name;
char*val;
}entry;
char*makeword(char*line,charstop);
char*fmakeword(FILE*f,charstop,int*len);
charx2c(char*what);
voidunescape_url(char*url);
voidplustospace(char*str);
main(intargc,char*argv[])
{entryentries[MAX_ENTRIES];
intnum_entries,i;
/*Parseparametersfromstdin,buildingatableofentries*/
for(num_entries=0;!feof(stdin);num_entries++){
entries[num_entries].val=fmakeword(stdin,'&',&cl);
plustospace(entries[num_entries].val);
unescape_url(entries[num_entries].val);
entries[num_entries].name=
makeword(entries[num_entries].val,'=');
}
/*SpitouttheHTMLboilerplate*/
printf("Content-type:text/html\n");
printf("\n");
printf(<html>);
printf(<head>);
printf("<title>NamedParameterEcho</title>\n");
printf("</head>");
printf(<body>);
printf("Youenteredthefollowingparameters:\n");
printf("<ul>\n");
/*Echotheparametersbacktotheuser*/
for(i=0;i<num_entries;i++)
printf("<li>%s=%s\n",entries[i].name,
entries[i].val);
/*Andcloseoutwithmoreboilerplate*/
printf("</ul>\n");
printf("</body>\n");
printf("</html>\n");
}
Again,wefollowthesamegeneralform.Theprogramstartsbydeclaringthe
variousutilityroutinesneededtoparsetheparameters,alongwithadata
structuretoholdtheparameterlist.Theactualcodebeginsbyreadingthe
parameterlistfromthestandardinputandbuildingalistofparameternamesand
valuesinthearraynamedentries.Oncethisiscomplete,aboilerplatedocument
headeriswrittentothestandardoutput,followedbytheparametersandsome
closingboilerplate.
Liketheotherexamples,thisprogramishandyforcheckingtheparametersbeing
passedtotheserverapplicationearlyintheforms-andapplication-debugging
process.Youcanalsouseitasaskeletonforotherapplicationsbyinserting
appropriateprocessingcodeaftertheparameterlistisbuiltupandalteringthe
outputsectiontosendbacktheappropriateresults.
Chapter10.Tables
OfalltheextensionsthatfoundtheirwayintoHTMLandXHTML,noneismore
welcomethantables.Whiletablesareusefulforthegeneraldisplayoftabular
data,theyalsoserveanimportantroleinmanagingdocumentlayout.Creative
useoftables,aswe'llshowinthischapter,cangoalongwaytoenlivenan
otherwisedulldocumentlayout.AndyoucanapplyalltheCascadingStyleSheet
(CSS)stylestothevariouselementsofatabletoachieveadesktop-published
lookandfeel.
10.1.TheStandardTableModel
Thestandardmodelfortablesisfairlystraightforward:atableisacollectionof
numbersandwordsarrangedinrowsandcolumnsofcells.Mostcellscontainthe
datavalues;otherscontainrowandcolumnheadersthatdescribethedata.
Youdefineatableandincludeallofitselementsbetweenthe<table>tagandits
corresponding</table>endtag.Tableelements,includingdataitems,rowand
columnheaders,andcaptions,eachhavetheirownmarkuptags.Workingfrom
lefttorightandtoptobottom,youdefine,insequence,theheaderanddatafor
eachcolumncellacrossanddownthetable.
Thelateststandardsalsoprovidearichcollectionoftagattributes,manyofwhich
oncewerepopularextensionstoHTMLassupportedbythepopularbrowsers.
Theymakeyourtableslookgood,byenablingspecialalignmentofthetable
valuesandheaders,borders,tablerulelines,andautomaticsizingofthedata
cellstoaccommodatetheircontent,amongothercapabilities.Thevariouspopular
browsershaveslightlydifferentsetsoftableattributes;we'llpointoutthose
variationsaswego.
10.1.1.TableContents
YoucanputnearlyanythingyoumighthavewithinthebodyofanHTMLor
XHTMLdocumentinsideatablecell,includingimages,forms,rules,headings,and
evenanothertable.Thebrowsertreatseachcellasawindowuntoitself,flowing
thecell'scontenttofillthespace,butwithsomespecialformattingprovisionsand
extensions.
10.1.2.AnExampleTable
Here'saquickexamplethatshouldsatisfyyouritchingcuriositytoseewhatan
HTMLtablelookslikeinasourcedocumentandwhenfinallyrendered,asshown
inFigure10-1.Moreimportantly,itshowsyouthebasicstructureofatable,from
whichyoucaninfermanyoftheelements,tagsyntaxandorder,attributes,and
soon,andtowhichyoumayreferasyoureadthefollowingvariousdetailed
descriptions:
Figure10-1.HTMLtableexample
<tablebordercellspacing=0cellpadding=5>
<captionalign=bottom>
Kumquatversusapokedeye,bygender</caption>
<tr>
<tdcolspan=2rowspan=2></td>
<thcolspan=2align=center>Preference</th>
</tr>
<tr>
<th>EatingKumquats</th>
<th>PokeInTheEye</th>
</tr>
<tralign=center>
<throwspan=2>Gender</th>
<th>Male</th>
<td>73%</td>
<td>27%</td>
</tr>
<tralign=center>
<th>Female</th>
<td>16%</td>
<td>84%</td>
</tr>
</table>
10.1.3.MissingFeatures
Atonetime,standardHTMLtablesdidn'thaveallthefeaturesofafull-fledged
table-generationtoolyoumightfindinapopularwordprocessor.Rather,the
popularbrowsers,InternetExplorerandNetscapeinparticular,provided
extensionstothelanguage.
Missingwerefeaturesthatsupportedrunningheadersandfooters,particularly
usefulwhenprintingalengthytable.Anothermissingfeaturewascontrolover
tablerulesanddivisions.
Today,thestandardsareaheadofthebrowsersintermsoftablefeatures;HTML4
andXHTMLstandardizethemanyextensionsandprovideadditionalsolutions.
10.2.BasicTableTags
Youcancreateawidevarietyoftableswithonlyfivetags:the<table>tag,which
encapsulatesatableanditselementsinthedocument'sbodycontent;the<tr>
tag,whichdefinesatablerow;the<th>and<td>tags,whichdefinethetable's
headersanddatacells;andthe<caption>tag,whichdefinesatitleorcaptionfor
thetable.Beyondthesecoretags,youmayalsodefineandcontrolwholesections
oftables,includingaddingrunningheadersandfooters,withthe<colgroup>,<col>,
<tbody>,<thead>,and<tfoot>tags.Eachtaghasoneormorerequiredandoptional
attributes,someofwhichaffectnotonlythetagitselfbutalsorelatedtags.
10.2.1.The<table>Tag
The<table>tagandits</table>endtagdefineandencapsulateatablewithinthe
bodyofyourdocument.Unlessyouplacethemwithinthebrowserwindowby
stylesheet,paragraph,division-level,orotheralignmentoptions,thebrowser
stopsthecurrenttextflow,breakstheline,insertsthetablebeginningonanew
line,andthenrestartsthetextflowonanewlinebelowthetable.
<table>
Function Definesatable
Attributes
align,background,bgcolor,border,bordercolor ,bordercolordark ,
bordercolorlight ,cellpadding,cellspacing,class,cols,dir,frame,height,
hspace,id,lang,nowrap,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,rules,style,
summary,title,valign,vspace,width
Endtag </table>;neveromitted
Contains table_content
Usedin block
Theonlycontentallowedwithinthe<table>isoneormore<tr>tags,whichdefine
eachrowoftablecontents,alongwiththevarioustablesectioningtags:<thead>,
<tfoot>,<tbody>,<col>,and<colgroup>.
10.2.1.1.Thealignattribute(deprecated)
TheHTML4andXHTMLstandardshavedeprecatedthisattributeinfavorofthe
alignpropertyprovidedbyCSS,yetitremainspopularandiscurrentlywell
supportedbythepopularbrowsers.
Likeimages,tablesarerectangularobjectsthatfloatinthebrowserdisplay,
alignedaccordingtothecurrenttextflow.Normally,thebrowserleft-justifiesa
table,abuttingitsleftedgetotheleftmarginofthedisplaywindow.Orthetable
maybecenteredifundertheinfluenceofthe<center>tag,acenteredparagraph,
oracentereddivision.Unlikeimages,however,tablesarenotinlineobjects.Text
contentnormallyflowsaboveandbelowatable,notbesideit.Youcanchange
thatdisplaybehaviorwiththealignattributeoracascadingstyledefinitionforthe
<table>tag.
Thealignattributeacceptsavalueofeitherleft,right,orcenter,indicatingthat
thetableshouldbeplacedflushagainsttheleftorrightmarginofthetextflow,
withthetextflowingaroundthetable,orinthemiddlewithtextflowingabove
andbelow,respectively.
Notethatthealignattributewithinthe<table>tagisdifferentfromthoseused
withinatable'selementtags,<tr>,<td>,and<th>.Inthosetags,theattribute
controlstextalignmentwithinthetable'scells,notalignmentofthetablewithin
thecontainingbody-textflow.
10.2.1.2.Thebgcolorandbackgroundattributes
Youcanmakethebackgroundofatableadifferentcolorthanthedocument's
backgroundwiththebgcolorattributeforthe<table>tag.Youmustsetthecolor
valueforthebgcolorattributetoeitherared,blue,andgreen(RGB)colorvalueor
astandardcolorname.AppendixGprovidesboththesyntaxofcolorvaluesand
theacceptablecolornames.
Thepopularbrowsersgiveeverycellinthetable(butnotthecaption)this
backgroundcolor.Youmayalsosetindividualrowandcellcolorsbyprovidingthe
bgcolorattributeorastyleattributeforthoserowsorcells.
Thebackgroundattribute,anonstandardextensionsupportedbyallthepopular
browsers,suppliestheURLofanimagethatistiledtofillthebackgroundofthe
table.Theimageisclippedifthetableissmallerthantheimage.Byusingthis
attributewithaborderlesstable,youcanputtextoveranimagecontainedwithin
adocument.
10.2.1.3.Theborderattribute
Theoptionalborderattributeforthe<table>tagtellsthebrowsertodrawlines
aroundthetableandtherowsandcellswithinit.Thedefaultisnobordersatall.
Youmayspecifyavalueforborder,butyoudon'thavetowithHTML.Alone,the
attributesimplyenablesbordersandasetofdefaultcharacteristics.WithXHTML,
useborder="border"toachievethesamedefaultresults.Otherwise,inHTMLorwith
XHTML,supplyanintegervalueforborderequaltothepixelwidthofthe3D
chiseled-edgelinesthatsurroundtheoutsideofthetableandmakeitappearto
beembossedontothepage.
10.2.1.4.Theframeandrulesattributes
WithNetscape4,theborderattributewasallornothing,affectingtheappearance
andspacingbothoftheframearoundthetableandoftherulelinesbetweendata
cells.InternetExplorerversions4andlaterandNetscape6andlaterversions,as
wellasthepopularFirefoxandOpera,letyouindividuallymodifythevariousline
segmentsthatmakeupthebordersaroundthetable(frame)andaroundthedata
cells(rules).
Thestandardframeattributemodifiesborder'seffectsforthelinesthatsurroundthe
table.Thedefaultvaluewhatyougetifyoudon'tuseframeatallisbox,whichtells
thebrowsertodrawallfourlinesaroundthetable.Thevalueborderdoesthe
samethingasbox.Thevaluevoidremovesallfouroftheframesegments.Theframe
valuesabove,below,lhs,andrhsdrawthevariousbordersegmentsonthetop,
bottom,left,andrightside,respectively,ofthetable.Thevaluehsidesdraws
bordersonthetopandbottom(horizontal)sidesofthetable;vsidesdrawsborders
ontheleftandright(vertical)sidesofthetable.
Withstandardtablesnowsupportedbythelatestversionsofallthepopular
browsers,youalsomaycontrolthethicknessofatable'sinternalcellbordersvia
therulesattribute.Thedefaultbehavior,representedbythevalueofall,isto
drawbordersaroundallcells.Specifyinggroupsplacesthickerbordersbetweenrow
andcolumngroupsdefinedbythe<thead>,<tbody>,<tfoot>,<col>,and<colgroup>
tags.Usingrowsorcolsplacesbordersonlybetweeneveryroworcolumn,
respectively,andusingnoneremovesbordersfromeverycellinthetable.
10.2.1.5.Thebordercolor,bordercolorlight,andbordercolordarkattributes
Thepopularbrowsersnormallydrawatableborderinthreecolors,usinglightand
darkvariationsonthedocument'sbackgroundcolortoachievea3Deffect.
InternetExplorer'snonstandardbordercolorattributeletsyousetthecolorofthe
tablebordersandrulestosomethingotherthanthebackground(ifbordersare
enabled,ofcourse).Thebordercolorattribute'svaluecanbeeitheranRGB
hexadecimalcolorvalueorastandardcolorname,bothofwhichwedescribefully
inAppendixG.
InternetExploreralsoletsyousettheborderedgecolorsindividuallywithspecial
extensionattributes:thebordercolorlightandbordercolordarkcolorsshadethelighter
anddarkeredgesoftheborder.The3Dbeveled-bordereffectistiedtothe
relationshipbetweenthesetwocolors.Ingeneral,thelightcolorshouldbeabout
25percentbrighterthanthebordercolor,andthedarkcolorshouldbeabout25
percentdarker.Thatis,ifyouusethematall:onlyyourInternetExplorerusers
willseetheeffects.
10.2.1.6.Thecellspacingattribute
Thecellspacingattributecontrolstheamountofspaceplacedbetweenadjacent
cellsinatableandalongtheouteredgesofcellsalongtheedgesofatable.
Browsersnormallyputtwopixelsofspacebetweencellsandalongtheouter
edgesofatable.Ifyouincludeaborderattributeinthe<table>tag,thecellspacing
betweeninteriorcellsgrowsbytwomorepixels(foratotaloffour)tomakespace
forthechiselededgeontheinteriorborder.Theouteredgesofedgecellsgrowby
thevalueoftheborderattribute.
Byincludingthecellspacingattribute,youcanwidenorreducetheinteriorcell
borders.Forinstance,tomakethethinnestpossibleinteriorcellborders,include
theborderandcellspacing=0attributesinthetable'stag.
10.2.1.7.Thecellpaddingattribute
Thecellpaddingattributecontrolstheamountofspacebetweentheedgeofacell
anditscontents,whichbydefaultis1pixel.Youmaymakeallthecellcontentsin
atabletouchtheirrespectivecellbordersbyincludingcellpadding=0inthetable
tag.Youmayalsoincreasethecellpaddingspacebymakingitsvaluegreaterthan
1.
10.2.1.8.Combiningtheborder,cellspacing,andcellpaddingattributes
Theinteractionsbetweentheborder,cellspacing,andcellpaddingattributesofthe
<table>tagcombineinwaysthatcanbeconfusing.Figure10-2summarizeshow
theattributescreateinteriorandexteriorbordersofvariouswidths.
Figure10-2.Theborder,cellspacing,andcellpaddingattributes
ofatable
Whileallsortsofcombinationsoftheborderandcellspacingattributesarepossible,
thesearethemostcommon:
border=1andcellspacing=0producesthenarrowestpossibleinteriorandexterior
borders:2pixelswide.
border=nandcellspacing=0makesthenarrowestpossibleinteriorborders(2
pixelswide)withanexternalborderthatisn+1pixelswide.
border=1andcellspacing=ntableshaveequal-widthexteriorandinteriorborders,
allwithchiselededgesjust1pixelwide.Allborderswillben+2pixelswide.
10.2.1.9.Thecolsattribute
Toformatatable,thebrowsermustfirstreadatable'sentirecontentto
determinethenumberandwidthofeachcolumninthetable.Thiscanbea
lengthyprocessforlongtables,forcinguserstowaittoseeyourpages.The
nonstandardcolsattributetellsthebrowser,inadvance,howmanycolumnsto
expectinthetable.Thevalueofthisattributeisanintegervaluedefiningthe
numberofcolumnsinthetable.
Thecolsattributeonlyadvisesthebrowser.Ifyoudefineadifferentnumberof
columns,thebrowserisfreetoignorethecolsattributeinordertorenderthe
tablecorrectly.Ingeneral,itisgoodformtoincludethisattributewithyour
<table>tag,ifonlytohelpthebrowserdoafasterjobofformattingyourtables.
10.2.1.10.Thevalignandnowrapattributes
Thevalignattributesetsthedefaultverticalalignmentofdataincellsforthe
entiretable.Acceptablevaluesforthevalignattributein<table>aretop,bottom,
middle,andbaseline;thedefaultverticalpositionisthecenterofthecell.
Browserstreateachtablecellasthoughit'sabrowserwindowuntoitself,flowing
contentsinsidethecellastheywouldcommonbodycontents(althoughtheyare
subjecttospecialtable-cellalignmentproperties).Accordingly,thebrowsers
automaticallywraptextlinestofilltheallottedtablecellspace.Thenowrap
attribute,whenincludedinthe<table>tag,stopsthatnormalwordwrappinginall
rowsinthetable.Withnowrap,thebrowserassemblesthecontentsofthecellonto
asingleline,unlessyouinserta<br>or<p>tag,whichthenforcesabreaksothat
thecontentscontinueonanewlineinsidethetablecell.
Withthe<table>tag,onlyOperasupportsvalign.Noneofthebrowserssupports
nowrapatthatlevel.Instead,youcanachievesimilareffectsbyincludingavalignor
nowrapattributewithintheindividual<tr>,<td>,and<th>tags,anapproachthatall
thepopularbrowserssupport.
10.2.1.11.Thewidthandheightattributes
Browsersautomaticallymakeatableonlyaswideasneededtocorrectlydisplay
allofthecellcontents.Ifnecessary,youcanmakeatablewiderwiththewidth
attribute.
Thevalueofthewidthattributeiseitheranintegernumberofpixelsorarelative
percentageofthescreenwidth,includingvaluesgreaterthan100percent.For
example:
<tablewidth=400>
tellstheextendedbrowsertomakethetable400pixelswide,includingany
bordersandcellspacingthatextendintotheouteredgeofthetable.Ifthetable
iswiderthan400pixels,thebrowserignorestheattribute.Alternatively:
<tablewidth="50%">
tellsthebrowsertomakethetablehalfaswideasthedisplaywindow.Again,this
widthincludesanybordersorcellspacingthatextendsintotheouteredgeofthe
tableandhasnoeffectifthetablenormallyismorethanhalftheuser'scurrent
screenwidth.
Userelativewidthsfortablesyouwanttoresizeautomaticallytotheuser's
window;forinstance,tablesyoualwayswanttoextendacrosstheentirewindow
(<tablewidth="100%">).Useanabsolutewidthvalueforcarefullyformattedtables
whosecontentsbecomehardtoreadinwidedisplaywindows.
Alsowiththepopularbrowsers,youcanusethenonstandardheightattributeto
suggestarecommendedheightforthetable.Thebrowsermakesthetableno
shorterthanthisheightbutmaymakethetabletallerifneededtocontainthe
table'scontents.Thisattributeisusefulwhentryingtostretchtablestofitina
frameorsomespecificareaofadocumentbutisoflittleuseotherwise,
particularlybecauseitisnotastandardattribute.
10.2.1.12.Thesummaryattribute
ThesummaryattributewasintroducedtoHTMLinthe4.0standard.Itsvalueisa
quote-enclosedstringthatdescribesthepurposeandsummarizesthecontentsof
thetable.Itsintendeduse,accordingtothestandard,istoprovideextended
accesstononvisualbrowsers,particularlyforuserswithdisabilities.
10.2.1.13.Thehspaceandvspaceattributes
Aswithimages,giveyourtablesomeextraspacewithinthebodyofyour
document.Usethenonstandardhspaceandvspaceattributesinthe<table>tag,each
withavalueequaltothenumberofpixelsofspacetooffsetthetablefromthe
leftandrightortopandbottom,respectively,oftheenclosingtext.Interestingly,
allofthepopularbrowsers,exceptforInternetExplorer,supporttheseas<table>
attributes,eventhoughInternetExplorersupportsthemwiththe<img>tag.
10.2.2.CommonTableAttributes
TheHTMLandXHTMLstandards,combinedwiththeCSSstandard,providea
numberofattributescommonnotonlytothe<table>tagandtheothertable-
creationtags,buttomostothertagsaswell.
10.2.2.1.Theidandtitleattributes
Usetheidattributewithaquote-enclosedstringvaluetouniquelylabela<table>
tagforlaterreferencebyahyperlinkoranapplet.Usethetitleattributewitha
stringvaluetooptionallytitlethetableoranyofitssegmentsforgeneral
reference.Atitle'svalueneednotbeunique,andthebrowsermayormaynot
useit.Thepopularbrowsers,forexample,displaythetitleattribute'stextvalue
whenevertheuserpassesthemousepointerovertheelement'scontents.[Theid
attribute,4.1.1.4][Thetitleattribute,4.1.1.5]
10.2.2.2.Thedirandlangattributes
AlthoughitscontentsarepredominantlyinEnglish,theWebisworldwide.The
HTML4andXHTMLstandardstakepainstoextendthelanguagetoallcultures.
Wesupportthateffortwholeheartedly.Thedirandlangattributesarejustsmall
partsofthatprocess.
Thedirattributeadvisesthebrowserinwhichdirectionthetextofthecontents
shouldflowfromlefttoright(dir=ltr),asforcommonWesternlanguageslike
EnglishandGerman,orrighttoleft(dir=rtl),asforcommonEasternlanguages
likeHebrewandChinese.
Thelangattributeletsyouexplicitlyindicatethelanguageusedinthetableor
evenindividualcellcontents.ItsvalueshouldbeanInternationalOrganization
forStandardization(ISO)standardtwo-letterprimarycodefollowedbyan
optionaldialectsubcode,withahyphen(-)betweenthetwo.
Allthelatestversionsofthepopularbrowserssupportthedirandlangattributes.
[Thedirattribute,3.6.1.1][Thelangattribute,3.6.1.2]
10.2.2.3.Theclassandstyleattributes
TheCSSstandardisthesanctionedwaytodefinedisplayattributesfor
HTML/XHTMLelements,anditisrapidlybecomingtheonlyway.Usethestyle
attributetodefinedisplaycharacteristicsforthetableanditselementsthattake
immediateeffectandoverridethedisplaystylesthatmaybecurrentlyineffect
forthewholedocument.Usetheclassattributetoreferenceastylesheetthat
definestheuniquedisplaycharacteristicsforthetableanditselements.
WediscusstheclassandstyleattributesandtheCSSstandardindetailinChapter
8.Theireffectsapplytoallaspectsoftables,andarewellsupportedbythe
popularbrowsers.[InlineStyles:ThestyleAttribute,8.1.1][StyleClasses,8.3]
10.2.2.4.Theeventattributes
Mostoftoday'sbrowsershaveinternalmechanismsthatdetectthevarioususer-
initiatedmouseandkeyboardeventsthatcanhappeninandaroundyourtables
andtheirelements.Forinstance,theusermightclickthemousepointerinoneof
thetablecellsorhighlightthecaptionandthenpresstheEnterkey.
Withthevariouseventattributes,suchasonClickandonKeyDown,youcanreactto
theseeventsbyhavingthebrowserexecuteoneormoreJavaScriptcommandsor
appletsthatyoureferenceasthevaluetotherespectiveeventattribute.See
Chapter12fordetails.
10.2.3.The<tr>Tag
Makeanewrowinatablewiththe<tr>tag.Placewithinthe<tr>tagoneormore
cellscontainingheaders,definedwiththe<th>tag,ordata,definedwiththe<td>
tag(seesection10.2.4).The<tr>tagacceptsanumberofspecialattributesthat
controlitsbehavior,alongwiththecommontableattributesdescribedearlierin
section10.2.2.
Everyrowinatablehasthesamenumberofcellsasthelongestrow;the
browserautomaticallycreatesemptycellstopadrowswithfewerdefinedcells.
<tr>
Function Definesarowwithinatable
Attributes
align,background ,bgcolor,bordercolor ,bordercolordark ,bordercolorlight
,char,charoff,class,dir,id,lang,nowrap,onClick,onDblClick,onKeyDown,
onKeyPress,onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,
style,title,valign
Endtag </tr>;maybeomittedinHTML
Contains tr_content
Usedin table_content
10.2.3.1.Thealignandvalignattributes
Thealignattributeforthe<table>tagmaybedeprecatedintheHTMLandXHTML
standards,butitisaliveandkickingfor<tr>andothertableelements.Thealign
attributeforthe<tr>tagletsyouchangethedefaulthorizontalalignmentofall
thecontentsofthecellsinarow.Theattributeaffectsallthecellswithinthe
currentrow,butnotsubsequentrows.
Analignattributevalueofleft,right,center,justify,orcharcausesthebrowserto
alignthecontentsofeachcellintherowagainsttheleftorrightedge,inthe
centerofthecell,spreadacrossthecell,ortoaspecifiedcharacterinthecell,
respectively.
Similarly,youcanchangethedefaultverticalalignmentforthecontentsofdata
cellscontainedwithinatablerowwiththevalignattribute.Normally,browsers
rendercellcontentscenteredvertically.Byincludingthevalignattributeinthe
<tr>tagwithavalueoftop,bottom,center,middle,orbaseline(InternetExplorer
only),youtellthebrowsertoplacethetablerow'scontentsflushagainstthetop
orbottomoftheircells,centered,oralignedtothebaselineofthetoplineoftext
inothercellsintherow,respectively(seeFigure10-3):
Figure10-3.Effectsofthevalignattribute;onlyInternet
Explorer(shownhere)supportsthebaselinevalueforvalign
<tableborder="border">
<tr>
<th>Alignment</th>
<th>Top</th>
<th>Baseline</th>
<th>Center</th>
<th>Middle></th>
<th>Bottom</th>
</tr>
<tralign="center">
<th><h1>Baseline__<br/>Anotherline</h1></th>
<tdvalign="top">AAyy</td>
<tdvalign="baseline">_AAyy_</td>
<tdvalign="center">AAyy</td>
<tdvalign="middle">AAyy</td>
<tdvalign="bottom">AAyy</td>
</tr>
</table>
Youalsocanspecifythehorizontalandverticalalignmentsforindividualcells
withinarow(seeSection10.2.3.1).Usethealignmentattributesinthe<tr>tag
tospecifythemostcommoncell-contentjustificationsfortherow(ifnotthe
default),anduseadifferentalignorvalignattributeforthoseindividualcellsthat
deviatefromthecommonalignment.
Table10-1containsthehorizontal(align)andvertical(valign)tablecell-content
attributevaluesandoptions.Valuesinparenthesesarethedefaultsforthe
popularbrowsers.
Table10-1.Tablecell-contentalignmentattributevaluesandoptions
Attribute Headers(<th>) Data(<td>)
align Left (Left)
(Center) Center
Right Right
Justify Justify
Char[a] Char[a]
valign Top Top
(Center) (Center)
(Middle) (Middle)
Bottom Bottom
Baseline Baseline
[a]
[a]Valuenotyetsupported.
10.2.3.2.Thecharandcharoffattributes
Evensimplewordprocessorsletyoulineupdecimalpointsfornumbersinatable.
UntiltheadventoftheHTML4.0standard,however,thelanguagewasdeficientin
thisfeature.Nowyoumayincludethecharattributetoindicatewhichletterin
eachofthetablerow'scellsshouldbetheaxisforthatalignment.Youneednot
includeavaluewithchar.Ifyoudon't,thedefaultcharacterislanguagebased:it's
aperiodinEnglish,forexample,andacommainFrench.Includethechar
attributeandasingleletterasitsvaluetospecifyadifferentalignmentcharacter.
Usethecharoffattributeandanintegervaluetospecifytheoffsettothefirst
occurrenceofthealignmentcharacteroneachline.Ifalinedoesn'tincludethe
alignmentcharacter,itshouldbehorizontallyshiftedtoendatthealignment
position.
ThecharandcharoffattributesaredefinedinHTML4andXHTMLbutarenotyet
supportedbyanyofthepopularbrowsers.
10.2.3.3.Thebgcolorandbackgroundattributes
Likeitsrelativeforthe<table>tag,thebgcolorattributeforthe<tr>tagsetsthe
backgroundcoloroftheentirerow.ItsvalueiseitheranRGBcolorvalueora
standardcolorname.AppendixGprovidesboththesyntaxofcolorvaluesandthe
acceptablecolornames.
Everycellintherowisgiventhisbackgroundcolor.Youcanchangeindividualcell
colorsbyprovidingthebgcolorattributeforthosecells.
Thenonstandardbackgroundattributewithitsimage-fileURLvalueplacesagraphic
tiledintoandbehindthetextoftheentiretablerow.Forexample,thistagfills
thetablerowwithbricks:
<trbackground="bricks.gif">
Allthepopularbrowserssupportbgcolorandallsupportthebackgroundextension,
exceptInternetExplorer.
10.2.3.4.Thebordercolor,bordercolorlight,andbordercolordarkattributes
Liketheirnonstandardbrethrenforthe<table>tag,InternetExploreronlyletsyou
usetheseattributestosetthecoloroftheborderswithinthecurrentrow.
Theirvaluesoverrideanyvaluessetbythecorrespondingattributesinthe
containing<table>tag.Seethecorrespondingdescriptionsoftheseextensionsin
section10.2.1.5,earlierinthischapter,fordetails.Colorvaluescanbeeither
RGBcolorvaluesorstandardcolornames,bothofwhichwedescribefullyin
AppendixG.
10.2.3.5.Thenowrapattribute
Browserstreateachtablecellasthoughitwereabrowserwindowuntoitself,
flowingcontentsinsidethecellastheywouldcommonbodycontents(although
subjecttospecialtablecell-alignmentproperties).Accordingly,thebrowsers
automaticallywraptextlinestofilltheallottedtablecellspace.Thenowrap
attribute,whenincludedinatablerow,stopsthatnormalwordwrappinginall
cellsinthatrow.Withnowrap,thebrowserassemblesthecontentsofthecellonto
asingleline,unlessyouinserta<br>or<p>tag,whichforcesabreaksothatthe
contentscontinueonanewlineinsidethetablecell.
10.2.4.The<th>and<td>Tags
The<th>and<td>tagsgoinsidethe<tr>tagsofatabletocreatetheheaderand
datacells,respectively,andtodefinethecellcontentswithintherows.Thetags
operatesimilarly;theonlyrealdifferencesarethatthebrowsersrenderheader
textmeanttotitleorotherwisedescribetabledatainboldfacefontstyleandthat
thedefaultalignmentoftheirrespectivecontentsmaybedifferentthanfordata.
Datatypicallygetsleft-justifiedbydefault;headersgetcentered(refertoTable
10-1).
<th>and<td>
Function Definetabledataandheadercells
Attributes
abbr,align,background,bgcolor,bordercolor ,bordercolordark ,
bordercolorlight ,char,charoff,class,colspan,dir,headers,height,id,lang,
nowrap,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,onMouseDown,
onMouseMove,onMouseOut,onMouseOver,onMouseUp,rowspan,scope,style,title,
valign,width
Endtag </th>or</td>;maybeomittedinHTML
Contains body_content
Usedin tr_content
Likethoseavailableforthetablerow(<tr>)tag,thetablecelltagssupportarich
setofstyleandcontent-alignmentattributesthatyoumayapplytoasingledata
orheadercell.Theseattributesoverridethedefaultvaluesforthecurrentrow.
Specialattributescontrolthenumberofcolumnsorrowsacellmayspaninthe
table.The<th>and<td>tagsalsoacceptthecommontableattributesdescribed
earlierinsection10.2.2.
Thecontentsofthe<th>and<td>tagscanbeanythingyoumightputinthebody
ofadocument,includingtext,images,forms,andsoonevenanothertable.And,
asdescribedearlier,thebrowserautomaticallycreatesatablelargeenough,both
verticallyandhorizontally,todisplayallthecontentsofanyandallthecells.
Ifaparticularrowhasfewerheaderordataitemsthanotherrows,thebrowser
addsemptycellsattheendtofilltherow.Ifyouneedtomakeanemptycell
beforetheendofarowforinstance,toindicateamissingdatapointcreatea
headerordatacellwithnocontent.
Emptycellslookdifferentfromthosecontainingdataorheadersifthetablehas
borders:theemptycelldoesnotappearembossedontothewindowbutinsteadis
simplyleftblank.Ifyouwanttocreateanemptycellthathasincisedborderslike
alltheothercellsinyourtable,besuretoplaceaminimalamountofcontentin
thecell:asingle<br>tag,forinstance.
10.2.4.1.Thealignandvalignattributes
Thealignandvalignattributesareidenticaltothoseofthesamenameforthe
tablerowtag(<tr>;see10.2.3,earlierinthischapter),exceptthatwhenused
witha<th>or<td>tag,theycontrolthehorizontalorverticalalignmentofcontent
injustthecurrentcell.Theirvalueoverridesanyalignmentestablishedbythe
respectivealignorvalignattributeofthe<tr>tagbutdoesnotaffectthealignment
ofsubsequentcells.RefertoTable10-1foralignmentdetails.
Youmaysetthealignattribute'svaluetoleft,right,orcenter,causingthe
browserstoalignthecellcontentsagainsttheleftorrightedgeorinthecenterof
thecell,respectively.
Inearlierversions,InternetExplorer(version5)alsosupportedthealignvalue
justifysothatthewordsspreadouttofillthecell,asinanewspapercolumn.No
longer.
Thevalignattributemayhaveavalueoftop(default),bottom,center,middle,or
baseline,tellingthebrowsertoalignthecell'scontentstothetoporbottomedge,
inthecenterormiddleofthecell,or(InternetExploreronly)tothebaselineof
thefirstlineoftextinothercellsintherow.
10.2.4.2.Thewidthattribute
Likeitstwininthe<table>tagthatletsyouwidenatable,thewidthattributefor
tablecelltagsletsyouwidenanindividualcellandhencetheentirecolumnit
occupies.Yousetthewidthtoanintegernumberofpixelsorapercentage
indicatingthecell'swidthasafractionofthetableasawhole.
Forexample:
<thwidth=400>
setsthecurrentheadercell'swidth,andhencetheentirecolumnofcells,to400
pixelswide.Alternatively:
<tdwidth="40%">
createsadatacellwithacolumnoccupying40percentoftheentiretable'swidth.
Becausethepopularbrowsersmakeallcellsinacolumnthesamewidth,you
shouldplaceawidthattributeinonlyonecellwithinacolumn,preferablythefirst
instanceofthecellinthefirstrow,forsourcereadability.Iftwoormorecellsin
thesamecolumnhappentohavewidthattributes,thewidestoneishonored.You
can'tmakeacolumnthinnerthantheminimumneededtodisplayallofthecells
inthecolumn.Accordingly,ifthebrowserdeterminesthatthecolumnofcells
needstobeatleast150pixelswidetoaccommodateallthecells'contents,it
ignoresawidthattributeinoneofthecolumn'scelltagsthatattemptstomake
thecellonly100pixelswide.
10.2.4.3.Theheightattribute
Theheightattributeletsyouspecifyaminimumheight,inpixels,forthecurrent
cell.Becauseallcellsinarowhavethesameheight,youneedtospecifythis
attributeononlyonecellintherow,preferablythefirst.Ifsomeothercellinthe
rowneedstobetallertoaccommodateitscontents,thebrowserignorestheheight
attribute,andallthecellsintherowaresettothelargersize.
Bydefault,allthecellsinarowaretheheightofthelargestcellintherowthat
justaccommodatesitscontents.
10.2.4.4.Thecolspanattribute
It'scommontohaveatableheaderthatdescribesseveralcolumnsbeneathit,
liketheheadersweusedinFigure10-1.Usethecolspanattributeinatable
headerordatatagtoextendatablecellacrosstwoormorecolumnsinitsrow.
Setthevalueofthecolspanattributetoanintegervalueequaltothenumberof
columnsyouwanttheheaderordatacelltospan.Forexample:
<tdcolspan="3">
tellsthebrowsertomakethecelloccupythesamehorizontalspaceasthreecells
inrowsaboveorbelowit.Thebrowserflowsthecontentsofthecelltooccupythe
entirespace.
Whathappensiftherearen'tenoughextracellsontheright?Thebrowserjust
extendsthecelloverasmanycolumnsasexisttotheright;itdoesn'taddextra
emptycellstoeachrowtoaccommodateanoverextendedcolspanvalue.Youmay
defeatthatlimitationbyaddingtheneededextrabutcontentlesscellstoasingle
row.(Givethemasingle<br>tagastheircontentsifyouwantanembossed
borderaroundthem.)
10.2.4.5.Therowspanattribute
Justasthecolspanattributelayersatablecellacrossseveralcolumns,therowspan
attributestretchesacelldowntwoormorerowsinthetable.
Includetherowspanattributeinthe<th>or<td>tagoftheuppermostrowofthe
tablewhereyouwantthecelltobeginandsetitsvalueequaltothenumberof
rowsyouwantittospan.Thecellthenoccupiesthesamespaceasthecurrent
rowandanappropriatenumberofcellsbelowthatrow.Thebrowserflowsthe
contentsofthecelltooccupytheentireextendedspace.Forexample:
<tdrowspan="3">
createsacellthatoccupiesthecurrentrowplusthetworowsbelowit.
Likethecolspanattribute,thebrowserignoresoverextendedrowspanattributesand
extendsthecurrentcellonlydownrowsyou'veexplicitlydefinedbyother<tr>
tagsfollowingthecurrentrow.Thebrowsersdonotaddemptyrowstoatableto
fillarowspanbelowthelastdefinedrowinatable.
10.2.4.6.Combiningthecolspanandrowspanattributes
Youmayextendasinglecellbothacrossseveralcolumnsanddownseveralrows
byincludingboththecolspanandrowspanattributesinitstableheaderordatatag.
Forexample:
<thcolspan="3"rowspan="4">
createsaheadercellthat,asyoumightexpect,spansacrossthreecolumnsand
downfourrows,includingthecurrentcellandextendingtwomorecellstothe
rightandthreemorecellsdown.Thebrowserflowsthecontentsofthecellto
occupytheentirespace,alignedinsideaccordingtothecurrentrow'salignment
specificationsortothoseyouexplicitlyincludeinthesametag,asdescribed
earlier.
10.2.4.7.Thenowrapattribute
Browserstreateachtablecellasthoughitwereabrowserwindowuntoitself,
flowingcontentsinsidethecellastheywouldcommonbodycontents(although
subjecttospecialtablecell-alignmentproperties).Accordingly,thebrowsers
automaticallywraptextlinestofilltheallottedtablecellspace.Thenowrap
attribute,whenincludedinatableheaderordatatag,stopsthatnormalword
wrapping.Withnowrap,thebrowserassemblesthecontentsofthecellontoasingle
line,unlessyouinserta<br>or<p>tag,whichforcesabreaksothatthecontents
continueonanewlineinsidethetablecell.
10.2.4.8.Thebgcolorandbackgroundattributes
Yetagain,youcanchangethebackgroundcolorthistimeforanindividualdata
cell.Thisattribute'svalueiseitheranRGBhexadecimalcolorvalueorastandard
colorname.AppendixGprovidesboththesyntaxofcolorvaluesandthe
acceptablecolornames.
ThebackgroundattributesuppliestheURLofanimagethatistiledtofillthe
backgroundofthecell.Theimageisclippedifthecellissmallerthantheimage.
Interestingly,InternetExplorer,likealltheotherpopularbrowsers,supports
backgroundwhenappliedtoasinglecell,butunliketheotherpopularbrowsers,
doesnotsupportbackgroundfor<table>or<tr>.
Neitherbackgroundnorbgcoloroverridesarelatedstylesheetproperty.
10.2.4.9.Thebordercolor,bordercolorlight,andbordercolordarkattributes
InternetExplorerletsyoualterthecolorsthatmakeupanindividualcell's
borderiftablebordersareturnedonwiththeborderattribute,ofcourse.Seethe
respectiveattributes'descriptionsunderthe<table>taginsection10.2.1.5,earlier
inthischapter,fordetails.
Thevaluesforthesethreeattributesoverrideanyvaluessetforthecontaining
<table>or<tr>tag.TheirvaluescanbeeitherRGBcolorvaluesorstandardcolor
names,bothofwhichwedescribefullyinAppendixG.
10.2.4.10.Thecharandcharoffattributes
Justasforthe<tr>tag,youmayusethecharattributewith<th>or<td>toindicate
whichletterinthetablecellshouldbetheaxisforalignment,suchasfordecimal
numbers.YouneednotincludeavaluewithcharinHTML.Ifyoudon't,thedefault
characterislanguagebased:it'saperiodinEnglish,forexample,andacommain
French.Includethecharattributeandasingleletterasitsvaluetospecifya
differentalignmentcharacter.
Usethecharoffattributeandanintegervaluetospecifytheoffsettothefirst
occurrenceofthealignmentcharacterinthecell.Ifacelldoesn'tincludethe
alignmentcharacter,itshouldbeshiftedhorizontallytoendatthealignment
position.
ThecharandcharoffattributesarestandardinHTML4andXHTMLbutarenotyet
supportedbyanyofthepopularbrowsers.
10.2.4.11.Theheadersandscopeattributes
Theheadersattributeassociatesheadercellswithadatacellinthetable.Thevalue
ofthisattributeisaquote-enclosedlistofnamesthathavebeendefinedfor
variousheadercellsusingtheidattribute.Theheadersattributeisespeciallyuseful
fornonvisualbrowsers,whichmightspeakthecontentsofaheadercellbefore
presentingtheassociateddatacellcontents.
Usethescopeattributetoassociatedatacellswithaheadercell.Withavalueof
row,allcellsintheheader'srowareassociatedwiththeheadercell.Specifyingcol
bindsallthecellsinthecurrentcolumntothecell.Usingrowgrouporcolgroupbinds
allthecellsinthecell'srowgroup(definedbya<thead>,<tbody>,or<tfoot>tag)or
columngroup(definedbya<col>or<colgroup>tag)withtheheadercell.
10.2.4.12.Theabbrattribute
Thevalueofthisattributeshouldbeanabbreviateddescriptionofthecell's
contents.Whenshortonspace,browsersmightchoosetorendertheabbreviation
instead,ortheymightuseitinnonvisualcontexts.
10.2.4.13.Theaxisattribute
Tablesareusuallychock-fullofdata,promptingthereadertoaskquestions.A
tabularexpensereport,forexample,naturallyleadstoquerieslike"Howmuch
didIspendonmeals?"or"Whatdidmycabfarestotal?"Inthefuture,browsers
maysupportsuchquerieswiththehelpoftheaxisattribute.
Thevalueofthisattributeisaquote-enclosedlistofcategorynamesthatmight
beusedtoformaquery.Asaresult,ifyouusedaxis=mealsonthecellscontaining
mealpurchases,thebrowsercouldlocatethosecells,extracttheirvalues,and
produceasum.
10.2.5.The<caption>Tag
Atablecommonlyneedsacaptiontoexplainitscontents,sothepopularbrowsers
provideatable-captiontag.Authorstypicallyplacethe<caption>tagandits
contentsimmediatelyafterthe<table>tag,butyoucanplaceitnearlyanywhere
insidethetableandbetweentherowtags.Thecaptionmaycontainanybody
content,muchlikeacellwithinatable.
<caption>
Function Definesatablecaption
Attributes
align ,class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,
onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,
title,valign
Endtag </caption>;neveromitted
Contains body_content
Usedin table_content
10.2.5.1.Thealignandvalignattributes
Bydefault,browsersplacethecaption'scontentscenteredabovethetable.You
mayplaceitbelowthetablewiththealignattributesettothevaluebottom(the
valuetop,ofcourse,isequivalenttothedefault).
Alsousethealignattributetocontrolthehorizontalpositionofthecaption,but
theinterpretationofthealternativevaluesvarieswiththepopularbrowsers:with
InternetExplorerandOpera,forexample,settingthealignattributetoleftor
rightrespectivelyleft-justifiesorright-justifiesthecaptiontextagainstthe
horizontaledgeatthetopofthetable.WithNetscapeandFirefox,thecaption
textgetsplacednexttoandatthetopoftheleftorrightsideofthetable,
respectively.
InternetExploreradditionallysupportsthevalignattributewithtoporbottomvalues
for<caption>.Incombinationwithalign,youplacethecaptiontextalignedatany
ofthefourcornersofthetable,butnotalongeitherside.Theotherbrowsers
ignorevalign.
Forexample,Figure10-4demonstrateshowInternetExplorerdisplaysthe
followingcaptionatthebottomofthetableandleft-justified,whereasFirefox,
becauseitignoresvalignandinterpretsleftalignmentdifferently,placesthe
captionagainsttheleftsideofthetable(Figure10-5):
Figure10-4.CombiningInternetExplorer'salignandvalign
<caption>attributesletsyouplacethetextatanyofthetable's
fourcornersaswellascenteredtoporbottom
<captionvalign=bottomalign=left>
Kumquatversusapokedeye,bygender
</caption>
Figure10-5.Firefox,likeNetscape,ignoresvalignandplacesthe
left-alignedcaptiontotheleftofthetable
10.2.5.2.Themanyotherattributes
Liketheothertabletags,<caption>supportsthemanyandvariouslanguage-,
event-,andstyles-relatedattributes,whichwedescribedearlierin"Common
TableAttributes".Usethemingoodhealth.Justbesuretousethecontextual
selectorTABLECAPTIONwhenreferringtocaptionstylesatthedocumentlevelorin
externalstylesheets.
10.3.AdvancedTableTags
Whileitispossibletobuildasimpletablequickly,complextableswithvarying
borderstyles,runningheadersandfooters,andcolumn-basedlayoutwerenot
easilyconstructedfromtheoldHTML3.2tablemodel.Microsoftrectifiedthis
inadequacysomewhatbyaddinganumberoftable-layoutcontrolstoInternet
Explorerversion3.0.TheseveryusefulextensionsfoundtheirwayintotheHTML
4standardandsubsequentlyintoXHTML.Theyproviderow-basedgroupingand
runningheadersandfooters,alongwithcolumn-basedlayoutfeatures.
10.3.1.DefiningTableSections
Withintables,allrowsarecreatedequal.Inrealtables,somerowsaremore
equalthanothers.Andmosttableshaveheaderandfooterrowsthatrepeatfrom
pagetopage.Inlargetables,adjacentrowsaregroupedanddelineatedwith
differentrulelinestomakethetableseasiertoreadandunderstand.HTML4and
XHTMLsupportallofthesefeatureswiththe<thead>,<tfoot>,and<tbody>tags.
10.3.2.The<thead>Tag
Usethe<thead>tagtodefineasetoftableheaderrows.The<thead>tagmay
appearonlyoncepertableandisplacedatthebeginning,justafterthe<table>
tag.Withinthe<thead>tag,youmayplaceoneormore<tr>tags,definingtherows
withinthetableheader.Ifgiventheopportunity,theHTML4/XHTML-compliant
browserreplicatestheseheadingrowswhenthetableisprintedordisplayedin
multiplesections.Thereafter,itrepeatstheseheadingsoneachprintedpageifthe
tableappearsonmorethanonepage.
<thead>
Function Definesatableheader
Attributes
align,char,charoff,class,dir,id,lang,onClick,onDblClick,onKeyDown,
onKeyPress,onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,
style,title,valign
Endtag </thead>;maybeomittedinHTML
Contains table_content
Usedin table_content
Theending</thead>tagisoptionalforHTML.Becausethe<thead>tagappearsonly
intableswhere,presumably,otherrowsaredesignatedasthetablebodyor
footer,browsersautomaticallyclosethe<thead>tagwhentheyencountera<tbody>
or<tfoot>tagorwhenthetableends.
Themanyattributesofthe<thead>tagoperateidentically,takethesamevalues,
andaffectalltheenclosed<tr>contentsasthoughyouhadspecifiedthem
individuallyforeach<tr>enTRy.Forexample,thealignattributeacceptsvaluesof
left,right,orcenter,controllingthehorizontalalignmentoftextinallofthe
heading'srows.Similarly,thevalignattributeacceptsvaluesoftop,middle,baseline
(InternetExploreronly),orbottom,dictatingtheverticalalignmentoftextinallof
theheadingrows.
Ifyoudon'tspecifyanyalignmentsorstyles,thebrowsercenterstheheadingtext
verticallyandhorizontallywithintherespectivecells,equivalenttospecifying
align=centerandvalign=middleforeach.Ofcourse,individualrowandcellor
stylesheetspecificationsmayoverridetheseattributes.
10.3.3.The<tfoot>Tag
Usethe<tfoot>tagtodefineafooterforatable.The<tfoot>tagmayappearonly
once,justbeforethe<tbody>tag.Like<thead>,itmaycontainoneormore<tr>tags
thatletyoudefinethoserowsthatthecurrentlypopularbrowsersuseasthe
tablefooter.Thereafter,thebrowserrepeatstheserowsifthetableisbroken
acrossmultiplephysicalorvirtualpages.Mostoften,thebrowserrepeatsthe
tablefooteratthebottomofeachportionofatableprintedonmultiplepages.
<tfoot>
Function Definesatablefooter
Attributes
align,char,charoff,class,dir,id,lang,onClick,onDblClick,onKeyDown,
onKeyPress,onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,
style,title,valign
Endtag </tfoot>;maybeomittedinHTML
Contains table_content
Usedin table_content
Theclosing</tfoot>tagisoptionalinHTMLbecausethefooterendsatthe
following<tbody>tagorattheendofthetable.
10.3.4.The<tbody>Tag
Usethe<tbody>tagtodivideyourtableintodiscretesections.The<tbody>tag
collectsoneormorerowsintoagroupwithinatable.Itisperfectlyacceptableto
haveno<tbody>tagswithinatable,althoughwhereyoumightincludeone,you
probablywillhavetwoormore<tbody>tagswithinatable.Soidentified,youcan
giveeach<tbody>groupdifferentrulelinesizesaboveandbelowthesection.
Withina<tbody>tag,onlytablerowsmaybedefinedusingthe<tr>tag.And,by
definition,a<tbody>sectionofatablestandsalone.Forexample,youmaynot
spanfromone<tbody>intoanother.
<tbody>
Function Definesasectionwithinatable
Attributes
align,char,charoff,class,dir,id,lang,onClick,onDblClick,onKeyDown,
onKeyPress,onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,
style,title,valign
Endtag </tbody>;maybeomittedinHTML
Contains table_content
Usedin table_content
Theclosing</tbody>tagisoptionalinHTMLbecausethesectionendsatthenext
<tbody>tag,orwhenthetableends.Like<tfoot>,therearemanyattributesforthe
<tbody>tag,butnoneissupportedbythepopularbrowsers.Ifyouhavespecial
alignmentattributesforthissection,you'llneedtospecifythemforeachrow
withinthe<tbody>tag.
10.3.5.UsingTableSections
Fromapresentationstandpoint,themostimportantthingyoucandowiththe
<thead>,<tfoot>,and<tbody>tagsisdivideyourtableintologicalsectionsthatare
delimitedbydifferentborders.Bydefault,InternetExplorerdoesnotdoanything
specialwiththebordersaroundtheheaders,footers,andsectionswithinyour
table.Byaddingtherulesattributetothe<table>tag,however,youcandraw
thickerrulelinesbetweenyour<thead>,oneormore<tbody>,and<tfoot>table
sections,helpingreadersbetterunderstandyourtable'sorganization.[Thealign
attribute(deprecated),10.2.1.1]
Forexample,hereisthesimpletableyousawearlierinthischapter,augmented
withaheaderandfooter.Noticethatwe'veomittedmanyoftheclosingtagsfor
brevityandreadabilityoftheHTMLbutthatthetagsmustappearinanXHTML-
compliantdocument:
<tablebordercellspacing=0cellpadding=5rules=groups>
<captionalign=bottom>Kumquatversusapokedeye,bygender</caption>
<thead>
<tr>
<tdcolspan=2rowspan=2>
<thcolspan=2align=center>Preference
</tr>
<tr>
<th>EatingKumquats
<th>PokeInTheEye
</tr>
</thead>
<tfoot>
<tr>
<tdcolspan=4align=center>
Note:eyepokesdidnotresultinpermanentinjury
</tr>
</tfoot>
<tbody>
<tralign=center>
<throwspan=2>Gender
<th>Male
<td>73%
<td>27%
</tr>
<tralign=center>
<th>Female
<td>16%
<td>84%
</tr>
</tbody>
</table>
ThetableasrenderedbyOperaisshowninFigure10-6.Noticethattherules
afterthetableheaderandbeforethefooterarethinnerthanthebordersaround
theothertablerows.Thishappenedbecauseweincludedthespecialrules=groups
attributetothe<table>tag.Youmayobtainsimilareffectsbyspecifyingrules=rows
orrules=all.
Figure10-6.UseHTML4/XHTMLtabletagstospeciallysection
yourtables
Longtablesoftenbenefitfromthickerruleseveryfewrows,makingiteasierto
readthetables.Dothisbygroupingtherulesinyourtablewithseveral<tbody>
tags.Eachsetofrowscontainedinasingle<tbody>tagwillhavethickerrules
beforeandafterit.
HereisanexpandedversionofourHTMLtableexample,withadditionalsections
setoffasseparategroups:
<tablebordercellspacing=0cellpadding=5rules=groups>
<captionalign=bottom>Kumquatversusapokedeye,bygender</caption>
<thead>
<tr>
<tdcolspan=2rowspan=2>
<thcolspan=2align=center>Preference
<tr>
<th>EatingKumquats
<th>PokeInTheEye
<tfoot>
<tr>
<tdcolspan=4align=center>
Note:eyepokesdidnotresultinpermanentinjury
<tbody>
<tralign=center>
<throwspan=4>Gender
<th>Malesunder18
<td>94%
<td>6%
<tralign=center>
<th>Malesover18
<td>73%
<td>27%
<tbody>
<tralign=center>
<th>Femalesunder18
<td>34%
<td>66%
<tralign=center>
<th>Femalesover18
<td>16%
<td>84%
</table>
TheresultisshowninFigure10-7.NoticetheGendercolumn?Netscapeversions
4andearlierplacedittotheleftandcenteredbetweentheMalesandFemales
rows,asyoumightexpect.However,theHTML4andXHTMLstandardsexplicitly
disallowspanning<tbody>sectionssothatthecompliantbrowsersalldisplaythe
examplewithjustuptofourrowsinthetable,separatedintotwogroups.You
couldcreateanynumberofgroupswithinthetablebyaddingmore<tbody>tags.
Figure10-7.Multiple<tbody>segmentsfurtherdivideatable,
butyoucannotspanacrossthem
10.3.6.DefiningColumnGroups
Thebasictablemodelisrowcentric.Sometimes,though,itiseasiertodealwith
yourtableasacollectionofcolumns.Usingthe<colgroup>and<col>tags,HTML4
andXHTML,asoriginallyimplementedbyInternetExplorerthroughtable
extensions,helpyouturnthetablesandthinkincolumns.
Unlikethesectioningtagsdescribedintheprevioussections,whichare
interspersedwiththerowsofatabletodefineheaders,footers,andsections
withinthetable,thecolumn-relatedtagscannotbeintermingledwiththecontent
ofatable.Youmustplacethemattheverybeginningofatable,beforethe
content.TheydefinethemodelbywhichHTML4/XHTML-compliantbrowsers
renderthecolumns.
10.3.7.The<colgroup>Tag
The<colgroup>tagdefinesacolumngroup.Youcanusethe<colgroup>tagintwo
ways:asasingledefinitionofseveralidenticalcolumns,orasacontainerfor
severaldissimilarcolumns.Youcanputoneormore<colgroup>tagswithina<table>
tag.Theending</colgroup>tagisrarelyusedinHTMLbutisrequiredinXHTML.In
HTML,the<colgroup>endsatthenext<colgroup>,<thead>,<tbody>,<tfoot>,or<tr>tag.
Allthecurrentlypopularbrowserssupport<colgroup>anditsattributes.
10.3.7.1.Thespanattribute
Usethespanattributewiththe<colgroup>tagtoachievethefirsttypeofcolumn
grouping.Thevalueofthespanattributeistheintegernumberofcolumnsaffected
bythe<colgroup>tag.Forexample,atablewithsixcolumnsfourinthefirstgroup
andtwointheotherwouldappearinthesourcecodeas:
<colgroupspan="4">
<colgroupspan="2">
WhentheHTML4/XHTML-compliantbrowsercollectsthetablecellsintocolumns
bytheexampledefinition,itgroupsthefirstfourcellsineachrowasthefirst
columngroupandthenexttwocellsintoasecondcolumngroup.Anyother
attributesoftheindividual<colgroup>tagsthenareappliedtothecolumns
containedwithinthatgroup.
10.3.7.2.Whentospanandcol
Tousethe<colgroup>tagasacontainerfordissimilarcolumns,leaveoutthespan
attribute,butincludewithineach<colgroup>taganindividual<col>tagforeach
columnwithinthegroup.Forinstance,inHTML:
<colgroup>
<col>
<col>
<col>
<col>
<colgroup>
<col>
<col>
Thismethodcreatesthesamenumberofcolumnsineachgroupaswehadwith
thespanattribute,butitletsyouspecifycolumnattributesindividually.Youcan
stillsupplyattributesforallthecolumnsviathe<colgroup>tag,buttheattributes
inthe<col>tagswilloverridethem,asappropriate.
<colgroup>
Function Definesacolumngroupwithinatable
Attributes
align,char,charoff,class,dir,id,lang,onClick,onDblClick,onKeyDown,
onKeyPress,onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,
span,style,title,valign,width
Endtag </colgroup>;usuallyomittedinHTML
Contains column_content
Usedin table_content
Forinstance,supposewewantourfirstexamplegroupoffourcolumnstoeach
occupy20percentofthetable,andtheremainingtwocolumnstoeachtakeup
10percentofthetotaltablewidth.That'seasywiththespanattribute:
<colgroupspan=4width="20%">
<colgroupspan=2width="10%">
Youcanalsocreatethisstructurewithindividuallyspecifiedcolumns(inHTML):
<colgroupwidth="20%">
<col>
<col>
<col>
<col>
<colgroupwidth="10%">
<col>
<col>
Youcanusebothmethodsinthesametable.Forinstance,wecouldspecifyour
examplecolumngroupings,completewithwidthattributes:
<colgroupspan=4width="20%"align=right>
<colgroupwidth="10%">
<colalign=left>
<colalign=right>
Noticethatthisletsusalignthecontentsofthetwocolumnsofthesecondgroup
individually(thedefaultalignmentiscentered).
10.3.7.3.Theother<colgroup>attributes
Themanyattributescommontotablescontrolthefamiliaraspectsofeachcolumn
inthe<colgroup>-encapsulatedcolumngroup.Theseattributesacceptthesame
valuesandbehaveexactlyliketheequivalentattributesforthe<td>tag.
10.3.8.The<col>tag
Usethe<col>tagtocontroltheappearanceofoneormorecolumnswithina
columngroup.
<col>
Function Defineacolumnwithinacolumngroup
Attributes
align,char,charoff,class,dir,id,lang,onClick,onDblClick,onKeyDown,
onKeyPress,onKeyUp,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,
span,style,title,valign,width
Endtag NoneinHTML;</col>or<col.../>inXHTML
Contains Nothing
Usedin column_content
The<col>tagmayappearonlywithina<colgroup>tagwithinatable.Ithasno
contentandthushasnoendingtaginHTML.Use</col>oraloneforwardslashat
theendofthetag(<col/>)fortherequiredXHTMLendtag.The<col>tag
representsoneormorecolumnswithina<colgroup>towhichanHTML4/XHTML-
compliantbrowserappliesthe<col>tag'sattributes.
Allthecurrentlypopularbrowserssupportthe<col>taganditsattributes.
10.3.8.1.Thespanattribute
Thespanattributeforthe<col>tag,likeforthe<colgroup>tag,letsyouspecifyhow
manysuccessivecolumnsareaffectedbythis<col>tag.Bydefault,onlyoneis
affected.Forexample,let'screatea<colgroup>thathasfivecolumns.Wealignthe
firstandlastcolumnstotheleftandright,respectively,andcenterthemiddle
three:
<colgroup>
<colalign=left>
<colalign=centerspan=3>
<colalign=right>
Youshouldusethe<col>tagonlywithin<colgroup>tagsthatdonotthemselvesuse
thespanattribute.Otherwise,theHTML4/XHTML-compliantbrowsersignorethe
individual<col>tagsandtheirattributes.
10.3.8.2.Theother<col>attributes
Themanyattributescommontotablescontrolthefamiliaraspectsofthecolumn
definedbythe<col>tag.Theseattributesacceptthesamevaluesandbehave
exactlyliketheequivalentattributesforthe<td>tag.
10.3.9.UsingColumnGroups
Columngroupsareeasiertousethantheyfirstappear.Thinkofthemasa
templateforhowtoformatyourtablecolumns.Theirmainpurposeistocreate
groupsthatcanbeseparatedbythickerruleswithinyourtableandtostreamline
theprocessofapplyingformattingattributestoallthecellsinoneormore
columns.
Returningtoouroriginaltableexample,wecanplaceathickerrulebetweenthe
columnlabelsandthedatacellsbyplacingthecolumnlabelsinonecolumngroup
andthedatacellsinanother(inHTML):
<tableborder=cellspacing=0cellpadding=5rules=groups>
<captionalign=bottom>Kumquatversusapokedeye,bygender</caption>
<colgroupspan=2>
<colgroupspan=2>
<thead>
<tr>
<tdcolspan=2rowspan=2>
<thcolspan=2align=center>Preference
<tr>
<th>EatingKumquats
<th>PokeInTheEye
<tbody>
<tralign=center>
<throwspan=4>Gender
<th>Malesunder18
<td>94%
<td>6%
<tralign=center>
<th>Malesover18
<td>73%
<td>27%
<tralign=center>
<th>Femalesunder18
<td>34%</td>
<td>66%</td>
<tralign=center>
<th>Femalesover18
<td>16%
<td>84%
<tfoot>
<tr>
<tdcolspan=4align=center>
Note:eyepokesdidnotresultinpermanentinjury
</table>
TheresultsareshowninFigure10-8.Allweaddedwerethetwo<colgroup>tags;
theadditionalbordersweredrawnbytherules=groupsattributeinthe<table>tag.
Forbordersbetweencolumngroupstobedrawn,therulesattributemustbesetto
groups,cols,orall.
Figure10-8.ExampledemonstratingthevariousHTML4/XHTML
tablefeatures
10.4.BeyondOrdinaryTables
Onthefaceofit,tablesareprettyordinary:justawayforacademicsandother
like-mindeddatacruncherstoformatitemsintocolumnsandrowsforeasy
comparison.Scratchbelowthesurface,though,andyouwillseethattablesare
reallyextraordinary.Besides<pre>,the<table>tagandrelatedattributesprovide
theonlywayforyoutoeasilycontrolthelayoutofyourdocument.Thecontent
insidea<pre>tag,ofcourse,isverylimited.Tables,ontheotherhand,may
containnearlyanythingallowedinnormalbodycontent,includingmultimediaand
forms.Andthetablestructureletsyouexplicitlycontrolwherethoseelements
appearintheuser'sbrowserwindow.Withtherightcombinationsofattributes,
tablesprovideawayforyoutocreatemulticolumntextandsideandstraddle
heads.Theyalsoenableyoutomakeyourformseasiertoread,understand,and
fillout.That'sjustforstarters.
Wedon'tknowthatwecanrecommendgettingtoocaughtupwithpage
layouttablesorbeyond.Remember,itain'taboutlooks,it'saboutcontent.But....
It'seasytoarguethattablesofinformationbenefitfromsomecontrolledlayout
andthatformsfollowaclosesecond.Tablesprovidetheonlywaytocreate
predictable,browser-independentlayoutsforyourwebpages.Usedinmoderation
andfilledwithqualitycontent,tablesareatoolthateveryauthorshouldbeable
towield.
Andnowthatwe'vewhettedyourappetiteforpagelayoutwithtables,don't
despairthatwe'veletyoudownbyendingthischapterwithoutexampleswehave
severalinChapter17.
Chapter11.Frames
Youcandividethebrowser'smaindisplaywindowintoindependentwindow
frames,eachsimultaneouslydisplayingadifferentdocumentsomethinglikeawall
ofmonitorsinaTVcontrolroom.Netscapeinventedthefeatureinthemid-
1990s.Instantlypopular,framesnowarestandardfeaturesforHTML4and
XHTML.
11.1.AnOverviewofFrames
Figure11-1isasimpleexampleofaframedisplay.Itshowshowyoucandivide
thedocumentwindowintocolumnsandrowsofindividualframesseparatedby
rulesandscrollbars.Althoughitisnotimmediatelyapparentintheexample,
eachframeinthewindowcontainsanindependentdocument.Framesmay
containanyvalidcontentthebrowseriscapableofdisplaying,includingXHTML
documentsandmultimedia.Iftheframe'scontentsincludeahyperlinkthatthe
userselects,thenewdocument'scontentsevenanotherframedocumentmay
replacethatsameframe,anotherframe'scontent,ortheentirebrowserwindow.
Framesareenabledwithaspecialframedocument.Itscontentsdonotget
displayed.Instead,theframedocumentcontainstagsthattellthebrowserhowto
divideitsmaindisplaywindowintodiscreteframesandwhatdocumentsgoinside
theframes.
Theindividualdocumentsreferencedanddisplayedintheframedocument
windowactindependently,toadegree;theframedocumentcontrolstheentire
window.Youcan,however,directoneframe'sdocumenttoloadnewcontentinto
anotherframe.Youdothatbyattachinganametoaframeandtargetingthe
namedframewithaspecialattributeforthehyperlink<a>tag.
11.2.FrameTags
Youneedtoknowonlytwotagsinordertocreateaframedocument:<frameset>
and<frame>.Inaddition,theHTML4andXHTMLstandardsprovidethe<iframe>tag,
whichyoumayusetocreateinline,orfloating,frames,andthe<noframes>tagto
handlebrowsersthatcannothandleframes.
Aframesetissimplythecollectionofframesthatmakeupthebrowser'swindow.
Column-androw-definitionattributesforthe<frameset>tagletyoudefinethe
numberofandinitialsizesforthecolumnsandrowsofframes.The<frame>tag
defineswhichdocumentHTMLorotherwiseinitiallygoesintotheframewithin
thoseframesetsandiswhereyoumaygivetheframeanametousefor
documenthyperlinks.
HereistheHTMLsourceweusedtogenerateFigure11-1:
<html>
<head>
<title>FramesLayout</title>
</head>
<framesetrows="60%,*"cols="65%,20%,*">
<framesrc="frame1.html">
<framesrc="frame2.html">
<framesrc="frame3.html"name="fill_me">
<framescrolling=yessrc="frame4.html">
<framesrc="frame5.html">
<framesrc="frame6.html"id="test">
<noframes>
Sorry,thisdocumentcanbeviewedonlywitha
frames-capablebrowser.
<ahref="frame1.html">Takethislink</a>
tothefirstHTMLdocumentintheset.
</noframes>
</frameset>
</html>
Figure11-1.Asimplesix-panelframelayout
Noticeafewthingsinthesimpleframeexampleanditsrenderedimage(Figure
11-1).First,liketables,thebrowserfillsframesinaframesetrowbyrow.
Second,Frame4sportsascrollbarbecausewetolditto,eventhoughthe
contentsmayotherwisefitwithoutscrolling.(Scrollbarsautomaticallyappearif
thecontentsoverflowtheframe'sdimensions,unlessexplicitlydisabledwiththe
scrollingattributeinthe<frame>tag.)
Anotheritemofinterestisthenameattributeintheexampleframetags.Once
named,[*]youcanreferencethatparticularframeasthetargetinwhichtodisplaya
hyperlinkeddocumentorperformsomeautomatedaction.Todothat,youadda
specialtargetattributetotheanchor(<a>)tagofthesourcelink.
[*]But,interestingly,notid'd,eventhoughtheattributeexistsforframesandcanidentifyotherHTML/XHTMLelements
ashyperlinktargets.
Forinstance,tolinkadocumentcallednew.htmlfordisplayinFrame3,which
we'venamedfill_me,theanchorlookslikethis:
<ahref="new.html"target="fill_me">
Iftheuserchoosesthehyperlinksay,inFrame1thenew.htmldocumentreplaces
theoriginalframe3.htmlcontentsinFrame3.[ThetargetAttributeforthe<a>
Tag,11.7.1]
11.2.1.What'sinaFrame?
Anyonewhohasopenedmorethanonewindowontheirdesktopdisplayto
comparecontentsoroperateinterrelatedapplicationsknowsinstinctivelythe
powerofframes.
Onesimpleuseforframesistoputcontentthatiscommoninacollection,such
ascopyrightnotices,introductorymaterial,andnavigationalaids,intooneframe,
withallotherdocumentcontentinanadjacentframe.Astheuservisitsnew
pages,eachloadsintothescrollingframe,whilethefixed-framecontentpersists.
Aricherframedocument-enabledenvironmentprovidesnavigationaltoolsfor
yourdocumentcollections.Forinstance,assignoneframetoholdatableof
contentsandvarioussearchingtoolsforthecollection.Haveanotherframehold
theuser-selecteddocumentcontents.Asusersvisityourpagesinthecontent
frame,theyneverlosesightofthenavigationalaidsintheotherframe.
Anotherbeneficialuseofframedocumentsistocompareareturnedformwithits
originaltoverifythecontenttheusersubmitted.Byplacingtheforminone
frameanditssubmittedresultinanother,youlettheuserquicklyverifythatthe
resultcorrespondstothedataenteredintheform.Iftheresultsareincorrect,the
formisreadilyavailabletobefilledoutagain.
11.3.FrameLayout
Framelayoutissimilartotablelayout.Usingthe<frameset>tag,youcanarrange
framesintorowsandcolumnswhiledefiningtheirrelativeorabsolutesizes.
11.3.1.The<frameset>Tag
Usethe<frameset>tagtodefineacollectionofframesandotherframesetsandto
controltheirspacingandborders.Youmayalsonestframesets,resultingina
richersetoflayoutcapabilities.
<frameset>
Function Definesacollectionofframes
Attributes border,bordercolor ,class,cols,frameborder ,framespacing ,id,onLoad,
onUnload,style,title
Endtag </frameset>;neveromitted
Contains frameset_content
Usedin html_content
Usethe<frameset>taginlieuofa<body>tagintheframedocument.Youmaynot
includeanyothercontentexceptvalid<head>and<frameset>contentinaframe
document.Combiningframeswithaconventionaldocumentcontaininga<body>
sectionmayresultinunpredictablebrowserbehavior.
11.3.1.1.Therowsandcolsattributes
The<frameset>taghasonerequiredattribute:eithercolsorrowsyourchoice.They
definethesizeandnumberofcolumnsorrowsofeitherframesornested
framesetsforthedocumentwindow.Bothattributesacceptaquote-enclosed,
comma-separatedlistofvaluesthatspecifieseithertheabsolute(pixels)or
relative(percentageorremainingspace)width(forcolumns)orheight(forrows)
fortheframes.Thenumberofattributevaluesdetermineshowmanyrowsor
columnsofframesthebrowserdisplaysinthedocumentwindow.
Aswithtables,thebrowsermatchesthesizeyougiveaframesetascloselyas
possible.Thebrowserdoesnot,however,extendtheboundariesofthemain
documentwindowtoaccommodateframesetsthatwouldotherwiseexceedthose
boundariesorfillthewindowwithemptyspaceifthespecifiedframesdon'tfillthe
window.Rather,browsersallocatespacetoaparticularframerelativetoallother
framesintherowandcolumnandresolutelyfilltheentiredocumentwindow.(Did
younoticethatthemainframewindowdoesnothavescrollbars?)
Forexample:
<framesetrows="150,300,150">
createsthreerowsofframes,eachextendingacrosstheentiredocumentwindow.
Thefirstandlastframesaresetto150pixelstall,andthesecondissetto300
pixels.Inreality,unlessthebrowserwindowisexactly600pixelstall,thebrowser
automaticallyandproportionatelystretchesorcompressesthefirstandlast
framessothateachoccupiesone-quarterofthewindowspace.Thecenterrow
occupiestheremaininghalfofthewindowspace.
Framerow-andcolumn-sizevaluesexpressedaspercentagesofthewindow
dimensionsaremoresensible.Forinstance,thefollowingexampleiseffectively
identicaltotheprecedingone:
<framesetrows="25%,50%,25%">
Ofcourse,ifthepercentagesdon'taddupto100percent,thebrowser
automaticallyandproportionallyresizeseachrowtomakeupthedifference.
Ifyouarelikeus,makingthingsaddupisnotastrength.Perhapssomeofthe
framedesignerssufferthesamedifficulty,whichwouldexplainwhytheyincluded
theveryniftyasteriskoptionfor<frameset>rowsandcolsvalues.Ittellsthebrowser
tosizetherespectivecolumnorrowtowhateverspaceisleftoverafterputting
adjacentframesintotheframeset.
Forexample,whenthebrowserencountersthefollowingframetag:
<framesetcols="100,*">
itmakesafixed-sizecolumn100pixelswideandthencreatesanotherframe
columnthatoccupiesalloftheremainingspaceinthebrowserwindow.
Here'safancierlayoutexample:
<framesetcols="10,*,10">
Thisonecreatestwoverythincolumnsdowntheedgesofthewindowandgives
theremainingcenterportiontothemiddlecolumn.
Youmayalsousetheasteriskformorethanonerow-orcolumn-attributevalue.
Inthatcase,thecorrespondingrowsorcolumnsequallydividetheavailable
space.Forexample:
<framesetrows="*,100,*">
createsa100-pixel-tallrowinthemiddleofthebrowserdisplayandequal-size
rowsaboveandbelowit.
Ifyouprecedetheasteriskwithanintegervalue,thecorrespondingrowor
columngetsproportionallymoreoftheavailablespace.Forexample:
<framesetcols="10%,3*,*,*">
createsfourcolumns:thefirstcolumnoccupies10percentoftheoverallwidthof
thedisplay.Thebrowserthengivesthesecondframethree-fifthsoftheremaining
space,andthethirdandthefourthareeachgivenone-fifthoftheremaining
space.
Usingasterisks(especiallywiththenumericprefix)makesiteasytodividethe
remainingspaceinaframeset.
Beaware,too,thatunlessyouexplicitlytellitnotto,thebrowserallowsusersto
resizetheindividualframedocument'scolumnsandrowsmanuallyand,hence,
changetherelativeproportionseachframeoccupiesintheframe'sdisplay.To
preventthis,usethenoresizeattributeforthe<frame>tag,whichwedescribelater.
[<frame>,11.4.1]
11.3.1.2.Theborder,frameborder,framespacing,andbordercolorattributes
Thepopularbrowsersprovideattributeextensionsthatyoumayusetogenerally
defineandchangetheborderssurroundingtheframesinaframeset.TheHTML4
andXHTMLstandardspreferinsteadthatyouincludetheseborder-relateddisplay
featuresviaCascadingStyleSheet(CSS)styles.
Bydefault,everyframeinaframesetissurroundedbyathin3Dborder(see
Figure11-1).Makethesebordersuniformlythickerorgetridofthemaltogether
withtheborderattributeforthe<frameset>tag.Setthevalueofborderto0toturn
offborders(seeFigure11-2).Thevalue1isthesameasthedefault.Touniformly
increasethewidthofalltheframebordersintheframeset,settheborderattribute
valuetoanintegergreaterthan1.
Figure11-2.Theborderandframeborderattributesletyou
removethebordersbetweenframes
Usetheframeborderattributewiththevalue1oryestoenable,orwithavalue0or
notodisableborders.Usetheframespacingattributewithanintegervalue1or
greatertothickentheborderbetweenframes.Whytwoseparateattributesto
achievethesameeffectasthesingleborder?Historicalreasons,mostly.Sufficeit
tosayherethatsomeconfusionstillexists.Allthepopularbrowsersacceptborder
for<frameset>,sopleaseuseitratherthantheindividualalternatives.
Allthepopularbrowsers,exceptOperaforsomereason,alsoletyoucontrolthe
coloroftheframeborderswiththebordercolorattribute(Figure11-3).Useacolor
nameorhexadecimaltripleasitsvalue.Forexample,althoughyoucan'tseethe
colorinthisblack-and-whitebook,thebordersinFigure11-3arelightgreen,
correspondingtothered,green,andblue(RGB)valueof"00CC00."(Forclarity,
wealsoincreasethesizeoftheborderwiththeborderattribute.)Youcanfinda
completelistofcolornamesandvaluesinAppendixG.
Figure11-3.Usethebordercolorandborderattributestocontrol
thecolorandspacingbetweenframes
11.3.1.3.FramesandJavaScript
AllthepopularbrowserssupportJavaScript-relatedeventhandlersthatletyour
framedocumentsreactwhentheyarefirstloadedandwhentheframewindow
getsresized(onLoad);whentheuserunloadsthemfromthebrowser(onUnload);
whenthewindowcontainingtheframesetlosesfocus,suchaswhentheuser
selectsanotherwindow(onBlur);orwhentheframesetbecomestheactivewindow
(onFocus).Includedas<frameset>attributes,theseeventhandlerstakequote-
enclosedlistsofJavaScriptcommandsandfunctioncallsastheirvalues.
Forexample,youmightnotifytheuserwhenallthecontentshavebeenloaded
intotheirrespectiveframesofalengthyframeset:
<framesetonLoad="window.alert('Everythingisloaded.Youmaynowcontinue.')">
Youalsomayusethesefourattributeswiththe<body>tag.WecoverJavaScript
eventhandlersinmoredetailinsection12.3.3.
11.3.1.4.Other<frameset>attributes
Likemostoftheotherstandardtags,the<frameset>taghonorsfourofthestandard
attributes:class,style,title,andid.
Usetheclassattributetoassociateapredefinedstyleclasswiththisframeand,
viastyleinheritance,itscontent.Alternatively,usethestyleattributetodefinea
styleinlinewiththe<frameset>tag.WecoverstylesmorecompletelyinChapter8.
Theidattributecreatesauniqueidentifierfortheframe,andthetitleattribute
createsatitlefortheframethatmightbepresentedtotheuserorusedbya
nonvisualbrowser.[Theidattribute,4.1.1.4][Thetitleattribute,4.1.1.5]
11.3.2.Nesting<frameset>Tags
Youcancreatesomeelaboratebrowserdisplayswithasingle<frameset>,butthe
framelayoutisunimaginative.Instead,createstaggeredframesandother,more
complex,layoutswithmultiple<frameset>tagsnestedwithinatop-level<frameset>in
theframedocument.
Forexample,createalayoutoftwocolumns,thefirstwithtworowsandthe
secondwiththreerows(asshowninFigure11-4),bynestingtwo<frameset>tags
withrowspecificationswithinatop-level<frameset>thatspecifiesthecolumns:
<framesetcols="50%,*">
<framesetrows="50%,*">
<framesrc="frame1.html">
<framesrc="frame2.html">
</frameset>
<framesetrows="33%,33%,*">
<framesrc="frame3.html">
<framesrc="frame4.html">
<framesrc="frame5.html">
</frameset>
</frameset>
Figure11-4.Staggeredframelayoutsusenested<frameset>
tags
11.4.FrameContents
Aframedocumentcontainsnodisplayablecontent,exceptperhapsamessagefor
nonframes-enabledbrowsers.Instead,<frame>tagsinsideoneormore<frameset>
tags(whichencapsulatethecontentsofaframedocument)provideURL
referencestotheindividualdocumentsthatoccupyeachframe.[<noframes>,
11.5]
11.4.1.The<frame>Tag
The<frame>tagappearsonlywithina<frameset>.Useittoset,viaitsassociatedsrc
attribute,theURLofthedocumentcontentthatinitiallygetsdisplayedinsidethe
respectiveframe.
<frame>
Function Definesasingleframeina<frameset>
Attributes bordercolor ,class,frameborder ,id,longdesc,marginheight,marginwidth,name,
noresize,scrolling,src,style,title
Endtag </frame>;rarelyincludedinHTML
Contains Nothing
Usedin frameset_content
Browsersplacetheframecontentsintotheframesetcolumnbycolumn,fromleft
toright,andthenrowbyrow,fromtoptobottom.Accordingly,thesequenceand
numberof<frame>tagsinsidethe<frameset>tagareimportant.
Thebrowserdisplaysemptyframesfor<frame>tagsthatdonothavesrcattributes.
Italsodisplaysemptyframesifthe<frameset>tagcallsformoreframesthanthe
corresponding<frame>tagsdefineifyourframedocumentcallsforthreecolumns
andyouprovideonlytwoframes,forexample.Orphanframesremainempty,and
youcannotputcontentintothemlater,eveniftheyhaveatargetnameoridfor
displayredirection.[Thenameandidattributes,6.3.1.3]
11.4.1.1.Thesrcattribute
Thevalueofthesrcattributeforthe<frame>tagistheURLofthedocumentthatis
tobedisplayedintheframe.Thereisnootherwaytoprovidecontentfora
frame.Youshouldn't,forinstance,includeany<body>contentwithintheframe
document;thebrowserignorestheframetagsanddisplaysjustthecontentsofa
<body>tagifitcomesfirst,orviceversa.
Thedocumentreferencedbythesrcattributemaybeanyvaliddocumentorany
displayableobject,includingimagesandmultimedia.Inparticular,thereferenced
documentmayitselfbecomposedofoneormoreframes.Theframesare
displayedwithinthereferencingframe,providingyetanotherwayofachieving
complexlayoutsusingnestedframes.
Becausethesourcemaybeacompletedocument,allthefeaturesofHTML/XHTML
applywithinaframe,includingbackgroundsandcolors,tables,fonts,andthelike.
Unfortunately,thisalsomeansthatmultipleframesinasinglebrowserwindow
mayconflictwitheachother.Specifically,ifeachnestedframedocument(nota
regularHTMLorXHTMLdocument)hasadifferent<title>tag,thetitleofthe
overallbrowserwindowisthetitleofthemostrecentlyloadedframedocument.
Theeasiestwaytoavoidthisproblemistoensurethatallrelatedframe
documentsusethesametitle.
11.4.1.2.Thenameandidattributes
Theoptionalnameattributeforthe<frame>taglabelsthatframeforlaterreference
byatargetattributefortheanchor(<a>)tagandthe<form>tag.Thisway,youcan
alterthecontentsofaframeusingahyperlinkinanotherframe.Otherwise,like
normalbrowserwindows,linkeddocumentsreplacethecontentsofthesource
frame.Wediscussnamesandtargetsatgreaterlengthlaterinthischapter.[The
targetAttributeforthe<a>Tag,11.7.1]
Similarly,theidattributeuniquelyidentifiesaframe,butthebrowsersdonot
supportitsusefortargetredirection,eventhoughtheydosupportid'suseasa
hyperlinktargetinmanyotherHTMLandXHTMLtags.
Thevalueofthenameoridattributeisatextstringenclosedinquotationmarks.
11.4.1.3.Thenoresizeattribute
Eventhoughyoumayexplicitlysetframedimensionswithattributesinthe
<frameset>tag,userscanmanuallyalterthesizeofacolumnorrowofframes.To
suppressthisbehavior,addthenoresizeattributetotheframetagsintherowor
columnwhoserelativedimensionsyoudonotwantusersfiddlingwith.For
example,foratwo-by-twoframedocument,anoresizeattributeinanyoneofthe
fourassociatedframetagseffectivelyfreezestherelativeproportionsofallthe
frames.
Thenoresizeattributeisespeciallyusefulforframesthatcontainfixedimages
servingasadvertisements,abuttonbar,oralogo.Byfixingthesizeoftheframe
tocontainjusttheimageandsettingthenoresizeattribute,youguaranteethat
theimageisdisplayedintheintendedmannerandthattheremainderofthe
browserwindowisalwaysgivenovertotheotherframesinthedocument.
11.4.1.4.Thescrollingattribute
Thebrowserdisplaysverticalandhorizontalscrollbarswithframeswhose
contentsarelargerthantheallottedwindowspace.Ifthereissufficientroomfor
thecontent,thescrollbarsdisappear.Thescrollingattributeforthe<frame>tag
givesyouexplicitcontroloverwhetherthescrollbarsappearordisappear.
Withscrolling="yes",allthepopularbrowsersexceptNetscapeaddscrollbarsto
thedesignatedframeevenifthereisnothingtoscroll.Ifyousetthescrolling
attributevaluetono,scrollbarsareneveraddedtotheframe,eveniftheframe
contentsarelargerthantheframeitself.Thevalueauto,thedefault,worksas
thoughyoudidn'tincludethescrollingattributeinthetag.
11.4.1.5.Themarginheightandmarginwidthattributes
Thebrowsernormallyplacesasmallamountofspacebetweentheedgeofa
frameanditscontents.Youcanchangethosemarginswiththemarginheightand
marginwidthattributes,eachincludingavaluefortheexactnumberofpixelsto
placearoundtheframe'scontents.
Youcannotmakeamarginlessthan1pixelormakeitsolargethatthereisno
roomfortheframe'scontents.That'sbecause,likemostotherHTMLattributes,
theseadvise;theydonotdictatetothebrowser.Ifyourdesiredmarginvalues
cannotbeaccommodated,thebrowserignoresthemandrenderstheframeas
bestitcan.
11.4.1.6.Theframeborderandbordercolorattributes
WithsomeearlierversionsofInternetExplorer,youcouldaddandremove
bordersfromasingleframewiththeframeborderattribute.Valuesofyesor1andno
or0respectivelyenableordisablebordersfortheframeandoverridethevalueof
theframeborderattributeforanyframesetcontainingtheframe.Don'tuseit.
WithallthepopularbrowsersexceptOpera,youalsocanchangethecolorofthe
individualframe'sborderswiththebordercolorattribute.Useacolornameor
hexadecimaltripleasitsvalue.Iftwoadjacentframeshavedifferentbordercolor
attributes,theresultingbordercolorisundefined.Youcanfindacompletelistof
colornamesandvaluesinAppendixG.
11.4.1.7.Thetitleandlongdescattributes
Likemostotherstandardtags,youcanprovideatitleforaframewiththetitle
attribute.Thevalueoftheattributeisaquote-enclosedstringthatdescribesthe
contentsoftheframe.Browsersmightdisplaythetitle,forinstance,whenthe
mousepassesovertheframe.
Ifthetitleattributeisn'tquiteenoughforyou,youcanusethelongdescattribute.
ItsvalueistheURLofadocumentthatdescribestheframe.Presumably,thislong
descriptionmightbeinsomealternativemedia,suitableforusebyanonvisual
browser.
11.5.The<noframes>Tag
Aframedocumenthasno<body>.Itmustnotbecausethebrowserignoresany
frametagsifitfindsany<body>contentbeforeitencountersthefirst<frameset>tag.
Aframedocument,therefore,isallbutinvisibletoanynonframes-capable
browser.The<noframes>taggivessomerelieftotheframes-disabled.
<noframes>
Function Suppliescontentfornonframes-capablebrowsers
Attributes class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,onMouseDown,
onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </noframes>;sometimesomittedinHTML
Contains body_content
Usedin frameset_content
Youshouldusethe<noframes>tagonlywithintheoutermost<frameset>tagofa
framedocument.Contentbetweenthe<noframes>taganditsrequiredendtag
(</noframes>)isnotdisplayedbyanyframes-capablebrowserbutisdisplayedin
lieuofothercontentsintheframedocumentbybrowsersthatdonothandle
frames.Thecontentofthe<noframes>tagcanbeanynormalbodycontent,
includingthe<body>tagitself.
Althoughthistagisoptional,experiencedauthorstypicallyincludethe<noframes>
tagintheirframedocumentswithcontentthatwarnsnonframes-capablebrowser
usersthatthey'remissingtheshow.Andsmartauthorsgivethoseusersaway
out,ifnotdirectaccesstotheindividualdocumentsthatmakeuptheframe
documentcontents.
Rememberourfirstframeexampleinthischapter?Figure11-5showswhat
happenswhenthatframedocumentgetsloadedintoanoldversionofMosaic.
Figure11-5.A<noframes>messageinanonframes-capable
browser
TheHTMLtoproducethismessagelookslikethis:
<noframes>
Sorry,thisdocumentcanbeviewedonlywitha
frame-capablebrowser.Gotothe<ahref="frame1.html">
firstHTMLdocument</a>intheset.
</noframes>
<noframes>worksbecausemostbrowsersareextremelytolerantoferroneoustags
andincorrectdocuments.Anonframesbrowsersimplyignorestheframetags.
What'sleft,then,isthecontentofthe<noframes>tag,whichthebrowserdutifully
displays.
IfyourbrowserstrictlyenforcessomeversionofHTMLorXHTMLthatdoesnot
supportframes,itmaysimplydisplayanerrormessageandrefusetodisplaythe
document,evenifitcontainsa<noframes>tag.
11.5.1.<noframes>Attributes
Noattributesarespecifictothe<noframes>tag,butyoucanuseanyofthe16
standardattributes:classandstyleforstylemanagement,langanddirfor
languagetypeanddisplaydirection,titleandidfortitlingandnamingthe
enclosedcontent,andanyoftheeventattributesforuser-activatedJavaScript
processingwithinthe<noframes>tag.[Thedirattribute,3.6.1.1][Thelang
attribute,3.6.1.2][Theidattribute,4.1.1.4][Thetitleattribute,4.1.1.5][Inline
Styles:ThestyleAttribute,8.1.1][StyleClasses,8.3][JavaScriptEventHandlers,
12.3.3]
11.6.InlineFrames
Tothispoint,ourdiscussionhascenteredonframesthataredefinedaspartofa
frameset.Aframeset,inturn,replacestheconventional<body>ofadocumentand
suppliescontenttotheuserviaitscontainedframes.
TheHTML4andXHTMLstandardsletyoudothingsabitdifferently:youcanalso
defineaframethatexistswithinaconventionaldocument,displayedaspartof
thatdocument'stextflow.Theseframesbehavealotlikeinlineimages,whichis
whytheyareknownasinlineframes.
Allthepopularbrowserssupportinlineframes.
11.6.1.The<iframe>Tag
Defineaninlineframewiththe<iframe>tag.The<iframe>tagisnotusedwithina
<frameset>tag.Instead,itappearsanywhereinyourdocumentthatan<img>tag
mightappear.The<iframe>tagdefinesarectangularregionwithinthedocumentin
whichthebrowserdisplaysaseparatedocument,includingscrollbarsand
borders.
<iframe>
Function Definesaninlineframewithinatextflow
Attributes align,class,frameborder,height,id,longdesc,marginheight,marginwidth,name,
scrolling,src,style,title,width
Endtag </iframe>;neveromitted
Contains body_content
Usedin text
Usethesrcattributewith<iframe>tospecifytheURLofthedocumentthat
occupiestheinlineframe.Alloftheother,optionalattributesforthe<iframe>tag,
includingname,class,frameborder,id,longdesc,marginheight,marginwidth,name,scrolling,
style,andtitle,behaveexactlylikethecorrespondingattributesforthe<frame>
tag.[The<frame>Tag,11.4.1]
Usethecontentofthe<iframe>tagtoprovideinformationtousersofbrowsersthat
donotsupportinlineframes.Compliantbrowsersignorethesecontents,whereas
allotherbrowsersignorethe<iframe>tagandthereforedisplayitscontentsas
thoughtheywereregularbodycontent.Forinstance,usethe<iframe>contentto
explaintouserswhattheyaremissing:
...otherdocumentcontent...<iframesrc="sidebar.html"width=75height=200align
=right>
Yourbrowserdoesnotsupportinlineframes.Toviewthis
<ahref="sidebar.html">document</a>correctly,youneed
toinstallamorerecentbrowseronyourcomputer.
</iframe>...subsequentdocumentcontent...
Inthisexample,welettheuserknowthatshewasaccessinganunsupported
featureandprovidedalinktothemissingcontent.
11.6.1.1.Thealignattribute
Likethedeprecatedalignattributeforthe<table>and<img>tags,thisinlineframe
attributeletsyoucontrolwheretheframegetsplacedinlinewiththeadjacent
textormovedtotheedgeofthedocument,allowingtexttoflowaroundthe
frame.
Forinlinealignment,usetop,middle,orbottomasthevalueofthisattribute.The
browseralignstheframewiththetop,middle,orbottomoftheadjacenttext,
respectively.Toallowtexttoflowaroundtheinlineframe,usetheleftorright
valuesforthisattribute.Theframeismovedtotheleftorrightedgeofthetext
flow,respectively,andtheremainingcontentofthedocumentisflowedaround
theframe.Avalueofcenterplacestheinlineframeinthemiddleofthedisplay,
withtextflowingaboveandbelow.
11.6.1.2.Theheightandwidthattributes
Thepopularbrowsersputthecontentsofaninlineframeintoapredefined,150-
pixel-tall,300-pixel-widebox.Usetheheightandwidthattributeswithvaluesas
thenumberofpixelstochangethosedimensions.
11.6.2.UsingInlineFrames
Althoughyou'llprobablyshyawayfromthemformostofyourwebpages,inline
framescanbeuseful,particularlyforprovidinginformationrelatedtothecurrent
documentbeingviewed,similartothesidebararticlesyoufindinaconventional
printedpublication.
Exceptfortheirlocationwithinconventionaldocumentcontent,inlineframesare
treatedexactlylikeregularframes.Youcanloadotherdocumentsintotheinline
frameusingitsname(seethenextsection)andlinktootherdocumentsfrom
withintheinlineframe.
11.7.NamedFrameorWindowTargets
Aswediscussedearlierinsection11.4.1,youcanlabelaframebyaddingthename
attributetoits<frame>tag.[2]Oncenamed,theframemaybecomethedestination
displaywindowforahyperlinkeddocumentselectedwithinadocumentdisplayed
insomeotherframe.Youaccomplishthisredirectionbyaddingthespecialtarget
attributetotheanchorthatreferencesthedocument.
[2]Theidattributeprovidesthesameuniquelabelingbutyoucannotuseitforframecontentredirection.Instead,the
browserignorestheid-namedtargetframeanddisplaysthelinkeddocumentinanewwindow.
11.7.1.ThetargetAttributeforthe<a>Tag
Ifyouincludeatargetattributewithinan<a>tag,thebrowserloadsanddisplays
thedocumentnamedinthetag'shrefattributeinaframeorwindowwhosename
matchesthetarget.Ifthenamedframeorwindowdoesn'texist,thebrowser
opensanewwindow,givesitthespecifiedlabel,andloadsthenewdocumentinto
thatwindow.Oncethisprocesshasbeencompleted,linkeddocumentscantarget
thenewwindow.
Targetedhyperlinksmakeiteasytocreateeffectivenavigationaltools.Asimple
tableofcontentsdocument,forexample,mightredirectdocumentsintoa
separatewindow:
<h3>TableofContents</h3>
<ul>
<li><ahref="pref.html"target="view_window">Preface</a>
<li><ahref="chap1.html"target="view_window">Chapter1</a>
<li><ahref="chap2.html"target="view_window">Chapter2</a>
<li><ahref="chap3.html"target="view_window">Chapter3</a>
</ul>
Thefirsttimetheuserselectsoneofthetable-of-contentshyperlinksthebrowser
opensanewwindow,labelsitview_window,anddisplaysthedesireddocument's
contentsinsideit.Iftheuserselectsanotherhyperlinkfromthetableofcontents
andtheview_windowisstillopen,thebrowseragainloadstheselecteddocument
intothatwindow,replacingthepreviousdocument.
Throughoutthewholeprocess,thewindowcontainingthetableofcontentsis
accessibletotheuser.Byclickingonahyperlinkinonewindow,theusercauses
thecontentsoftheotherwindowtochange.
Insteadofopeninganentirelynewbrowserwindow,amorecommonuseoftarget
istodirecthyperlinkcontentstooneormoreframesina<frameset>displayorto
aninline<iframe>window.Youmightplacethetableofcontentsintooneframeof
atwo-framedocumentandusetheadjacentframetodisplaytheselected
documents:
<framesetcols="150,*">
<framesrc="toc.html">
<framesrc="pref.html"name="view_frame">
</frameset>
Whenthebrowserinitiallydisplaysthetwoframes,theleftframecontainsthe
tableofcontents,andtherightframecontainsthePreface(seeFigure11-6).
Figure11-6.Tableofcontentsframecontrolscontentof
adjacentframe
Whenauserselectsahyperlinkfromthetableofcontentsintheleftframe(for
example,Chapter1),thebrowserloadsanddisplaystheassociateddocumentinto
theview_frameframeontherightside(Figure11-7).Asotherlinksgetselected,
therightframe'scontentschange,whiletheleftframecontinuouslymakesthe
tableofcontentsavailabletotheuser.
Figure11-7.ThecontentsofChapter1aredisplayedinthe
adjacentframe
11.7.2.SpecialTargets
Therearefourreservedtargetnamesforspecialdocument-redirectionactions:
_blank
Thebrowseralwaysloadsatarget="_blank"linkeddocumentintoanewly
opened,unnamedwindow.
_self
Thistargetvalueisthedefaultforall<a>tagsthatdonotspecifyatarget,
causingthetargetdocumenttobeloadedanddisplayedinthesameframeor
windowasthesourcedocument.Thistargetisredundantandunnecessary
unlessusedincombinationwiththetargetattributeinthe<base>tagina
document'shead(seethenextsection,11.7.3).
_parent
Thistargetcausesthedocumenttobeloadedintotheparentwindowor
framesetcontainingtheframecontainingthereference.Ifthereferenceisin
awindowortop-levelframe,itisequivalenttothetarget_self.
Abriefexamplemayhelpclarifyhowthishyperlinktargetworks.Considera
linkinaframethatispartofathree-columnframeset.Thisframeset,inturn,
isarowinthetop-levelframesetbeingdisplayedinthebrowserwindow.
Figure11-8showsthisarrangement.
Ifnotargetisspecifiedforthehyperlink,itisloadedintothecontaining
frame.Ifatargetof_parentisspecified,thedocumentisloadedintothearea
occupiedbythethree-columnframesetcontainingtheframethatcontainsthe
link.
Figure11-8.Usingspecialtargetsinnestedframesand
framesets
_top
Thistargetcausesthedocumenttobeloadedintothewindowcontainingthe
hyperlink,replacinganyframescurrentlydisplayedinthewindow.
Continuingwiththeframehierarchy,asshowninFigure11-8,usingatarget
of_topwouldremoveallthecontainedframesandloadthedocumentintothe
entirebrowserwindow.
Allfourofthesetargetvaluesbeginwiththeunderscorecharacter.Thebrowser
ignoresanyotherwindowortargetbeginningwithanunderscore,sodon'tuse
theunderscoreasthefirstcharacterofanyframenameoridyoudefineinyour
documents.
11.7.3.The<base>DefaultTarget
Itcanbetedioustospecifyatargetforeveryhyperlinkinyourdocuments,
especiallywhenmostaretargetedatthesamewindoworframe.Toalleviatethis
problem,youcanaddatargetattributetothe<base>tag.[<base>,6.7.1]
Thetargetattributeinthe<base>tagsetsthedefaulttargetforeveryhyperlinkin
thecurrentdocumentthatdoesnotcontainanexplicittargetattribute.For
instance,inourexampletableofcontentsdocument,almosteverylinkcausesthe
documenttobedisplayedinanotherwindownamedview_frame.Insteadof
includingthattargetineachhyperlink,youshouldplacethecommontargetin
thetableofcontents'<base>tagwithinits<head>:
<head>
<title>TableofContents</title>
<basetarget="view_frame">
</head>
<body>
<h3>TableofContents</h3>
<ul>
<li><ahref="pref.html">Preface</a></li>
<li><ahref="chap1.html">Chapter1</a></li>
<li><ahref="chap2.html">Chapter2</a></li>
<li><ahref="chap3.html">Chapter3</a></li>
</ul>
</body>
Noticethatwedon'tincludeanyothertargetreferencesinthelistofhyperlinks,
becausethebrowserloadsanddisplaysalltherespectivedocumentsinthebase
targetview_frame.
11.7.4.TraditionalLinkBehavior
Beforetheonsetofframes,eachtimeyouselectedahyperlink,thecorresponding
documentreplacedthecontentsofthebrowserwindow.Withframes,this
behaviorismodifiedsothatthecorrespondingdocumentreplacesthecontentof
thereferencingframe.Thisisoftennotthedesiredbehavior,anditcanbe
disconcertingtopeoplebrowsingyourdocuments.
Forexample,supposeyouhavearrangedallofthedocumentsonyoursiteto
presentthemselvesinthreeframes:anavigationalframeatthetopofthe
browserwindow,ascrollingcontentframeinthemiddle,andafeedbackformat
thebottom.Younamedthecontentframewiththenameattributeofthe<frame>tag
inthetop-leveldocumentforyourcollectionandusedthetargetattributeofthe
<base>tagineverydocumentonyoursitetoensurethatalllinksareloadedinto
thecentercontentframe.
Thisarrangementworksperfectlyforallthedocumentsonyoursite,butwhat
happenswhenauserselectsalinkthattakeshimtoadifferentsite?The
referenceddocumentisstillloadedintothecentercontentframe.Nowtheuseris
confrontedbyadocumentfromsomeothersite,surroundedbyyournavigation
andfeedbackframes![3]Veryimpolite.
[3]CheckoutChapter17forhowtostepoutintotheforefrontwhenyourpageshappentobeontheotherendofa
targetlesshyperlink.
Thesolutionistomakesurethateveryhyperlinkthatreferencesaremote
documenthasatargetof_top.Thisway,whentheuserselectsalinkthattakes
himawayfromyoursite,theremotedocumentreplacesthecontentsoftheentire
browserwindow,includingyournavigationandfeedbackframes.Ifthemajorityof
thelinksinyourdocumentsaretoothersites,youmightconsideradding
target="_top"toa<base>taginyourdocumentandusingexplicittargetattributesin
thelinkstoyourlocaldocuments.
11.8.XFrames
Framesarearags-to-richessuccessstory.Fromanonstandardextensioninthe
NetscapebrowsertoastandardcomponentofHTMLandXHTML,frameshave
proventhemselvesasacoreelementoftheHTMLworld.Nonetheless,thereare
problemswithframesthathaveneverbeenfullyresolved:
Navigationwithabrowser'sBackbuttoncanbeunpredictable.
Youcannotdirectlyreferenceadocumentwithinaframeset.
YoucannotreferenceaparticularcollectionofframeswithasingleURL.
Searchenginesoftendonotfollowframedcontent.
Tocorrectthesedeficiencieswhileretainingthepowerofframes,theWorldWide
WebConsortium(W3C)hasproposedaslightlydifferentmodelforframed
content.Thismodelisstillaworkingdocument,andhasnotyetbeen
implementedinanybrowser.Still,webrieflydescribeitheretomakeauthors
awareofwhattheymightexpectfromframesinthenearfuture.
11.8.1.AnXFramesDocument
WithinHTMLandXHTML,framesreplacethe<body>ofadocument,leavingthe
<html>and<head>tagsintact.IntheXFramesmodel,anXFramesdocument
replacestheentire<html>document,carryingwithititsown<head>andframed
content.Withinthe<head>tag,authorscanprovidea<title>and<style>tags;the
framedcontentisthendenotedwithin<group>and<frame>tags.AshortXFrames
documentmightlooklikethis:
<framesxmlns="http://www.w3.org/2002/06/xframes/">
<head>
<title>KumquatLore</title>
<styletype="text/css">
#header{height:10em}
#toc,#nav{width:20%}
#footer{height:4em}
</style>
</head>
<groupcompose="vertical">
<framexml:id="header"source="lore.xhtml"/>
<groupcompose="horizontal">
<framexml:id="toc"source="toc.xhtml"/>
<framexml:id="main"source="intro.xhtml"/>
<framexml:id="nav"source="main-nav.xhtml"/>
</group>
<framexml:id="footer"source="copyright.xhtml"/>
</group>
</frames>
The<head>tagsetsthetitlefortheframeddocumentanddefinesstylesthatwill
affectthedisplayofthecorrespondinglynamedframeswithinthedocumentset.
The<group>tag,analogoustothe<frameset>tag,definesagroupofframesand
othergroupswhoselayoutiscontrolledbythecomposeattribute.The<frame>tag
definesasingledocumentwhosecontentisdisplayedwithinthatframeinthe
document.Inthisdocument,fiveframesarearrangedinthreerows,withone
frameatthetop,oneatthebottom,andthreeinthemiddlerow.Inthatrow,the
leftandrightframeseachoccupy20percentoftheavailablespace,withthe
centerframetakinguptheremainder.Individualframesarenamedwiththexml:id
attribute;thesenamesarereferencedwhenloadingnewcontentinaframe,
whenassociatingstyleswithaframe,andwhencreatingaURLtodisplaya
specificframeset,asdescribedshortly.
Thecomposeattributeinthe<group>tagprovidessomeadditionallayoutcapabilities
thatconventionalframesdonotallow.Whilethehorizontalandverticallayout
choicesperformtheappropriateaction,thesingleandfreechoicesaremore
interesting.Settingcomposetosinglecausesthebrowsertodisplayonlyoneofthe
framesinthegroupatatime,whileprovidingsomesortofmechanismtoindicate
thepresenceofotherframesandawaytoselectthem.Onecanimagineapull-
downmenuthatletstheuserchooseoneframeatatime,forexample.
Thefreevalueforthecomposeattributedisplaystheframesinagroupasasetof
freelymovablewindowswithinadisplayarea.Theusercanmoveandrearrange
thewindowsasdesired,evenoverlappingthem!Presumably,thiswouldallow
framestobedisplayedinasortof"desktop"withinthebrowser,completelyatthe
user'sdiscretion.
11.8.2.XFramesURLs
Tosupportexplicitreferencetoframeswithinaframeddocument,theXFrames
modelextendsthedefinitionofaURLtoincludeaspecial#frameskeyword.This
featureletsyouspecifythecontentforeachframeinadocument,somethingthat
isimpossiblewiththecurrentHTMLandXHTMLframesmodel.
Tousethisfeature,addthespecial#frameskeywordtotheendofaURL
referencingaframedocument.FollowthekeywordwithalistofframeIDsand
theirdesiredcontent,allenclosedinparentheses.Sounddifficult?It'snot:
http://www.kumquat.com/lore.html#frames(toc=section7.xhtml,main=arctic-quats.xhtml)
ThisURLopenstheframeddocumentnamedlore.html,andloadsthetocandmain
frameswiththedesiredpages.Theotherframesnamedinthedocumentare
loadedwiththeirdefaultcontentbecausetheyarenotmentionedinthisURL.
Frameswithoutdefaultcontentareleftblank.
Thispowerfulsyntaxhaslotsofbenefitsforauthorsandendusers.Authorscan
nowconstructlinksthatwillopenacompletesetofframeddocumentsina
specific,repeatablemanner.Anduserscansaveabookmarktoaframed
document,assuredthatwhentheyreturntothedocument,alltheframeswillbe
openedwiththesamecontentaswhentheysavedtheURL.
Chapter12.ExecutableContent
Oneofthemostusefulwebtechnologiesistheabilitytodeliverapplications
directlytothebrowser.Thesetypicallysmallprogramsperformsimpletaskson
theclientcomputer,fromrespondingtousermouseorkeyboardactionstospicing
upyourwebpagedisplayswithmultimedia-enablingsoftware.
YoucanembedscriptsinyourdocumentsusingalanguageknownasJavaScript.
Oryoucanloadandexecutesmall,Java-based,platform-independentapplications
knownasapplets.Duringexecution,theseprogramsmaygeneratedynamic
content,interactwiththeuser,validateformdata,orevencreatewindowsand
runentireapplicationsindependentofyourpages.Thepossibilitiesareendless,
andtheygofarbeyondthesimpledocumentmodeloriginallyenvisionedfor
HTML.
Inthischapter,weshowyou,withsimpleexamples,howtoincludetwokindsof
executablecontentscriptsandappletsinyourdocuments.Wewon't,however,
teachyouhowtowriteanddebugexecutablecontent.ThisisabookaboutHTML
andXTHML,afterall.Rather,getanexpertopinion:turntoanyofthemany
excellenttextsfromO'Reilly,especiallythecompanionJavaScript:TheDefinitive
Guide,byDavidFlanagan.
12.1.AppletsandObjects
Appletsrepresentashiftinthebasicmodelofwebcommunications.Inmostother
webapplications,serversperformmostofthecomputationalwork,clientbrowsers
beingnotmuchmorethanglorifiedterminals.Withapplets,webtechnologyshifts
totheclient,distributingsomeorallofthecomputationalloadfromtheserverto
theclientcomputeranditsbrowser.
Appletsalsorepresentawayofextendingabrowser'sfeatureswithoutforcing
userstoacquirenewbrowsers,asisthecasewhendevelopersimplementnewtag
andattributeextensionstoHTML.Nordousershavetoacquireandinstalla
specialapplication,asisrequiredforhelperorplug-inapplications.[*]Thismeans
thatonceusershaveabrowserthatsupportsapplets(allthecurrentlypopular
onesdo),youcandeliverappletsdirectlytothebrowser,includingdisplayand
multimediainnovations.
[*]Actually,InternetExplorer6usersmustdownloadandinstallJavasupport.Readonfordetails.
12.1.1.TheObjectModel
Java-basedappletswebpage-referencedprogramsretrievedfromanetwork
serverandexecutedontheuser'sclientcomputerareanexampleofwhatthe
HTML4andXHTMLstandardscallinclusions.Aswithimages,thebrowserfirst
loadstheHTMLdocument,thenexaminesitforinclusionsadditional,separate,and
discretecontentthattheclientbrowseristohandle.AGIFimageisonetypeof
inclusion.A.wavsoundfile,anMPEGmovie,andaJava-basedclockprogramare
othertypes.
TheHTML4andXHTMLstandardsgenerallycalltheinclusioncontentsobjects.In
fact,inyourdocumentyoumayidentifyandloadnearlyanyobjectfileoverthe
networkthroughauniversal<object>tag,discussedindetailshortlyinsection
12.2.1.
Oncetheobjecthasbeendownloaded,thestandardsdictatethatthebrowser
somehowrendertheobject,byinternalorexternalmechanisms.Otherwise,plug-
insandotherhelperapplicationsmayprovidethenecessaryrendering
mechanism.InternetExplorer,forexample,hasitsinternalresourcesplayanAVI
movie,whereasotherbrowsersrelyuponsomethird-partysoftware,suchas
RealPlayerorQuickTime,toshowthemovie.
12.1.1.1.Theappletmodel
WithJavaapplets,thebrowsersetsasideaportionofthedocumentdisplayspace.
Youmaycontrolthesizeandpositionofthisdisplayarea;theappletcontrols
whatispresentedinside.
Theappletissoftware,anexecutableprogram.Accordingly,besidesprovidinga
displayspace,thebrowser,intandemwiththeclientcomputerenvironmentand
resources,providestheappletwitharuntimeenvironmentcalledavirtual
machine.
Duringexecution,Javaappletshaveaccesstoarestrictedenvironmentwithinthe
user'scomputer.Forinstance,appletshaveaccesstothemouseandkeyboardso
thattheymayreceiveinputfromtheuser.Dependingonthesecuritypolicyin
place,appletsalsomayinitiatenetworkconnectionsandretrievedatafromother
serversontheInternet.Insum,appletsarefull-fledgedprograms,completewith
avarietyofinputandoutputmechanisms,alongwithafullsuiteofnetwork
services.
Youmayplaceseveralappletsinasingledocument;theyallexecuteinparallel
andmaycommunicatewitheachother.Whilethebrowsermaylimittheiraccess
toitscomputersystem,appletshavecompletecontroloftheirvirtual
environmentwithinthebrowser.
12.1.1.2.Theappletadvantage
Thereareseveraladvantagesofapplets,nottheleastofwhichisprovidingmore
compellinguserinterfaceswithinawebpage.Forinstance,anappletmightcreate
auniquesetofmenus,choices,textfields,andsimilaruser-inputtoolsdifferent
fromthoseavailablethroughthebrowser.Whentheuserclicksabuttonwithin
theapplet'sinteraction/displayregion,theappletmightrespondbydisplaying
resultswithintheregion,signalinganotherapplet,orevenloadingacompletely
newpageintothebrowser.
Wedon'tmeantoimplythattheonlyuseofappletsistoenhancetheuser
interface.Anappletisafull-fledgedprogramthatcanperformanynumberof
computationalanduser-interactivetasksontheclientcomputer.Anappletmight
implementareal-timevideodisplay,performcircuitsimulation,engagetheuser
inagame,provideachatinterface,andsoon.
12.1.1.3.Usingappletscorrectly
Anappletisnothingmorethananothertoolyoucanusetoproducecompelling
andusefulwebpages.Keepinmindthatanappletusescomputationalresources
ontheclienttorunandthereforeplacesaloadontheuser'scomputer.Itcan
degradesystemperformance.
Similarly,ifanappletusesalotofnetworkbandwidthtoaccomplishitstask(a
real-timevideofeed,forexample),itmaymakeothernetworkcommunication
unbearablyslow.Whilesuchapplicationsarefun,theydolittlemorethanannoy
yourtargetaudience.
Touseanappletcorrectly,balancetheloadbetweenthebrowserandtheserver.
Foreachpage,decidewhichtasksarebestlefttotheserver(formsprocessing,
indexsearches,andthelike)andwhichtasksarebettersuitedforlocal
processing(user-interfaceenhancements,real-timedatapresentation,small
animations,inputvalidation,andsoon).Dividetheprocessingaccordingly.
Rememberthatmanyusershaveslowernetworkconnectionsandcomputersthan
youdo,anddesignyourappletstosatisfythemajorityofyouraudience.
Usedtherightway,appletsseamlesslyenhanceyourpagesandprovidea
satisfyingexperienceforyouraudience.Usedimproperly,appletsarejustanother
annoyingbandwidthwaster,alienatingyourusersandhurtingyourpages.
12.1.1.4.Writingapplets
CreatingJavaappletsisaprogrammingtask,notusuallyajobfortheHTMLor
XHTMLauthor.Fordetails,werecommendthatyouconsultanyofthemanyJava
programmingtexts,includingthosefromO'Reilly.
DevelopedbySunMicrosystems,Inc.ofMountainView,California,Javasupports
anobject-orientedprogrammingstylewhereinclassesofappletscanbeusedand
reusedtobuildcomplexapplications.Onewouldthinkthatappletswritteninthe
samelanguageshouldruninanybrowserthatsupportsJava.Asissooftenthe
case,realityismorecomplex.UntilNetscape6andInternetExplorer6,browsers
includedtheirownJavaVirtualMachines(JVMs),andtheirimplementations,
especiallyMicrosoft's,couldbequirky.CertainMicrosoftimplementationdecisions
inInternetExplorer4andearliercausedsomevalidJavaappletstofailwhen
running.MicrosoftfixedtheseproblemswithInternetExplorerversion5but,
becauseofitslawsuitwithSun,chosenottoincludeaJVMinInternetExplorer6.
[*]Althoughthismaysoundlikebadnewsforapplets,infact,InternetExplorer6
promptsyoutodownloadMicrosoft'sJVM.Sun'sJavaPlug-inisfreeoverthe
Internet.UsersofanybrowsercaninstalltheJavaPlug-intogetstate-of-the-art
Javasupport.
[*]Aswewrotethis,eventhissituationmaychange,withMicrosoftreversingitselfanddecidingtoincludeaJVMina
servicepackforWindowsXP.ThereisstillnosignofdefaultinclusionofaJVMinInternetExplorer6downloads,
however.
WeshouldtakethisopportunityalsotomentionActiveX,analternative
executablecontenttechnologyoriginallydevelopedbyMicrosoft.ActiveXitselfis
proprietary,closelycoupledwithvariousversionsofMicrosoftWindows,and
Microsoft'splug-inworksonlywhenusedwithInternetExplorer,though
alternativeplug-inimplementationsnowexistforallthepopularbrowsers.
ActiveXcontrols(astheyarecalled)runonbrowserversionstargetedtovarious
versionsofWindows,butasingleActiveXcontrolwillnotrunonthesedifferent
versionswithoutrecompilation.ThisisincontrastwithJavaapplets;asingleJava
appletcanbewrittenandcompiledonceandimmediatelyrunonabroadrangeof
browsersandoperatingsystems.
ActiveXalsopresentsanunacceptablyhighsecurityrisktoanyuserwhose
browsersupportsActiveXtechnology.[ ]Thoughovertheyearssecurityhas
gottenbetter,itisridiculouslyeasytopenetrateanddamageacomputerrunning
abrowserthatallowsActiveXappletstobeexecuted.Infact,allthepopular
browsers,InternetExplorerincluded,letusersexplicitlyblockActiveXapplets.For
thisreason,wecannotrecommendActiveXasaviableappletimplementation
technologyandwegosofarastorecommendthatusersdisableActiveX
capabilitywithintheirbrowsers.
[ ]Youcanfindagooddescriptionoftherisksathttp://www.digicrime.com/activex.
12.2.EmbeddedContent
Inthissection,wecoverthreetagsthatsupportembeddedcontent.The<object>
tagisintheHTML4andXHTMLstandards.Itisageneralizedhybridofthe
deprecated<applet>tagforembeddingapplets,particularlyJavaapplets,andthe
<embed>tagextensionthatletsyouincludeanobjectwhoseMultipurposeInternet
MailExtension(MIME)typereferencestheplug-inneededtoprocessandpossibly
displaythatobject.
Thelateststandardsstronglyencourageyoutousethe<object>tagtoincorporate
appletsandotherdiscreteinclusionsinyourdocuments,includingimages
(althoughthestandardsdonotgosofarastodeprecatethe<img>tag).Use
<object>withtheclassidattributetoinsertJavaandotherappletsintoadocument,
alongwiththeirexecutionparametersascontentsoftheassociated<param>tag.
Use<object>withthedataattributetodownloadanddisplaynon-HTML/XHTML
content,suchasmultimedia,intheuser'scomputingenvironment.Objectdata
maybeprocessedandrenderedbyanincludedapplet,byutilitiesthatcomewith
yourbrowser,orbyaplug-in(helper)applicationthattheusersupplies.
Forapplets,thebrowsercreatesadisplayregioninthecontainingtextflow
exactlylikeaninlineimageoran<iframe>:withoutlinebreaksandasasingle
largeentity.Thebrowserthendownloadsandexecutestheapplet'sprogramcode,
ifspecified,anddownloadsandrendersanyincludeddatajustafterdownloadand
displayofthedocument.Executionoftheappletcontinuesuntilthecode
terminatesitselforwhentheuserstopsviewingthepagecontainingtheapplet.
Withdata,thebrowserdecodestheobject'sdatatypeandeitherhandlesits
renderingdirectly,suchaswithGIF,PNG,andJPEGimages,orinvokesan
associatedplug-inapplicationforthejob.
12.2.1.The<object>Tag
The<object>tagwasoriginallyimplementedbyMicrosofttosupportitsActiveX
controls.OnlylaterdidMicrosoftaddJavasupport.Inasimilarmanner,Netscape
initiallysupportedthealternative<embed>and<applet>tagsforinclusionobjectsand
laterprovidedlimitedsupportforthe<object>tag.
Allthatjostlingforpositionbythebrowsergiants[*]madeusnervous,andwe
werehesitantinpreviouseditionsofthisbooktoevensuggestthatyouuse
<object>atall.Wenowheartilyendorseit,basedonthestrengthoftheHTML4
and(particularly)XHTMLstandards,especiallybecausethecurrentlypopular
browserssupport<object>.
[*]Believeitornot,Netscapeoncedominatedthebrowsermarket!
Nonetheless,beawarethatthepopularbrowsersinterpret<object>and<embed>a
bitdifferently.Forexample,InternetExplorerstilltreats<object>contentas
ActiveXcontrolsandlaunchesitshelperprogramtodisplaythedata.Bycontrast,
thebrowserdisplays<embed>contentwithinthedocumentdisplay.
<object>
Function Embedsanobjectorappletinadocument
Attributes
align,archive,border,class,classid,codebase,codetype,data,declare,dir,height,
hspace,id,lang,name,notab ,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,
onLoad,onMouseDown,onMouseMove,onMouseOut,onMouseOver,onMouseUp,shapes,standby,
style,tabindex,title,type,usemap,vspace,width
Endtag </object>;neveromitted
Contains object_content
Usedin text
Thecontentsofthe<object>tagmaybeanyvalidHTMLorXHTMLcontent,along
with<param>tagsthatpassparameterstoanapplet.Ifthebrowsercanretrievethe
requestedobjectandsuccessfullyprocessit,eitherbyexecutingtheappletorby
processingtheobject'sdatawithaplug-inapplication,thecontentsofthe<object>
tag,exceptforthe<param>tags,areignored.Ifanyproblemoccursduringthe
retrievalandprocessingoftheobject,thebrowserwon'tinserttheobjectintothe
documentbutinsteadwilldisplaythecontentsofthe<object>tag,exceptforthe
<param>tags.Inshort,youshouldprovidealternativecontentincasethebrowsers
cannothandlethe<object>tagortheobjectcannotbeloadedsuccessfully.
12.2.1.1.Theclassidattribute
Usetheclassidattributetospecifythelocationoftheobject,typicallyaJavaclass,
whichyouwantthebrowsertoinclude.Thevaluemaybetheabsoluteorrelative
URLofthedesiredobject.RelativeURLsareconsideredtoberelativetotheURL
specifiedbythecodebaseattributeifitisprovided;otherwise,theyarerelativeto
thecurrentdocument'sURL.
Forexample,toexecuteaclockJavaappletcontainedinafilenamedclock.class,
youmightincludethefollowingcodeinyourHTMLdocument:
<objectclassid="java:clock.class">
</object>
Thebrowserlocatesthecodefortheappletusingthecurrentdocument'sbase
URL.Hence,ifthecurrentdocument'sURLis:
http://www.kumquat.com/harvest_time.html
thebrowserretrievestheappletcodeforourclock.classexampleas:
http://www.kumquat.com/clock.class
12.2.1.2.Thecodebaseattribute
UsethecodebaseattributetoprovideanalternativebaseURLfromwhichthe
browsershouldretrieveanobject.ThevalueofthisattributeisaURLpointingto
adirectorycontainingtheobjectreferencedbytheclassidattribute.Thecodebase
URLoverrides,butdoesnotpermanentlyreplace,thedocument'sbaseURL,which
isthedefaultifyoudon'tusecodebase.[ReferencingDocuments:TheURL,6.2]
Continuingwithourpreviousexamples,supposeyourdocumentcomesfrom
http://www.kumquat.com,buttheclockappletiskeptinaseparatedirectory
namedclasses.Youcannotretrievetheappletbyspecifying
classid="classes/clock.class".Rather,includethecodebaseattributeandnewbase
URL:
<objectclassid="clock.class"codebase="http://www.kumquat.com/classes/">
</object>
whichresolvestotheURL:
http://www.kumquat.com/classes/clock.class
AlthoughweusedanabsoluteURLinthisexample,youalsocanusearelative
URL.Forinstance,appletstypicallyarestoredonthesameserverasthehost
documents,sowe'dusuallybebetteroff,forrelocation'ssake,specifyinga
relativeURLforthecodebase,suchas:
<objectcode="clock.class"codebase="/classes/">
</object>
Theclassidattributeissimilartothecodeattributeofthe<applet>tag,providing
thenameofthefilecontainingtheobject;itisusedinconjunctionwiththe
codebaseattributetodeterminethefullURLoftheobjecttoberetrievedandplaced
inthedocument.
12.2.1.3.Thearchiveattribute
Forperformancereasons,youmaychoosetopreloadcollectionsofobjects
containedinoneormorearchives.ThisisparticularlytrueofJava-based
applications,whereoneJavaclassreliesonmanyotherclassestogetitswork
done.Thevalueofthearchiveattributeisaquote-enclosedlistofURLs,each
pointingtoanarchivetobeloadedbythebrowserbeforeitrendersorexecutes
theobject.
12.2.1.4.Thecodetypeattribute
Thecodetypeattributeisrequiredonlyifthebrowsercannotdetermineanapplet's
MIMEtypefromtheclassidattributeoriftheserverdoesnotdeliverthecorrect
MIMEtypewhendownloadinganobject.Thisattributeisnearlyidenticaltotype
(seesection6.7.2.4),exceptthatitisusedtoidentifyprogramcodetype,
whereastypeshouldbeusedtoidentifydatafiletypes.
Thefollowingexampleexplicitlytellsthebrowserthattheobject'scodeisJava:
<objectcode="clock.class"codetype="application/java">
</object>
12.2.1.5.Thedataattribute
Usethedataattributetospecifythedatafile,ifany,thattheobjectistoprocess.
Thedataattribute'svalueistheURLofthefile,eitherabsoluteorrelativetothe
document'sbaseURLortothatwhichyouprovidewiththecodebaseattribute.The
browserdeterminesthedatatypebythetypeofobjectthatisbeinginsertedin
thedocument.
Thisattributeissimilartothesrcattributeofthe<img>tag,inthatitdownloads
datatobeprocessedbytheincludedobject.Thedifference,ofcourse,isthatthe
dataattributeletsyouincludejustaboutanyfiletype,notjustanimagefile.In
fact,the<object>tagexpects,butdoesn'trequire,thatyouexplicitlynamean
enablingapplicationfortheobjectwiththeclassidattribute,orindicatetheMIME
typeofthefileviathetypeattributetohelpthebrowserdecidehowtoprocess
andrenderthedata.
Forexample,hereisanimageincludedasanobject,ratherthanasan<img>file:
<objectdata="pics/kumquat.gif"type="image/gif">
</object>
12.2.1.6.Thetypeattribute
ThetypeattributeletsyouexplicitlydefinetheMIMEtypeofthedatathatappears
inthefileyoudeclarewiththedataattribute.(Usecodetypetoindicateanapplet's
MIMEtype.)Ifyoudon'tprovidedata,oriftheMIMEtypeofthedataisapparent
fromtheURLorisprovidedbytheserver,youmayomitthisattribute.We
recommendthatyouincludeitanyway,toensurethatthebrowserhandlesyour
datacorrectly.
ForexamplesofdataMIMEtypes,lookinyourbrowserpreferencesfor
applications.Thereyou'llfindalistofthemanyfiledatatypesyourbrowser
recognizesandtheapplication,ifnotthebrowseritself,thatprocessesand
rendersthatfiletype.
12.2.1.7.Thealign,class,border,height,hspace,style,vspace,andwidth
attributes
Aswiththecorrespondingattributesforthe<img>tag,severalattributesletyou
controltheappearanceofthe<object>displayregion.Theheightandwidth
attributescontrolthesizeoftheviewingregion.Thehspaceandvspaceattributes
defineamarginaroundtheviewingregion.Thevalueforeachdimension
attributeshouldbeanactualnumberofpixels.
Thealignattributedetermineshowthebrowseralignstheregionincontextwith
thesurroundingtext.[*]Usetop,texttop,middle,absmiddle,baseline,bottom,orabsbottom
toaligntheobjectdisplayspacewithadjacenttext,orleftandrightalignments
forwraparoundcontent.
[*]ThealignattributeisdeprecatedintheHTML4andXHTMLstandardsbecauseoftheCSSstandard,butitisstill
popularlyusedandsupported.
Thedisplayregion'sdimensionsoftenmustmatchsomeotherappletrequirement,
sobecarefultocheckthesevalueswiththeappletprogrammer.Sometimesthe
appletmayscaleitsdisplayoutputtomatchyourspecifiedregion.
Forinstance,ourexampleclockappletmightgroworshrinktofitnearlyanysize
displayregion.Instead,wemightfixittoasquarespace,100x100pixels:
<objectclassid="clock.class"height="100"width="100">
</object>
Aswith<img>,usetheborderattributetocontrolthewidthoftheframethat
surroundstheobject'sdisplayspacewhenyouincludeitaspartofahyperlink.
Thenullvalue(border=0)removestheframe.[<img>,5.2.6]
Usetheclassandstyleattributestocontrolthedisplaystyleforthecontent
enclosedbythetagandtoformatthecontentaccordingtoapredefinedclassof
the<object>tag.[InlineStyles:ThestyleAttribute,8.1.1][StyleClasses,8.3]
12.2.1.8.Thedeclareattribute
Thedeclareattributeletsyoudefineanobjectbutrestrainsthebrowserfrom
downloadingandprocessingit.Usedinconjunctionwiththenameattribute,this
facilityissimilartoaforwarddeclarationinamoreconventionalprogramming
languagethatletsyoudeferdownloadofanobjectuntilitactuallygetsusedin
thedocument.
12.2.1.9.Theid,name,andtitleattributes
Usetheidornameattributetouniquelylabelanobject.Usethetitleattributeto
simplytitlethetag.Eachattribute'svalueisatextstring.Thebrowsermay
choosetodisplayatitletotheuserormayuseitinsomeothermannerwhile
renderingthedocument.Useidornametoreferencetheobjectinotherelements
ofyourdocument,includinghyperlinksandotherobjects.
Forexample,supposeyouhavetwoclockappletsinyourdocument,alongwith
twoappletstheuseroperatestosetthoseclocks.Provideuniquelabelsforthe
clockappletsusingthenameoridattribute,thenpassthoselabelstothesetting
appletsusingthe<param>tag,whichwediscusslaterinthischapterinsection
12.2.2:
<objectclassid="clock.class"id="clock1">
</object>
<objectclassid="clock.class"id="clock2">
</object>
<objectclassid="setter.class">
<paramid="clockToSet"value="clock1">
</object>
<objectclassid="setter.class">
<paramid="clockToSet"value="clock2">
</object>
Becausewehavenoneedtodistinguishbetweenthesetterapplets,wechoose
nottoidentifytheirinstances.
12.2.1.10.Theshapesandusemapattributes
RecallfromourdetaileddiscussionofhyperlinksinChapter6thatyoucandivide
apictureintogeometricregionsandattachahyperlinktoeach,creatingaso-
calledimagemap.Theshapesandusemapattributesforthe<object>taggeneralize
thatfeaturetoincludeotherobjecttypes.
Thestandardshapesattributeinformsthebrowserthatthe<object>tag'scontents
areaseriesofhyperlinksandshapedefinitions.Theusemapattributeandrequired
URLvaluepointtoa<map>whereyoudefinetheshapesandassociatedhyperlinks,
identicaltotheclient-sideimagemapsdiscussedinsection6.5.2.
Forexample,hereistheimagemapwedescribedinChapter6,rewrittenin
XHTMLasa"shaped"object:
<objectdata="pics/map.gif"shapes="shapes">
<ashape="rect"coords="0,0,49,49"href="main.html#link1"></a>
<ashape="rect"coords="50,0,99,49"href="main.html#link2"></a>
<ashape="rect"coords="0,50,49,99"href="main.html#link3"></a>
<ashape="rect"coords="50,50,99,99"href="main.html#link4"></a>
</object>
andasthemorefamiliarimagemap:
<objectdata="pics/map.gif"usemap="#map1">
</object>
...
<mapname="map1">
<areacoords="0,0,49,49"href="main.html#link1"/>
<areacoords="50,0,99,49"href="main.html#link2"/>
<areacoords="0,50,49,99"href="main.html#link3"/>
<areacoords="50,50,99,99"href="main.html#link4"/>
</map>
Youalsomaytakeadvantageofalltheattributesassociatedwiththehyperlink,
<map>,and<area>tagstodefineandarrangetheimage-mapregions.Forinstance,
werecommendthatyouincludealternative(altattribute)textdescriptionsfor
eachsensitiveregionoftheimagemap.
12.2.1.11.Thestandbyattribute
Thestandbyattributeletsyoudisplayamessagetheattribute'svaluetext
stringduringthetimethebrowserisdownloadingtheobjectdata.Ifyourobjects
arelargeorifyouexpectslownetworkresponsesaddthisattributeasacourtesy
toyourusers.
12.2.1.12.Thetabindexandnotabattributes
ForInternetExplorerwithActiveXobjectsonly,thenotabattributeexcludesthe
objectfromthedocumenttabbingorder.
Asanalternativetothemouse,usersalsomaypresstheTabkeytoselectand
theReturnorEnterkeytoactivateahyperlinkortoaccessaformcontrol,and
browsersmayprovideothermechanismstoselectcontent.Normally,eachtime
theusermovestothenextobjectbypressingtheTabkey,forexamplethebrowser
stepstothenexthyperlinkorformcontrolintheorderinwhichtheyappearin
thedocument.Tochangethatorder,usetheHTML4/XHTMLstandardtabindex
attributeandanintegervaluetoindicatetheobject'spositioninthesequenceof
selectableelementsonthepage.
12.2.1.13.Thedirandlangattributes
Usethedirandlangattributes,liketheircounterpartsformostothertags,to
specifythelanguageanddialectofthe<object>-enclosedcontentsaswellasthe
directionbywhichthebrowseraddstextcharacterstothedisplay.[Thedir
attribute,3.6.1.1][Thelangattribute,3.6.1.2]
12.2.1.14.Objecteventhandling
Asuser-initiatedmouseandkeyboardeventsoccurwithintheobject,youmay
wanttoperformspecialactions.Accordingly,youcanusethe10standardevent
attributestocatchtheseeventsandexecuteJavaScriptcode.Wedescribe
JavaScripteventhandlersmorefullyshortlyinsection12.3.3.
12.2.1.15.Supportingincompatiblebrowsers
Becausesomebrowsersmaynotsupportappletsorthe<object>tag,sometimes
youmayneedtotellreaderswhattheyaremissing.Youdothisbyincludingbody
contentbetweenthe<object>and</object>tags.
Browsersthatsupportthe<object>tagsignoretheextraneouscontentinside.Of
course,browsersthatdon'tsupportobjectsdon'trecognizethe<object>tags.Being
generallytolerantofapparentmistakes,browsersusuallyignoretheunrecognized
tagsandblithelygoontodisplaywhatevercontentappearsinside.It'sassimple
asthat.Thefollowingfragmenttellsobject-incapablebrowserusersthatthey
won'tseeourclockexample:
<objectclassid=clock.class>
Ifyourbrowserwerecapableofhandlingapplets,you'dsee
aniftyclockrighthere!
</object>
Moreimportantly,object-capablebrowsersdisplaythecontentsofthe<object>tag
iftheycannotload,execute,orrendertheobject.Ifyouhaveseveralobjectsof
similarintentbutwithdifferingcapabilities,youcannesttheir<object>tags.The
browsertrieseachobjectinturn,stoppingwiththefirstoneitcanhandle.Thus,
theoutermostobjectmightbeafull-motionvideo.Withinthat<object>tag,you
mightincludeasimplerMPEGvideo,andwithinthat<object>tag,asimpleGIF
image.Ifthebrowsercanhandlefull-motionvideo,yourusersgetthefulleffect.
Ifthatlevelofvideoisn'tavailable,thebrowsercantrythesimplerMPEGvideo
stream.Ifthatfails,thebrowsercanjustdisplaytheimage.Ifimagesaren't
possible,theinnermost<object>tagmightcontainatextdescriptionoftheobject.
<param>
Function Suppliesaparametertoanembeddedobject
Attributes id,name,type,value,valuetype
Endtag NoneinHTML;</param>or<param.../>inXHTML
Contains Nothing
Usedin applet_content
The<param>taghasnocontentand,withHTML,noendtag.Itappears,perhaps
withother<param>tags,onlybetweenan<object>or<applet>taganditsendtag.
Usethe<param>tagtopassparameterstotheembeddedobject,suchasaJava
applet,asrequiredforittofunctioncorrectly.
12.2.2.1.Theid,name,andvalueattributes
The<param>taghastworequiredattributes:nameorid,andvalue.You'veseenthese
attributesbeforewithforms.Together,theydefineaname/valuepairthatthe
browserpassestotheapplet.
Forinstance,ourclockappletexamplemightletusersspecifythetimezoneby
whichitsetsitshourhand.Topasstheparameteridentifiedas"timezone"with
thevalue"EST"toourexampleapplet,specifytheparametersas:
<objectclassid="clock.class">
<paramid="timezone"value="EST"/>
</object>
Thebrowserpassesthename/valuepairstotheapplet,butthatisnoguarantee
thattheappletisexpectingtheparameters,thatthenamesandvaluesare
correct,orthattheappletwillevenusetheparameters.Correctparameter
names,includingcapitalizationandacceptablevalues,aredeterminedbythe
appletauthor.ThewiseHTML/XHTMLauthorworkscloselywiththeapplet
programmerorhasdetaileddocumentationtoensurethattheappletparameters
arenamedcorrectlyandareassignedvalidvalues.
12.2.2.2.Thetypeandvaluetypeattributes
Usethetypeandvaluetypeattributestodefinethetypeoftheparameterthe
browserpassestotheembeddedobjectandhowthatobjectistointerpretthe
value.Thevaluetypeattributecanhaveoneofthreevalues:data,ref,orobject.The
valuedataindicatesthattheparametervalueisasimplestring.Thisisthedefault
value.TherefvalueindicatesthatthevalueisaURLofsomeotherresourceon
theWeb.Finally,objectindicatesthatthevalueisthenameofanotherembedded
objectinthecurrentdocument.Thismaybeneededtosupportinterobject
communicationwithinadocument.
ThevalueofthetypeattributeistheMIMEmediatypeofthevalueofthe
parameter.Thisusuallyisofnosignificancewhentheparametervalueisasimple
string,butitcanbeimportantwhenthevalueisactuallyaURLpointingtosome
otherobjectontheWeb.Inthosecases,theembeddedobjectmayneedtoknow
theMIMEtypeoftheobjectinordertouseitcorrectly.Forexample,this
parametertellstheembeddedobjectthattheparameterisactuallytheURLofa
MicrosoftWorddocument:
<paramid="document"value="http://kumquats.com/quat.doc"
type="application/msword"valuetype="ref"/>
12.2.3.The<applet>Tag(Deprecated)
Usethe<applet>tagwithinyourdocumentstodownloadandexecuteanapplet.
Also,usethetagtodefinearegionwithinthedocumentdisplayfortheapplet's
displayarea.Youmaysupplyalternativecontentwithinthe<applet>tagfordisplay
bybrowsersthatdonotsupportapplets.
<applet>
Function Insertsanapplicationintothecurrenttextflow
Attributes align,alt,archive,class,code,codebase,height,hspace,id,mayscript,name,object,
style,title,vspace,width
Endtag </applet>;neveromitted
Contains applet_content
Usedin text
Mostappletsrequireoneormoreparametersthatyousupplyinthedocumentto
controltheirexecution.Puttheseparametersbetweenthe<applet>tagandits
corresponding</applet>endtag,usingthe<param>tag.Thebrowserwillpassthe
document-specificparameterstotheappletatthetimeofexecution.[<param>,
12.2.2]
The<applet>taghasbeendeprecatedintheHTML4andXHTMLstandardsin
deferencetothegeneralized<object>tag,whichcandothesameas<applet>and
muchmore.Nonetheless,<applet>isapopulartagandremainssupportedbythe
popularbrowsers.
12.2.3.1.Appletrendering
Thebrowsercreatesanapplet'sdisplayregioninthecontainingtextflowexactly
likeaninlineimage:withoutlinebreaksandasasinglelargeentity.Thebrowser
downloadsandexecutestheappletjustafterdownloadanddisplayofthe
documentandcontinuesexecutionuntilthecodeterminatesitselfortheuser
stopsviewingthepagecontainingtheapplet.
12.2.3.2.Thealignattribute
Aswithanimageor<iframe>,youcanusethealignattributetocontroltheapplet's
displayregionwithrespecttoitssurroundingtext,althoughthestandardsprefer
thatyouuserespectiveCascadingStyleSheet(CSS)alignmentproperties.Set
thealignattribute'svaluetotop,texttop,middle,absmiddle,baseline,bottom,or
absbottom,orusetheleftandrightalignmentsforwraparoundcontent.Fora
detaileddescription,seesection5.2.6.
12.2.3.3.Thealtattribute
Thealtattributegivesyouawaytotellusersgracefullythatsomethingismissing
if,forsomereason,theappletcannotorwillnotexecuteontheircomputer.Its
valueisaquote-enclosedmessagestringthat,likethealtattributeforimages,
getsdisplayedinlieuoftheappletitself.Thealtmessageisonlyforbrowsersthat
supportapplets.Seesection12.2.1.15earlierinthischaptertofindouthowto
informusersofapplet-incapablebrowserswhytheycan'tviewanapplet.
12.2.3.4.Thearchiveattribute
ThearchiveattributecollectscommonJavaclassesintoasinglelibrarythatis
cachedontheuser'slocaldisk.Oncethedataiscached,thebrowserdoesn'tneed
tousethenetworktoaccessanapplet;itretrievesthesoftwarefromthelocal
cache,therebyreducingtheinherentdelaysofadditionalnetworkactivitytoload
theclass.
ThevalueofthearchiveattributeisaURLidentifyingthearchivefile.Thesuffixof
thearchivefilenamemaybeeither.zipor.jar.Archived.zipfilesareinthe
familiarZIParchiveformat.Archived.jarfilesareintheJavaarchiveformat.
Archived.jarfilessupportcompressionandadvancedfeaturessuchasdigital
signatures.
Youcanusethearchiveattributewithany<applet>tag,eveniftheclassreferenced
bythetag'scodeattributedoesnotexistinthearchive.Iftheclassisnotfoundin
thearchive,thebrowsersimplyattemptstoretrievetheclassrelativetothe
documentURLorthecodebaseURL,ifspecified.
12.2.3.5.Thecodeandcodebaseattributes
Thecodeattributeisrequiredwith<applet>.Usecodetospecifythefilename,not
theURL,oftheJavaclasstobeexecutedbythebrowser.Like<object>,makethe
searchrelativetoanotherstoragelocationbyusingthecodebaseattribute,
describedearlierinsection12.2.1.2,oranarchive,asdescribedearlierinsection
12.2.1.3.Theextensionsuffixofthefilenameshouldbe.class.Ifyoudon't
includethesuffix,somebrowsersappend.classautomaticallywhensearchingfor
theapplet.
Hereisourclockexamplefromearlierrewrittenasan<applet>:
<appletcode="clock.class"codebase="http://www.kumquat.com/classes/">
</applet>
whichthebrowserretrievesanddisplaysfrom:
http://www.kumquat.com/classes/clock.class
12.2.3.6.Thenameattribute
Thenameattributeletsyousupplyauniquenameforthisinstanceofthecode
classthecopyoftheappletthatrunsontheindividualuser'scomputer.Aswith
othernamedelementsinyourdocument,providinganamefortheappletlets
otherpartsofyourdocument,includingotherapplets,referenceandinteractwith
thisone(e.g.,forsharingcomputedresults).
12.2.3.7.Theheight,hspace,vspace,andwidthattributes
Usetheheightandwidthattributes(identicaltothecounterpartsforthe<img>and
<object>tags)todefinethesizeoftheapplet'sdisplayregioninthedocument.Use
hspaceandvspacetointerposesomeemptyspacearoundtheappletregionand
therebysetitofffromthetext.Theyallacceptvaluesindicatingthesizeofthe
regioninpixels.[Theheightandwidthattributes,5.2.6.10]
12.2.3.8.Themayscriptattribute
ThemayscriptattributeindicatesthattheJavaappletisaccessingJavaScript
featureswithinthebrowser.Normally,Javaappletsattemptingtoaccess
JavaScriptcauseabrowsererror.IfyourappletsaccessJavaScript,youmust
specifymayscriptinthe<applet>tag.
12.2.3.9.Thetitleattribute
Thevalueofthisattributeisaquotedstringthatprovidesatitle,ifnecessary,for
theapplet.
12.2.3.10.Theobjectattribute
Thisunfortunatelynamedattributeanditsstringvaluereferencethenameofthe
resourcethatcontainsaserializedversionoftheapplet.Howandwhatitdoesis
anenigma;noneofthepopularbrowserssupportsit.
12.2.4.The<embed>Tag(Extension)
Atonetime,the<embed>tagwastheonlywayyoucouldincludeareferencein
yourdocumentforthebrowsertohandlesomespecialplug-inapplicationand
perhapsdataforthatapplication.Today'sstandardisthe<object>tagwiththedata
attribute,andwerecommendthatyouuseitinlieuof<embed>.Nonetheless,<embed>
currentlyremainswellsupportedbyallthepopularbrowsers.
With<embed>,youreferencethedataobjectviathesrcattributeandURLvaluefor
downloadbythebrowser.ThebrowserusestheMIMEtypeofthesrc'dobjectto
determinetheplug-inthatisrequiredtoprocesstheobject.Alternatively,you
mayalsousethetypeattributetospecifyaMIMEtypewithoutanobjectand
therebyinitiateexecutionofaplug-inapplication,ifitexistsontheuser's
computer.
Likeallothertags,thenonstandard<embed>tagextensionhasasetofpredefined
attributesthatdefineparametersandmodifythetag'sbehavior.Unlikemost
othertags,however,thebrowsersletyouincludeplug-in-specificname/value
attributepairsin<embed>that,insteadofalteringtheactionofthetagitself,get
passedtotheplug-inapplicationforfurtherprocessing.
<embed>
Function Embedsanobjectinadocument
Attributes align,border ,height,hidden,hspace ,name,palette ,pluginspage ,src,type,
units,vspace ,width
Endtag None
Contains Nothing
Usedin text
Forexample,thistag:
<embedsrc=movie.aviwidth=320height=200autostart=trueloop=3>
hasattributesthatareprocessedbythe<embed>tag(src,width,andheight),andtwo
thatarenotrecognized,butratherarepassedtotheplug-inassociatedwithAVI
videoclips:autostartandloop.[*]
[*]InternetExplorerhasbuilt-insupportforAVImovies;otherbrowsersrequirethatusersdownloadandinstallaplug-in
thatplaystheAVImovie.
Itisnotpossibletodocumentallthepossibleattributesthatthemanydifferent
plug-insmightneedwiththeirassociated<embed>tags.Instead,youmustturnto
theplug-indevelopertolearnaboutalloftheirrequiredandoptionalattributes
foreachplug-inthatyouplantouseinyourpages.
12.2.4.1.Thealign,border,height,hspace,vspace,andwidthattributes
Thebrowserdisplaysembeddedobjectstotheuserinaregionsetasidewithin
thedocumentwindow.The<embed>tag'salign,border,height,width,hspace,andvspace
attributesletyoucontroltheappearanceofthatregionexactlyastheydoforthe
<img>tag,sowewon'tbelaborthem.[<img>,5.2.6]
Briefly,theheightandwidthattributescontrolthesizeoftheviewingregion.
Normally,youshouldspecifytheheightandwidthinpixels,butyoumayuse
someotherunitsofmeasureifyoualsospecifytheunitsattribute(seesection
12.2.4.8,laterinthischapter).Thehspaceandvspaceattributesdefineamargin,in
pixels,aroundtheviewingregion.Thealignattributedetermineshowthebrowser
alignstheregionwithinsurroundingtext,andtheborderattributedeterminesthe
widthoftheborder,ifany,surroundingtheviewingregion.
Allthepopularbrowserssupporttheheight,width,andalignattributes,butunlike
<applet>or<object>,InternetExplorerdoesnotsupportborder,hspace,orvspacefor
the<embed>tag.
12.2.4.2.Thehiddenattribute
Thehiddenattributemakesanobjectinvisibletotheuser,forcingittohavea
heightandwidthof0.Notethatsettinghiddendoesnotcausethebrowserto
displayanemptyregionwithinthedocument,butrathercompletelyremovesthe
objectfromthecontainingtextflow.
Thisattributeisusefulforaudiostreamsplacedwithindocuments.TheHTML
entry:
<embedsrc=music.wavhiddenautostart=trueloop=true>
embedsanaudioobjectinthepage.Thebrowserdoesnotshowanythingtothe
user,butratherplaysbackgroundmusicforthepage.Bycontrast,theplug-in
associatedwith:
<embedsrc=music.wav>
mightpresentanaudiocontrolpaneltouserssothattheycanstartandstopthe
audioplayback,adjustthevolume,andsoforth.
12.2.4.3.Thenameattribute
Likeothernameattributes,thisoneletsyoulabeltheembeddedobjectforlater
referencebyotherelementsinyourdocument,includingotherobjects.Thevalue
ofthenameattributeisacharacterstring.
12.2.4.4.Thepaletteattribute
NetscapeandInternetExplorersupportthepaletteattribute,butincompletely
differentways.WithNetscape,thevalueofthepaletteattributeiseitherforeground
orbackground,indicatingwhichpaletteofwindowsystemcolorstheplug-inusesfor
itsdisplay.
WithInternetExplorer,thevalueofpaletteisapairofhexadecimalcolorvalues,
separatedbyaverticalbar.Thefirstvaluedeterminestheforegroundcolorused
bytheplug-in;thesecondsetsthebackgroundcolor.Thus,specifyingthispalette:
palette=#ff0000|#00ff00
causestheplug-intouseredasitsforegroundcolorandgreenasitsbackground
color.Foracompletedescriptionofhexadecimalcolorvalues,seeAppendixG.
12.2.4.5.Thepluginspageattribute
Thepluginspageattribute,oncesupportedonlybyNetscape,butnolonger,specifies
theURLofawebpagethatprovidesinstructiononwheretoobtainandhowto
installtheplug-inassociatedwiththeembeddedobject.Nowallthepopular
browsersdirectyoutotheirsupportingplug-inhomepagesfordownloads.
12.2.4.6.Thesrcattribute
Likeitsdocument-referencingcounterpartsformyriadothertags,thesrcattribute
suppliestheURLofthedataobjectthatyouembedintheHTMLdocument.The
serverprovidingtheobjectmustbeconfiguredsothatitnotifiesthebrowserof
thecorrectMIMEtypeoftheobject.Ifnot,thebrowserusesthesuffixofthelast
elementofthesrcvaluetheobject'sfilenameintheURLpathtodeterminethe
typeoftheobject.ThebrowserusesthisMIMEtypetodeterminewhichplug-init
executestoprocesstheobject.
Ifyoudon'tincludeansrcattributewiththe<embed>tag,youmustincludeatype
attributetoexplicitlyreferencetheMIMEtypeand,asaresult,theplug-in
application.
12.2.4.7.Thetypeattribute
Usethetypeattributeinadditiontoorinlieuofthesrcattribute.Itsvalue
explicitlyindicatestheMIMEtypeoftheembeddedobject,whichinturn
determineswhichplug-inthebrowserinvokestoprocesstheobject.Thisattribute
isnotrequiredifyouincludethesrcattributeandthebrowsercandeterminethe
objecttypefromtheobject'sURLorserver.Youmustsupplyatypeattributeifyou
don'tincludethesrcattribute.
Itmayseemoddtousean<embed>tagwithoutansrcattributereferencetosome
object,butthisiscommoniftheplug-inrequiresnodataorretrievesitsdata
dynamicallyafteritisstarted.Inthesecases,thetypeattributeisrequiredsothat
thebrowserknowswhichplug-intoinvoke.
12.2.4.8.Theunitsattribute
Pixelsarethedefaultunitofmeasurefortheheightandwidthattributesthat
controlthe<embed>displayspace.Theunitsattributeletsyouexplicitlystatethat
theabsolutemeasureispixels,orchangeittotherelativeen,whichisone-half
thecurrentpointsizeoftextinthedocument.Withtheenunits,youtailorthe
object'sviewingarea(viewport)tobeproportionaltoitsimmediatelysurrounding
content,thesizeofwhichisvariedbytheuser.
Forexample,thistagcreatesaviewportof200x320pixels:
<embedsrc=movie.aviheight=200width=320units=pixels>
Bychangingunitstoen,thatsameviewport,whenincludedwithinaflowof12-
pointtext,becomes1200x1920pixels.
12.2.5.The<noembed>Tag(Extension)
The<noembed>tag,althoughnotpartofthestandards,issupportedbythepopular
browsers;theyconsequentlyignorethe<noembed>enclosedtext.Ontheother
hand,browsersthatdonotrecognize<embed>ignore<noembed>,too,consequently
displayingthelattertag'senclosedtextandtherebysupplyingalternativecontent
totelluserswhattheyaremissinginthe<embed>content.
<noembed>
Function Suppliescontentto<embed>-incompatiblebrowsers
Attributes None
Endtag </noembed>;neveromitted
Contains Nothing
Usedin text
Normally,youusethecontentsofthe<noembed>tagtodisplaysomesortof
messageplacatingusersofinadequatebrowsers:
<embedsrc=cool.movautostart=trueloop=true>
<noembed>Toviewthecoolmovie,youneedtoupgradetoabrowser
thatsupportsthe<embed>tag!</noembed>
Werecommendusinga<noembed>messageonlyinthosecaseswheretheobjectis
crucialfortheusertocomprehendanduseyourdocument.And,inthosecases,
youshouldprovidealinktoadocumentthatcanstandalonewithoutthe
embeddedobject,ornicelyexplainthedifficulty.
12.3.JavaScript
Alltheexecutablecontentelementswe'vediscussedsofarhavehadonecommon
trait:theyareseparatefromthebrowserandtheHTML/XHTMLdocumentseparate
data,separateexecutionengine.
JavaScriptisdifferent.Itisascriptinglanguagethattapsthenativefunctionality
ofthebrowser.YoumaysprinkleJavaScriptstatementsthroughoutyour
documents,eitherasblocksofcodeorassinglestatementsattachedtoindividual
tags.JavaScript-enabledbrowsers,includingallthecurrentlypopularones,
interpretandactupontheJavaScriptstatementsyouprovidetodosuchthingsas
altertheappearanceofthedocument,controlthedisplay,validateand
manipulateformelements,andperformgeneralcomputationaltasks.
AswithJava,wedonotpretendtoteachJavaScriptprogramminginthisbook.
We'llshowyouhowtoembedandexecuteJavaScriptwithinyourdocuments,but
weaskthatyouturntobookslikethecompanionJavaScript:TheDefinitiveGuide
(O'Reilly)foracompletereference.
12.3.1.The<script>Tag
OnewaytoplaceJavaScriptcodeinyourdocumentisviatheHTMLandXHTML
standard<script>tag.
Thebrowserprocesseseverythingbetween<script>and</script>asexecutable
JavaScriptstatementsanddata.YoucannotplaceHTMLorXHTMLwithinthistag;
thebrowserflagsitasanerror.
However,browsersthatdonotsupport<script>processitscontentsasregular
HTML,totheconfusionoftheuser.Forthisreason,werecommendthatyou
includethecontentsofthe<script>taginsideHTMLcomments,justlikeCSS
<style>rules:
<scriptlanguage="JavaScript">
<!--
JavaScriptstatementsgohere
//-->
</script>
Forbrowsersthatignorethe<script>tag,thecontentsaremaskedbythe
commentdelimiters<!--and-->.JavaScript-enabledbrowsers,ontheotherhand,
automaticallyrecognizeandinterprettheJavaScriptstatementsdelimitedbythe
commenttags.Byusingthisskeletonforallyour<script>tags,youcanbesure
thatallbrowsershandleyourdocumentgracefully,ifnotcompletely.
Unfortunately,aswediscussinChapter16,scriptcontentforXHTMLdocuments
mustbewithinaspecialCDATAdeclaration,ratherthanwithincomments.Hence,
HTMLbrowserswon'thonorXHTMLscripts,andviceversa.Ouronly
recommendationatthispointistofollowthepopularbrowsers:writeinHTML,but
useasmanyofthefeaturesofXHTMLasyoucaninpreparationforthefuture.
Youmayincludemorethanone<script>taginadocument,locatedineitherthe
<head>orthe<body>.TheJavaScript-enabledbrowserexecutesthestatementsin
order.Variablesandfunctionsdefinedwithinone<script>tagmaybereferenced
byJavaScriptstatementsinother<script>tags.Infact,onecommonJavaScript
programmingstyleistouseasingle<script>inthedocument<head>todefine
commonfunctionsandglobalvariablesforthedocumentandthentocallthose
functionsandreferencetheirvariablesinotherJavaScriptstatementssprinkled
throughoutthedocument.
<script>
Function Definesanexecutablescriptwithinadocument
Attributes charset,defer,language,src,type
Endtag </script>;neveromitted
Contains scripts
Usedin head_content,body_content
12.3.1.1.Thelanguageandtypeattributes
Usethelanguageortypeattributeinthe<script>tagtodeclarethescripting
languagethatyouusedtocomposethecontentsofthetag.TheHTML4and
XHTMLstandardsdeprecatethelanguageattributeinfavorofthetypeattribute.
Regrettably,thevalueforeachattributeisdifferent.
IfyouareusingJavaScriptbyfarthemostcommonscriptinglanguageonthe
Webuselanguage=JavaScriptortype="text/javascript".Youmayoccasionallyseethe
languagevalueVBScript(text/vbscriptfortype),indicatingthattheenclosedcodeis
writteninMicrosoft'sVisualBasicscript.
WithJavaScript,youmayalsousethelanguagevalue"JavaScript1.2",indicating
thattheenclosedscriptiswrittenforbrowsersthatsupportversion1.2ofthe
language(mostcurrentbrowsersdo).Versioningcanbeaproblem,butit'snot
toosevere.Netscape2.0,forinstance,supportsJavaScript1.0butdoesnot
processscriptsidentifiedas"JavaScript1.1".Thenagain,whatproportionofyour
audienceisstillrunningNetscape2.0?
12.3.1.2.Thesrcandcharsetattributes
ForparticularlylargeJavaScriptprogramsandonesyoureuseoften,youshould
storethecodeinaseparatefile.Inthesecases,havethebrowserloadthat
separatefilethroughthesrcattribute.ThevalueofthesrcattributeistheURLof
thefilecontainingtheJavaScriptprogram.ThestoredfileshouldhaveaMIME
typeofapplication/javascript,butitwillbehandledautomaticallybyaproperly
configuredserverifthefilenamesuffixis.js.
Forexample:
<scripttype="text/javascript"src="http://www.kumquat.com/quatscript.js">
</script>
tellsthe<script>-ablebrowsertoloadaJavaScriptprogramnamed
quatscript.jsfromtheserver.Althoughthereareno<script>contents,theending
</script>stillisrequired.
Usedinconjunctionwiththesrcattribute,thecharsetattributetellsthebrowser
thecharactersetusedtoencodetheJavaScriptprogram.Itsvalueisthenameof
anyInternationalOrganizationforStandardization(ISO)standardcharacterset
encoding.
12.3.1.3.Thedeferattribute
SomeJavaScriptscriptscreateactualdocumentcontentusingthedocument.write
method.Ifyourscriptsdonotalterthecontentsofthedocument,addthedefer
attributetothe<script>tagtospeeditsprocessing.Becausethebrowserknows
thatitcansafelyreadtheremainderofthedocumentwithoutexecutingyour
scripts,itdefersinterpretationofthescriptuntilafterthedocumenthasbeen
renderedfortheuser.
12.3.2.The<noscript>Tag
Usethe<noscript>tagtotellusersofbrowsersthatdonotsupportthe<script>tag
thattheyaremissingsomething.You'vealreadyseenmanyexamplesofthistype
oftag.Youknowthedrill....
<noscript>
Function Suppliescontentto<script>-challengedbrowsers
Attributes class,dir,id,lang,onClick,onDblClick,onKeyDown,onKeyPress,onKeyUp,onMouseDown,
onMouseMove,onMouseOut,onMouseOver,onMouseUp,style,title
Endtag </noscript>;neveromitted
Contains body_content
Usedin text
Veryold,albeit<script>-able,browserslikeNetscape2andInternetExplorer3
blithelydisplaythecontentsofthe<noscript>tag,totheconfusionoftheirusers.
Giventhepaucityofusersofthesebrowsers,wequestiontheneed,butthereare
waystodetectandhandle<script>-challengedbrowsers,detailedinanygood
JavaScriptbook.
The<noscript>tagsupportsthesixstandardHTML4/XHTMLattributesclassand
styleforstylemanagement,langanddirforlanguagetypeanddisplaydirection,
titleandidfortitlingandnamingtheenclosedcontentandtheeventattributes
foruser-initiatedprocessing.[Thedirattribute,3.6.1.1][Thelangattribute,
3.6.1.2][Theidattribute,4.1.1.4][Thetitleattribute,4.1.1.5][InlineStyles:
ThestyleAttribute,8.1.1][StyleClasses,8.3][JavaScriptEventHandlers,
12.3.3]
12.3.3.JavaScriptEventHandlers
OneofthemostimportantfeaturesJavaScriptprovidesistheabilitytodetectand
reacttoeventsthatoccurwhileadocumentisloading,rendering,andbeing
browsedbytheuser.TheJavaScriptcodethathandlestheseeventsmaybe
placedwithinthe<script>tag,butmorecommonly,itisassociatedwithaspecific
tagviaoneormorespecialtagattributes.
Forexample,youmightwanttoinvokeaJavaScriptfunctionwhentheuser
passesthemouseoverahyperlinkinadocument.TheJavaScript-awarebrowsers
supportaspecial"mouseover"event-handlerattributeforthe<a>tag,called
onMouseOver,todojustthat:
<ahref="doc.html"onMouseOver="status='Clickme!';
returntrue">
Whenthemousepassesoverthisexamplelink,thebrowserexecutesthe
JavaScriptstatements.(NoticethatthetwoJavaScriptstatementsareenclosedin
quotesandseparatedbyasemicolon,andthatsinglequotessurroundthetext-
messageportionofthefirststatement.)
Whileacompleteexplanationofthiscodeisbeyondourscope,thenetresultis
thatthebrowserplacesthemessage"Clickme!"inthestatusbarofthebrowser
window.Commonly,authorsusethissimpleJavaScriptfunctiontodisplayamore
descriptiveexplanationofahyperlink,inplaceoftheoftencrypticURLthatthe
browsertraditionallydisplaysinthestatuswindow.
HTMLandXHTMLbothsupportarichsetofeventhandlersthroughrelatedon-
eventtagattributes.ThevalueofanyoftheJavaScriptevent-handlerattributes
isaquotedstringcontainingoneormoreJavaScriptstatementsseparatedby
semicolons.Ifnecessary,youcanbreakextremelylongstatementsacrossseveral
lines.Youalsoshouldtakecaretouseentitiesforembeddeddoublequotesinthe
statements,toavoidsyntaxerrorswhenprocessingtheattributevalues.
12.3.3.1.Standardeventhandlerattributes
Table12-1presentsthecurrentsetofeventhandlersastagattributes.Mostare
supportedbythepopularbrowsers,whichalsosupportavarietyofnonstandard
eventhandlers(taggedwithasterisksinthetable).
Weputtheeventhandlersintotwocategories:userrelatedanddocument
related.Theuser-relatedonesarethemouseandkeyboardeventsthatoccur
whentheuserhandleseitherdeviceonthecomputer.User-relatedeventsare
quiteubiquitous,appearingasstandardattributesinnearlyallthestandardtags
(eventhoughtheymaynotyetbesupportedbyanybrowser),sowedon'tlist
theirassociatedtagsinTable12-1.Instead,we'lltellyouwhichtagsdonotaccept
theseeventattributes:<applet>,<base>,<basefont>,<bdo>,<br>,<font>,<frame>,
<frameset>,<head>,<html>,<iframe>,<isindex>,<meta>,<param>,<script>,<style>,and
<title>.
Table12-1.Eventhandlers
Eventhandler HTML/XHTMLtags
onAbort[*] <img>
onBlur <a>,<area>,<body>,<button>,<frameset>,<input>,<label>,<select>,<textarea>
onChange <input>,<select>,<textarea>
onClick Mosttags
onDblClick Mosttags
onError[*] <img>
onFocus <a>,<area>,<body>,<button>,<frameset>,<input>,<label>,<select>,<textarea>
onKeyDown Mosttags
onKeyPress Mosttags
onKeyUp Mosttags
onLoad <body>,<frameset>,<img>[*]
onMouseDown Mosttags
onMouseMove Mosttags
onMouseOut Mosttags
onMouseOver Mosttags
onMouseUp Mosttags
onReset <form>
onSelect <input>,<textarea>
onSubmit <form>
onUnload <body>,<frameset>
[*]
[*]Nonstandardhandlers.
Someevents,however,occurrarelyandwithspecialtags.Theserelatetothe
specialeventsandstatesthatoccurduringthedisplayandmanagementofa
documentanditselementsbythebrowser.
12.3.3.2.Themouse-relatedevents
TheonClick,onDblClick,onMouseDown,andonMouseUpattributesrefertothemouse
button.TheonClickeventhappenswhentheuserpressesdownandthenquickly
releasesthemousebutton.Iftheuserthenquicklyclicksthemousebuttonfora
secondtime,theonDblClickeventgetstriggeredinthebrowseraswell.
Ifyouneedtodetectbothhalvesofamouseclickasseparateevents,use
onMouseDownandonMouseUp.Whentheuserpressesthemousebutton,theonMouseDown
eventoccurs.TheonMouseUpeventhappenswhentheuserreleasesthemouse
button.
TheonMouseMove,onMouseOut,andonMouseOvereventshappenwhentheuserdragsthe
mousepointer.TheonMouseOvereventoccurswhenthemousefirstentersthe
displayregionoccupiedbytheassociatedHTMLelement.Afterentry,onMouseMove
eventsaregeneratedasthemousemovesaboutwithintheelement.Finally,
whenthemouseexitstheelement,onMouseOutoccurs.
Forsomeelements,theonFocuseventcorrespondstoonMouseOver,andonBlur
correspondstoonMouseOut.
12.3.3.3.Thekeyboardevents
TheHTML4andXHTMLstandardscurrentlysupportonlythreeeventsrelatingto
userkeyboardactions:onKeyDown,onKeyUp,andonKeyPress.TheonKeyDowneventoccurs
whentheuserdepressesakeyonthekeyboard;onKeyUphappenswhenthekeyis
released.TheonKeyPresseventistriggeredwhenakeyispressedandreleased.
Usually,you'llhavehandlersforeithertheupanddowneventsorthecomposite
key-pressevent,butnotforboth.
12.3.3.4.Documentevents
Mostofthedocument-relatedeventhandlersrelatetotheactionsandstatesof
formcontrols.Forinstance,onResetandonSubmithappenwhentheuseractivates
therespectiveresetorsubmitbutton.Similarly,onSelectandonChangeoccuras
usersinteractwithcertainformelements.SeeChapter9foradetaileddiscussion
oftheseforms-relatedevents.
Therealsoaresomedocument-relatedeventhandlersthatoccurwhenvarious
documentelementsgethandledbythebrowser.Forinstance,theonLoadevent
mayhappenwhenaframesetiscompleteorwhenthebodyofanHTMLorXHTML
documentgetsloadedanddisplayedbythebrowser.Similarly,onUnloadoccurs
whenadocumentisremovedfromaframeorwindow.
12.3.4.javascriptURLs
YoucanreplaceanyconventionalURLreferenceinadocumentwithoneormore
JavaScriptstatements.ThebrowserthenexecutestheJavaScriptcode,insteadof
downloadinganotherdocument,wheneverthebrowserreferencestheURL.The
resultofthelaststatementistakentobethe"document"referencedbytheURL
andisdisplayedbythebrowseraccordingly.Theresultofthelaststatementisnot
theURLofadocument;itistheactualcontenttobedisplayedbythebrowser.
TocreateajavascriptURL,usejavascriptastheURL'sprotocol:
<ahref="javascript:generate_document()">
Inthisexample,theJavaScriptfunctiongenerate_document()getsexecutedwhenever
theuserselectsthehyperlink.Thevaluereturnedbythefunction,presumablya
validHTMLorXHTMLdocument,isrenderedanddisplayedbythebrowser.
Itmaybethattheexecutedstatementreturnsnovalue.Inthiscase,thecurrent
documentisleftunchanged.Forexample,thisjavascriptURL:
<ahref="javascript:alert('Error!')">
popsupanalertdialogboxanddoesnothingelse.Thedocumentcontainingthe
hyperlinkisstillvisibleafterthedialogboxisdisplayedanddismissedbytheuser.
12.3.5.JavaScriptEntities
CharacterentitiesinHTMLandXHTMLconsistofanampersand(&),anentity
nameornumber,andaclosingsemicolon.Forinstance,toinserttheampersand
characteritselfinadocumenttextflow,usethecharactersequence&.
Similarly,JavaScriptentitiesconsistofanampersand,oneormoreJavaScript
statementsenclosedincurlybraces,andaclosingsemicolon.Forexample:
&{document.fgColor};
Youmustseparatemultiplestatementsbysemicolonswithinthecurlybraces.The
valueofthelast(oronly)statementisconvertedtoastringandreplacesthe
entityinthedocument.
Normally,entitiescanappearanywhereinadocument.JavaScriptentities,
however,arerestrictedtovaluesoftagattributes.Thisletsyouwrite"dynamic
tags"whoseattributesarenotknownuntilthedocumentisloadedandthe
JavaScriptisexecuted.Forexample,thistagsetsthetextcolorofthedocument
tothecolorvaluereturnedbytheindividual'sfavorite_color()function:
<bodytext=&{favorite_color()};>
SupportforJavaScriptentitiesisinconsistentamongthevariousbrowsersandfor
thisreasonwerecommendagainsttheiruse.
12.3.6.The<server>Tag
The<server>tagisastrangebeast.Thewebserverprocessesitandthebrowser
neverseesit,sowhatyoucandowiththistagdependsontheserveryouare
using,notonthereader'sbrowser.
Netscape'swebservers,forexample(nottobeconfusedwiththeirbrowser),use
the<server>tagtoletyouplaceJavaScriptstatementswithinadocumentthatthe
serverprocesses.TheresultsoftheexecutedJavaScriptaretheninsertedinto
thedocument,replacingthe<server>tag.Acompletediscussionofthisso-called
"server-side"JavaScriptiscompletelybeyondthisbook;weincludethisbrief
referenceonlytodocumentthe<server>tag.
Likethe<script>tag,the<server>tagcontainsJavaScriptcode.However,thelatter
tagandcontentcodemustappearinsidethedocument<head>.Theserverextracts
itfromthedocumentandexecutesitwhenthedocumentisrequestedfor
download.
<server>
Function Definesserver-sideJavaScript
Attributes None
Endtag </server>;neveromitted
Contains JavaScript
Usedin head_content
Obviously,server-sideJavaScriptistightlycoupledtotheserver,nottothe
browser.Tofullyexploitthistagandthebenefitsofserver-sideJavaScriptor
otherserver-sideprogramminglanguages,consultyourwebserver's
documentation.
12.4.JavaScriptStylesheets(Antiquated)
Muchofabrowser'sworkismanipulatingthedisplay,andmuchofitsdisplaycode
alreadyhasbeenexposedforJavaScripting.Soitseemedonlynatural,perhaps
evenrelativelyeasy,forthedevelopersatNetscapetoimplementJavaScript
Stylesheets(JSS).BasedontheWorldWideWebConsortium(W3C)-
recommendedCSSmodel,outlinedinChapter8,thisalternativedocumentstyle
technologyletsyouprescribedisplaypropertiesforallthevariousHTML
elements,eitherinlineastagattributes,atthedocumentlevel,orforanentire
documentcollection.
JSSisantiquated.EventheinventoreschewssupportforJSSentirelyinfavorof
thestandardCSS2.Wearestrongproponentsofreasonablestandards,andnow
thattheCSS2modelisfullysupportedinHTML4andXHTML,wecan't
recommendthatyouuseanythingbutCSS-standardstylesheets.
Wethoroughlydiscusstheconceptsandideasbehindstylesheetsspecifically,
CascadingStyleSheetsinChapter8,sowewon'trepeatourselveshere.Rather,
weaddressonlyhowtocreateandmanipulatestyleswithJavaScriptherepurely
forhistoricalreasons.Beforeforgingaheadinthissection,werecommendthat
youfirstabsorbtheinformationinChapter8.
12.4.1.JavaScriptStylesheetSyntax
Netscapeversions4andearlierimplementedJSSbyextendingseveralexisting
HTMLtagsanddefiningafewobjectsthatstoreyourdocument'sstyles.Netscape
nolongersupportsJSS,nordoesanyotherbrowser.
12.4.1.1.External,document-level,andinlineJSS
AswithCSS,youcanreferenceandloadexternalJSSfileswiththe<link>tag.For
example:
<linkhref="styles.js"
rel=stylesheettype=text/JavaScript>
TheonlyrealdifferencebetweenthistagandtheoneforaCSSexternal
stylesheetisthatthetypeattributeofthe<link>tagissettotext/JavaScriptrather
thantext/CSS.Thereferencedfile,styles.js,containsJavaScriptstatementsthat
definestylesandclassesthatNetscapethenusestocontroldisplayofthecurrent
document.
Document-levelJSSisdefinedwithina<style>taginthe<head>ofthedocument,
justlikewithCSS.Again,thereisonlyonerealdifference:thetypeattributeof
the<style>tagissettotext/JavaScriptratherthantext/CSS.
Thecontentsofthe<style>tagforJSSarequitedifferentfromthoseforCSS,
however.Forexample:
<styletype=text/JavaScript>
<!--
tags.BODY.marginLeft="20px";
tags.P.fontWeight="bold";
//-->
</style>
First,noticethatweusethestandardJavaScriptandHTMLcommentstosurround
ourJSSdefinitions,preventingnoncompliantbrowsersfromprocessingthemas
HTMLcontent.Alsonoticethatthesyntaxofthestyledefinitionisthatof
JavaScript,wherelettercase,amongotherthings,doesmakeadifference.
YouassociateinlineJavaScript-basedstyleruleswithaspecifictagusingthestyle
attribute,justlikewithCSSinlinestyles.ThevalueoftheattributeisalistofJSS
assignments,separatedbysemicolons.Forexample:
<pstyle="color='green';fontWeight='bold'">
createsagreen,boldfacedtextparagraph.Noticefirstthatyouneedtoenclose
inlinestylevalueswithinsinglequotationmarks,notdoublequotationmarks,as
youmightusefordocument-levelandexternalJSSstyles.Thisisreasonable
becausethestyleattributevalueitselfmustbeenclosedindoublequotation
marks.
AlsonotethatinlineJSSdefinitionsuseonlythepropertyname,notthe
containingtagobjectthatownstheproperty.ThismakessensebecauseinlineJSS
stylesaffectonlythecurrenttag,notallinstancesofthetag.
12.4.1.2.JSSvalues
Ingeneral,allofthevaluesyoumayuseforCSSyoumayalsouseinJSS
definitions.Forkeyword,length,andpercentagevalues,simplyenclosethevalue
inquotesanduseitasyouwouldanystringvalueinJavaScript.Thus,theCSS
valueboldbecomes"bold"or'bold'forJSSdocument-levelorinlinestyles,
respectively;12ptinCSSbecomes'12pt'or"12pt"inJSS.
Specifycolorvaluesasthecolornameorahexadecimalcolorvalue,enclosedin
singleordoublequotes.JSSdoesnotsupporttheCSSdecimalred,green,and
blue(RGB)notation.
JSSURLvaluesarestringscontainingthedesiredURL.Thus,theCSSURLvalue
(http://www.kumquat.com)becomes'http://http://www.kumquat.com'foraJSSinlinestyle,
or"http://www.kumquat.com"atthedocumentlevel.
OneuniquepowerofJSSisthatanyvaluecanbecomputeddynamicallywhen
thebrowserprocessesthedocument.Insteadofstaticallyspecifyingthefontsize,
forexample,youcancomputeitonthefly:
tags.P.fontSize=favorite_font_size();
WeassumethattheJavaScriptfunctionfavorite_font_size()somehowdetermines
thedesiredfontsizeandreturnsastringvaluecontainingthatsize.This,inturn,
isassignedtothefontSizepropertyforthe<p>tag,definingthefontsizeforall
paragraphsinthedocument.
12.4.1.3.Definingstylesfortags
JavaScriptdefinesadocumentpropertycalledtagsthatcontainsthestyle
propertiesforallHTMLtags.Todefineastyleforatag,simplysettheappropriate
propertyofthedesiredstylepropertywithinthetagpropertyofthedocumentobject.
Forexample:
document.tags.P.fontSize='12pt';
document.tags.H2.color='blue';
ThesetwoJSSdefinitionssetthefontsizeforthe<p>tagto12pointsandrender
all<h2>tagsinblue.TheequivalentCSSdefinitionsare:
p{font-size:12pt}
h2{color:blue}
Becausethetagspropertyalwaysreferstothecurrentdocument,youmayomit
documentfromanyJSStagstyledefinition.Wecouldhavewrittenthepreceding
twostylesas:
tags.P.fontSize='12pt';
tags.H2.color='blue';
Moreover,aswementionedpreviously,youmayomitthetagname,aswellasthe
documentandtagspropertiesforinlineJSS,usingthestyleattribute.
CapitalizationandcasearesignificantinJSS.Thetagnameswithinthetags
propertymustalwaysbefullycapitalized.Theembeddedcapitalletterswithinthe
tagpropertiesaresignificant:anydeviationfromtheexactletteringproducesan
error,andNetscapewon'thonoryourJSSdeclaration.AllofthefollowingJSS
definitionsareinvalid,thoughthereasonsarenotoverlyapparent:
tags.p.fontsize='12pt';
tags.Body.Color='blue';
tags.P.COLOR='red';
Thecorrectversionsare:
tags.P.fontSize='12pt';
tags.BODY.color='blue';
tags.P.color='red';
Itcanbeverytedioustospecifyanumberofpropertiesforasingletag,soyou
cantakeadvantageoftheJavaScriptwithstatementtoreduceyourtyping
burden.Thesestyles:
tags.P.fontSize='14pt';
tags.P.color='blue';
tags.P.fontWeight='bold';
tags.P.leftMargin='20%';
canmoreeasilybewrittenas:
with(tags.P){
fontSize='14pt';
color='blue';
fontWeight='bold';
leftMargin='20%';
}
Youcanapplysimilarstylestodiversetagsjustaseasily:
with(tags.P,tags.LI,tags.H1){
fontSize='14pt';
color='blue';
fontWeight='bold';
leftMargin='20%';
}
12.4.1.4.Definingstyleclasses
LikeCSS,JSSletsyoutargetstylesforspecificwaysthatatagcanbeusedin
yourdocument.JSSusestheclassespropertytodefineseparatestylesforthe
sametag.Therearenopredefinedpropertieswithintheclassesproperty;instead,
anypropertyyoureferenceisdefinedasaclasstobeusedbythecurrent
document.Forexample:
classes.bold.P.fontWeight='bold';
with(classes.abstract.P){
leftMargin='20pt';
rightMargin='20pt';
fontStyle='italic';
textAlign='justify';
}
Thefirststyledefinesaclassofthe<p>tagnamedboldwhosefontweightissetto
bold.Thenextstyleusesthewithstatementtocreateaclassofthe<p>tagnamed
abstractwiththespecifiedproperties.TheequivalentCSSruleswouldbe:
P.bold{font-weight:bold}
P.abstract{left-margin:20pt;
right-margin:20pt;
font-style:italic;
text-align:justify
}
Oncedefined,useaJSSclassjustlikeanyCSSclass:withtheclassattributeand
theclassname.
LikeCSS,JSSalsoletsyoudefineaclasswithoutdefiningthetagthatusesthe
class.Thisletsyoudefinegenericclassesthatyoucanlaterapplytoanytag.To
createagenericstyleclassinJSS,usethespecialtagpropertyall:
classes.green.all.color="green";
Youcanthenaddclass="green"toanytagtohaveNetscaperenderitscontentsin
green.TheequivalentCSSis:
.green{color:green}
12.4.1.5.Usingcontextualstyles
OneofthemostpowerfulaspectsofCSSisitscontextualstylecapability,wherein
thebrowserappliesastyletotagsonlyiftheyappearinthedocumentina
certainnesting.JSSsupportscontextualstylesaswell,throughthespecial
contextual()methodwithinthetagsproperty.Theparameterstothismethodare
thetagsandclassesthatdefinethecontextinwhichNetscapeappliesthestyle.
Forexample:
tags.contextual(tags.UL,tags.UL,tags.LI).listStyleType='disc';
definesacontextwhereintheelements(tags.LI)ofanunorderedlistnested
withinanotherunorderedlist(tags.UL,tags.UL)usethediscastheirbulletsymbol.
TheCSSequivalentis:
ululli{list-style-type:disc}
Youcanmixtagsandclassesinthecontextual()method.Forinstance:
tags.contextual(classes.abstract.P,tags.EM).color='red';
tellsthebrowsertodisplayinred<em>tagsthatappearwithinparagraphsthatare
oftheabstractclass.TheCSSequivalentis:
p.abstractem{color:red}
Becausethetagsobjectisunambiguouslyincludedwithinthecontextual()method,
youmayomititfromthedefinition.Hence,ournestedlistexamplemaybe
rewrittenas:
tags.contextual(UL,UL,LI).listStyleType='disc';
12.4.2.JavaScriptStylesheetProperties
AsubsetoftheCSSstylepropertiesaresupportedinJSS.Table12-2showsthe
JSSstyleproperties,theirCSSequivalents,andthesectionsinwhichthose
propertiesarefullydocumented.
Table12-2.JSSpropertiesandCSSequivalents
JSSproperty CSSproperty Seesection
align float 8.4.7.9
backgroundImage background-image 8.4.5.2
backgroundColor background-color 8.4.5.1
borderBottomWidth border-bottom-width 8.4.7.4
borderLeftWidth border-left-width 8.4.7.4
borderRightWidth border-right-width 8.4.7.4
borderStyle border-style 8.4.7.5
borderTopWidth border-top-width 8.4.7.4
clear clear 8.4.7.7
display display 8.4.10.1
fontSize font-size 8.4.3.2
fontStyle font-style 8.4.3.5
height height 8.4.7.10
lineHeight line-height 8.4.6.2
listStyleType list-style-type 8.4.8.3
marginBottom margin-bottom 8.4.7.11
marginLeft margin-left 8.4.7.11
marginRight margin-right 8.4.7.11
marginTop margin-top 8.4.7.11
paddingBottom padding-bottom 8.4.7.12
paddingLeft padding-left 8.4.7.12
paddingRight padding-right 8.4.7.12
paddingTop padding-top 8.4.7.12
textDecoration text-decoration 8.4.6.4
textTransform text-transform 8.4.6.7
textAlign text-align 8.4.6.3
textIndent text-indent 8.4.6.5
verticalAlign vertical-align 8.4.6.7
whiteSpace white-space 8.4.10.2
width width 8.4.7.16
JSSalsodefinesthreemethodsthatallowyoutodefinemargins,padding,and
borderwidthswithinasinglestyleproperty.Thethreemethods,margins(),
paddings(),andborderWidths(),acceptfourparameters,correspondingtothetop,
right,bottom,andleftmargins,padding,andborderwidth,respectively.Unlike
theirCSScounterparts(margin,discussedinsection8.4.7.11;padding,discussedin
section8.4.7.12;andborder-width,discussedinsection8.4.7.4),theseJSS
methodsrequirethatyoualwaysspecifyallfourparameters.Thereisno
shorthandwayinJSStosetmultiplemargins,paddings,orborderwidthswitha
singlevalue.
Chapter13.DynamicDocuments
ThestandardHTML/XHTMLdocumentmodelisstatic.Oncedisplayedonthe
browser,adocumentdoesnotchangeuntiltheuserinitiatessomeactivity,such
asselectingahyperlink.TheNetscapedevelopersfoundthatlimitation
unacceptableandbuiltsomespecialfeaturesintotheirbrowserthatletyou
changeHTMLdocumentcontentdynamically.Infact,theyprovidetwodifferent
mechanismsfordynamicdocuments,whichwedescribeindetailinthischapter.
InternetExplorersupportssomeofthesemechanisms,whichwe'lldiscussaswell.
Weshouldmentionthatmanyofthefeaturesofdynamicdocumentshavebeen
displacedbyplug-inbrowseraccessoriesand,inparticular,applets,aswellasthe
newAsynchronousJavaScriptandXML(Ajax)technologies.Nonetheless,
NetscapeandInternetExplorercontinuetosupportdynamicdocuments,andwe
believethetechnologyhasvirtuesyoushouldbeawareof,ifnottakeadvantage
of,inyourHTMLdocuments.[AppletsandObjects,12.1]
13.1.AnOverviewofDynamicDocuments
RecallfromourdiscussioninChapter1thattheclientbrowserinitiatesdataflow
ontheWebbycontactingaserverwithadocumentrequest.Theserverhonors
therequestbysendingthedocumenttotheclient.Theclientsubsequently
displaysthedocument'scontentstotheuser.Fornormalwebdocuments,asingle
transactioninitiatedfromtheclientsideisallthatisneededtocollectanddisplay
thedocument.Oncedisplayed,however,itdoesnotchange.
Dynamicdocuments,ontheotherhand,aretheresultofmultipletransactions
initiatedfromeitherorboththeserversideandtheclientside.Aclient-pull
documentisonethatinitiatesmultipletransactionsfromtheclientside.Whenthe
serveristheinstigator,thedynamicdocumentisknownasaserver-push
document.
Inaclient-pulldocument,specialHTMLcodestelltheclienttoperiodicallyrequest
anddownloadanotherdocumentfromoneormoreserversonthenetwork,
dynamicallyupdatingthedisplay.
Server-pushdocumentsalsoadvancethewayserverscommunicatewithclients.
Normally,overtheWeb,theclientstaysconnectedwithaserverforonlyaslong
asittakestoretrieveasingledocument.Withserver-pushdocuments,the
connectionremainsopenandtheservercontinuestosenddatatotheclient
periodically,addingtoorreplacingthepreviouscontents.
Mozilla-basedbrowsers,includingFirefoxandNetscape,currentlyaretheonly
browsersabletohandleHTTPserver-pushdynamicdocumentsnatively.And
becauseserver-pushdocumentsdon'tworkwithoutanHTTPserver,youcan't
developandtestthemunlessyouhaveaserverrunninglocallyaswell.
13.1.1.AnotherWordofCaution
Asalways,wetellyouexactlyhowtousetheseexcitingbutnonstandard
features,andweadmonishyounottousethemunlessyouhaveacompellingand
overridingreasontodoso.Weareparticularlystridentwiththatadmonitionfor
dynamicdocuments,notonlybecausetheyaren'tpartoftheHTMLstandard,but
alsobecausedynamicdocumentscanhogthenetwork.Theyrequirelarger,longer
downloadsthantheirstaticcounterparts,andtheyrequiremanymore(inthe
caseofclient-pull)orlonger-term(forserver-push)client/serverconnections.
Multipleconnectionsonasingleserverarelimitedtoafewofthemillionsofweb
usersatatime.We'dhatetoseeyourreadersmissoutbecauseyou'vecreateda
jigglingimageinadynamicdocumentthatwouldotherwisehavebeenan
effectiveandreadilyaccessiblestaticdocumentthatmorepeoplecouldenjoy.
13.2.Client-PullDocuments
Client-pulldocumentsarerelativelyeasytoprepare,andyoucanrunthem
locallywithoutrequiringanHTTPserver.That'sbecausetheclient-pulldocument
hasthebrowserrequestandloadanotherdocument,eveniffromlocalstorage.
Allyouneedtodoisembeda<meta>tagintotheheaderofyourHTMLorXHTML
document.Thespecialtagtellstheclientbrowsertodisplaythecurrentdocument
foraspecifiedperiodoftimeandthenloadanddisplayanentirelynewone,just
asthoughtheuserhadselectedthenewdocumentfromahyperlink.(Notethat
currentlythereisn'taneasywaytochangejustaportionofadocument
dynamicallyusingclient-pull,thoughyoucoulduseframesifyouwantedasplit-
screeneffect.)[<meta>,6.8.1]
13.2.1.UniquelyRefreshing
Client-pulldynamicdocumentsworkwithallthepopularbrowsersbecausethey
respondtoaspecialHTTPheaderfieldcalledRefresh.
YoumayrecallfrompreviousdiscussionsthatwheneveranHTTPserversendsa
documenttotheclientbrowser,itprecedesthedocument'sdatawithoneormore
headerfields.Oneheaderfield,forinstance,containsadescriptionofthe
document'scontenttype,usedbythebrowsertodecidehowtodisplaythe
document'scontents.Forexample,theserverprecedesHTMLdocumentswiththe
header"Content-type:text/html,"whosemeaningshouldbefairlyobvious.
AswediscussedinChapter6,youcanaddyourownspecialfieldstoanHTML
document'sHTTPheaderbyinsertinga<meta>tagintoits<head>.[<meta>,6.8.1]
TheHTTPRefreshfieldimplementsclient-pulldynamicHTMLdocuments,enabled
bythe<meta>tagformat:
<metahttp-equiv="Refresh"content="fieldvalue">
Thetag'shttp-equivattributetellstheHTTPservertoincludetheRefreshfield,with
avaluespecifiedbythecontentattribute(ifany,carefullyenclosedinquotation
marks),inthestringofheadersitsendstotheclientbrowserjustbeforeitsends
therestofthedocument'scontent.ThebrowserrecognizestheRefreshheaderas
themarkofadynamicHTMLdocumentandrespondsaccordingly,aswediscussin
thenextsection.
13.2.2.TheRefreshHeaderContents
ThevalueofthecontentattributeinthespecialRefresh<meta>tagdetermineswhen
andhowthebrowserupdatesthecurrentdocument.Setittoaninteger,andthe
browserdelaysthatmanysecondsbeforeautomaticallyloadinganother
document.Youmaysetthecontentfieldvalueto0,meaningnodelayatall.In
thatcase,thebrowserloadsthenextdocumentimmediatelyafteritfinishes
renderingthecurrentone,whichallowsyoutoachievesomeverycrude
animationeffects.[<meta>,6.8.1]
13.2.2.1.Refreshingthesamedocument
IftheRefreshfield'scontentvalueisjustthenumberofseconds,thebrowser
reloadsthatsamedocumentoverandoveragain,delayingthespecifiedtime
betweeneachcycle,untiltheusergoestoanotherdocumentorshutsdownthe
browser.
Forexample,thebrowserreloadsthefollowingclient-pulldocumentevery15
seconds:
<html>
<head>
<metahttp-equiv="Refresh"content="15">
<title>KumquatMarketPrices</title>
</head>
<body>
<h3>KumquatMarketPrices</h3>
Kumquatsarecurrentlytradingat$1.96perpound.
</body>
</html>
Thefinancialwizardsamongyoumayhavenoticedthat,withsomespecial
softwaretricksontheserverside,youcanupdatethepriceofkumquatsinthe
documentsothatitactslikeaticker-tapemachine,withthelatestkumquat
commoditypriceupdatedevery15seconds.
13.2.2.2.Refreshingwithadifferentdocument
Insteadofreloadingthesamedocumentrepeatedly,youcantellthebrowserto
loadadifferentdocumentdynamically.Youdosobyaddingthatdocument'sURL
afterthedelaytimeandaninterveningsemicoloninthe<meta>tag'scontent
attribute.Forexample:
<metahttp-equiv="Refresh"
content="15;URL=http://www.kumquat.com/next.html">
causesthebrowsertoretrievethenext.htmldocumentfromthe
www.kumquat.comwebserverafterhavingdisplayedthecurrentdocumentfor15
seconds.
13.2.2.3.Cyclingbetweendocuments
KeepinmindthattheeffectsoftheRefresh<meta>tagapplyonlytothedocument
inwhichitappears.Hence,tocyclebetweenseveraldocuments,youmustinclude
aRefresh<meta>tagineachone.Toachievetheeffect,setthecontentvalueforeach
documentinthecyclewithaURLwhichpointstothenextdocument,andthelast
documentpointingbacktothefirstonetocompletethecycle.
Forexample,thefollowingarethe<meta>tagsfortheheadersofeachinathree-
HTML-documentcycle.
Thefirst.htmldocumentcontains:
<metahttp-equiv="Refresh"
content="30;URL=second.html">
Thesecond.htmldocumentcontains:
<metahttp-equiv="Refresh"
content="30;URL=third.html">
Andthethird.htmldocumenthasinits<head>(besidesothercrazyideas):
<metahttp-equiv="Refresh"
content="30;URL=first.html">
Ifitisleftalone,thebrowserendlesslyloopsbetweenthethreedocumentsat30-
secondintervals.
Cyclingdocumentsmakeexcellentattractors,catchingtheattentionofpassers-by
toaweb-drivenkiosk,forexample.Userscannavigatethroughthewider
collectionofkioskdocumentsbyclickinghyperlinksinoneofthekiosk'sattractor
pagesandthenbyclickingsubsequentones.[*]
[*]Thisbringsupagoodpoint:theusermayoverridetheRefreshdynamicactionatanytime(forinstance,byclicking
ahyperlinkbeforetheclient-pulltimeoutexpires).ThebrowseralwaysignorestheRefreshactioninlieuofuser
interaction.
Tocompletethecycle,documentsselectedfromanattractorpagealsoshould
havetheirownRefreshfieldsthatpointbacktotheoriginatingattractordocument
inthecyclingsetofattractors.Youshouldspecifyafairlylongdelayperiodforthe
nonattractorpages120to300secondsormoresothatthekioskdoesn't
automaticallyresetwhileauserisreadingthecurrentdocument.However,the
delayperiodshouldbeshortenoughsothatthekioskresetstotheattractor
modeinareasonableperiodoftimeaftertheuserfinishes.
13.2.3.PullingNon-HTMLContent
Theclient-pullfeatureisnotrestrictedtoHTMLdocuments,althoughitis
certainlyeasiesttocreatedynamicdocumentswithHTML.Withabitofserver-
sideprogramming,youcanaddaRefreshfieldtotheHTTPheaderofanysortof
document,fromaudiofilestoimagestovideoclips.
Forexample,createareal-timevideofeedbyaddingaRefreshheaderfieldineach
ofasequenceofimagesgrabbedanddigitizedfromacamera.Includeadelayof0
withtheURLthatpointstothenextimagesothatasquicklyasthebrowser
displaysoneimage,itretrievesthenext.Assumingthatthenetworkkeepsup,
theresultisacrude(reallycrude)TV.
Becausethebrowserclearsthewindowbeforepresentingeachsubsequentimage,
theresultingflickerandflashmakeitalmostimpossibletopresentacoherent
sequenceofimages.Thistechniqueismoreeffectivewhenpresentingaseriesof
imagesdesignedtobeviewedasaslideshow,wheretheuserexpectssomesort
ofdisplayactivitybetweeneachimage.
Perhapsabetteruseoftheclient-pullfeatureiswithlong-playingmultimedia
documents,whichthepopularbrowsersusespecialhelperapplicationstodisplay.
Onamultitaskingcomputer,suchasonerunningLinuxorWindows,thebrowser
downloadsonedocument,whileahelperapplicationplaysanother.Combinethe
client-pullcapabilitieswiththatmultitaskingtoimprovemultimediadocument
performance.Insteadofwaitingforasingle,largedocumentsuchasamovieor
audiofiletodownloadbeforeplaying,breakitintosmallersegments,each
automaticallydownloadedbytheprevioussegmentviatheRefreshheader.The
browserplaysthefirstsegmentwhiledownloadingthesecond,thenthird,then
fourth,andsoon.
13.2.4.CombiningRefreshwithOtherHTTPHeaderFields
Youcanhaveyourclient-pulldynamicdocumentsperformsomeneattricksby
combiningtheeffectsoftheRefreshfieldwithotherHTTPheaderfields.One
combinationthatisparticularlyusefulisRefreshwithaRedirectfield.
TheRedirectfieldletstheservertellthebrowsertoretrievetherequested
documentelsewhereatthefield'saccompanyingURLvalue.Theclientbrowser
automaticallyredirectsitsrequesttothenewURLandgetsthedocumentfrom
thenewlocation,usuallywithouttellingtheuser.Weretrieveredirected
documentsallthetimeandmaynevernotice.
ThemostcommoncauseforredirectioniswhensomeonemovesanHTML
documentcollectiontoanewdirectoryortoanewserver.Asacourtesy,the
webmasterprogramstheoriginalhostservertosendanHTTPheaderfield
containingtheRedirectfieldandnewURL(withoutadocumentbody)toanyand
allbrowsersthatrequestthedocumentfromtheoriginallocation.Thatway,the
newdocumentlocationistransparenttousers,andtheywon'thavetoresettheir
browserbookmarks.
Butsometimesyouwanttheuserstoresettheirbookmarkstothenewlocation,
becausetheoldonewon'tberedirectingbrowsersforever(perhapsbecauseit's
beingtakenoutofservice).Onewaytonotifyusersofthenewlocationistohave
theredirectionURLpointtosomeHTMLdocumentotherthanthehomepageof
thenewcollectionthatcontainsamessageaboutthenewlocation.Oncenoted,
usersthentakea"Continue"hyperlinktothenewhomepagelocationandset
theirbookmarksaccordingly.
BycombiningtheRedirectandRefreshfields,youcanmakethatnotificationscreen
automaticallymovetothenewhomepage.IfthebrowserreceivesanHTTP
headerwithbothfields,ithonorsboth;itimmediatelyfetchestheredirectedURL
anddisplaysit,anditsetstherefreshtimerandreplacementURL,ifspecified.
Whenthetimeexpires,thebrowserautomaticallyretrievesthenextURLyournew
homepagelocation.
13.2.4.1.ArandomURLgenerator
AnotherapplicationforthecombinationofRedirectandRefreshHTTPheaderfields
isaperpetual,randomURLgenerator.You'llneedsomeprogrammingskillsto
createaserver-sideapplicationthatselectsarandomURLfromapreparedlist
andoutputsaRedirectfieldthatreferencesthatURLalongwithaRefreshfieldthat
reinvokestherandom-URLapplicationaftersomedelay.
Whenthemodernbrowserreceivesthecompleteheader,itimmediatelyloadsand
displaystherandomlyselecteddocumentspecifiedintheRedirectfield'sURL.After
thedelayspecifiedintheRefreshfield,thebrowserrerunstherandom-URL
generatorontheserver(asspecifiedintherefreshURL),andthecyclestarts
over.TheresultisanendlesscycleofrandomURLsdisplayedatregularintervals.
13.2.5.PerformanceConsiderations
Client-pulldocumentsconsumeextranetworkresources,especiallywhenthe
refreshdelayissmall,becauseeachrefreshmayinvolveanewconnectiontoa
server.Itmaytakeabrowserseveralsecondstocontacttheserverandbegin
retrievingthedocument.Asaresult,rapidupdatesgenerallyarenotfeasible,
especiallyoverslownetworkconnections.
Useclient-pulldynamicdocumentsforlow-frequencyupdatesofentire
documents,orforcyclingamongdocumentswithoutuserintervention.
13.3.Server-PushDocuments
Netscapeinventedserver-pushdynamicdocuments.Withthetechnology,the
client/serverconnectionremainsopenafteraninitialtransferofdata,andthe
serverperiodicallysendsnewdatatotheclient,updatingthedocument'sdisplay.
Server-pushismadepossiblebysomespecialprogrammingontheserverside
andisenabledbythemultipart/mixed-mediatypefeatureofMultipurpose
InternetMailExtensions(MIME),thecomputerindustry'sstandardformultimedia
documenttransmissionovertheInternet.
13.3.1.TheMultipart/MixedMediaType
Aswementionedearlierinthischapterinthediscussionofclient-pulldynamic
documents,theHTTPserversendsatwo-parttransmissiontotheclientbrowser:
aheaderdescribingthedocument,followedbythedocumentitself.The
document'sMIMEtypeispartoftheHTTPheaderfield.Normally,theserver
includes"Content-Type:text/html"inanHTMLdocument'sheaderbeforesending
itsactualcontents.Bychangingthatcontenttypeto"multipart/mixed,"youcan
sendanHTMLdocumentorseveraldocumentsinseveralpieces,ratherthanina
singlechunk.OnlyMozilla-basedbrowsers,suchasNetscapeandFirefox,though,
understandandrespondtothemultipartheaderfield;otherbrowserseither
ignoreadditionalpartsorrefusethedocumentaltogether.
ThegeneralformoftheMIMEmultipart/mixed-mediaContent-Typeheaderlookslike
this:
Content-type:multipart/mixed;boundary="SomeRandomString"
ThisHTTPheadercomponenttellstheMozillaclienttoexpectthedocumentto
followinseveralpartsandtolookforSomeRandomString,whichseparatestheparts.
Thatboundarystringshouldbeuniqueandshouldnotappearanywhere,inanyof
theindividualparts.Thecontentoftheserver-to-clienttransmissionlookslike
this:
SomeRandomString
Content-type:text/plain
Dataforthefirstpart
SomeRandomString
Content-type:text/plain
Dataforthesecondpart
SomeRandomString
Theprecedingexamplehastwodocumentparts,bothcomposedofjustplaintext.
Theserversendseachpart,precededbyourSomeRandomStringdocument-boundary
delimiter(whichitselfisprecededbytwodashes),followedbytheContent-Typefield
andthenthedataforeachpart.Thelasttransmissionfromservertoclientisa
singlereferencetotheboundarystring,followedbytwomoredashesindicating
thatthiswasthelastpartofthedocument.
Uponreceiptofeachpart,theMozillabrowserautomaticallyaddstheincoming
datatothecurrentdocumentdisplay.
YouhavetowriteaspecialHTTPserverapplicationtoenablethistypeofserver-
pushdynamicdocumentonethatcreatesthespecialHTTPMIMEmultipart/mixed
headerandsendsthevariousdocumentsseparatedbytheboundarydelimiter.
13.3.2.TheMultipart/X-Mixed-ReplaceMediaType
Server-pushdynamicdocumentauthorsmayuseanexperimentalvariantofthe
MIMEmultipart/mixedmediatypeknownasmultipart/x-mixed-replacemedia.The
differencebetweenthisspecialcontenttypeanditspredecessoristhat,insteadof
simplyaddingcontenttothecurrentdisplay,the"replace"versionhaseach
subsequentpartreplacetheprecedingone.
Theformatofthemixed-replaceHTTPheaderisverysimilartoits
multipart/mixedcounterpart;theonlydifferenceisintheContent-Type:
multipart/x-mixed-replace;boundary=SomeRandomString
Allotherrulesregardingtheformatofthemultipartcontentarethesame,
includingtheboundarystringusedtoseparatethepartsandtheindividual
Content-Typefieldsforeachpartofthecontent.
13.3.3.ExploitingMultipartDocuments
ItiseasytoseehowyoucanusethetwospecialMIMEmultipartcontenttypesto
createserver-pushdynamicdocuments.Bydelayingthetimebetweenparts,you
mightcreateanautomaticallyscrollingmessageintheMozillabrowserwindow.
Orbyreplacingportionsofthedocumentthroughthex-mixed-replaceMIMEtype,
youmightincludeadynamicbillboardinyourdocument,orperhapseven
animation.
Notethatserver-pushmultipartdocumentsneednotapplyonlytoHTMLorother
plain-textdocuments.Images,too,areaMIME-encodedcontenttype,soyoucan
havetheHTTPservertransmitseveralimagesinsequenceaspartsofamultipart
transmission.Becauseyoumayalsohaveeachnewimagereplacetheprevious
one,theresultiscrudeanimation.Donecorrectly,overanetworkofsufficient
bandwidth,theeffectcanbequitesatisfying.
13.3.3.1.Efficiencyconsiderations
Server-pushdocumentsmaintainaconnectionbetweentheclientandserverfor
thedurationofthedynamicdocument'sactivity.Forsomeservers,thismay
consumeextranetworkresourcesandmayalsorequirethatseveralprocesses
remainactive,servicingtheopenconnection.Makesuretheserver-pushprocess
(and,hence,theclient/serverconnection)expiresuponcompletionoraftersome
idleperiod.Otherwise,someonewillinadvertentlycamponanendlesslycycling
server-pushdocumentandchokeoffotherusers'accesstotheserver.
Beforechoosingtoimplementserver-pushdocuments,makesurethatyour
servercansupporttheaddedprocessingandnetworkingload.Keepinmindthat
manysimultaneousserver-pushdocumentsmaybeactive,multiplyingtheimpact
ontheserverandseriouslyaffectingoverallserverperformance.
13.3.4.CreatingaServer-PushDocument
CreateaspecialapplicationthatrunswiththeHTTPservertoenableserver-push
dynamicdocuments.TheapplicationmustcreatethespecialMIMEContent-Type
headerfieldthatnotifiestheMozillabrowserthatthefollowingdocumentcomes
inseveralpartsaddedtoorreplacingaportionofthecurrentdocument.The
applicationmustcreatetheappropriateboundarydelimiterandsendtheContent-
Typeheaderanddataforeachpart,perhapsalsodelayingtransmissionofeach
partbysomeperiodoftime.Consultyourserver'sdocumentationtolearnhowto
createaserver-sideapplicationthatcanbeinvokedbyaccessingaspecificURLon
theserver.Withsomeservers,thismaybeassimpleasplacingtheapplicationin
acertaindirectoryontheserver.Withothers,youmayhavetobendover
backwardandhowlatthemoononcertaindays.
13.3.4.1.Server-pushexampleapplicationforNCSAandApachehttpd
TheNationalCenterforSupercomputingApplications(NCSA)andApachehttpd
serversrunonmostUnixandLinuxsystems.Administratorsusuallyconfigurethe
serverstorunserver-sideapplicationsstoredinadirectorynamedcgi-bin.
Thefollowingisasimpleshellscriptthatillustrateshowtosendamultipart
documenttoaNetscapeorFirefoxclientviahttpd:[2]
[2]ItisanidiosyncrasyofNCSAhttpdthatnospacesareallowedintheContent-Typefieldthatprecedesyour
multipartdocument.Someauthorsliketoplaceaspaceafterthesemicolonandbeforetheboundarykeyword.Don'tdo
thiswithNCSAhttpd;runthewholeContent-Typetogetherwithoutspacestogettheservertorecognizethe
correctmultipartcontenttype.
#!/bin/sh
#
#Lettheclientknowwearesendingamultipartdocument
#withaboundarystringof"NEXT"
#
echo"HTTP/1.0200"
echo"Content-type:multipart/x-mixed-replace;boundary=NEXT"
echo""
echo"NEXT"
whiletrue
do
#
#Sendthenextpart,followedbyaboundarystring
#Thensleepfivesecondsbeforerepeating
#
echo"Content-type:text/html"
echo""
echo<html>
echo<head>
echo"<title>ProcessesOnThisServer</title>"
echo"</head>"
echo<body>
echo"<h3>ProcessesOnThisServer</h3>"
echo"Date:"
date
echo<p>
echo<pre>
ps-el
echo"</pre>"
echo"</body>"
echo"</html>"
echo"NEXT"
sleep5
done
Inanutshell,thisexamplescriptupdatesalistoftheprocessesrunningonthe
servermachineeveryfiveseconds.Theupdatecontinuesuntilthebrowserbreaks
theconnectionbymovingontoanotherdocument.
Weofferthisshellscriptexampletoillustratethebasiclogicbehindanyserver-
pushdocumentgenerator.Inreality,youshouldtrytocreateyourserver-side
applicationsusingamoreconventionalprogramminglanguage,suchasPerlorC.
Theseapplicationswillrunmoreefficientlyandcanbetterdetectwhentheclient
hasseveredtheconnectiontotheserver.
Chapter14.MobileDevices
Justnow,asmostwebdevelopershavebecomeveryproficientatdeveloping
engagingcontentforthepopularPC-basedbrowsers,theyarebeingconfronted
withthechallengeofprovidingequallyelegantpagesforthoseubiquitous,tiny
mobiledevices.Butmobileweb-enableddeviceswerenotanticipatedbackinthe
early1990swhenHTMLwasfirstdefinedandrefined,andthecurrentstandards
don'thelpmuch,either.Inthischapter,welookatthebroadrangeofmobileweb-
enableddevices,thechallengetheypresenttowebdesigners,andasubsetof
XHTMLthataddressesthosedevices.Wealsooffersomesuggestionsandlotsof
sympathyforcreatingeffectivecontentthatworksacrossmanyofthesedevices.
14.1.TheMobileWeb
WiththeWorldWideWebnowfirmlyentrenchedasapartofnormalmodernlife,
itisonlynaturalthatuserswanttoaccesswebcontentwherevertheymaybe,at
anytime.Respondingtothisdemand,vendorsnowofferanincrediblearrayof
devicesandaccessmethodstomeetthatneed.Althoughthetypesofdevices
numberinthehundreds,theoverallmarketcanbeexaminedasafewkey
productcategories.
14.1.1.Devices
Mostoftoday'smobiledevicesmobilephonesandpersonaldigitalassistants
(PDAs)havedigitaldisplays,typicallyanLCD,andonboardprocessing.Sowhynot
abuilt-inbrowser?
14.1.1.1.Mobilephones
Thebrowsersoftwareresidesinthecellphone'scoreoperatingsystemandthe
endusercannoteasilyupgradeorextendit.And,aswediscussinmoredetail
shortly,ithasfarfewerfeaturesthanarenormallyassociatedwithatypical
desktopbrowser.Otherfeaturesareavailableonlytothepersistentuserwillingto
endurehorrificallybaduserinterfacestoreachthem.
ThecellphoneprovidergivesyouaccesstotheInternetbyanyoneofseveral
differenttechnologies,andsomerestricttheavailablecontent,ormakeitdifficult
toaccesscontentoutsideoftheirproprietarywebportal.
14.1.1.2.PDAs
PDAsarguablyprovidethebestmobilewebexperience.ThePDAmarketplaceis
dominatedbydevicesrunningthePalmOSoperatingsystemfromPalmSource,
Inc.(originallyPalmComputing,Inc.)andthoserunningtheWindowsMobile
operatingsystemfromMicrosoft.Regardlessofvendor,thesedevicesprovidea
high-qualitybrowserthatmayincludemanyofthefeaturesyouwouldnormally
findinadesktopbrowser.Theendusercanupgradeorextendthebrowserwith
relativeease.Othernetworkapplications,suchasemailandFTP,maybe
availableaswell.
PDAstypicallyrelyontheInstituteofElectricalandElectronicsEngineers(IEEE)
standard802.11,commonlyknownasWiFi(pronounced"whyfie"),forwireless
Ethernet-basedconnectivitywithanetworkand,ultimately,theInternet.Some
PDAsuseBluetooth,analternativewirelesstechnology,toconnectwithanother
networkdevice,suchasamobilephone,laptopcomputer,orBluetoothnetwork
accesspoint,inordertoultimatelyconnectwiththeWeb.
14.1.1.3.Convergencedevices
Convergencedevicesattempttomarrytheconvenienceofamobilephonewith
theflexibilityandpowerofaPDA.Theyusecellularnetworkconnectivity,but
mayalsooffer802.11networking,aswell.Theycanrunmostapplications
availabletoPDAusersandprovidesomeintegrationbetweenthePDAexperience
andconventionaltelephonyfeatures.Convergenceproductsarecurrentlyoffered
byPalmSource(runningPalmOSandWindowsMobile)andvariouscellularphone
manufacturers(runningWindowsMobile).Convergencedevicesofferdistinct
compromisesbetweenthePDAexperience,withitslargerscreenandcomputing
power,andmobilephones,withtheirsmallformfactorandeaseofuse.
14.1.2.CellularAccess
Inadditiontothedevicetype,userscanchoosefromanumberofaccessplans
thatallowtheirmobiledevicetoconnectwiththeInternet.Aswithmobile
devices,hundredsofaccessplansareavailable,buttheycangenerallybe
categorizedintoafewcommongroups.
14.1.2.1.Lowspeed
Oftenknownasfirst-orsecond-generationdataaccess,low-speedcellularaccess
operatesatratessimilartothatofa56-kilobauddial-upmodem.Providers
typicallychargebythebyte(!),withpackagesofferingblocksofbytesona
monthlybasis.Becauseofitsspeedandrelativelyhighcost,low-speedaccessis
intendedforintermittent,sparseuseforspecificsmall-volumetasks.Continuous
accessusingtheseplansisnotfeasible,bothfromthecostperspectiveandfrom
itsarduouslyslowdatarate.Thiskindoflow-speedaccessisavailableexclusively
onmobilephonesandsomeconvergencedevicesfrommanydifferentvendors.
14.1.2.2.High-speedcellularaccess
Recentadvancesincellulartechnologyhaveenabledcarrierstoofferhigh-speed
cellularaccesswithspeedsrangingupto1.5megabitspersecond.Atthese
speeds,userscanenjoyahigh-qualitywebexperiencethatincludesvideoand
audiocontent.Recognizingthemarketpotential,mostcarriersofferhigh-speed
accessinasingle-price,unlimited-usageplan.Marketedunderavarietyof
monikers(suchasEDGEandEVDO,amongothers),thiskindofconnectivitywas
originallydeployedinmobilephones,butisfastshowingupinPDAs,convergence
devices,andsomelaptopcomputers.
14.1.2.3.WiFi
Manyweb-enabledPDAsandsomeconvergencedevicesinclude802.11wireless
networkingand,consequently,canconnectwithcompatiblewirelessLANaccess
pointsthathavebecomeubiquitousinthelastfewyears.Wholecitiesand
campusesnowprovidepervasivewirelessandconsequentmobileaccesstothe
Internet.Whilemostdevicesofferthe"b"versionofthetechnology(802.11b),
whichoperatesatamaximumof11megabitspersecond,somenewerdevices
includethe"g"version,whichprovidesforratesupto54megabitspersecond.
Accesscostsrangefromfree(homenetworks,employernetworks,andpublic
accesspoints)totensofdollarspermonthforindependentsuppliers,suchas
CingularandT-Mobile.
Basedonthisdeviceandaccesstaxonomy,themobilewebcontentdesignerhas
ninepotentialuserenvironmentstoconsider.Unfortunately,itgetsmuchworse
becauseeachspecificdeviceandaccessplanmayhaveitsownrestrictionsand
idiosyncrasies.Aswe'llseeinthenextsection,dozensofvariablescanaffectthe
overallmobilewebuserexperience.
14.2.DeviceConsiderations
Whendesigningcontentformobiledevices,thedeveloperneedstokeepmany
designconstraintsinmind.Ifthedeveloperneglectsanyoneofthem,the
resultingwebpageswillbedifficultifnotimpossibletouseonthemobileweb.We
suggestthatthesuccessfulmobilewebdesigneralwayskeepbrowser,input,
network,anddisplayconstraintsinmindtokeepfromgettinginabind.[*]
[*]Theastutereaderwillnotethat"browser,input,network,anddisplay"fromthecleverandhelpfulacronymBIND.
14.2.1.BrowserConstraints
Browservariationspresentthebiggestchallengetothemobilewebcontent
designer.Limitedbythehostdevice,mobilebrowserscannotsupportthefull
rangeoftagsavailableinaconventionaldesktopbrowser.Forthosetagsthatare
supported,implementationisnotconsistentacrossarangeofmobiledevices.Asa
result,designersneedtocarefullyconsiderwhichtagstheywilluseintheir
contentandoftenhavetosacrificemorecomplicatedpagedesignsinfavorof
simplerpagesthatdisplaycorrectlyonalargernumberofdevices.
Beyondtagavailability,mobilebrowsersmayormaynotsupportscripting,
stylesheets,frames,embeddedobjects,layers,cookies,andothersupport
structureswithinthepagecontent.Evenwidelysupported<meta>tags,suchas
refreshtags,maynotbesupported.Ingeneral,cautiousdesignerswillavoidany
oftheseelementsintheircontent.Whiletheresultingcontentwillcertainlybe
simpler,itisguaranteedtobeviewableonmanydevices.Unlikedesktopbrowsers
thattrytomuddlethroughwhenpresentedwithunsupportedtags,manymobile
browsersjustgiveupwhenconfrontedwithcomplexcontent.Morethananything
else,mobilewebdesignersdonotwantattemptstoaccesstheircontenttoresult
ina"pagenotviewable"errorwithinthebrowser.
Evenwhenthecontentstickstothe"safe"tags,asdescribedlaterinthischapter,
theresultsareunpredictableamongdifferentbrowsers.Therearenostandard
fonts,andsomemobilebrowsersofferonlyonefont,inonesize,withoutboldor
italicembellishment.Mostdevicesallowtheusertoselectdifferentfontsizesfor
thedevicetoaccommodateagingeyesandsmalldisplays;thesesizedifferences
candramaticallyaffecttherenderingofcontentonthedevice'ssmallscreen.
Somemobilebrowserscannothandleanysortofimagesintheirpages,although
thisisbecominglessofaprobleminmorerecentmobiledevices.Almostall
mobilebrowsershaveadifficulttimewithlargeimagesandmayignoreoralter
suchimagesastheyseefit.Thereisnocleardefinitionofwhatconstitutesa
"large"image;itisintheeyeofthebrowserandmaybedeterminedbyboth
imagedimensionsandoverallsize.Formattingandwrappingoftextwithimages
isinconsistent,andmobilebrowsersoftenignoreimagealignmentattributes
altogether.Needlesstosay,thecurrentgenerationofdevicescannothandleany
sortofembeddedvideo,flash,oranimatedcontentinanyform.
14.2.2.InputConstraints
Cellularphoneslackthesinglemostconvenientinputdevicethatmakesthe
desktopbrowsersuccessful:amouse.PDAsandconvergencedevicesdonotsuffer
thislimitation,typicallyallowingtheusertotaponthescreenwithastylus,but
themajorityofyourtargetaudienceformobilecontentisusingacellularphone.
Consequently,generalpagenavigationisachoreonmobiledevices.Movingthe
focuswithinapagetoselectalinkcanbetediousatbest,especiallywhenthere
areseverallinkstonavigateamong.
Enteringtextonacellularphoneistiresome,too.Mostphonesoffertwotext
entrymodes:amultitapmodewherepressingakeycyclesthroughtheletterson
thatkey,andapredictivemodewheretheuseraddslettersuntilthephonefinds
thedesiredwordbasedontheletterpattern.Theformeristediousbutultimately
moreaccurate;thelattermaybequicker,butusuallyfailsbecausetypingURLsis
themostcommonmobilewebactivityanddoesnotfollowtypicalspelling
patterns.
Forbothmodes,typingpunctuationisdifficultbecausefewercommonpunctuation
symbolsareoftenavailablethroughasinglekey,whichcyclesthroughadozenor
moresymbols.
14.2.3.NetworkConstraints
Mostmobilecontentdesignersarekeenlyawareoftheconstraintsimposedbythe
slownetworkingspeedsofmostmobiledevices.Whatmanyfailtoappreciate,
however,ishowmuchusershavetopayforeachbyteofmobilewebcontent.
Ironically,today'smobilewebdesignersneedtoreturntoa1995-eradesign
mindset,whenadvanceddial-upspeedswerereachingjust56kilobitspersecond
andconnectiontimesweremeteredbytheInternetserviceprovider(ISP).Isyour
contentsovaluablethatusersarewillingtopayeverytimetheywanttoview
yourpages?
Beyondbandwidthconcerns,mobiledeviceusersoftenoperatewithinodd,
carrier-imposedlimitationsthatnetworkPCuserswouldnevertolerate.Some
URLsmaybeblockedbycertaincarriers,andothersmaybepassedthroughproxy
serversthatalterortranslatecontentforthemobiledevice.Itisdifficultto
predicthowaparticularcarrierwilltreataparticularpage.Thebestdefensive
strategyistokeepyourcontentassimpleaspossibletoavoidoddtranslationand
conversionofyourpages.
Finally,networkconnectivityisnotconstantwhileviewingcontentonamobile
device.Usersmayreachyoursite,viewapageortwo,andsuddenlylosetheir
connectionastheypassintoadeadzoneintheircoverage.Contentthatrequires
lotsofnavigationamongpagescanbefrustratinginmarginalcoverageareas.
14.2.4.DisplayConstraints
Thereisnodenyingoneattributeofallmobiledevices:thedisplayissmall,even
tiny.Evenconvergencedevicedisplays,whichmanufacturersboasttobethe
largestwithinthemobilephonemarket,areminisculewhencomparedtoa
conventionaldesktopbrowser.Mostdevicesprovideverticalscrolling,allowing
contenttoflowbeyondthebottomofthedisplay,butveryfewsupporthorizontal
scrolling.Asaresult,contentmustbeconsciouslydesignedtoworkinasmall
displaywithtightlyboundedhorizontalspaceandalimitedamountofvertical
space.
Tomakemattersworse,theactualdisplaydimensionsaredifferentforalmost
everydevicethatreachesthemarket.Unlikedesktops,wheredesignerstypically
assume800x600or1024x768displays,thedimensionsofamobiledevicecan
rangefrom128x128onsomecellularphonesto320x480andhigheronsome
PDAs.Cellphonesoftensportodddisplaysizes,suchas176x220or122x96.In
general,youcannotmakeanyassumptionsaboutdisplaysizenorshouldyou
targetaspecificsizewithyourcontent.Thisisgooddesignadviceforanyweb
pageinanyenvironment!
14.3.XHTMLBasic
Recognizingtheinherentlimitationsinmobilebrowsing,andseekingtopromotea
standardcontentmodelforthosedevices,theWorldWideWebConsortium(W3C)
hasdefinedareducedversionofXHTMLthatcaterstothesedevices.Knownas
XHTMLBasic,thisversionofXHTMLdefinesastandardsetoftagsthatare
sufficientforcreatingeffectivecontentformobiledevices,yetaresimpleenough
toensurethattheywillbeconsistentlyadoptedacrossawiderangeofmobile
browsers.
Beforewarned:justbecauseastandardsupportsmobiledevicesdoesn'tmean
thatabrowserwill.Oftenhardwarelimitationspreventimplementation.
14.3.1.SupportedTags
XHTMLBasicisbestaddressedasseveralgroupsoftagsthattogetherdefinea
minimalbutusefulversionofXHTML.
14.3.1.1.Basiccontent
XHTMLBasicwouldn'tworkifitdidn'tsupportthefourcoretagsthatdefineany
document:<html>,<head>,<title>,and<body>.Youshouldneverwriteadocument
withoutthesetags,ofcourse,andyoushouldusethemtodelimityourdocument
accordingly.
Morecomplicateddocumentstructureisnotsupported.XHTMLBasicspecifically
excludesframesandlayersfrommobilewebdevices.
Withinthedocumentbody,XHTMLBasicsupportsacoresetoftext-structural
tags,includingthesixheadingtags(<h1>tHRough<h6>),<br>,<p>,<pre>,and
<blockquote>.Thesearesufficienttocreateflowsoftextthatareorganizedinto
paragraphsandblocksoftextandareidentifiedbyheadingsatvariouslevels,
whichmakesforareadabledocumentinanybrowser.
Withinatextflow,XHTMLBasicalsosupportsallofthecontent-basedstyletags,
including<abbr>,<acronym>,<address>,<cite>,<code>,<dfn>,<em>,<kbd>,<q>,<samp>,
<strong>,and<var>.Butgiventhepaucityoffontsonmostmobiledevices,
especiallymobilephones,amobilebrowsermaybehard-pressedtoevenhave
morethanonewaytorepresentallthesetags.Thiswarningalsoappliestothe
headingtags,asitishighlyunlikelythatmostmobilephonescanoffersixfont
sizestodistinguishthesixheadingtags.
DevicefontlimitationsalsoforcetheXHTMLBasicstandardtoruleoutthe
physicalstyletags,suchasboldanditalictext.Withnoguaranteethatthose
styleswillbeavailable,itwouldbemisleadingtosupporttheequivalenttags.
Bidirectionaltextalsoisnotsupported;manymobiledeviceshaveahardenough
timerenderingconventionaltextflows.
XHTMLBasichasastrongfocusonusingstylesheetstomanagethepresentation
ofyourmobilecontent,butnotwithinthecontextofthepageitself:the<style>
tagitselfisnotsupported.Instead,XHTMLBasicdeferstoexternalstylesheets
and,tosupportthem,includesthe<div>and<span>tagssothatyoucandelimit
yourcontentandapplystylestoitasneeded.Usetheclassattributetoassociate
astylewiththattext.
Ofcourse,XHTMLBasicalsosupportsthe<a>tagsothatyoucanlinkyourpages
tootherdocuments.
14.3.1.2.Images,objects,andscripting
Althoughyoushoulduseitveryjudiciously,XHTMLBasicdoesincludethe<img>
tag.Youshouldneverdropimagesintoyourdocumentswithoutdue
consideration,andevenmoresoformobilebrowsing,becausetheycan
dramaticallyaffectthetimeneededtodownloadadocumentandevenmaybreak
certainbrowsersiftheyaretoolarge.Weoffermoreadviceonusingimages
effectivelyinyourdocumentslaterinthischapter.
XHTMLBasicalsosupportsmoregeneralobjectembeddinginmobilecontentwith
the<object>and<param>tags.Whiletheintentisnoble,thesetagspavetheroadto
heckformobilebrowsing.Supportishighlybrowseranddevicespecific,andthe
mobilemarketisnotyetmatureenoughtoletauthorsassumebroadsupportfor
anysortofembeddedcontentbeyondsimpleimages.Nonetheless,ifyouareable
totargetyourcontenttoaspecificdevicethatprovidesappropriatesupport,these
tagsarehereforyouruse.
XHTMLBasicdoesnotsupportscriptingoreventhandling.Noneoftheevent-
handlingattributesissupported,norarethe<script>and<noscript>tags.Giventhe
limitedmemoryandcomputingpowerofthetypicalmobiledevice,thisisnot
unreasonable.Highlydynamic,script-drivenpagesarebetterlefttoafulldesktop
browser.
14.3.1.3.Lists
Inordertoprovideadditionalstructuretoyourcontent,XHTMLBasicsupports
ordered(<ol>),unordered(<ul>),anddefinition(<dfn>)listsandtheirsupporting
<li>,<dl>,<dd>,and<dt>tags.Theselistscanreallyhelptoorganizeandstructure
yourcontent,especiallynavigationpagesthatoffermultiplelinkstotheuser.
Inparticular,couplinganumberedlistoflinkswiththeaccesskeyattributeintheir
associated<a>tagsmakesitveryeasyforacellphone-basedbrowseruserto
navigateyourpageswithasinglepressofakey.
14.3.1.4.Forms
Interactivityisanotherfeaturecriticaltowebbrowsing,soXHTMLBasicprovides
supportforforms,includingthebasicstructureandinputelements<form>,<input>,
<label>,<select>,<option>,and<textarea>tags.TheXHTMLBasicspecificationdoes
notrestrictthekindsofformelementsthatyoumightuse,butkeepinmindthat
somemobiledevicesmaynotsupportextremelylargechoiceitemsormenus.
TheonlyformelementsspecificallyprohibitedbytheXHTMLBasicstandardare
fileandimageuploadingelements.Ironically,thesewouldbeattractivebrowser
optionsforallthosecellphonesthatsportbuilt-incamerasbyallowingusersto
uploadpicturestoawebserver.
14.3.1.5.Tables
Webdesignerscommonlyusetablestostructurecontentdisplay.Whileyoumay
achievesimilareffectsforthemobilebrowser,bejudicious.Althoughnotexplicitly
stated,theXHTMLstandardbearersfrownonthepracticeandwantyoutouse
tablesfortablesofinformation,notlayout.
XHTMLBasicsupportsonlythecoretabletags:<table>,<tr>,<td>,<th>,and
<caption>.Fancierthings,suchasspanningcolumnsandevennestedtables,are
specificallynotsupportedbytheXHTMLBasicstandard.Complextablesmaynot
berenderedcorrectly,andthenarrowdisplaysizecaneasilydisruptyour
intendedtablepresentation.Subtletableeffects,suchasvaryingcellmarginsand
rulewidths,willalmostcertainlybehandledinconsistentlybetweenmobile
browsersandarebestavoidedtoensurebroadcompatibilityofyourcontent.
14.3.1.6.Documentheader
XHTMLBasicsupportsafewofthecommontagsfoundinthedocument<head>;
specifically,the<meta>,<link>,and<base>tags.Theprimaryintentofthe<link>and
<base>tagsistoallowyoutolinktoyourstylesheetsfromwithinyourmobile
documents.Besomewhatcautiouswiththe<meta>tag,though:themobile
browsersdonotsupportallvariationsofitsattributes.
14.3.2.DesignVersusIntent
WhiletheXHTMLBasicstandarddefinesaspecificsetoftagsthatshouldworkon
anycompliantmobilebrowser,donotbemisledintothinkingthatyoucanpush
theelementsofXHTMLBasictothelimitindesigningyourcontent.Themobile
devicemarketistooyoungandthebrowserstooimmaturetoprovideconsistent
supportforeverypossibletagvariationwithinXHTMLBasic.More,ahem,mature
designersmaythinkbacktowhentheyweredesigningpagesinthemid-90s,
whencreatingcontentthatworkedacrossNetscapeNavigatorandearlyversions
ofInternetExplorerwaschallengingatbestandmorelikelyinfuriating.Both
browsersattemptedtoimplementtheearlyHTMLstandards,butthereweretoo
manyvariationsintheproductstomakeanyone'slifeeasy.
Theintentofthemobile-webstandardistocreateasmallsetoftagsthatwork
reasonablywellacrossawiderangeofdevices,fromphonestoPDAstoset-top
boxesandotherdevices.TheW3Cevenlistsappliancessuchassmart
refrigeratorsandwashingmachinesaspotentialtargetsforhumaninteractions
throughwebpages.Gooddesignerswillstaywithintheintentofthedesign,using
thetagsinareasonablemannerandavoidingtricksandclevercodingto
implementaparticularpage.Theresultingcontentwillworkwellonlotsof
devices,andthedesignerswillbecalmerandhappierpeople.
14.4.EffectiveMobileWebDesign
Thereisnosecrettocreatingeffectivemobilecontent.Infact,theadvicewe've
beengivingthroughoutthisbookappliestomobiledevicesjustlikeitdoesfor
theirlargerdesktopcousins:knowyouraudience,knowtheirneeds,andknow
theirbrowsingenvironment.Withthatsaid,themobilebrowsingexperienceis
differentenoughfromthedesktopthatwe'dberemissifwedidnotoffersome
specifichintstomakeyourwebcontentlookandactgreat.
Withthepopularityofmobilewebaccessmushrooming,thereisanabundanceof
mobilewebdesignadvice,goodandbad.Inthefollowingsections,we'llofferup
ourfavoritebitsofguidance,baseduponpersonalexperienceandmanyvisitsto
manybadmobilesites.
14.4.1.UnderstandYourUser
Peopleturntoamobilebrowserfordifferentreasonsthanwhentheyaccessthe
Webfromthedesktoporlaptop.Mostusersarenotseekinganextendedperusal
ofsomedeep,thought-provokingdissertation,noraretheylookingtoapplyfor
theirnexthomemortgage.Instead,theymostoftenneedsmallbitsofdata
deliveredquickly:newsheadlines,weatherinformation,flightinformation,sports
scores,andthelike.Browsershavebecometheinterfacetomanyother
networkeddevices,too,soamobilebrowsercanhavecommercialandindustrial
applications.Theywon'tbelookingtodownloadlargepicturesorafeature-length
movie.Theymaywanttoreceivedrivingdirections,toobtainapricecheck,to
buyticketstoamovieinarealtheater,toadjusttheoperatingparametersofa
smartmachine,to....
Keepthisinmindwhendesigningyourcontent.Whatareyoumakingavailableto
yourusers?Whywouldtheywanttoviewitinamobilebrowser?Isyourcontent
sousefulthatuserswillwanttoseeitontherun,intheirhand,whiletheydo
otherthings?Don'ttrytoshoehornyoursiteintoamobileformatjusttosayyou
didit.Selectanddelivercontentthatmatterstopeoplewhentheyareinamobile
setting.Inalmostallcases,judiciouseditingisthefirststeptocreatingan
effectivemobileexperience.
Onceyouhavedeterminedwhowillseeanduseyourcontentintheirmobile
browser,thinkabouttheirenvironmentduringthebrowsingsession.Mostlikely,
theywillbedistractedwhileviewingyoursite;manywillbedriving,inameeting,
ortalkingwithothers.Yourcontentneedstopunchthroughthedistraction,
quicklydelivertheneededdata,andgetoutoftheway.Itneedstobeeasily
understood,readilynavigated,andquicklyaccessed.Bandwidthrestrictionswill
mostlikelymakeyourcontentarriveslowly;don'tmakethingsworsebymaking
usersworktogetwhattheywant.Fastandmobilearethecatchwords.
14.4.2.LinksandNavigation
Exceptforoverlylargepages,poorlydesignedcontentnavigationmodelsarethe
worstaspectofmostmobilewebpages.Manypagesofferusefulcontent,butthey
makeitsodifficulttonavigatethatmostusersgiveupandsurfelsewhere.It
seemsthatmanydesigners,havingbuiltcomplexnavigationstructuresfora
conventionaldesktopbrowser,feelcompelledtoreusethatsamestructureina
tiny,littlemobilebrowser.Italsoseemsapparentthatthesedesignersnever
actuallytrytousetheircontentinamobileenvironment.Iftheydid,surelythey
wouldmakethingssimplerandmoreaccessible.
Movingaroundwithinapageonamobilebrowserismuchmoredifficultthanina
desktopbrowser.Scrollingisapaininamobilebrowser,requiringmanyclicksof
tinybuttons.Shiftingfocusfromlinktolinkissimilarlytedious,oftenrequiring
useofslightlydifferenttinybuttons.Bekindtoyourusers:designyourpage
navigationtoavoidscrollingandfocusmovementwhereverpossible.Ifyou
requiretraditional"home,""next,"and"previous"linksinyourpages,putthemat
theverytop,whereuserscanseethemandaccessthemimmediately.Don'tforce
userstoscrollthroughtheentirepagetofindyournavigationelementsatthe
verybottom.Usejustafeweffectivenavigationalelementsthatclearlyindicate
wheretheywillleadtheuser.
Somebrowserssupporttheaccesskeyattribute,allowingyoutoassociateakeyon
thekeypadwithalinkorformelementinyourcontent.Pressingthekeyselects
thelinkorswitchesthefocustoanappropriateformelement.Ifyouarrangeyour
linksasanumberedlistmap,eachwithanaccesskeynumber,userscanquickly
jumptoalinkwithasinglekeypress,insteadoftediouslytappingtogettothe
desiredlink.Forexample:
KumquatResources:
<ol>
<li><aaccesskey="1"href="growers.html">Growers</li>
<li><aaccesskey="2"href="vendors.html">Vendors</li>
<li><aaccesskey="3"href="fanclubs.html">FanClubs</li>
</ol>
enablestheusertopress"1"onthedevicekeypadinordertoaccessthekumquat
growerspage,"2"toseevendors,and"3"tofindafanclub.Enabletheseas
simplehyperlinks,andtheuserhastomakeseveralkeypressestoaccessand
selecttheembeddedlink.Smalldesigndecisionslikethiscanmakeabig
differenceintheoveralluserexperience.
Ingeneral,followingalinkinamobilebrowseriscostly,inbothtimeandmoney.
Clearlyidentifyyourlinkssothattheuserknowswheretheyleadandwhatthey
willprovide.Anonymous"clickhere"linksareannoying.Usersdonotwantto
exploreyoursite;theywanttogettothedesiredcontentquickly.Ifalinkmight
leadtoalargeamountofcontent,suchasanimage,letusersknowinthelinking
pagesothattheycanchoosetoavoidit.
Especiallyavoidimage-basedlinks,exceptwhentheimagesareverysmall.Many
mobilebrowsersallowtheusertonavigatethepageandselectalinkbeforethe
fullpageisloaded.Rememberthatthepagegetsfullydownloadedfromthe
serverbeforegoingbackanddownloadingsupportingfilessuchasimages.
Accordingly,text-basedlinksappearnearlyimmediately,whereasimage-based
onesmaketheuserwait.Inanycase,avoidimage-mapnavigationbecausethe
regionsinthemapmaynotbeeasilyvisibleorselectable,astheywouldina
browserwithamouse.
Resisttheurgetolinktootherwindowswiththetargetattribute.Manymobile
browserscannothandlemultiplewindowsandwillsimplydropthelinkingwindow
content.Userswillbeconfusedandyourcontentwillcertainlynotbepresented
asyouintended.
14.4.3.Forms
Formspresentachallengetothemobilewebdesigner.Tomakethemobile
experienceinteractive,youneedtoincludeformsforuserstoinputrequestsand
parametersandforthemtoreceivecustomizedcontentfromasite.
Unfortunately,mostformsdonottranslatewelltothemobilebrowser,wheretext
inputandfieldselectionisdifficultanderror-prone.Mobileuserscravequick,
customizedinformation.Designyourformstobeeasytouse,andyouruserswill
returnagainandagaintousethem.
Asalways,goodcontentbeginswithgoodeditingandformsarenoexception.
Makesurethatyourformsareshortandtothepoint.Clearlyandsuccinctlylabel
thevariousinputfieldsandelementssothatusersknowimmediatelywhatis
expectedofthem.Wheneverpossible,setdefaultvaluesintheformsothatusers
neednotfumblethrougheveryelementbeforetheycansubmittheform.Thisis
especiallyusefulwhenausermustreturntoaformtocorrectanerror.Forcing
theusertoreenterdataeachtimehevisitstheformisespeciallypunitive.
Textentryisaspecialproblem,especiallywhenenteringpasswordsandother
maskedtext.Notallmobiledeviceshandlemaskedtextinputcleanly,and
enteringamaskedpasswordusingmultitaptextentryisexquisitelypainful.In
somemobilebrowsers,thetextentryisconductedinaseparatepop-upwindow
providedbythebrowser,forcingtheusertogothroughseverallevelsofselection
andacknowledgmenttoplaceasingletextvalueinafield.
Keepitsimple.Formswithmanyinputelementsdonottranslatewelltothesmall
mobilescreen.Asusersscrollthroughtheformtofillitout,theyareunableto
seethepreviouselementsalreadyenteredandcannotseetheitemstocome.
Thisdisorientationmakesithardertogetformsrightinamobilesetting.You
mightconsiderbreakingyourlargeformintomultiplesmallerforms,lettingusers
incrementallyentertheirinformation.Ifyoutakethisapproach,makesureyou
validatedataasyoureceiveit;don'tcollectsixscreensofinformationandthen
forcetheusertoreturntothefirstscreentofixanerror.
14.4.4.LayoutandPresentation
Themobilewebisnottheplaceforfancylayoutandslickcontentpresentation.
ThelimitedtagsinXHTMLBasichelpensurethis,andtheprudentmobile
designerwillnottrytogobeyondthoselimits.Whilethetransitionfromthe
feature-richdesktopbrowsertotheminimalmobileenvironmentcanbedifficult,
designersmustrememberthatthepointofcontentdesignistoinformtheuser,
nottoimpressyourdesignerpeers.
14.4.4.1.Stylesheets
Allisnotlostforthosewantingtocreateattractivemobilecontent.Good
designersusestylesheetstoseparatetheircontentfromitspresentation
attributes.Thisalsomakesiteasiertohaveasinglecontentsourcewhose
appearanceiscontrolledbydifferentstylesheetsdependingontheuserdevice.
Becauseinlinestylesarenotrecommendedorsupportedinthestandardfor
mobilecontent,useexternallinkstoyourmobilecontentstylesheets.For
example:
<linkrel="stylesheet"type="text/css"media="handheld"href="sheet.css">
Inthislink,themediaattributeiskey:itensuresthatthisstylesheetwillbe
appliedwhenyourcontentisviewedonamobiledevice,andwillbeignored
otherwise.You'llwanttokeepyourstylesheetssmallbecausetheycontributeto
thedelayrequiredtoloadyourpagesoveraslowermobileconnection.
Know,too,thatnotallmobilebrowserssupportstylesheets.Forthosethatdo,
connectivityissuesmaypreventthebrowserfromloadingthestylesheet.Testall
yourcontentwithoutanystylesheet,andmakesurethatitpresentswellwithout
styles.
14.4.4.2.Textfonts
Fontspresentaparticularproblemtomobilecontentdesigners.Unlikedesktop
browserswithaccesstohundredsoffontsinmanyvariations,mobilebrowsers
oftenhavejustoneavailable.Itmaycomeinonlyoneortwosizes,andmaynot
offeritalicandboldcharacters.Therealityisthatthetinydisplaysonmobile
devicesarenotequippedtoshowcomplexfonts,sothedevicevendorsavoid
thembecausetheywouldbeillegible.
Toworkaroundthesefontrestrictions,useheadertagstoenabledifferentfont
sizes,iftheyareavailable,insteadofrelativeorabsolutefontsizing.Mostmobile
browserstrytomakeadistinctionbetweenthe<h1>,<h2>,and<h3>tags,souse
themasintendedforpagetitles,sectionheaders,andcontentdelimitersinyour
pages.Keepinmind,too,thatmanymobilebrowsersrepresentallthevarious
emphasistags(bold,italic,emphasis,andthelike)withboldtext.Ifyoutryto
usedifferentemphasistagsinasinglepage,yourusersmayseeonlyonekindof
emphasizedtext.
14.4.4.3.Marginsandspacing
Thenarrowdisplayonmobiledevicesconstrainshowyoulayoutyourpages.
Avoidanysortofmargins;you'lljustbegivingupprecioushorizontalspace.The
sameistruefornestedlists:deepnestingwillcauseyourcontenttocreeptothe
right,forcingyourtextintoasingleriverofwordsdowntherightedgeofthe
display.
Absolutespacingandlayoutcontrolisdifficultonmobiledevices.Common
desktoptricks,suchas1x1imagesandtransparentGIFs,justdon'tworkasyou
wouldexpectonamobiledevice.StandardHTMLelementssuchasframesand
layersaregenerallynotsupported,andlimitedtablesupportmakestable-based
layoutdifficultaswell.Ingeneral,viewthemobiledeviceasasimpleverticalflow
ofcontentandallowthemobilebrowsertoformatyourcontentasbestitcan
withoutyourinterference.
Finally,beawarethatadaptationmayoccurwithyourcontent.Adaptationisthe
automatedconversionofyourcontenttomakeitmoresuitableforamobile
client.Itmayoccurattheserver,whenamobiledeviceisfoundtoberequesting
apage.Itoftenoccurswithinthecarriernetworks,wherepagesarestrippedof
offendingtagsandimagesaredramaticallyreducedtomakethemmore
acceptabletothemobiledevice.Italsooccursimplicitlyinthemobilebrowser,
whereunsupportedtagsandattributesareignoredduringrendering.
Youcannotpreventadaptation.Yourbestbetistoavoiditbycreatingsimple
contentthatwillnotbesubjectedtoadaptationatanylayer.Inshort,thesimpler
thatyourcontentis,themorelikelyitisgoingtoappearasintendedonthe
mobiledevice.
14.4.5.Images
IntheearlydaysoftheWeb,imagesmadelifedifficult.Dial-upconnectionsjust
weren'tabletodeliverlargeimagesinatimelyfashion,leadingtouser
frustrationandunusablepages.Olderwebusersmayrememberthedayswhen
linksoftenhadparentheticalsizesappendedtothem.Whenrunningona28.8
kilobitmodem,selectingalinkfollowedby"(132K)"gaveyoutimetograba
coffeewhiletheimagemadeitswaytoyourbrowser.
Fabulousadvancesincheapbandwidthhavemadeanimage-richwebexperience
thenorm.Designersareusedtousinglargeimagestomaketheirpagesbeautiful.
Unfortunately,thesekindsofdesignsfailonslowmobiledevices,aswellasfast
mobiledeviceswithlimitedmemory.Asaresult,images,especiallylargeimages,
arealuxuryinamobileenvironment.
Thatisn'ttosaythatimagesareforbiddeninyourmobilecontent.Instead,use
imagessparingly.Asmalllogomayworkjustfineinyourpages,andtiny
navigationaliconswillcertainlymakeyourpageseasiertouse.Ifyoumust
deliverlargeimagesdoitwithaseparatelink,withawarningaboutthesizeof
theobjecttheuserwillbeaccessing.Thisway,usersunderstandthecostbefore
theyselectthelink.
Whenyoudodeliverlargeimages,usecommonfileformatssuchasGIF89aand
JPEG.Weknowofnomobilebrowserthatcannothandlethesewell-established
fileformats.Keepinginmindthesmalldisplaysizesofmobiledevices,useimages
thatareclosetothedisplaysize.Inanycase,donotsendanenormousimage
andexpectthebrowsertoscaleittothedisplaysize.Itisdownrightmeanto
senda"gigantic"1024x768imageoveraslowmobileconnection,swampingthe
mobiledevice'smemoryandforcingthedevicetoshrinktheimagetofitits
display.Tofurtherassistthebrowser,alwaysusetheheightandwidthattributesin
the<img>tagtoletthebrowserknowwhattoexpectastheimagetricklesin.
14.4.6.GeneralAdvice
Inclosing,weofferonefinalbitofadvice:lessismore.Themobilewebisnotthe
placetoshowoffyourcutting-edgepage-layoutskillsorfancyimagelibrary.
Instead,itisaboutquickdeliveryofgreatcontentthatmeetsaspecificneedata
specificpointintime.
Tostayfocusedonthisminimalistapproach,consideradoptingtheW3C's
recommendedmobilepagedesignguidelines:
Designallyourpagestoworkwithinadisplaythatis120pixelswide.While
manynewerdevicesarewiderthanthis,targetingthissmallernumberwill
ensurereasonablepresentationonabroadrangeofdevices,oldandnew.
UseGIF89aorJPEGimages.Aswenotedbefore,thisensuresthatyour
imageswillrenderonalmostanymobiledevice.
DonotdeviatefromtheXHTMLBasicdocumenttype.Usingtagsnot
supportedbyXHTMLBasicalmostguaranteesrenderingerrorsonalarge
percentageofmobiledevices.
Usestylesheetstoseparatecontentfrompresentation.XHTMLBasicdefines
thebestwaytointegratestylesheetswithyourmobilecontent.
Keepyourtotalpagesizeunder20kilobytes.Thisincludesthebasepage
content,anyassociatedstylesheets,andallincludedimages.
Byadoptingtheseguidelines,judiciouslyeditingyourcontent,andstructuring
yourpagestobeeasilynavigated,you'llbecreatingremarkablemobilecontent
thatwillhaveyouruserscheering.
Chapter15.XML
HTMLisamaverick.Itonlylooselyfollowstherulesofformalelectronic
document-markupdesignandimplementation.Thelanguagewasbornoutofthe
needtoassembletext,graphics,andotherdigitalcontentandsendthemoverthe
globalInternet.IntheearlydaysoftheWeb'sboom,thedemandforbetter
browsersanddocumentserversdrivenbyhordesofnewuserswithinsatiable
appetitesformoreandcoolerwebpagesleftlittletimeforworryingaboutthings
likestandardsandpractices.
Ofcourse,withoutguidingstandards,HTMLwouldeventuallyhavedevolvedinto
Babel.Thatalmosthappened,duringthebrowserwarsinthemid-tolate1990s.
Chaosisnotanacceptablefoundationforanindustrywhosevalueismeasuredin
thetrillionsofdollars.AlthoughthestandardspeopleattheWorldWideWeb
Consortium(W3C)managedtoreininthemaverickHTMLwithstandardversion
4,itisstilltoowildfortheroyalherdofmarkuplanguages.
TheHTML4.01standardisdefinedusingtheStandardGeneralizedMarkup
Language(SGML).WhilemorethanadequateforformalizingHTML,SGMLisfar
toocomplextouseasageneraltoolforextendingandenhancingHTML.Instead,
theW3ChasdevisedastandardknownastheExtensibleMarkupLanguage,or
XML.BasedonthesimplerfeaturesofSGML,XMLiskinder,gentler,andmore
flexible,wellsuitedtoguidingthebirthandorderlydevelopmentofnewmarkup
languages.WithXML,HTMLisbeingrebornasXHTML.
Inthischapter,wecoverthebasicsofXML,includinghowtoreadit,howtocreate
simpleXMLDocumentTypeDefinitions(DTDs),andthewaysyoumightuseXML
toenhanceyouruseoftheInternet.Inthenextchapter,weexplorethedepthsof
XHTML.
Youdon'thavetounderstandeverythingthereistoknowaboutXMLtowrite
XHTML.Wethinkit'shelpful,butifyouwanttocuttothechase,feelfreetoskip
tothenextchapter.Beforeyoudo,however,youmaywanttotakealookatsome
oftheusesofXMLcoveredattheendofthischapter,startingwithsection15.8.
ThischapterprovidesonlyanoverviewofXML.Ourgoalistowhetyourappetite
andmakeyouconversantinXML.Forfullfluency,consultLearningXMLbyErikT.
RayorXMLinaNutshellbyW.ScottMeansandElliotteRustyHarold,bothfrom
O'Reilly.
15.1.LanguagesandMetalanguages
Alanguageiscomposedofcommonlyacceptedsymbolsthatweassembleina
meaningfulwayinordertoexpressourselvesandtopassalonginformationthat
isintelligibletoothers.Forexample,Englishisalanguagewithrules(grammar)
thatdefinehowtoputitssymbols(words)togethertoformsentences,
paragraphs,and,ultimately,booksliketheoneyouareholding.Ifyouknowthe
wordsandunderstandthegrammar,youcanreadthebook,evenifyoudon't
necessarilyunderstanditscontents.
Animportantdifferencebetweenhumanandcomputer-basedlanguagesisthat
humanlanguagesareself-describing.WeuseEnglishsentencesandparagraphs
todefinehowtocreatecorrectEnglishsentencesandparagraphs.Ourbrainsare
marvelousmachinesthathavenoproblemunderstandingthatyoucanusea
languagetodescribeitself.However,computerlanguagesarenotsorichand
computersarenotsobrightthatyoucouldeasilydefineacomputerlanguage
withitself.Instead,wedefineonelanguageametalanguagethatdefinestherules
andsymbolsforothercomputerlanguages.
Softwaredeveloperscreatethemetalanguagerulesandthendefineoneormore
languagesbasedonthoserules.[*]Themetalanguagealsoguidesdeveloperswho
createtheautomatedagentsthatdisplayorotherwiseprocessthecontentsof
documentsthatuseitslanguage(s).
[*]Theuseofmetalanguageshaslongbeenpopularintheworldofcomputerprogramming.TheCprogramming
language,forinstance,hasasetofrulesandsymbolsdefinedbyoneofseveralmetalanguages,includingyacc.
Developersuseyacctocreatecompilers,whichinturnprocesslanguagesourcefilesintocomputer-intelligible
programs(hence,itsname:YetAnotherCompilerCompiler).yacc'sonlypurposeistohelpdeveloperscreatenew
programminglanguages.
XMListhemetalanguagetheW3Ccreatedandthatdevelopersusetodefine
markuplanguagessuchasXHTML.BrowserdevelopersrelyonXML's
metalanguagerulestocreateautomatedprocessesthatreadthelanguage
definitionofXHTMLandimplementtheprocessesthatultimatelydisplayor
otherwiseprocessXHTMLdocuments.
Whybotherwithamarkupmetalanguage?Because,asthefamiliarproverbgoes,
theW3Cwantstoteachushowtofishsothatwecanfeedourselvesfora
lifetime.WithXML,thereisastandardizedwaytodefinemarkuplanguagesfor
differentneeds,insteadofhavingtorelyuponHTMLextensions.Mathematicians
needawaytoexpressmathematicalnotations,forinstance;composersneeda
waytopresentmusicalscores;businesseswanttheirwebsitestotakesales
ordersfromcustomers;physicianslooktoexchangemedicalrecords;plant
managerswanttoruntheirfactoriesfromweb-baseddocuments.Allofthese
groupsneedanacceptable,resilientwaytoexpressthesedifferentkindsof
informationsothatthesoftwareindustrycandeveloptheprogramsthatprocess
anddisplaythesediversedocuments.
XMLprovidestheanswer.Eachcontentsectorthebusinessgroup,thefactory-
automationconsortium,atradeassociationmaydefineamarkuplanguagethat
suitstheirparticularneedforinformationexchangeandprocessingovertheWeb.
ComputerprogrammersthencreateXML-compliantprocessesparsersthatreadthe
newlanguagedefinitionsandallowtheservertoprocessthedocumentsofthose
languages.
15.1.1.CreationVersusDisplay
Whilethereisnolimittothekindsofmarkuplanguagesthatyoucancreatewith
XML,displayingyourdocumentsmaybemorecomplicated.Forinstance,when
youwriteHTML,abrowserunderstandswhattodowiththe<h1>tagbecauseitis
definedintheHTMLDTD.
WithXML,youcreatetheDTD.[*]Forexample,wouldn'tarecipeDTDbeagreat
waytocaptureandstandardizeallthosekumquatrecipesyou'vebeencollecting
inyourkitchendrawers?Withspecial<ingredient>and<portion>tags,therecipes
areeasytodefineandunderstand.However,browserswon'tknowwhattodowith
thesenewtagsunlessyouattachastylesheetthatdefinestheirhandling.Without
astylesheet,XML-compliantbrowsersrenderthesetagsinaverygeneric
waycertainlynottheflourishingpresentationyourkumquatrecipesdeserve.
[*]AnalternativetoDTDsisXMLSchemas.Schemasofferfeaturesrelatedtodatatypingandaremore
programmaticallyorientedthandocument-oriented.Formoreinformation,checkoutXMLSchemabyEricvanderVlist
(O'Reilly).
Evenwithstylesheets,therearelimitationstopresentingXML-basedinformation.
Let'ssayyouwanttocreatesomethingmorechallenging,suchasaDTDfor
musicalnotationorsiliconchipdesign.WhiledescribingthesedatatypesinaDTD
ispossible,displayingthisinformationgraphicallyiscertainlybeyondthe
capabilitiesofanystylesheetswe'veseenyet;properlydisplayingthistypeof
graphicallyrichinformationwouldrequireaspecializedrenderingtool.
Nonetheless,yourrecipeDTDisagreattoolforcapturingandsharingrecipes.As
we'llseelaterinthischapter,XMLisn'tsimplyaboutcreatingmarkuplanguages
fordisplayingcontentinbrowsers.Ithasgreatpromiseforsharingandmanaging
informationsothatthosepreciouskumquatdisheswillbepreservedformany
generationstocome.Justbearinmindthat,inadditiontowritingaDTDto
describeyournewXML-basedmarkuplanguage,inmostcasesyouwillwantto
supplementtheDTDwithastylesheet.[ ]
[ ]Infact,itispossibletowriteXMLdocumentsusingonlyastylesheet.DTDsarehighlyrecommendedbutoptional.
Seehttp://www.w3c.org/TR/xml-stylesheetfordetails.
15.1.2.ALittleHistory
Tocompleteyoureducationintothewhysandwhereforesofmarkuplanguages,it
helpstoknowhowallthesemarkuplanguagescametobe.
Inthebeginning,therewasSGML.SGMLwasintendedtobetheonly
metalanguagefromwhichallmarkuplanguageswouldderive.WithSGML,you
candefineeverythingfromhieroglyphicstoHTML,negatingtheneedforany
othermetalanguage.
TheproblemwithSGMListhatitissobroadandall-encompassingthatmere
mortalscannotuseit.UsingSGMLeffectivelyrequiresveryexpensiveand
complextoolsthatarecompletelybeyondthescopeofregularpeoplewhojust
wanttobangoutanHTMLdocumentintheirsparetime.Asaresult,developers
createdothermarkuplanguagesthataregreatlyreducedinscopeandaremuch
easiertouse.TheHTMLstandardsthemselveswereinitiallydefinedusinga
subsetofSGMLthateliminatedmanyofitsmoreesotericfeatures.TheDTDin
AppendixDusesthissubsetofSGMLtodefinetheHTML4.01standard.
RecognizingthatSGMLwastoounwieldytodescribeHTMLinausefulwayand
thattherewasagrowingneedtodefineotherHTML-likemarkuplanguages,the
W3CdefinedXML.XMLisaformalmarkupmetalanguagethatusesselectfeatures
ofSGMLtodefinemarkuplanguagesinastylesimilartothatofHTML.It
eliminatesmanySGMLelementsthataren'tapplicabletolanguagessuchas
HTML,andsimplifiesotherelementstomakethemeasiertouseandunderstand.
XMLisamiddlegroundbetweenSGMLandHTML,ausefultoolfordefiningawide
varietyofmarkuplanguages.XMLisbecomingincreasinglyimportantastheWeb
extendsbeyondbrowsersandmovesintotherealmofdirectdatainterchange
amongpeople,computers,anddisparatesystems.Asmallnumberofpeoplewind
upcreatingnewmarkuplanguageswithXML,andmanymorepeoplewanttobe
abletounderstandXMLDTDsinordertouseallofthesenewmarkuplanguages.
15.2.DocumentsandDTDs
Tobeperfectlycorrect,wemustexplainthat"XML"hascometomeanmany
subtlydifferentthings.AnXMLdocumentisadocumentcontainingcontentthat
conformstoamarkuplanguagedefinedfromtheXMLstandard.AnXML
DocumentTypeDefinition(XMLDTD)isasetofrulesmoreformallyknownas
entityandelementdeclarationsthatdefineanXMLmarkuplanguage;i.e.,how
thetagsarearrangedinacorrect(valid)XMLdocument.Tomakethingseven
moreconfusing,entityandelementdeclarationsmayappearinanXMLdocument
itself,aswellaswithinanXMLDTD.
AnXMLdocumentcontainscharacterdata,whichconsistsofplaincontentand
markupintheformoftagsandXMLdeclarations.Thus:
<blah>harrumph</blah>
isalineinawell-formedXMLdocument.Well-formedXMLdocumentsfollow
certainrules,suchastherequirementforeverytagtohaveaclosingtag.These
rulesarepresentedinthecontextofXHTMLinChapter16.
TobeconsideredvalidavalidXMLdocumentconformstoaDTDeveryXML
documentmusthaveacorrespondingsetofXMLdeclarationsthatdefinehowthe
tagsandcontentshouldbearrangedwithinit.Thesedeclarationsmaybeincluded
directlyintheXMLdocument,ortheymaybestoredseparatelyinanXMLDTD.If
anXMLDTDexiststhatdefinesthe<blah>tag,ourwell-formedXMLdocumentis
valid,providedyouprefaceitwitha<!DOCTYPE>tagthatexplainswheretofindthe
appropriateDTD:
<?xmlversion="1.0"?>
<!DOCTYPEblahSYSTEM"blah.dtd">
<blah>harrumph</blah>
Theexampledocumentbeginswiththeoptional<?xml>directivedeclaringthe
versionofXMLituses.Itthenusesthe<!DOCTYPE>directivetoidentifytheDTDthat
someautomatedsystem,suchasabrowser,usestoprocessandperhapsdisplay
thecontentsofthedocument.Inthiscase,aDTDnamedblah.dtdshouldbe
accessibletothebrowser[*]sothatthebrowsercandeterminewhetherthe<blah>
tagisvalidwithinthedocument.
[*]Weusethewordbrowserherebecausethat'swhatmostpeoplewillusetoprocessandviewXMLdocuments.The
XMLspecificationusesthemoregenericphrase"processingapplication"because,insomecases,theXMLdocument
willbeprocessednotbyatraditionalbrowser,butbysomeothertoolthatknowshowtointerpretXMLdocuments.
XMLDTDscontainonlyXMLentityandelementdeclarations.XMLdocuments,on
theotherhand,maycontainbothXMLelementdeclarationsandconventional
contentthatusesthoseelementstocreateadocument.Thisinterminglingof
contentanddeclarationsisperfectlyacceptabletoacomputerprocessinganXML
document,butitcangetconfusingforhumanstryingtolearnaboutXML.Forthis
reason,wefocusourattentioninthischapterontheXMLentityandelement
declarationfeaturesthatyoucanusetodefinenewtagsanddocumenttypes.In
otherwords,weareaddressingonlytheDTDfeaturesofXML;thecontent
featuresmirrortherulesandrequirementsyoualreadyknowanduseinorderto
createHTMLdocuments.
15.3.UnderstandingXMLDTDs
TouseamarkuplanguagedefinedwithXML,youshouldbeabletoreadand
understandtheelementsandentitiesfoundinitsXMLDTD.Butdon'tbeputoff:
whileXMLDTDsareverbose,filledwithobscurepunctuation,anddesigned
primarilyforcomputerconsumption,theyareactuallyeasytounderstandonce
yougetpastallthesyntacticsugar.Remember,yourbrainisbetteratlanguages
thananycomputer.
Aswesaidpreviously,anXMLDTDisacollectionofXMLentityandelement
declarationsandcomments.Entitiesarename/valuepairsthatmaketheDTD
easiertoreadandunderstand,andelementsaretheactualmarkuptagsdefined
bytheDTD,suchasHTML's<p>and<h1>tags.TheDTDalsodescribesthecontent
andgrammarforeachtaginthelanguage.Alongwiththeelementdeclarations,
you'llalsofindattributedeclarationsthatdefinetheattributesauthorsmayuse
withthetagsdefinedbytheelementdeclarations.
Thereisnorequiredorder,althoughthecarefulDTDauthorarrangesdeclarations
insuchawaythathumanscaneasilyfindandunderstandthem,computers
notwithstanding.ThebelovedDTDauthorincludeslotsofcomments,too,that
explainthedeclarationsandhowtheycanbeusedtocreateadocument.
Throughoutthischapter,weuseexamplestakenfromtheXHTML1.0DTD,which
youcanfindinitsentiretyattheW3Cwebsite.Althoughitislengthy,you'llfind
thisDTDtobewellwritten,complete,and,withalittlepractice,easyto
understand.
XMLalsoprovidesforconditionalsectionswithinaDTD,allowinggroupsof
declarationstobeoptionallyincludedorexcludedbytheDTDparser.Thisisuseful
whenaDTDactuallydefinesseveralversionsofamarkuplanguage;thedesired
versioncanbederivedbyincludingorexcludingappropriatesections.TheXHTML
1.0DTD,forexample,definesboththe"regular"versionofHTMLandaversion
thatsupportsframes.Byallowingtheparsertoincludeonlytheappropriate
sectionsoftheDTD,therulesforthe<html>tagcanchangetosupporteithera
<body>tagora<frameset>tag,asneeded.
15.3.1.Comments
ThesyntaxforcommentswithinanXMLDTDisexactlylikethatforHTML
comments:commentsbeginwith<!--andendwith-->.TheXMLprocessorignores
everythingbetweenthesetwoelements.Commentsmaynotbenested.
15.3.2.Entities
Anentityisafancytermforaconstant.Entitiesarecrucialtocreatingmodular,
easilyunderstoodDTDs.Althoughtheymaydifferinmanyways,allentities
associateanamewithastringofcharacters.Whenyouusetheentityname
elsewherewithinaDTD,orinanXMLdocument,languageparsersreplacethe
namewiththecorrespondingcharacters.DrawinganexamplefromHTML,the<
entityisreplacedbythe<characterwhereveritappearsinanHTMLdocument.
Entitiescomeintwoflavors:parsedandunparsed.AnXMLprocessorwillhandle
parsedentitiesandignoreunparsedones.Thevastmajorityofentitiesare
parsed.Anunparsedentityisreservedforusewithinattributelistsofcertain
tags;itisnothingmorethanareplacementstringusedasavalueforatag
attribute.
Youcanfurtherdividethegroupofparsedentitiesintogeneralentitiesand
parameterentities.GeneralentitiesareusedintheXMLdocument,and
parameterentitiesareusedintheXMLDTD.
Youmaynotrealizethatyou'vebeenusinggeneralentitieswithinyourHTML
documentsallalong.They'retheonesthathaveanampersand(&)character
precedingtheirname.Forexample,theentityforthecopyright(©)symbol
(©)isageneralentitydefinedintheHTMLDTD.AppendixFlistsallofthe
othergeneralentitiesyouknowandlove.
Tomakelifeeasier,XMLpredefinesthefivemostcommongeneralentities,which
youcanuseinanyXMLdocument.Whileitisstillpreferredthattheybeexplicitly
definedinanyDTDthatusesthem,thesefiveentitiesarealwaysavailabletoany
XMLauthor:
&&
''
>>
<<
""
You'llfindparameterentitieslitteredthroughoutanywell-writtenDTD,including
theHTMLDTD.Parameterentitieshaveapercentsign(%)precedingtheirnames.
ThepercentsigntellstheXMLprocessortolookuptheentitynameintheDTD's
listofparameterentities,insertthevalueoftheentityintotheDTDinplaceof
theentityreference,andprocessthevalueoftheentityaspartoftheDTD.
Thatlastbitisimportant.Byprocessingthecontentsoftheparameterentityas
partoftheDTD,theXMLprocessorallowsyoutoplaceanyvalidXMLcontentina
parameterentity.ManyparameterentitiescontainlengthyXMLdefinitionsand
mayevencontainotherentitydefinitions.Parameterentitiesaretheworkhorses
oftheXMLDTD;creatingDTDswithoutthemwouldbeextremelydifficult.[*]
[*]CandC++programmersmayrecognizethattheentitymechanisminXMLissimilartothe#definemacro
mechanisminCandC++.TheXMLentitiesprovideonlysimplecharacter-stringsubstitutionanddonotemployC's
moreelaboratemacroparametermechanism.
15.3.3.EntityDeclarations
Let'sdefineanentitywiththe<!ENTITY>taginanXMLDTD.Insidethetag,first
supplytheentitynameandvalue,andthenindicatewhetheritisageneralora
parameterentity:
<!ENTITYnamevalue>
<!ENTITY%namevalue>
Thefirstversioncreatesageneralentity;thesecond,becauseofthepercent
sign,createsaparameterentity.
Forbothentitytypes,thenameissimplyasequenceofcharactersbeginningwith
aletter,colon,orunderscoreandfollowedbyanycombinationofletters,
numbers,periods,hyphens,underscores,orcolons.Theonlyrestrictionisthat
namesmaynotbeginwithasymbolotherthanthecolonorunderscore,orthe
sequence"xml"(eitherupper-orlowercase).
Theentityvalueiseitheracharacterstringwithinquotes(unlikeHTMLmarkup,
youmustusequotesevenifitisastringofcontiguousletters)orareferenceto
anotherdocumentcontainingthevalueoftheentity.Fortheseexternalentity
values,you'llfindeitherthekeywordSYSTEM,followedbytheURLofthedocument
containingtheentityvalue,orthekeywordPUBLIC,followedbytheformalnameof
thedocumentanditsURL.
Afewexampleswillmakethisclear.Hereisasimplegeneralentitydeclaration:
<!ENTITYfruit"kumquatorothersimilarcitrusfruit">
Inthisdeclaration,theentity"&fruit;"withinthedocumentisreplacedwiththe
phrase"kumquatorothersimilarcitrusfruit"whereveritappears.
Similarly,hereisaparameterentitydeclaration:
<!ENTITY%ContentType"CDATA">
Anywherethereference%ContentType;appearsinyourDTD,itisreplacedwiththe
wordCDATA.Thisisthetypicalwaytouseparameterentities:tocreateamore
descriptivetermforagenericparameterthatwillbeusedmanytimesinaDTD.
Hereisanexternalgeneralentitydeclaration:
<!ENTITYboilerplateSYSTEM"http://server.com/boilerplate.txt">
IttellstheXMLprocessortoretrievethecontentsofthefileboilerplate.txtfrom
server.comanduseitasthevalueoftheboilerplateentity.Anywhereyouuse
&boilerplate;inyourdocument,thecontentsofthefileareinsertedaspartofyour
documentcontent.
Hereisanexternalparameterentitydeclaration,liftedfromtheHTMLDTD,which
referencesapublicexternaldocument:
<!ENTITY%HTMLlat1PUBLIC"-//W3C//ENTITIESLatin1forXHTML//EN"
"xhtml-lat1.ent">
ItdefinesanentitynamedHTMLlat1whosecontentsaretobetakenfromthepublic
documentidentifiedas-//W3C//ENTITIESLatin1forXHTML//EN.Iftheprocessor
doesnothaveacopyofthisdocumentavailable,itcanusetheURLxhtml-
lat1.enttofindit.Thisparticularpublicdocumentisactuallyquitelengthy,
containingallofthegeneralentitydeclarationsfortheLatin1character
encodingsforHTML.[*]Accordingly,simplywritingthisintheHTMLDTD:
[*]Youcanenjoythisdocumentforyourselfathttp://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent.
%HTMLlat1;
causesallofthosegeneralentitiestobedefinedaspartofthelanguage.
ADTDauthorcanusethePUBLICandSYSTEMexternalvalueswithgeneraland
parameterentitydeclarations.Youshouldstructureyourexternaldefinitionsto
makeyourDTDsanddocumentseasytoreadandunderstand.
You'llrecallthatwebeganthesectiononentitieswithamentionofunparsed
entitieswhoseonlypurposeistobeusedasvaluestocertainattributes.You
declareanunparsedentitybyappendingthekeywordNDATAtoanexternalgeneral
entitydeclaration,followedbythenameoftheunparsedentity.Ifwewantedto
convertourgeneralboilerplateentitytoanunparsedgeneralentityforuseasan
attributevalue,wecouldsay:
<!ENTITYboilerplateSYSTEM"http://server.com/boilerplate.txt"NDATAtext>
Withthisdeclaration,attributesdefinedastypeENTITY(asdescribedinSection
15.5.1)coulduseboilerplateasoneoftheirvalues.
15.3.4.Elements
Elementsaredefinitionsofthetagsthatyoucanuseindocumentsbasedonyour
XMLmarkuplanguage.Insomeways,elementdeclarationsareeasierthanentity
declarationsbecauseallyouneedtodoisspecifythenameofthetagandwhat
sortofcontentthattagmaycontain:
<!ELEMENTnamecontents>
Thenamefollowsthesamerulesasnamesforentitydefinitions.Thecontentssection
maybeoneoffourtypesdescribedhere:
ThekeywordEMPTYdefinesatagwithnocontent,suchas<hr>and<br>in
HTML.EmptyelementsinXMLgetabitofspecialhandling,asdescribedin
section15.4.5.
ThekeywordANYindicatesthatthetagcanhaveanycontent,without
restrictionorfurtherprocessingbytheXMLprocessor.
Thecontentmaybeasetofgrammarrulesthatdefinestheorderandnesting
oftagswithinthedefinedelement.Youusethiscontenttypewhenthetag
beingdefinedcontainsonlyothertags,withoutconventionalcontentallowed
directlywithinthetag.InHTML,the<ul>tagissuchatag,asitcancontain
only<li>tags.
Mixedcontent,denotedbyacomma-separatedlistofelementnamesandthe
keyword#PCDATA,isenclosedinparentheses.Thiscontenttypeallowstagsto
haveuser-definedcontent,alongwithothermarkupelements.The<li>tag,
forexample,maycontainuser-definedcontentaswellasothertags.
ThelasttwocontenttypesformthemeatofmostDTDelementdeclarations.This
iswherethefunbegins.
15.4.ElementGrammar
Thegrammarofhumanlanguageisrichwithavarietyofsentencestructures,
verbtenses,andallsortsofirregularconstructsandexceptionstotherules.
Nonetheless,youmasteredmostofitbytheageofthree.Computerlanguage
grammarstypicallyaresimpleandregular,andhavefewexceptions.Infact,
computergrammarsuseonlyfourrulestodefinehowelementsofalanguage
maybearranged:sequence,choice,grouping,andrepetition.
15.4.1.Sequence,Choice,Grouping,andRepetition
Sequencerulesdefinetheexactorderinwhichelementsappearinalanguage.
Forinstance,ifasequencegrammarrulestatesthatelementAisfollowedbyB
andthenbyC,yourdocumentmustprovideelementsA,B,andCinthatexact
order.Amissingelement(AandC,butnoB,forexample),anextraelement(A,
B,E,thenC),oranelementoutofplace(C,A,thenB)violatestheruleanddoes
notmatchthegrammar.
Inmanygrammars,XMLincluded,sequencesaredefinedbysimplylistingthe
appropriateelements,inorderandseparatedbycommas.Accordingly,our
examplesequenceintheDTDwouldappearsimplyasA,B,C.
ChoicegrammarrulesprovideflexibilitybylettingtheDTDauthorchooseone
elementfromamongagroupofvalidelements.Forexample,achoicerulemight
statethatyoumaychooseelementsD,E,orF;anyoneofthesethreeelements
wouldsatisfythegrammar.Likemanyothergrammars,XMLdenoteschoicerules
bylistingtheappropriatechoicesseparatedbyapipecharacter(|).Thus,we
couldwriteoursimplechoiceintheDTDasD|E|F.Ifyoureadtheverticalbar
asthewordor,choicerulesbecomeeasytounderstand.
Groupingrulescollecttwoormorerulesintoasinglerule,buildingricher,more
usablelanguages.Forexample,agroupingrulemightallowasequenceof
elements,followedbyachoice,followedbyasequence.Youcanindicategroups
withinarulebyenclosingtheminparenthesesintheDTD.Forexample:
Document::=A,B,C,(D|E|F),G
requiresthatadocumentbeginwithelementsA,B,andC,followedbyachoiceof
oneelementoutofD,E,orF,followedbyelementG.
Repetitionrulesletyourepeatoneormoreelementssomenumberoftimes.With
XML,aswithmanyotherlanguages,youdenoterepetitionbyappendingaspecial
charactersuffixtoanelementorgroupwithinarule.Withoutthespecial
character,thatelementorgroupmustappearexactlyonceintherule.Special
charactersincludetheplussign(+),meaningthattheelementmayappearoneor
moretimesinthedocument;theasterisk(*),meaningthattheelementmay
appearzeroormoretimes;andthequestionmark(?),meaningthattheelement
mayappeareitherzerooronetime.
Forexample,therule:
Document::=A,B?,C*,(D|E|F)+,G*
createsanunlimitednumberofcorrectdocumentswiththeelementsAthroughF.
Accordingtotherule,eachdocumentmustbeginwithA,optionallyfollowedbyB,
followedbyzeroormoreoccurrencesofC,followedbyatleastone,butperhaps
more,ofeitherD,E,orF,followedbyzeroormoreGs.Allofthefollowing
examples(andmanyothers)matchthisrule:
ABCDG
ACCCFFGGG
ACDFDFGG
Youmightwanttoworkthroughtheseexamplestoprovetoyourselfthatthey
are,infact,correctwithrespecttotherepetitionrule.
15.4.2.MultipleGrammarRules
Bynow,youcanprobablyimaginethatspecifyinganentirelanguagegrammarin
asingleruleisdifficult,althoughpossible.Unfortunately,theresultwouldbean
almostunreadablesequenceofnearlyunintelligiblerules.Toremedythis
situation,theitemsinarulemaythemselvesberulescontainingotherelements
andrules.Inthesecases,theitemsinagrammarthatarethemselvesrulesare
knownasnonterminals,andtheitemsthatareelementsinthelanguageare
knownasterminals.Eventually,allthenonterminalsmustreferencerulesthat
createsequencesofterminals,orthegrammarwouldneverproduceavalid
document.
Forexample,wecanexpressoursamplegrammarintworules:
Document::=A,B?,C*,Choices+,G*
Choices::=D|E|F
Inthisexample,DocumentandChoicesarenonterminals,andA,B,C,D,E,F,
andGareterminals.
ThereisnorequirementinXML(ormostothergrammars)thatdictatesorlimits
thenumberofnonterminalsinyourgrammar.Mostgrammarsusenonterminals
whereveritmakessenseforclarityandeaseofuse.
15.4.3.XMLElementGrammar
Therulesfordefiningthecontentsofanelementmatchthegrammarruleswe
justdiscussed.Youmayusesequences,choices,groups,andrepetitiontodefine
theallowablecontentsofanelement.Thenonterminalsinrulesmustbenamesof
otherelementsdefinedinyourDTD.
Afewexamplesshowhowthisworks.Considerthedeclarationofthe<html>tag,
takenfromtheHTMLDTD:
<!ELEMENThtml(head,body)>
Thisdefinestheelementnamedhtmlwhosecontentisaheadelementfollowedbya
bodyelement.Noticeyoudonotenclosetheelementnamesinanglebrackets
withintheDTD;youusethatnotationonlywhentheelementsareactuallyused
inadocument.
WithintheHTMLDTD,youcanfindthedeclarationofthe<head>tag:
<!ELEMENThead(%head.misc;,
((title,%head.misc;,(base,%head.misc;)?)|
(base,%head.misc;,(title,%head.misc;))))>
Gulp.WhatonEarthdoesthismean?First,noticethataparameterentitynamed
head.miscappearsseveraltimesinthisdeclaration.Let'sgogetit:
<!ENTITY%head.misc"(script|style|meta|link|object)*">
Nowthingsarestartingtomakesense:head.miscdefinesagroupofelements,from
whichyoumaychooseone.However,thetrailingasteriskindicatesthatyoumay
includezeroormoreoftheseelements.Thenetresultisthatanywhere%head.misc;
appears,youcanincludezeroormorescript,style,meta,link,orobjectelements,
inanyorder.Soundfamiliar?
Returningtotheheaddeclaration,weseethatweareallowedtobeginwithany
numberofthemiscellaneouselements.Wemustthenmakeachoice:eithera
groupconsistingofatitleelement,optionalmiscellaneousitems,andanoptional
baseelementfollowedbymiscellaneousitems;oragroupconsistingofabase
element,miscellaneousitems,atitleelement,andsomemoremiscellaneous
items.
Whysuchaconvolutedruleforthe<head>tag?Whynotjustwrite:
<!ELEMENThead(script|style|meta|link|object|base|title)*>
whichallowsanynumberofheadelementstoappear,ornoneatall?TheHTML
standardrequiresthatevery<head>tagcontainexactlyone<title>tag.Italso
allowsforonlyone<base>tag,ifany.Otherwise,thestandarddoesallowany
numberoftheotherheadelements,inanyorder.
Putsimply,theheadelementdeclaration,whileinitiallyconfusing,forcestheXML
processortoensurethatexactlyonetitleelementappearsintheheadelement
andthat,ifspecified,justonebaseelementappearsaswell.Itthenallowsforany
oftheotherheadelements,inanyorder.
ThisoneexampledemonstratesalotofthepowerofXML:theabilitytodefine
commonlyusedelementsusingparameterentitiesandtheuseofgrammarrules
todictatedocumentsyntax.Ifyoucanworkthroughtheheadelementdeclaration
andunderstandit,youarewellonyourwaytoreadinganyXMLDTD.
15.4.4.MixedElementContent
Mixedelementcontentextendstheelementgrammarrulestoincludethespecial
#PCDATAkeyword.PCDATAstandsfor"parsedcharacterdata"andsignifiesthatthe
contentoftheelementwillbeparsedbytheXMLprocessorforgeneralentity
references.Aftertheentitiesarereplaced,thecharacterdataispassedtothe
XMLapplicationforfurtherprocessing.
Whatthisboilsdowntoisthatparsedcharacterdataistheactualcontentofyour
XMLdocument.Elementsthatacceptparsedcharacterdatamaycontainplainold
text,pluswhateverothertagsyouallow,asdefinedintheDTD.
Forinstance:
<!ELEMENTtitle(#PCDATA)>
meansthatthetitleelementmaycontainonlytextwithentities.Noothertags
areallowed,justasintheHTMLstandard.
Amorecomplexexampleisthe<p>tag,whoseelementdeclarationis:
<!ELEMENTp%Inline;>
Anotherparameterentity,%Inline;,isdefinedintheHTMLDTDas:
<!ENTITY%Inline"(#PCDATA|%inline;|%misc;)*">
whichexpandstotheseentitieswhenyoureplacetheparameters:
<!ENTITY%special"br|span|bdo|object|img|map">
<!ENTITY%fontstyle"tt|i|b|big|small">
<!ENTITY%phrase"em|strong|dfn|code|q|sub|sup|samp|kbd|
var|cite|abbr|acronym">
<!ENTITY%inline.forms"input|select|textarea|label|button">
<!ENTITY%misc"ins|del|script|noscript">
<!ENTITY%inline"a|%special;|%fontstyle;|%phrase;|%inline.forms;">
Whatdowemakeofallthis?The%Inline;entitydefinesthecontentsofthep
elementasparsedcharacterdata,plusanyoftheelementsdefinedby%inline;
andanydefinedby%misc;.Notethatcasedoesmatter:%Inline;isdifferentfrom
%inline;.
The%inline;entityincludeslotsofstuff:specialelements,font-styleelements,
phraseelements,andinlineformelements.%miscincludestheins,del,script,and
noscriptelements.YoucanreadtheHTMLDTDfortheotherentitydeclarationsto
seewhichelementsarealsoallowedasthecontentsofapelement.
WhydidtheHTMLDTDauthorsbreakupalltheseelementsintoseparategroups?
Iftheyweresimplydefiningelementstobeincludedinthepelement,theycould
havebuiltasinglelonglist.However,HTMLhasrulesthatgovernwhereinline
elementsmayappearinadocument.Theauthorsgroupedelementsthatare
treatedsimilarlyintoseparateentitiesthatcouldbereferencedseveraltimesin
theDTD.ThismakestheDTDeasiertoreadandunderstand,aswellaseasierto
maintainwhenachangeisneeded.
15.4.5.EmptyElements
Elementswhosecontentisdefinedtobeemptydeserveaspecialmention.XML
introducednotationalrulesforemptyelements,differentfromthetraditional
HTMLrulesthatgovernthem.
HTMLauthorsareusedtospecifyinganemptyelementasasingletag,suchas
<br>or<img>.XMLrequiresthateveryelementhaveanopeningandaclosingtag,
soanimagetagwouldbewrittenas<img></img>,withnoembeddedcontent.Other
emptyelementswouldbewritteninasimilarmanner.
Becausethisformatworkswellfornonemptytagsbutisabitofoverkillforempty
ones,youcanuseaspecialshorthandnotationforemptytags.Towriteanempty
taginXML,justplaceaslash(/)immediatelybeforetheclosinganglebracketof
thetag.Thus,youcanwritealinebreakas<br/>andanimagetagas<img
src="myimage.gif"/>.Noticethattheattributesoftheemptyelement,ifany,appear
beforetheclosingslashandbracket.
15.5.ElementAttributes
ThefinalpieceoftheDTDpuzzleinvolvesattributes.Youknowattributes:they
arethename/valuepairsincludedwithtagsinyourdocumentsthatcontrolthe
behaviorandappearanceofthosetags.Todefineattributesandtheirallowed
valueswithinanXMLDTD,usethe<!ATTLIST>directive:
<!ATTLISTelementattributes>
Theelementisthenameoftheelementtowhichtheattributesapply.Theattributes
arealistofattributedeclarationsfortheelement.Eachattributedeclarationin
thislistconsistsofanattributename,itstype,anditsdefaultvalue,ifany.
15.5.1.AttributeValues
Attributevaluescanbeofseveraltypes,eachdenotedinanattributedefinition
withoneofthefollowingkeywords:
CDATA
Indicatesthattheattributevalueisacharacterorstringofcharacters.Thisis
theattributetypeyouwouldusetospecifyURLsorotherarbitraryuserdata.
Forexample,thesrcattributeofthe<img>taginHTMLhasavalueofCDATA.
ID
Indicatesthattheattributevalueisauniqueidentifierwithinthescopeofthe
document.Thisattributetypeisusedwithanattribute,suchastheHTMLid
attribute,whosevaluedefinesanIDwithinthedocument,asdiscussedin
"CoreAttributes"inAppendixB.
IDREForIDREFS
IndicatethattheattributeacceptsanIDdefinedelsewhereinthedocument
viaanattributeoftypeID.YouusetheIDtypewhendefiningIDs;youuse
IDREFandIDREFSwhenreferencingasingleIDandalistofIDs,respectively.
ENTITYorENTITIES
Indicatethattheattributeacceptsthenameorlistofnamesofunparsed
generalentitiesdefinedelsewhereintheDTD.Thedefinitionanduseof
unparsedgeneralentitiesiscoveredinsection15.3.2.
NMTOKENorNMTOKENS
IndicatethattheattributeacceptsavalidXMLnameorlistofnames.These
namesaregiventotheprocessingapplicationasthevalueoftheattribute.
Theapplicationdetermineshowtheyareused.
Inadditiontothesekeyword-basedtypes,youcancreateanenumeratedtypeby
listingthespecificvaluesallowedwiththisattribute.Tocreateanenumerated
type,listtheallowedvalues,separatedbypipecharactersandenclosedin
parentheses,asthetypeoftheattribute.Forexample,hereishowthemethod
attributeforthe<form>tagisdefinedintheHTMLDTD:
method(get|post)"get"
Themethodattributeacceptsoneoftwovalues,eithergetorpost;getisthedefault
valueifnothingisspecifiedinthedocumenttag.
15.5.2.RequiredandDefaultAttributes
Afteryoudefinethenameandtypeofanattribute,youmustspecifyhowtheXML
processorshouldhandledefaultorrequiredvaluesfortheattribute.Youdothis
bysupplyingoneoffourvaluesaftertheattributetype.
Ifyouusethe#REQUIREDkeyword,theassociatedattributemustalwaysbeprovided
whentheelementisusedinadocument.WithintheXHTMLDTD,thesrcattribute
ofthe<img>tagisrequiredbecauseanimagetagmakesnosensewithoutan
imagetodisplay.
The#IMPLIEDkeywordmeansthattheattributemaybeusedbutisnotrequired
andthatnodefaultvalueisassociatedwiththeattribute.Ifitisnotsuppliedby
thedocumentauthor,theattributehasnovaluewhentheXMLprocessorhandles
theelement.Forthe<img>tag,thewidthandheightattributesareimpliedbecause
thebrowserderivessizinginformationfromtheimageitselfiftheseattributesare
notspecified.
Ifyouspecifyavalue,itthenbecomesthedefaultvalueforthatattribute.Ifthe
userdoesnotspecifyavaluefortheattribute,theXMLprocessorinsertsthe
defaultvalue(thevaluespecifiedintheDTD).
Ifyouprecedethedefaultvaluewiththekeyword#FIXED,thevalueisnotonlythe
defaultvaluefortheattribute,itistheonlyvaluethatcanbeusedwiththat
attributeifitisspecified.
Forexample,examinetheattributelistfortheformelement,taken(andabridged)
fromtheHTMLDTD:
<!ATTLISTform
actionCDATA#REQUIRED
method(get|post)"get"
enctypeCDATA"application/x-www-form-urlencoded"
onsubmitCDATA#IMPLIED
onresetCDATA#IMPLIED
acceptCDATA#IMPLIED
accept-charsetCDATA#IMPLIED
>
Thisexampleassociatessevenattributeswiththeformelement.Theaction
attributeisrequiredandacceptsacharacterstringvalue.Themethodattributehas
oneoftwovalues,eithergetorpost.getisthedefault,soifthedocumentauthor
doesn'tincludethemethodattributeintheformtag,theXMLparserassumes
method=getautomatically.
Theenctypeattributefortheformelementacceptsacharacterstringvalueand,if
notspecified,defaultstoavalueofapplication/x-www-form-urlencoded.Theremaining
attributesallacceptcharacterstrings,arenotrequired,andhavenodefault
valuesiftheyarenotspecified.
IfyoulookattheattributelistfortheformelementintheHTMLDTD,you'llsee
thatitdoesnotexactlymatchourexample.That'sbecausewe'vemodifiedour
exampletoshowthetypesoftheattributesafteranyparameterentitieshave
beenexpanded.IntheactualHTMLDTD,theattributetypesareprovidedas
parameterentitieswhosenamesgiveahintofthekindsofvaluestheattribute
expects.Forexample,thetypeoftheactionattributeappearsas%URI;,notCDATA,
butelsewhereintheDTDisdefinedtobeCDATA.Byusingthisstyle,theDTD
authorletsyouknowthatthestringvalueforthisattributeshouldbeaURL,not
justanyoldstring.Similarly,thetypeoftheonsubmitandonresetattributesisgiven
as%Script.Thisisahintthatthecharacterstringvalueshouldnameascripttobe
executedwhentheformissubmittedorreset.
15.6.ConditionalSections
Aswementionedearlierinthischapter,XMLletsyouincludeorignorewhole
sectionsofyourDTD,soyoucantailorthelanguageforalternativeuses.The
HTMLDTD,forinstance,definestransitional,strict,andframe-basedversionsof
thelanguage.DTDauthorscanselecttheportionsoftheDTDtheyplantoinclude
orignorebyusingXMLconditionaldirectives:
<![INCLUDE[
...anyXMLcontent...
]]>
or:
<![IGNORE[
...anyXMLcontent...
]]>
TheXMLprocessoreitherincludesorignoresthecontents,respectively.
Conditionalsectionsmaybenested,withthecaveatthatallsectionscontained
withinanignoredsectionareignored,eveniftheyaresettobeincluded.
YourarelyseeaDTDwiththeINCLUDEandIGNOREkeywordsspelledout.Instead,you
seeparameterentitiesthatdocumentwhythesectionisbeingincludedor
ignored.SupposeyouarecreatingaDTDtoexchangeconstructionplansamong
builders.Becauseyouhaveaninternationalcustomerbase,youbuildaDTDthat
canhandlebothEnglishandmetricunits.Youmightdefinetwoparameter
entities:
<!ENTITY%English"INCLUDE">
<!ENTITY%Metric"IGNORE">
YouwouldthenplacealltheEnglish-specificdeclarationsinaconditionalsection
andisolatethemetricdeclarationssimilarly:
<![%English[...Englishstuffhere...]]>
<![%Metric[...Metricstuffhere...]]>
TousetheDTDforEnglishconstructionjobs,define%EnglishasINCLUDEand%Metric
asIGNORE,whichcausesyourDTDtousetheEnglishdeclarations.Formetric
construction,reversethetwosettings,ignoringtheEnglishsectionandincluding
themetricsection.
15.7.BuildinganXMLDTD
Nowthatwe'veemergedfromthegorydetailsofXMLDTDs,let'sseehowthey
workbycreatingasimpleexample.YoucancreateaDTDwithanytexteditorand
aclearideaofhowyouwanttomarkupyourXMLdocuments.You'llneedanXML
parserandprocessingapplicationtoactuallyinterpretanduseyourDTD,aswell
asastylesheettopermitXML-capablebrowserstodisplayyourdocument.
15.7.1.AnXMLAddressDTD
Let'screateasimpleXMLDTDthatdefinesamarkuplanguageforspecifying
documentscontainingnamesandaddresses.Westartwithanaddresselement,
whichcontainsotherelementsthattagtheaddresscontents.Ouraddresselement
hasasingleattributeindicatingwhetheritisaworkorahomeaddress:
<!ELEMENTaddress(name,street+,city,state,zip?)>
<!ATTLISTaddresstype(home|business)#REQUIRED>
Voilà!Thefirstdeclarationcreatesanelementnamedaddressthatcontainsaname
element,oneormorestreetelements,acityandstateelement,andanoptional
zipelement.Theaddresselementhasasingleattribute,type,whichmustbe
specifiedandcanhaveavalueofeitherhomeorbusiness.
Let'sdefinethenameelementsfirst:
<!ELEMENTname(first,middle?,last)>
<!ELEMENTfirst(#PCDATA)>
<!ELEMENTmiddle(#PCDATA)>
<!ELEMENTlast(#PCDATA)>
Thenameelementalsocontainsotherelementsafirstname,anoptionalmiddle
name,andalastnameeachdefinedinthesubsequentDTDlines.Thesethree
elementshavenonestedtagsandcontainonlyparsedcharacterdata;i.e.,the
actualnameoftheperson.
Theremainingaddresselementsareeasy,too:
<!ELEMENTstreet(#PCDATA)>
<!ELEMENTcity(#PCDATA)>
<!ELEMENTstate(#PCDATA)>
<!ELEMENTzip(#PCDATA)>
<!ATTLISTziplengthCDATA"5">
Alltheseelementscontainparsedcharacterdata.Thezipelementhasan
attributenamedlengththatindicatesthelengthofthezipcode.Ifthelength
attributeisnotspecified,itissetto5.
15.7.2.UsingtheAddressDTD
OncewehavedefinedouraddressDTD,wecanuseittomarkupaddress
documents.Forexample:
<addresstype="home">
<name>
<first>Chuck</first>
<last>Musciano</last>
</name>
<street>123KumquatWay</street>
<city>Cary</city>
<state>NC</state>
<ziplength="10">27513-1234</zip>
</address>
WithanappropriateXMLparserandanapplicationtousethisdata,wecanparse
andstoreaddresses,createaddressestosharewithotherpeopleandapplications,
andcreatedisplaytoolsthatwouldpublishaddressesinawiderangeofstylesand
media.AlthoughourDTDissimple,ithasdefinedastandardwaytocapture
addressdatathatiseasytouseandunderstand.
15.8.UsingXML
Ouraddressexampleistrivial.Ithardlyscratchesthesurfaceofthewiderangeof
applicationsthatXMLissuitedfor.Towhetyourappetite,herearesomecommon
usesforXMLthatyouwillcertainlybeseeingnowandinthefuture.
15.8.1.CreatingYourOwnMarkupLanguage
WetouchedonthisearlierwhenwementionedthatthelatestversionsofHTML
arebeingreformulatedascompliantXMLDTDs.WecovertheimpactXMLhason
HTMLinthenextchapter.
Butevenmoresignificantly,XMLenablescommunitiesofuserstocreate
languagesthatbestcapturetheiruniquedataandideas.Mathematicians,
chemists,musicians,andprofessionalsfromhundredsofotherdisciplinescan
createspecialtagsthatrepresentuniqueconceptsinastandardizedway.Evenif
nobrowserexiststhatcanaccuratelyrenderthesetagsinadisplayableform,the
abilitytocaptureandstandardizeinformationistremendouslyimportantfor
futureextractionandinterpretationoftheseideas.
FormoremainstreamXMLapplicationswithestablishedaudiences,itiseasyto
envisioncustombrowsersbeingcreatedtoappropriatelydisplaytheinformation.
Smallerapplicationsormarketsmayhavemoreofachallengecreatingmarkup
languagesthatenjoysuchwideacceptance.Creatingthecustomdisplaytoolfora
markuplanguageisdifficult;deliveringthattoolformultipleplatformsis
expensive.Aswe'venoted,youcanmitigatesomeofthesedisplayconcerns
throughappropriateuseofstylesheets.Luckily,XML'scapabilitiesextendbeyond
documentdisplay.
15.8.2.DocumentExchange
BecauseXMLgrewoutofthetremendoussuccessofHTML,manypeoplethinkof
XMLasyetanotherdocument-displaytool.Infact,therealpowerofXMLliesnot
inthedocument-displayarena,butintheworldofdatacaptureandexchange.
Despitethebillionsofcomputersdeployedworldwide,sharingdataisastedious
anderror-proneasever.Competingapplicationsdonotoperatefromcommon
document-storageformats,sosendingasingledocumenttoanumberof
recipientsisfraughtwithperil.Evenwhenvendorsattempttocreatean
interchangeformat,itstilltendstobeproprietaryandoftenisviewedasa
competitiveadvantageforparticipatingvendors.Thereislittleincentivefor
vendorstoreleaseapplicationcodeforthepurposeofcreatingeasydocument-
exchangetools.
XMLavoidstheseproblems.Itisplatformneutral,isgeneric,andcanperform
almostanydata-capturetask.Itisequallyavailabletoallvendorsandcaneasily
beintegratedintomostapplications.ThestabilizationoftheXMLstandardand
theincreasingavailabilityofXMLauthoringandparsingtoolsismakingiteasier
tocreateXMLmarkuplanguagesfordocumentcaptureandexchange.
Mostimportantly,documentexchangerarelyrequiresdocumentpresentation,
thuseliminating"displaydifficulties"fromtheequation.Often,anexisting
applicationusesXMLtoincludedatafromanothersourceandthenusesitsown
internaldisplaycapabilitiestopresentthedatatotheenduser.Thecostofadding
XML-baseddataexchangetoexistingapplicationsisrelativelysmall.
15.8.3.ConnectingSystems
Alevelbelowapplications,thereisalsoaneedforsystemstoexchangedata.As
business-to-businesscommunicationincreases,thisneedgrowsevenfaster.In
thepast,thismeantthatsomeonehadtodesignaprotocoltoencodeand
exchangethedata.WithXML,exchangingdataisaseasyasdefiningaDTDand
integratingtheparserintoyourexistingapplications.
Thedatasetsexchangedcanbequitesmall.ImagineshoppingforanewPCon
theWeb.Ifyoucouldcaptureyoursystemrequirementsasasmalldocument
usinganXMLDTD,youcouldsendthatspecificationtoahundreddifferent
vendorstoquoteyouasystem.Ifyouextendthatmodeltoincludealmost
anythingyoucanshopforfromcarstohottubsXMLprovidesanelegantbaselayer
ofcommunicationamongcooperatingvendorsontheInternet.
AlmostanydatathatiscapturedandstoredcanmoreeasilybesharedusingXML.
Formanysystems,theXMLDTDsmaydefineadata-transferprotocolandnothing
more.ThedatamayneveractuallybestoredusingtheXML-definedmarkup;it
mayexistinanXML-compatibleformonlylongenoughtopassonthewire
betweentwosystems.
OneincreasinglypopularuseofXMLiswebservices,whichmakeitpossiblefor
diverseapplicationstodiscovereachotherandexchangedataseamlesslyover
theInternet,regardlessoftheirprogramminglanguageorarchitecture.Formore
informationonwebservices,consultWebServicesEssentialsbyEthanCerami
(O'Reilly).
InconjunctionwithXML-baseddataexchange,theExtensibleStylesheet
Language,orXSL,isincreasinglybeingusedtodescribetheappearanceand
definitionofthedatarepresentedbytheseXMLDTDs.MuchlikeCascadingStyle
Sheets(CSS)anditsabilitytotransformHTMLdocuments,XSLsupportsthe
creationofstylesheetsforanyXMLDTD.YoucanuseCSSwithXMLdocumentsas
well,butitisnotasprogrammaticallyrichasXSL.WhileCSSstopswith
stylesheets,XSLisastylelanguage.XSLcertainlyaddressestheneedfordata
display,anditprovidesrichtoolsthatallowdatarepresentedwithoneDTDtobe
transformedintoanotherDTDinacontrolledanddeterministicfashion.A
completediscussionofXSLisbeyondthescopeofthisbook;consultXSLTby
DougTidwell(O'Reilly)forcompletedetails.
ThepotentialforXMLgoeswellbeyondthatoftraditionalmarkupand
presentationtools.WhatwenowseeanduseintheXMLworldisonlyscratching
thesurfaceofthepotentialforthistechnology.
15.8.4.StandardizingHTML
Last,butcertainlynotleast,theW3CusesXMLtodefineastandardversionof
HTMLknownasXHTML.XHTMLretainsalmostallofthefeaturesofHTML4.01,
butitalsointroducesanumberofminor(andafewnot-so-minor)differences.
ThenextchaptercomparesandcontrastsXHTMLandHTML,mappingoutthe
differencessothatyoucanbegincreatingdocumentsthatcomplywithboththe
HTMLandXHTMLstandards.
Chapter16.XHTML
Despiteitsname,youdon'tusetheExtensibleMarkupLanguage(XML)todirectly
createandmarkupwebdocuments.Instead,youuseXMLtodefineanew
markuplanguage,whichyouthenusetomarkupwebdocuments.Thisshould
comeasnosurprisetoanyonewhohasreadtheprecedingchapterinthisbook.
Nor,then,shoulditsurpriseyouthatoneofthefirstlanguagesdefinedusingXML
isanXMLizedversionofHTML,themostpopularmarkuplanguageever.HTMLis
beingdisciplinedandcleanedupbyXML,tobringitbackintolinewiththelarger
familyofmarkuplanguages.ThisstandardisXHTML1.0.[*]
[*]Throughoutthischapter,weuse"XHTML"tomeantheXHTML1.0standard.ThereisanascentXHTML1.1standard
thatdivergesfromHTML4.01andismorerestrictivethanXHTML1.0.WedescribethesalientfeaturesofXHTML1.1in
section16.4.
BecauseofHTML'slegacyfeaturesandoddities,usingXMLtodescribeHTMLwas
notaneasyjobfortheWorldWideWebConsortium(W3C).Infact,certainHTML
rules,aswe'lldiscusslater,cannotbeexpressedwithXML.Nonetheless,ifthe
W3Chasitsway,XHTMLwillultimatelyreplacetheHTMLwecurrentlyknowand
love.
SomuchofXHTMLisidenticaltoHTML'scurrentstandard,version4.01,thatyou
canapplyalmosteverythingpresentedelsewhereinthisbooktobothHTMLand
XHTML.Wedetailthedifferences,bothgoodandbad,inthischapter.Tobecome
fluentinXHTML,you'llfirstneedtoabsorbtherestofthisbook,andthenadjust
yourthinkingtoembracewhatwepresentinthischapter.
16.1.WhyXHTML?
Aswedescribedintheprecedingchapter,HTMLbeganasasimplemarkup
languagesimilarinappearanceandusagetootherStandardGeneralizedMarkup
Language(SGML)-basedmarkuplanguages.Initsearlyyears,littleeffortwasput
intomakingHTMLperfectlySGMLcompliant.Asaresult,oddfeaturesandalax
attitudetowardenforcingtherulesbecamestandardpartsofbothHTMLandthe
browsersthatprocessedHTMLdocuments.
AstheWebgrewfromanexperimentintoanindustry,thedesireforastandard
versionofHTMLledtothecreationofseveralofficialversions,culminatingmost
recentlywithversion4.01.AsHTMLhasstabilizedintothislatestversion,
browsershavebecomemorealikeintheirsupportofvariousHTMLfeatures.In
general,theworldofHTMLhassettledintoafamiliarsetofconstructsandusage
rules.
Unfortunately,HTMLoffersonlyalimitedsetofdocument-creationprimitives,is
incapableofhandlingnontraditionalcontentsuchaschemicalformulae,musical
notation,ormathematicalexpressions,andfailstoadequatelysupportalternative
displaymediasuchashandheldcomputersorintelligentcellularphones.Weneed
newwaystodeliverinformationthatcanbeparsed,processed,displayed,sliced,
anddicedbythemanydifferentcommunicationtechnologiesthathaveemerged
sincetheWebsparkedthedigitalcommunicationrevolutionadecadeago.
Insteadoftryingtoreininanotherherdofmaverick,nonstandardmarkup
languages,theW3CintroducedXMLasastandardwaytocreatenewmarkup
languages.XMListheframeworkuponwhichorganizationscandeveloptheirown
markuplanguagestosuittheneedsoftheirusers.XMLisanupdatedversionof
SGML,streamlinedandenhancedfortoday'sdynamicsystems.Andwhilethe
W3Coriginallyintendeditasatooltocreatedocumentmarkuplanguages,XMLis
alsobecomingquiteusefulasastandardwaytodefinesmalllanguagesthat
differentapplicationsuseasdata-exchangeprotocols.
Ofcourse,wedon'twanttoabandontheplethoraofdocumentsalreadymarked
upwithHTML,ortheinfrastructureofknowledge,tools,andtechnologiesthat
currentlysupportHTMLandtheWeb.Yet,wedonotwanttomissthe
opportunitiesofXML,either.XHTMListhebridge.ItusesthefeaturesofXMLto
defineamarkuplanguagethatisnearlyidenticaltostandardHTML4.01andgets
usallstarteddowntheXMLroad.
16.1.1.XHTMLDocumentTypeDefinitions
HTML4.01comesinthreevariants,eachdefinedbyaseparateSGMLDocument
TypeDefinition(DTD).XHTMLalsocomesinthreevariants,withXMLDTDs
correspondingtothethreeSGMLDTDsthatdefineHTML4.01.Tocreatean
XHTMLdocument,youmustchooseoneoftheseDTDsandthencreatea
documentthatusesthatDTD'selementsandrules.
ThefirstXHTMLDTDcorrespondstothe"strict"HTMLDTD.Thestrictdefinition
excludesalldeprecatedelements(tagsandattributes)inHTML4.01andforces
authorstouseonlythosefeaturesthatarefullysupportedinHTML.Manyofthe
HTMLelementsandattributesdealingwithpresentationandappearance,suchas
the<font>tagandthealignattribute,aremissingfromthestrictXHTMLDTDand
havebeenreplacedbytheequivalentpropertiesintheCascadingStyleSheets
(CSS)model.
MostHTMLauthorsfindthestrictXHTMLDTDtoorestrictivebecausemanyofthe
deprecatedelementsandattributesarestillinwidespreadusethroughoutthe
Web.Moreimportantly,lotsofcontentoutthereontheWebusesthelegacy
elementsandattributes,andthepopularbrowsersstillsupportmostofthe
deprecatedelements.TheonlyrealadvantageofusingthestrictXHTMLDTDis
thatcompliantdocumentsareguaranteedtobefullysupportedinfutureversions
ofXHTML.[*]
[*]IftheW3Chasitsway,HTMLwon'tchangebeyondversion4.01.NomoreHTML;allnewdevelopmentswillbein
XHTMLandmanyotherXML-basedlanguages.
Mostauthorswillprobablychoosetousethe"transitional"XHTMLDTD.It'sclosest
tothecurrentHTMLstandardandincludesallthosewonderful,butdeprecated,
featuresthatmakelifeasanHTMLauthoreasier.WiththetransitionalXHTML
DTD,youcaneaseintotheXMLfamilywhilestayingcurrentwiththebrowser
industry.
ThethirdDTDisforframes.ItisidenticaltothetransitionalDTDinallother
respects;theonlydifferenceisthereplacementofthedocumentbodywith
appropriateframeelements.Youmightthinkthat,forcompleteness'ssake,there
wouldbestrictandtransitionalframeDTDs,buttheW3Cdecidedthatifyouuse
frames,youmightaswelluseallthedeprecatedelementsaswell.
16.2.CreatingXHTMLDocuments
Forthemostpart,creatinganXHTMLdocumentisnodifferentfromcreatingan
HTMLdocument.Usingyourfavoritetexteditor,simplyaddthemarkupelements
toyourdocument'scontentsintherightorder,anddisplayitusingyourfavorite
browser.Tobestrictlycorrect("valid,"astheysayattheW3C),yourXHTML
documentneedsaboilerplatedeclarationupfrontthatspecifiestheDTDyouused
tocreatethedocumentanddefinesanamespaceforthedocument.
16.2.1.DeclaringDocumentTypes
ForanXHTMLbrowsertocorrectlyparseanddisplayyourXHTMLdocument,you
shouldtellitwhichversionofXMLisbeingusedtocreatethedocument.Youmust
alsostatewhichXHTMLDTDdefinestheelementsinyourdocument.
TheXMLversiondeclarationusesaspecialXMLprocessingdirective.Ingeneral,
theseXMLdirectivesbeginwith<?andendwith?>,butotherwisetheylooklike
typicaltagsinyourdocument.[*]TodeclarethatyouareusingXMLversion1.0,
placethisdirectiveinthefirstlineinyourdocument:
[*]<!wasalreadytaken.
<?xmlversion="1.0"encoding="UTF-8"?>
ThistellsthebrowserthatyouareusingXML1.0alongwiththe8-bitUnicode
characterset,theonemostcommonlyusedtoday.Theencodingattribute'svalue
shouldreflectthecharactersetusedinyourdocument.Refertotheappropriate
InternationalOrganizationforStandardization(ISO)standardsforotherencoding
names.
Onceyou'vegottentheimportantissueoftheXMLversionsquaredaway,you
shouldthendeclarethemarkuplanguage'sDTD:
<!DOCTYPEhtml
PUBLIC"-//W3C//DTDXHTML1.0Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Withthisstatement,youdeclarethatyourdocument'srootelementishtml,as
definedintheDTDwhosepublicidentifierisdefinedas"-//W3C//DTDXHTML1.0
Strict//EN".ThebrowsermayknowhowtofindtheDTDmatchingthispublic
identifier.Ifitdoesnot,itcanusetheURLfollowingthepublicidentifierasan
alternativelocationfortheDTD.
Asyoumayhavenoticed,thepreceding<!DOCTYPE>directivetoldthebrowserto
usethestrictXHTMLDTD.Here'stheoneyou'llprobablyuseforyourtransitional
XHTMLdocuments:
<!DOCTYPEhtml
PUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
And,asyoumightexpect,the<!DOCTYPE>directivefortheframe-basedXHTMLDTD
is:
<!DOCTYPEhtml
PUBLIC"-//W3C//DTDXHTML1.0Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
16.2.2.UnderstandingNamespaces
Asdescribedinthelastchapter,anXMLDTDdefinesanynumberofelementand
attributenamesaspartofthemarkuplanguage.Theseelementsandattributes
arestoredinanamespacethatisuniquetotheDTD.Asyoureferenceelements
andattributesinyourdocument,thebrowserlooksthemupinthenamespaceto
findouthowtheyshouldbeused.
Forinstance,the<a>tag'sname(a)andattributes(e.g.,hrefandstyle)aredefined
intheXHTMLDTD,andtheirnamesareplacedintheDTD'snamespace.Any
processingagentusuallyabrowser,butyoureyesandbraincanservethesame
functioncanlookupthenameintheappropriateDTDtofigureoutwhatthe
markupmeansandwhatitshoulddo.
WithXML,yourdocumentactuallycanusemorethanoneDTDandtherefore
requiremorethanonenamespace.Forexample,youmightcreateatransitional
XHTMLdocumentbutalsoincludespecialmarkupforsomemathexpressions
accordingtoanXMLmathlanguage.WhathappenswhenboththeXHTMLDTD
andthemathDTDusethesamenametodefinedifferentelements,suchas<a>for
XHTMLhypertextand<a>foranabsolutevalueinmath?Howdoesthebrowser
choosewhichnamespacetouse?
Theansweristhexmlns[*]attribute.Useittodefineoneormorealternative
namespaceswithinyourdocument.Youcanplaceitwithinthestarttagofany
elementwithinyourdocument,anditsURL-like[ ]valuedefinesthenamespace
thatthebrowsershoulduseforallcontentwithinthatelement.
[*]XMLnamespacexmlnsgetit?ThisiswhyXMLdoesn'tletyoubeginanyelementorattributewiththethree-letterprefix
of"xml":it'sreservedforspecialXMLattributesandelements.
[ ]ItlookslikeaURL,andyoumightthinkthatitreferencesadocumentthatcontainsthenamespace,butalas,it
doesn't.Itissimplyauniquenamethatidentifiesthenamespace.Displayagentsusethatplaceholdertorefertotheir
ownresourcesforhowtotreatthenamedelementorattribute.
WithXHTML,accordingtoXMLconventions,youshouldattheveryleastinclude
withinyourdocument's<html>taganxmlnsattributethatidentifiestheprimary
namespaceusedthroughoutthedocument:
<htmlxmlns="http://www.w3.org/TR/xhtml1">
Ifandwhenyouneedtoincludemathmarkup,usethexmlnsattributeagainto
definethemathnamespace.So,forinstance,youcouldusethexmlnsattribute
withinsomemath-specifictagofyourotherwisecommonXHTMLdocument
(assumingtheMATHelementexists,ofcourse):
<divxmlns="http://www.w3.org/1998/Math/MathML">x2/x</div>
Inthiscase,theXML-compliantbrowserwouldusethe
http://www.w3.org/1998/Math/MathMLnamespacetodivinethatthisisthe
MATH,nottheXHTML,versionofthe<div>tag,andshouldthereforebedisplayed
asadivisionequation.
Itwouldquicklybecometediousifyouhadtoembedthexmlnsattributeintoeach
andevery<div>taganytimeyouwantedtoshowadivisionequationinyour
document.Abetterwayparticularlyifyouplantoapplyittomanydifferent
elementsinyourdocumentistoidentifyandlabelthenamespaceatthebeginning
ofyourdocument,andthenrefertoitbythatlabelasaprefixtotheaffected
elementinyourdocument.Forexample:
<htmlxmlns="http://www.w3.org/TR/xhtml1"
xmlns:math="http://www.w3.org/1998/Math/MathML">
Themathnamespacecannowbeabbreviatedto"math"laterinyourdocument.So
thestreamlined:
</math:div>x2/x</div>
nowhasthesameeffectasthelengthyearlierexampleofthemath<div>tag
containingitsownxmlnsattribute.
ThevastmajorityofXHTMLauthorswillneverneedtodefinemultiple
namespacesandsowillneverhavetousefullyqualifiednamescontainingthe
namespaceprefix.Evenso,youshouldunderstandthatmultiplenamespacesexist
andthatyouwillneedtomanagethemifyouchoosetoembedcontentbasedon
oneDTDwithincontentdefinedbyanotherDTD.
16.2.3.AMinimalXHTMLDocument
AsacourtesytoallfledglingXHTMLauthors,wenowpresenttheminimaland
correctXHTMLdocument,includingalltheappropriateXML,XHTML,and
namespacedeclarations.Withthismostdifficultpartoutoftheway,youneed
onlysupplycontenttocreateacompleteXHTMLdocument:
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEhtml
PUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/TR/xhtml1"xml:lang="en"lang="en">
<head>
<title>Everydocumentmusthaveatitle</title>
</head>
<body>
...yourcontentgoeshere...</body>
</html>
Workingthroughtheminimaldocumentoneelementatatime,webeginby
declaringthatwearebasingthedocumentontheXML1.0standardandusing8-
bitUnicodecharacterstoexpressitscontentsandmarkup.Wethenannounce,in
thefamiliarHTML-like<!DOCTYPE>statement,thatwearefollowingthemarkuprules
definedinthetransitionalXHTML1.0DTD,whichallowusfreereintousenearly
anyHTML4.01elementinourdocument.
Ourdocumentcontentactuallybeginswiththe<html>tag,whichhasitsxmlns
attributedeclarethattheXHTMLnamespaceisthedefaultnamespaceforthe
entiredocument.Alsonotethelangattribute,inboththeXMLandXHTML
namespaces,whichdeclaresthatthedocumentlanguageisEnglish.
Finally,weincludethefamiliardocument<head>and<body>tags,alongwiththe
required<title>tag.
16.3.HTMLVersusXHTML
ThemajorityofHTMLiscompletelycompatiblewithXHTML,andthisbookis
devotedtothatmajority.Inthischapter,however,wetalkabouttheminority:
wheretheHTML4.01standardandtheXHTMLDTDdiffers.Ifyoutrulydesireto
createdocumentsthatarebothHTMLandXHTMLcompliant,youmustheedthe
variouswarningsandcaveatsweoutlineinthefollowingsections.
Thebiggestdifferencethat'sDifferencewithacapitalDandthatspellsdifficultis
thatwritingXHTMLdocumentsrequiresmuchmoredisciplineandattentionto
detailthaneventhemostfastidiousHTMLauthoreverdreamednecessary.In
W3Cparlance,thatmeansyourdocumentsmustbeimpeccablywellformed.
ThroughoutthehistoryofHTMLandinthisbookauthorshavebeenencouragedto
createwell-formeddocuments,butyouhavetobreakrankwiththeHTML
standardsforyourdocumentstobeconsideredwellformedbyXMLstandards.
Nonetheless,youreffortstomasterXHTMLwillberewardedwithdocumentsthat
arewellformedandasenseofsatisfactionfromplayingbythenewrules.Youwill
trulybenefitinthefuture,too:throughXML,yourdocumentswillbeableto
appearinplacesyouneverdreamedwouldexist(mostlygoodplaces,wehope).
16.3.1.CorrectlyNestedElements
Onerequirementofawell-formedXHTMLdocumentisthatitselementsare
nestedcorrectly.Thisisn'tanydifferentfromtheHTMLstandards:simplyclose
themarkupelementsintheorderinwhichyouopenedthem.Ifoneelementis
withinanother,theendtagoftheinnerelementmustappearbeforetheendtag
oftheouterelement.
Hence,inthefollowingwell-formedXHTMLsegment,weendtheitalicstagbefore
weendtheboldone,becausewestarteditalicizingafterwestartedboldingthe
content:
<b>Closetheitalicstag<i>first</i></b>.
Ontheotherhand,thefollowing:
<b>Wellformed,thisis<i>not!</b></i>
isnotwellformed.
XHTMLstrictlyenforcesothernestingrestrictionsthathavealwaysbeenpartof
HTMLbuthavenotalwaysbeenenforced.Theserestrictionsarenotformallypart
oftheXHTMLDTD;theyareinsteaddefinedaspartoftheXHTMLstandardthatis
basedontheDTD.[*]
[*]ThisishairsplittingwithintheXHTMLstandard.TheXMLstandardhasnomechanismtodefinewhichtagsmaynot
beplacedwithinanothertag.SGML,uponwhichXMLisbased,doeshavesuchafeature,butitwasremovedfromXML
tomakethelanguageeasiertouseandimplement.Asaresult,theserestrictionsaresimplylistedinanappendixofthe
XHTMLstandardinsteadofbeingexplicitlydefinedintheXHTMLDTD.
Nestingrestrictionsincludethefollowing:
The<a>tagcannotcontainanother<a>tag.
The<pre>tagcannotcontain<img>,<object>,<big>,<small>,<sub>,or<sup>tags.
The<button>tagcannotcontain<input>,<select>,<textarea>,<label>,<button>,
<form>,<fieldset>,<iframe>,or<isindex>tags.
The<label>tagcannotcontainother<label>tags.
The<form>tagcannotcontainother<form>tags.
Theserestrictionsapplytonestingatanylevel.Forexample,becausean<a>tag
cannotcontainanyother<a>tags,anytagcontainedwithinthat<a>tagcannot
itselfcontainan<a>tag,eventhoughitmightotherwise.
16.3.2.EndTags
Aswe'vedocumentedthroughoutthisbook,anyHTMLtagthatcontainsother
tagsorcontenthasacorrespondingendtag.However,oneofthehallmarksof
HTML(codifiedinthe4.01standard)isthatyoumayleaveouttheendtagsifthe
processingagentcaninfertheirpresence.ThisiswhymostofusHTMLauthors
commonlyleaveoutthe</p>endtagbetweenadjacentparagraphs.Also,listsand
tablescanbecomplicatedtowadethrough,andnothavingtovisuallystumble
overallthe</li>,</td>,</th>,and</tr>endtagscertainlymakesHTMLeasierto
read,albeitabitmoreambiguous.
ThisisnotsoforXHTML.Everytagthatcontainsothertagsorcontentmusthave
acorrespondingendtagpresent,correctlynestedwithintheXHTMLdocument.A
missingendtagisanerrorandrendersthedocumentnoncompliant.Although
seeminglydraconian,thisandthenestingrulesnonethelessremoveanyandall
ambiguitiesastowhereonetagstartsandanothertagends.
16.3.3.HandlingEmptyElements
InXML,andthusXHTML,everytagmusthaveacorrespondingendtageventhose
thataren'tallowedtocontainothertagsorcontent.Accordingly,XHTMLexpects
thelinebreaktoappearas<br></br>inyourdocument.Ugh.
Fortunately,thereisanacceptablealternative:includeaslashbeforetheclosing
bracketofthetagtoindicateitsending(e.g.,<br/>).Ifthetaghasattributes,the
slashcomesafteralltheattributessothatanimagecouldbedefinedas:
<imgsrc="kumquat.gif"/>
WhilethisnotationmayseemforeignandannoyingtoanHTMLauthor,itactually
servesausefulpurpose.AnyXHTMLelementthathasnocontentcanbewritten
thisway.Thus,anemptyparagraphcanbewrittenas<p/>,andanemptytable
cellcanbewrittenas<td/>.Thisisahandywaytomarkemptytablecells.
Cleverasitmayseem,writingemptytagsinthisabbreviatedwaymayconfuse
HTMLbrowsers.Toavoidcompatibilityproblems,youcanfooltheHTMLbrowsers
byplacingaspacebeforetheforwardslashinanemptyelementusingtheXHTML
versionofitsendtag.Forexample,use<br/>,withaspacebetweenthebrand/,
insteadoftheXHTMLequivalents<br/>and<br></br>.Table16-1containsallofthe
emptyHTMLtags,expressedintheiracceptableXHTML(transitionalDTD)forms.
Table16-1.HTMLemptytagsinXHTMLformat
<area/> <base/> <basefont/>
<br/> <col/> <frame/>
<hr/> <img/> <input/>
<isindex/> <link/> <meta/>
<param/>
16.3.4.CaseSensitivity
Ifyouthoughtgettingallthoseendtagsintherightplaceandcleaningupthe
occasionalnestingerrorwouldmakewritingXHTMLdocumentsdifficult,holdon
toyourhat.XHTMLiscase-sensitiveforalltagandattributenames.InanXHTML
document,<a>and<A>aredifferenttags;srcandSRCaredifferentattributes,and
soaresRcandSrC!HowforgivingHTMLseemsnow.
TheXHTMLDTDdefinesallformerHTMLtagsandattributesusinglowercase
letters.UppercasetagorattributenamesarenotvalidXHTMLtagsorattributes.
ThiscanbeadifficultsituationforanyauthorwishingtoconvertexistingHTML
documentsintoXHTML-compliantones.Lotsofwebpagesuseuppercasetagand
attributenames,tomakethemstandoutfromthesurroundinglowercase
content.
Tobecomecompliant,allthosenamesmustbeconvertedtolowercaseeventhe
onesyouusedinyourCSSstylesheetdefinitions.Fortunately,it'seasyto
accomplishthiskindofchangewithvariouseditingtools,andXHTMLauthoring
systemsshouldperformtheconversionforyou.
16.3.5.QuotedAttributeValues
Asifallthosecase-sensitiveattributenamesweren'taggravatingenough,XHTML
requiresthatyouencloseeveryattributevalueeventhenumericonesindouble
quotes.InHTML,youcouldquoteanythingyourheartdesired,butquotemarks
arerequiredonlyiftheattributevalueincludedwhitespaceorotherspecial
characters.TobeXHTMLcompliant,everyattributemustbeenclosedinquotes.
Forexample:
<tablerows=3>
iswronginXHTML.Itiscorrectlywrittenas:
<tablerows="3">
16.3.6.ExplicitAttributeValues
WithinHTML,thereareasmallnumberofattributesthathavenovalue.Instead,
theirmerepresencewithinatagcausesthattagtobehavedifferently.Ingeneral,
theseattributesrepresentasortofon/offswitchforthetag,likethecompact
attributeforthevariouslisttagsortheismapattributeforthe<img>tag.
InXHTML,everyattributemusthaveavalue.Thosewithoutvaluesmustuse
theirownnames.Thus,compactinXHTMLiscorrectlyspecifiedas
compact="compact",andcheckedbecomeschecked="checked".Eachmustcontainthe
requiredattributevalueenclosedinquotes.Table16-2containsalistofattributes
withtherequiredXHTMLvalues.
Table16-2.XHTMLvaluesforvaluelessHTMLattributes
checked="checked" compact="compact" declare="declare"
defer="defer" disabled="disabled" ismap="ismap"
multiple="multiple" noresize="noresize" noshade="noshade"
nowrap="nowrap" readonly="readonly" selected="selected"
BeawarethatthisattributevaluerequirementmaycausesomeoldHTML
browserstoignoretheattributealtogether.Allthemodernbrowsersdon'thave
thatproblem,sothevastmajorityofuserswon'tnoticeanydifference.Thereis
nogoodsolutiontothisproblem,otherthandistributingHTML4.0-compliant
browserstotheneedy.
16.3.7.HandlingSpecialCharacters
XHTMLismoresensitivethanHTMLtotheuseofthe<and&charactersin
JavaScriptandCSSdeclarationswithinyourdocuments.InHTML,youcanavoid
potentialconflictsbyenclosingyourscriptsandstylesheetsincomments(<!--and
-->).XMLbrowsers,however,maysimplyremoveallthecontentsofcomments
fromyourdocument,therebydeletingyourhiddenscriptsandstylesheets.
ToproperlyshieldyourspecialcharactersfromXMLbrowsers,encloseyourstyles
orscriptsinaCDATAsection.ThistellstheXMLbrowserthatanycharacters
containedwithinareplainoldcharacters,withoutspecialmeanings.Forexample:
<scriptlanguage="JavaScript">
<![CDATA[
...JavaScripthere...
]]>
</script>
Thisdoesn'tsolvetheproblem,though.HTMLbrowsersignorethecontentsofthe
CDATAXMLtagbuthonorthecontentsofcomment-enclosedscriptsand
stylesheets,whereasXMLbrowsersdojusttheopposite.Werecommendthatyou
putyourscriptsandstylesinexternalfilesandreferencetheminyourdocument
withappropriateexternallinks.
SpecialcharactersinattributevaluesareproblematicinXHTML,too.Inparticular,
youalwaysshouldwriteanampersandwithinanattributevalueusing&and
notsimplyan&character.Similarly,playitsafeandencodeless-thanandgreater-
thansignsusingtheir<and>entities.Forexample,while:
<imgsrc=seasonings.gifalt="Salt&pepper">
isperfectlyvalidHTML,youmustwriteitas:
<imgsrc="seasonings.gif"alt="Salt&pepper"/>
forittobecompliantXHTML.
16.3.8.TheidandnameAttributes
EarlyversionsofHTMLusedthenameattributewiththe<a>tagtocreatea
fragmentidentifierinthedocument.ThisfragmentcouldthenbeusedinaURLto
refertoaparticularspotwithinadocument.Thenameattributewaslateraddedto
othertags,suchas<frame>and<img>,allowingthoseelementstobereferencedby
namefromotherspotsinthedocument.
WithHTML4.0,theW3Caddedtheidattributetoalmosteverytag.Likename,id
letsyouassociateanidentifierwithnearlyanyelementinadocumentforlater
referenceanduse,perhapsbyahyperlinkorascript.
XHTMLhasastrongpreferencefortheidattributeastheanchorofchoicewithin
adocument.Thenameattributeisdefinedbutformallydeprecatedforthose
elementsthathavehistoricallyusedit.WithwidespreadsupportofHTML4.0now
inplace,youshouldbegintoavoidthenameattributewherepossibleandinstead
usetheidattributetobindnamestoelementsinyourdocuments.Ifyoumust
usethenameattributeoncertaintags,includeanidenticalidattributetoensure
thatthetagwillbehavesimilarlywhenprocessedbyastrictXHTMLbrowser.
16.4.XHTML1.1
InMay2001,theW3CreleasedanupdatedtheXHTMLstandard,XHTML1.1.
Whilemoststandardsexpandupontheirpreviousversions,XHTML1.1takesthe
unusualstepofdefiningamorerestrictiveversionofXHTML.Ifyouthinkof
XHTML1.0asunwieldy,picky,andtimeconsuming,you'llfindXHTML1.1even
moreso.Inouropinion,XHTML1.1isanexampleofthestandardsprocesstaken
toabsurdlevels,definingastandardthatmaybeacademicallypurebutis
essentiallyunusable.
16.4.1.DifferencesinXHTML1.1
XHTML1.1beginswiththeXHTML1.0strictDTDandmakesafewmodifications.
BysupportingonlythestrictversionofXHTML1.0,version1.1eliminatesall
deprecatedelementsandallbrowserextensionsstillincommonuseontheWeb.
Italsomakesthefollowingminorchanges:
Thelangattributehasbeenremovedfromeveryelement.Instead,authors
shouldusethexml:langattribute.
Thenameattributehasbeenremovedfromthe<a>and<map>elements.Authors
shouldusetheidattributeinitsplace.
Finally,theXHTML1.1standarddefinesanewsetofelementsthatimplementa
typographicfeatureknownasrubytext.Rubytextisshortrunsoftextplaced
alongsidethebasetext;itisoftenusedtoannotatethetextortoindicate
pronunciation.RubytexthasitsrootsinEastAsiandocuments,particularly
ChineseschoolbooksandJapanesebooksandmagazines.Rubytextistypically
displayedinasmallerfont[*]thanthebasetextandfollowscertainalignment
rulestoensurethatitappearsadjacenttotheappropriatebasetextelement.
[*]Theoriginofthename"ruby"liesinthenamethatprintersuseforthe5.5-pointfontusedbytheBritishpresstoset
thissmalleradjacenttext.
Youdefineandmanagerubytextwithasetofelementsthatprovidesgrouping
andlayoutcontrol.We'llbeblunt:thisnewfeatureissoesotericandofsolittle
importancetothevastmajorityofHTMLauthorseventhosewhowouldsubject
themselvestotheneedlessagonyofXHTML1.1conformancethatitdoesnot
warrantextensivecoverageinthisbook.Thosewhoareinterestedcanfinda
completediscussionofrubytextathttp://www.w3.org/TR/ruby.
Fortherestofus,itissufficienttoknowthatthereareafewnewelementsin
XHTML1.1thatyouwouldbewisenottouseinyourownDTDs,ifonlytoprevent
confusionwiththeXHTML1.1DTD.Thesenewelementsare:
<ruby>
Definesasegmentofrubytext
<rb>
Definestherubybasetext
<rt>
Definestherubytextassociatedwiththebasetext
<rp>
Isusedasa"rubyparenthesis"togrouprelatedrubyelements
<rbc>
Servesasarubybasetextcontainertogroupseveralbasetextelements
<rtc>
Servesasarubytextcontainertogroupseveralrubyelements
Shouldyouencounteranyoftheseelementsinadocument,refertothe
aforementionedspecificationfordetailsonhowtheyareused.Ingeneral,you'll
findasingleouter<ruby>elementwithatleastone<rb>and<rt>elementwithinit.
Youcancollectmultiple<rb>and<rt>elementswithinan<rp>elementorgroup
themwithinthe<rbc>or<rtc>containerelement.
16.5.ShouldYouUseXHTML?
ForadocumentauthorusedtoHTML,XHTMLisclearlyamorepainfuland
certainlyalessforgivingdocumentmarkuplanguage.Whereasatonetimewe
pridedourselvesonbeingabletocrankoutHTMLwithpencilandpaper,it'smuch
moretedioustowriteXHTMLwithoutspecialdocument-preparationapplications.
Whyshouldanyauthorwanttotakeonthatextrabaggage?
16.5.1.TheDustyDeckProblem
Overjustafewyears,authorshavegeneratedbillionsuponbillionsofwebpages.
Itisasafebetthatthemajorityofthesepagesarenotcompliantwithany
definedversionofHTML.Itisanevensaferbetthatthevastmajorityofthese
pagesarenotXHTMLcompliant.
TheharshrealityisthatthesebillionsofpageswillneverbeconvertedtoXHTML.
Whohasthetimetogoback,rootouttheseoldpages,andtweakthemtomake
themXHTMLcompliantespeciallywhentheendresult,asperceivedbytheuser,
willnotchange?LikethedustydecksofCOBOLprogramsthatlayunchangedfor
decadesbeforeY2Kforcedprogrammerstobringthemuptosnuff,thesedusty
decksofwebpageswillalsolieuntoucheduntilasimilarlydramaticeventforces
ustoupdatethem.
However,thedusty-deckproblemisnoexcusefornotwritingcompliant
documentsgoingforward.Leavethoseolddocumentsalone,butdon'tcreatea
newconversionproblemeverytimeyoucreateanewdocument.Alittleeffort
nowwillhelpyourdocumentsworkacrossawiderrangeofbrowsersinthe
future.
16.5.2.AutomaticConversion
Ifyoursenseofresponsibilityleadsyoutoundertaketheconversionofyour
existingHTMLdocumentsintoXHTML,you'llfindautilitynamedTidytobe
exceptionallyuseful.WrittenbyDaveRaggett,oneofthemoversandshakersat
theW3C,itautomatesasignificantamountoftheworkrequiredtoconvertHTML
documentsintoXHTML.
WhileTidy'scapabilitiesaretoovariedandwonderfultobefullylistedhere,we
canatleastassureyouthatTidycandetectandcorrectcaseconversion,quoted
attributes,andproperelementnesting.Forthecompletelistoffeaturesandthe
latestversionofTidyforvariouscomputingplatforms,visit
http://tidy.sourceforge.net.
16.5.3.LenientBrowsersandLazyAuthors
Thereisagoodruleofthumbregardingdatasharing,especiallyontheInternet:
belenientinwhatyouacceptandstrictinwhatyouproduce.Thisisanota
commentaryonsocialpolicy,butratherapragmaticadmonitiontotolerate
ambiguityanderrorsindatayoureceivewhilemakingsurethatanythingyou
sendisscrupulouslycorrect.
Webbrowsersaregoodexamplesoflenientacceptors.Mostcurrentwebpages
havesomesortoferrorinthem,albeitoftenjustanerrorofomission.
Nonetheless,browsersaccepttheerrorandpresentareasonabledocumenttothe
user.Thisleniencyletsauthorsgetawaywithallsortsofthings,oftenwithout
evenknowingthey'vemadeamistake.
Mostauthorsstopdevelopingapagewhenitlooksgoodandworksthewaythey
wantitto.VeryfewtakethetimetoruntheirpagesthroughthevariousHTML-
compliancetoolstocatchpotentialerrors.Manyofthosewhodotrytotestfor
compliancearesooverwhelmedbythenumberofminorerrorstheyhave
committedthattheysimplygiveupandcontinuetocreatebadpagesthatcanbe
handledbygoodbrowsers.
Becausethenumberofbadpagescontinuestogrow,browserscannotaffordto
startbeingstrict.Anybrowserthattriedtoenforceeventhemostbasicrulesof
theHTMLstandardwouldbeabandonedbyuserswhowanttoseewebpages,not
errormessages.Aviciouscycleensues:badpagesforcetheuseoflenient
browsers,whichencouragethecreationofmorebadpages.Breakthecycleby
vowingtocreateonlyXHTML-compliantcontentwheneveryoucan.
16.5.4.Time,Money,andStandards
XHTMLwasdevelopedasanXMLrepresentationoftheHTMLstandard.Itis
intended,goingforward,tobecomethesinglestandardeveryoneshoulduseto
createcontentfortheWeb.
Inaperfectworld,standardsareuniversallyadoptedandused.Fullcomplianceis
requiredofanydocumentbeforeitisplacedontheWeb.Conversionoflegacy
documentsisdoneimmediately.
Intherealworld,ashortageoftimeandmoneypreventstheuniversaluseof
standards.Underpressuretoquicklydeliversomethingthatworks,developers
turnoutpagesthatworkonlywellenough.Becausebrowsersallowsecond-rate
contenttoexistontheWeb,theneedtocomplywithastandardbecomesa
secondaryissueonethatistooquicklyignoredinthedizzyingpaceofweb
development.
16.5.5.ManVersusMachine
Allisnotlost,however.WhileXHTMLispainfulandtediousforhumanstocreate,
itisquiteeasyformachinestocreate.Thenumberofweb-authoringtools
continuestoincrease,andthepagescreatedbythesemachinesshouldbe
completelyXHTMLcompliant.Whileitdoesn'tmakemucheconomicsensefora
webauthortospendalotoftimegettingallthoseendtagsintherightspot,it
doesmakesensefortheprogrammerdevelopinganauthoringtooltoensurethat
thetoolgeneratesallthosecorrectendtags.Theeffortthewebauthorexpendsis
leveragedexactlyonceforeachpage;theeffortofthetoolcreatorisleveraged
overandover,eachtimethetoolproducesanewpage.
ItseemsthattherealfutureofXHTMLliesintherealmofmachine-generated
content.XHTMLisfartoopickytobesuccessfullyusedbythemillionsofcasual
webauthorswhocreatesmallsites.However,ifthosesameauthorsuseatoolto
createtheirpages,theycouldbegeneratingXHTML-compliantpagesandnever
evenknowit.
Ifyouareamongthatsmallcommunityofdeveloperswhocreatetoolsthat
generateHTMLoutput,youaredoingagreatdisservicetoyourmanypotential
customersifyourtooldoesnotgenerateexcruciatinglycorrectXHTML-compliant
output.ThereisnotechnicalexcuseforanytoolnottogenerateXHTML-compliant
output.Iftherearecompatibilityissuessurroundinghowtheoutputmightbe
used(withanonXHTMLbrowser,perhaps),thetoolshouldprovideaswitchthat
letstheauthorselectXHTML-compliantoutputasanoption.
16.5.6.WhattoDo?
WerecommendthatallHTMLauthorstakethetimetoabsorbthedifferences
betweenHTMLandXHTMLoutlinedinthischapter.Giventheresourcesand
opportunity,youshouldtrytocreateXHTML-compliantpageswhereverpossible
forthesitesyouarecreating.Certainlyyoushouldchooseauthoringtoolsthat
supportXHTMLandgiveyoutheoptionofgeneratingXHTML-compliantpages.
Oneday,XHTMLmayreplaceHTMLastheofficialstandardlanguageoftheWeb.
Evenso,thenumberofnoncompliantpagesontheWebisoverwhelming,forcing
browserstohonoroldHTMLconstructsandfeaturesforatleastthenextfive
years.Forbetterorworse,HTMLisheretostayasthedefactostandardforweb
authorsforyearstocome.
Chapter17.Tips,Tricks,andHacks
We'vesprinkledanumberoftips,tricks,andhacksthroughoutthisbook,along
withstyleguidelines,examples,andinstructions.Sowhyhaveaspecialchapter
ontips,tricks,andhacks?BecauseHTMLandXHTMLarethelanguages,albeit
constrained,thatmaketheWebtheexcitingplacethatitis,andinterested
readerswanttoknow,"HowdoIdothecoolstuff?"
17.1.TopoftheTips
ThemostimportanttipforevenveteranauthorsistosurftheWebyourself.We
canshowandexplainafewneattrickstogetyoustarted,buthundredsof
thousandsofauthorsouttherearecombiningandrecombiningHTMLandXHTML
tagsandjugglingcontenttocreatecompellingandusefuldocuments.
Allthepopularbrowsersprovideawaytoviewthesourceforthewebpagesthat
youdownload.Examine(don'tsteal)themforhowtheycreatetheeye-catching
andeffectivefeatures,andusethemtoguideyourowncreations.Getafeelfor
themoreeffectivewebcollections.Howaretheirdocumentsorganized?How
largeiseachdocument?
Wealllearnfromexperience,sogogetit!
17.1.1.DesignforYourAudience
Werepeatedlyarguethroughoutthisbookthatcontentmattersmost,notlook.
Butthatdoesn'tmeanpresentationdoesn'tmatter.
Effectivedocumentsmatchyourtargetaudience'sexpectations,givingthema
familiarenvironmentinwhichtoexploreandgatherinformation.Serious
academicians,forinstance,expectajournal-likeappearanceforatreatiseonthe
physiologyofthekumquat:longonmeaningfulwords,figures,anddiagramsand
shortonfrivoloustrappingslikecutebulletsandfontabuse.Don'tinsultthe
reader'seye,exceptwhenexercisingartisticlicensetojarortoattackyour
reader'ssensibilities.Byanticipatingyouraudienceanddesigningyourdocuments
toappealtotheirtastes,youalsosubtlydeflectunwantedsurfersfromyour
pages.
Forinstance,usesubtlecolorsandmutedtexttransitionsbetweensectionsfora
classicalartmuseum'scollection,tomimicthehushedenvironmentofareal
classicalartmuseum.Thetypicalrock'n'roll-crazedweb-surfermaniacprobably
won'ttakemorethanaglanceatyoursite,butthemillionaireartspatronmight.
Also,useeffectivelayouttogentlyguideyourreaders'eyestoareasofinterestin
yourdocuments.Dothat,byadheringtothebasicrulesofdocumentlayoutand
design,suchasplacingfiguresanddiagramsnear(ifnotinlinewith)theircontent
references.Nothing'sworsethanhavingtoscrollupanddownthebrowser
windowinadesperatesearchforapicturethatcanexplaineverything.
Wewon'tlieandsuggestthatwe'redesignexperts.Wearen't,butthey'renot
hardtofind.So,anothertipfortheseriouswebpageauthoristoseek
professionalhelp.Thebestsituationistohavedesignexperienceyourself.Next
bestistohaveaprolookingoveryourshoulder,oratleastsomewherewithin
earshot.
Makeatriptoyourlocallibraryanddosomereadingonyourown,too.Better
yet,browsethevariousonlineguides.CheckoutWebDesigninaNutshellby
JenniferNiederstRobbins(O'Reilly).Yourreaderswillbegladyoudid.[Toolsfor
theWebDesigner,1.6]
17.1.2.ConsistentDocuments
Thenextbesttipwecangiveyouistoreuseyourdocuments.Don'tstartfrom
scratcheachtime.Rather,developaconsistentframework,eventothepointofa
contentoutlineintowhichyouaddthedetailandcharacterforeachpage.And
endeavortocreateCSS2-basedstylesheetssothatthelookandfeelofyour
documentsremainsconsistentacrossyourcollection.
17.2.CleaningUpAfterYourHTMLEditor
AlthoughyoucancreateandeditHTML/XHTMLdocumentswithatexteditor,such
asviorNotepad,mostHTMLauthorsuseanapplicationthatisdesignedfor
creatingwebpagesseveralarefreeofcharge,manyofferafreeevaluationperiod,
andmostareavailablefordownloadovertheWeb.Beforewarned,though;inour
experience,youwillrarely(ifever)beabletocreateawebdocumentfromoneof
theseeditorswithouthavingtoinspect,addto,edit,andsometimesevenrepair
thesourceHTMLthattheeditorgenerates.Thefollowingsectionsdiscussafew
thingsthatyoushouldknowaboutandwatchoutfor.
17.2.1.WhereDidMyDocumentGo?
OneofthefirstthingsyouwillnoticeisthatmanyoftheHTMLeditors
automaticallyintroduceintoyourdocumentmarkupthatyoudidnotexplicitly
selectorwrite.RememberthisverysimpleHTMLdocumentthatwestartedwith
inChapter2?
<html>
<head>
<title>MyfirstHTMLdocument</title>
</head>
<body>
<h2>MyfirstHTMLdocument</h2>
Hello,<i>WorldWideWeb!</i>
<!--No"Hello,World"forus-->
<p>
Greetingsfrom<br>
<ahref="http://www.ora.com">O'ReillyMedia</a>
<p>
Composedwithcareby:
<cite>(insertyournamehere)</cite>
<br>©2000andbeyond
</body>
</html>
HereiswhatthesourcelookslikeafteryouloaditintoMicrosoftWordfromOffice
XP:
<htmlxmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<metahttp-equiv=Content-Typecontent="text/html;charset=windows-1252">
<metaname=ProgIdcontent=Word.Document>
<metaname=Generatorcontent="MicrosoftWord10">
<metaname=Originatorcontent="MicrosoftWord10">
<linkrel=File-Listhref="html_files/filelist.xml">
<title><html></title>
<!--[ifgtemso9]><xml>
<w:WordDocument>
<w:Compatibility>
<w:BreakWrappedTables/>
<w:SnapToGridInCell/>
<w:WrapTextWithPunct/>
<w:UseAsianBreakRules/>
</w:Compatibility>
<w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
</w:WordDocument>
</xml><![endif]-->
<style>
<!--
/*StyleDefinitions*/
p.MsoNormal,li.MsoNormal,div.MsoNormal
{mso-style-parent:"";
margin:0in;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:12.0pt;
font-family:"TimesNewRoman";
mso-fareast-font-family:"TimesNewRoman";}
p.MsoPlainText,li.MsoPlainText,div.MsoPlainText
{margin:0in;
margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.0pt;
font-family:"CourierNew";
mso-fareast-font-family:"TimesNewRoman";}
@pageSection1
{size:8.5in11.0in;
margin:1.0in65.95pt1.0in65.95pt;
mso-header-margin:.5in;
mso-footer-margin:.5in;
mso-paper-source:0;}
div.Section1
{page:Section1;}
-->
</style>
<!--[ifgtemso10]>
<style>
/*StyleDefinitions*/
table.MsoNormalTable
{mso-style-name:"TableNormal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-parent:"";
mso-padding-alt:0in5.4pt0in5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.0pt;
font-family:"TimesNewRoman";}
</style>
<![endif]-->
</head>
<bodylang=EN-USstyle='tab-interval:.5in'>
<divclass=Section1>
<pclass=MsoPlainText><html><o:p></o:p></p>
<pclass=MsoPlainText><head><o:p></o:p></p>
<pclass=MsoPlainText><title>MyfirstHTMLdocument</title><o:p></o:p></p>
<pclass=MsoPlainText></head><o:p></o:p></p>
<pclass=MsoPlainText><body><o:p></o:p></p>
<pclass=MsoPlainText><h2>MyfirstHTMLdocument</h2><o:p></o:p></p>
<pclass=MsoPlainText>Hello,<i>WorldWideWeb!</i><o:p></o:p></p>
<pclass=MsoPlainText><spanstyle='mso-spacerun:yes'></span><!--No
"Hello,World"forus--><o:p></o:p></p>
<pclass=MsoPlainText><p><o:p></o:p></p>
<pclass=MsoPlainText>Greetingsfrom<br><o:p></o:p></p>
<pclass=MsoPlainText><ahref="http://www.ora.com">O'Reilly
Media</a><o:p></o:p></p>
<pclass=MsoPlainText><p><o:p></o:p></p>
<pclass=MsoPlainText>Composedwithcareby:<o:p></o:p></p>
<pclass=MsoPlainText><cite>(insertyournamehere)</cite><o:p></o:p></p>
<pclass=MsoPlainText><br>&copy;2000andbeyond<o:p></o:p></p>
<pclass=MsoPlainText></body><o:p></o:p></p>
<pclass=MsoPlainText></html></p>
</div>
</body>
</html>
Yeow!Wheredidthedocumentgo?Excessivemarkupmakesthesourcedocument
almosthumanlyimpossibletoread.Whatinfuriatesdocumentpuristslikeus,
beyondthefactthatlotsofstuffthatweneitherwantednoraskedforwasadded,
isthatWordautomaticallytreatsanytextdocumentcontainingHTMLmarkupas
fodderforitsmill.Youcanremovethe.htmlor.htmsuffixfromthefilenameor
delete<html>and<head>fromthedocument,tonoavailWordwillstillgetyou.
Microsoftisn'taloneinclutteringthesource.MostHTMLeditorsaddatleasta
<meta>tagthatcontainstheirproductinformation.Manygothroughand"fix"your
documenttocomplywithcurrentstandardsandpractices,tooforexample,by
addingallthoseparagraphandlist-itemendtagsthatHTMLallowsyoutoomit.
(FromanXHTMLstandpoint,weadmitthatthismeddlingisprobablyvalid.)
Toitscredit,Wordrunswell,unlikeothertoolsthatroutinelycrashedwithout
warningaswefoughtwiththeirtreatmentofthemarkup.Microsoftevenoffersa
Wordplug-inthatremovestheadditionalmarkupsothatyoucanrecovera
reasonablefacsimileoftheoriginaldocument.[*]
[*]Youcanfindthisplug-inathttp://office.microsoft.com/downloads/2000/Msohtmf2.aspx.
17.2.2.WhenandWhytoEdittheEditor
NomatterhowgoodtheHTMLeditoris,you'llinevitablyhavetoeditthe(albeit
cluttered)sourceitgenerates.We'vehadtodoitalotourselves,andsohaveall
thewebdeveloperswe'vetalkedwithoverthelastfewyears.
NotallHTMLeditorsprovideaneasymeanstoaddJavaScripttoyourdocuments,
andmanyarenotup-to-datewiththeHTML/XHTMLandCSS2standards.
Remember,too,thatthepopularbrowsersdon'talwaysagreeonhowtheyrender
atag,andevendifferentversionsofthesamebrowsermaydiffer.Furthermore,
eventhebestHTMLeditorsdon'tnecessarilysupportextensionstothelanguage.
Sointothesourceyou'llhavetogo,whethertoincludesomeHTMLfeaturenot
yetsupportedbytheeditor(suchasanewCSS2property),toinsertanattribute
valueorkeyword,ortomodifyonesthattheeditoradded.
Thetipisthis:composefirst.Trytostartwithaclean,finisheddocument.
Concentrateoncontentfromtheoutset,andaddthespecialeffectslater.Usea
goodHTMLeditorfromthestart,orprepareyourdocumentsintwostepswithtwo
differenttoolsagoodcontenteditorfollowedbyagoodHTMLeditorparticularlyif
youplantodistributethedocumentinaformatotherthanHTML.
17.2.3.UsetheBest
Ifyoucomposewebpages,wecan'timagineyounotusinganHTMLeditorof
somesort.Theconvenienceisjusttoocompelling.Butchoosecarefully:some
HTMLeditorsareabysmal,andyou'llspendmoretimehuntingdownmisplaced
tagsanderrantattributesthanyou'llspendactuallycreatingthedocument.Top
tip:yougetwhatyoupayfor.
It'snosurprisethatHTMLeditorsvarygreatlyintheirfeatures.Manyeditorslet
youswitchthedisplayfromsourcetexttowhatmayappearwhenrenderedbya
browser.Somesimplyletyouaddtagsandmodifyattributevaluesthroughpull-
downmenusandhot-keyoptions.OthersareWYSIWYGlayouttoolsthatmakeit
easytoincludegraphicsandothermultimediacontent.Otheradvancedfeatures
includeembeddingandtestingappletsandscripts.
Ingeneral,HTMLeditorsfallintooneoftwocategories:eithertheyaregood
layouttools,includingadvancedstylingfeaturesandtoolsfordynamiccontent,or
theyexcelatcontentcreationandmanagement.Obviously,ifyouareproducing
flashy,commercialwebpagesthatrelyonadvancedlayouttechniquesandinclude
lotsofdifferentstylesanddynamiccontent,useagoodlayouttool.Ifyouare
producingacontent-richdocument,useatoolthatprovidesgoodeditorial
assistance.
Nomatterwhichtypeyouuse,therearesomecommonconsiderationstokeepin
mindwhenselectinganHTMLeditor:
Isitup-to-date?
NoHTMLeditorisyetentirelyup-to-datewiththecurrentstandards,
particularlyCSS2.Readtheproductspecificationsandupdateoften.
Doesitincludeasourceeditor?
AlthoughyoumayloadanHTMLeditor-generateddocumentintoadifferent
texteditortochangethesource,it'smuchmoreconvenientiftheeditoritself
letsyouviewandedittheHTMLsource.Also,makesurethatyourHTML
editordoesn'tautomatically"fix"yoursourceedits.
Isitmodifiable?
Ideally,theHTMLeditorshouldletyoucustomizeitsbehaviortofityour
specifications.Forexample,ataminimumyoushouldbeallowedtochoose
yourownfontcolors,styles,andbackgrounds,ifthoseareautomatically
includedintheeditor'sboilerplatedocument.
Isitaffordableandreliable?
Wecan'tstressenoughthatyougetwhatyoupayfor.Ifcreatingwebpagesis
morethanjustapassingfancy,getthebesteditoryoucanfind.Findonethat
iswellsupportedandwellreviewedbyotherHTMLauthors.Askaround,and
perhapsjoinanHTMLauthor'snewsgrouptogetthelatestscooponproducts.
17.3.TrickswithTables
Bydesign,tablesletauthorscreateappealing,accessibletablesofinformation.
Butthetabletagsalsocanbeexploitedtocreateinnovative,attractivepage
designsthatareotherwiseunattainableinstandardHTMLandXHTML.
17.3.1.MulticolumnPages
Oneverycommonandpopularpage-layoutelementmissingfromHTMLand
XHTMLismultiplecolumnsoftext.Here'satiponhowtousetablestoachieve
thateffect.[*]
[*]Okay,it'struethatearlierversionsofNetscapesupportedthe<multicol>extension.Nolonger.Thisisamore
universalsolution.
17.3.1.1.Basicmulticolumnlayout
Thebasictwo-columnlayoutusing<table>hasasingletablerowwiththreedata
cells:oneeachforthecolumnsoftextandaninterveningemptycelltomore
attractivelyseparatethetwocolumns.We'vealsoaddedalargecellspacing
attributevaluetocreateadditionalinterveningspacebetweenthecolumns.
ThefollowingexampleHTMLtableisanexcellenttemplateforasimpletwo-
columntextlayout:
<tableborder=0cellspacing=7>
<tr>
<td>Copyforcolumn1...
<td><br>
<td>Copyforcolumn2...
</table>
SeeFigure17-1fortheresults.
Figure17-1.Asimpletwo-columnlayout
Theonethingthebrowserswon'tdoisautomaticallybalancethetextinthe
columns,resultinginadjacentcolumnsofapproximatelythesamelength.You'll
havetoexperimentwithyourdocument,manuallyshiftingtextfromonecolumn
toanotheruntilyouachieveanicelybalancedpage.
Keepinmind,though,thatusersmayresizetheirdisplaywindows,andthe
columns'contentswillshiftaccordingly.Sodon'tspendalotoftimegettingthe
lastsentencesofeachcolumntolineupexactly;they'reboundtobeskewedin
otherbrowser-windowwidths.
Ofcourse,youcaneasilyconverttheexamplelayouttothreeormorecolumnsby
dividingthetextamongmorecellsinthetable.Butkeepinmindthatpageswith
morethanthreecolumnsmayprovedifficulttoreadonsmalldisplays,wherethe
actualcolumnwidthmightbequitesmall.
17.3.1.2.Straddleheads
Thebasicmulticolumnformatisjustthestart.Byaddingcellsthatspanacross
thecolumns,youcreateheadlines.Similarly,youcanmakefiguresspanacross
morethanonecolumn:simplyaddthecolspanattributetothecellcontainingthe
headlineorfigure.Figure17-2showsanattractivethree-columnlayoutwith
straddleheadsandaspanningfigure,createdfromthefollowingHTMLsource
withtabletags:
Figure17-2.Fancystraddleheadsandspanningfigureswith
HTMLtabletags
<tableborder=0cellspacing=7>
<tr>
<thcolspan=5><h2>TheHistoryoftheKumquat</h2>
<trvalign=top>
<tdrowspan=2>Copyforcolumn1...
<tdrowspan=2width=24><br>
<td>Copyforcolumn2...
<tdwidth=24><br>
<td>Copyforcolumn3...
<tr>
<tdcolspan=3align=center><imgsrc="pics/fruit.gif">
<p>
<i>TheNobleFruit</i>
</table>
Toachievethisnicelayout,weusedthecolspanattributeonthecellinthefirst
rowtospanallfivetablecolumns(threewithcopyandthetwointercolumn
spaces).Weusedtherowspanattributeonthefirstcolumnanditsadjacentcolumn
spacertoextendthecolumnsdownbesidethefigure.Thefigure'scellhasa
colspanattributesothatthecontentsspantheothertwocolumnsandintervening
spaces.
17.3.2.SideHeads
Theonlytext-headingfeaturesavailableinHTMLandXHTMLarethe<h1>tHRough
<h6>tags.Thesetagsarealwaysembeddedinthetextflow,separatingadjacent
paragraphsoftext.Throughmultiplecolumns,youcanachieveanalternative
stylethatplacesheadingsintoaseparatesidecolumn,runningvertically
alongsidethedocumenttext.
Figure17-3showsyouafairlyfancypairofsideheads,theresultofthefollowing
bitofsourceXHTMLtablecode:
Figure17-3.Tabletagscreatedthesesideheads
<table>
<tr>
<thwidth="20%"align="right">
<h3>Section1</h3></th>
<td></td>
<td>
Copyforsection1goesonandonabit
sothatitwilltakeupmorethanonelineinthe
tablecellwindow...</td>
</tr>
<tr>
<thalign="right">
<h3>Section2</h3></th>
<td></td>
<td>
Copyforsection2goesonandonabit
sothatitwilltakeupmorethanonelineinthe
tablecellwindow...</td>
</tr>
</table>
Noticehowwecreatedreasonablyattractivesideheadssetofffromtheleft
marginofthebrowserwindowbyadjustingthefirstheadercell'swidthandright-
justifyingthecellcontents.
Justasinourmulticolumnlayout,theexampleside-headlayoutusesanempty
columntocreateaspacebetweenthenarrowleftcolumncontainingtheheading
andthewiderrightcolumncontainingthetextassociatedwiththatheading.It's
besttospecifythatcolumn'swidthasapercentageofthetablewidthinsteadof
explicitlyinnumbersofpixels,tomakesurethattheheadingcolumnscalestofit
bothwideandnarrowdisplaywindows.
17.3.3.BetterFormsLayout
OfallthefeaturesinHTMLandXHTML,formscryoutforbetterlayoutcontrol.
Unlikeotherstructuredelements,formslookbestwhenrenderedinafixedlayout
withprecisemarginsandverticalalignmentofelements.However,exceptfor
carefullyplanned,<pre>-formattedformsegments,thestandardsjustdon'tgiveus
anyspecialtoolstobettercontrolformslayout.Youcanaccomplishalotwith
stylesheets,butthatgetscomplicatedquickly.Instead,tablesprovideeasyforms
layout.
17.3.3.1.Basicformslayout
Yourformsalmostalwayslookbetterandareeasierforyourreaderstofollowif
youuseatabletostructureandaligntheelements.Forexample,youmightusea
verticalalignmenttoyourforms,withfieldlabelstotheleftandtheirrespective
formelementsalignedtoanadjacentverticalmarginontheright.Don'ttrythat
withjuststandardHTMLorXHTML.Rather,prepareaformthatcontainsatwo-
columntable.ThefollowingHTMLsourcedoesjustthat,asshowninFigure17-4:
Figure17-4.Alignyourformsnicelywithtables
<formmethod=postaction="http:/cgi-bin/process">
<table>
<tr>
<thalign=right>Name:
<td><inputtype=textsize=32>
<tr>
<thalign=right>Address:
<td><inputtype=textsize=32>
<tr>
<thalign=right>Phone:
<td><inputtype=textsize=12>
<tr>
<tdcolspan=2align=center>
<inputtype=submitvalue="Register">
</table>
</form>
Ofcourse,morecomplexformlayoutscanbemanagedwithtables,too.We
recommendthatyoufirstsketchtheformlayoutonpaperandplanhowvarious
combinationsoftableelements,includingrow-andcolumn-straddledtablecells,
mightbeusedtoaffectthelayout.
17.3.3.2.Buildingformswithnestedtables
Aswementionedearlier,youcanplaceatableinsideacellinanothertable.
Whilethisalonecanleadtosomeelaboratetabledesigns,nestedtablesalsoare
usefulformanagingasubsetofformelementswithinthelargertablecontaining
theentireform.Thebestapplicationforusinganestedtableinaformisfor
layingoutcheckboxesandradiobuttons.
Forexample,insertthefollowingrowcontainingatableintotheformtableinthe
previousexample.Itcreatesacheckboxwithfourchoices:
<tr>
<thalign=rightvalign=top>Preferences:
<td>
<table>
<tr>
<td><inputtype=checkboxname=pref>Lemons
<td><inputtype=checkboxname=pref>Limes
<tr>
<td><inputtype=checkboxname=pref>Oranges
<td><inputtype=checkboxname=pref>Kumquats
</table>
Figure17-5showsyouhowthisnestedtableattractivelyformatsthecheckboxes,
whichbrowserswouldotherwiserenderonasinglelineandnotwellaligned.
Figure17-5.Nestingtablestoformatelementsofaform
17.4.TrickswithWindowsandFrames
Forthevastmajorityoflinksinyourdocuments,you'llwantthenewlyloaded
documentdisplayedinthesamewindow,replacingthepreviousone.Thatmakes
sensebecauseyourusersusuallyfollowasequentialpaththroughyourcollection.
Butsometimesitmakessensetoopenadocumentinanewwindowsothatthe
newdocumentandtheolddocumentarebothdirectlyaccessibleontheuser's
screen.Ifthenewdocumentisrelatedtotheoriginal,forinstance,itmakes
sensetohavebothinview.Othertimes,youmightwanttoopenmorethanone
documentinmultiplewindowsinaframeset.Morecommonly,thenewdocument
startstheuserdownanewwebofdocuments,andyouwanthertoseeand
rememberwhereshecamefrom.
Regardlessofthereason,itiseasytoopenanewbrowserwindowfromyour
document.Allyouneedtodoisaddthetargetattributeintheappropriate
hyperlink(<a>)tag.
17.4.1.TargetingWindows
Wenormallyusethetargetattributetoloadadocumentintoaspecificframethat
we'venamedinaframeset.Italsoservestocreateanewwindow,byoneoftwo
methods:
Referenceanewname
Ifyouuseanameyouhaven'tpreviouslydefinedasthevalueforthetarget
attributeofahyperlink,thepopularbrowsersautomaticallycreateanew
windowwiththatnameandloadthereferenceddocumentintothatwindow.
Thisisthepreferredwaytocreatenewwindowsbecauseyoucan
subsequentlyusethenametoloadotherdocumentsintothesamewindow.
Usingthistechnique,youcancontrolwhichdocumentgetsloadedwhere.
Createanunnamedwindow
Allthepopularbrowserssupportaspecialtargetnamed_blank[*]thatletsyou
createanewwindow.The_blankwindowhaslimiteduse,though,becauseitis
namelessyoucannotdirectanyotherdocumentsintothatwindow.(New
documentsloadedviahyperlinksselectedbytheuserwithinthewindowget
displayedinthatsamewindow,ofcourse.)
[*]Somebrowsersalsoacceptthename_new.Ifyoucan'tget_blanktoworkwithyourbrowser,
try_new.
17.4.2.OverridingOthers'Targets
Evervisitedasitewhosehomepageisaframedocumentthatnevergivesup?
Youknow,thekindthatleavesitsgreatbiglogoonthetopofthewindowandits
siteTOCrunningdownthesideofthedisplay,staringyouinthefacelongafter
you'vehyperlinkedawayfromthesite?Whatifyoursite'sframesetgetstrapped
intooneoftheirwindowframes?Whattodo?(Apparentlytheirwebmasters
haven'theardaboutthe_blanktarget.)
TheshortansweristouseJavaScripttoforceopenanewwindowforyour
documents.Butthat,too,ispotentiallyconfusingforusersbecausetheymay
alreadyhaveafullwindowreadyforyourdocument.So,toembellish,let
JavaScriptdiscoverwhetheryourpageisdestinedforacornerframeorforthe
wholewindow.
Hereisanexamplescriptthatloadsawebpagecalledindex2.htmlintoitsown
fullwindow.NotethatJavaScript-enabledbrowserswon'tletyoucleara
previouslyloadeddocumentdisplayunlessyourdocumentownsit.So,inthecase
wherethetargetisnotthewholewindow(i.e.,selfisnotwindow.top),theexample
scriptopensanewwindowthatbecomesthetargetforyourpages.Theusermay
choosetocloseyourdocumentwindowandreturntotheotherone,orviceversa:
<html>
<head>
<title>Ineedawindowofmyown</title>
<scriptlanguage="JavaScript">
<!--
if(self!=window.top)
window.open("http://www.kumquats.com/index2.html");
else
self.location.href="http://www.kumquats.com/index2.html";
//-->
</script>
</head>
<body>
Yourbrowserapparentlydoesn'tsupportJavaScript.Please
<ahref="http://www.kumquats.com/index2.html">hyperlinktooursitemanually.</a>
</body>
</html>
17.4.3.MultipleFramesinOneLink
Loadinganewdocumentfromahyperlinkisasnap,evenifyouputthenew
documentintoanalternativeframeorwindowfromitshyperlinkparent.
Occasionally,though,you'llwanttoloaddocumentsintotwoframeswhenthe
userclicksjustonelink.Withabitoftrickery,youcanloadtwoormoreframesat
once,providedtheyarearrangedacertainwayinthebrowserwindow.
Considerthisframelayout:
<framesetrows=2>
<framesetcols=2>
<framename=A>
<framename=B>
</frameset>
<frameset>
<framename=C>
<framename=D>
</frameset>
</frameset>
IfsomeoneclicksalinkinframeA,theonlythingyoucandoisupdateoneofthe
fourframes.SupposeyouwantedtoupdateframesBandDatthesametime.The
trickistoreplaceframesBandDwithasingleframe,likethis:
<framesetcols=2>
<framesetrows=2>
<framename=A>
<framename=C>
</frameset>
<framename=BD>
</frameset>
Aha!Nowyouhaveasingletargetinwhichtoloadasingledocument,frameBD.
ThedocumentyouloadshouldcontaintheoriginalframesBandDinonecolumn,
likethis:
<framesetcols=2>
<framename=B>
<framename=D>
</frameset>
ThetwoframesfillframeBD.WhenyouupdateframeBD,bothframesare
replaced,givingtheappearanceoftwoframesbeingupdatedatonce.
Thedrawbacktothisisthattheframesmustbeadjacentandabletobegrouped
intoasingledocument.Formostpages,though,thissolutionworksfairlywell.
We'veonlyscratchedthesurfaceofHTMLandXHTMLtipsandtrickshere.Our
advice:keephacking!
AppendixA.HTMLGrammar
Forthemostpart,browsersdonotrigidlyenforcetheexactsyntaxofanHTMLor
evenanXHTMLdocument.Thisgivesauthorswidelatitudeincreatingdocuments
andgivesrisetodocumentsthatworkonmostbrowsersbutactuallyare
incompatiblewiththeHTMLandXHTMLstandards.Ouradviceistosticktothe
standards,unlessyourdocumentsarefly-by-nightaffairs.
Thestandardsexplicitlydefinetheorderingandnestingoftagsanddocument
elements.ThissyntaxisembeddedwithintheappropriateDocumentType
Definition(DTD)andisnotreadilyunderstoodbythosewhoarenotversedin
StandardGeneralizedMarkupLanguage(SGML;fortheHTML4.01DTD,see
AppendixD)orExtensibleMarkupLanguage(XML;fortheXHTML1.0DTD,see
AppendixE).Accordingly,weprovideanalternatedefinitionoftheallowableHTML
andXHTMLsyntax,usingafairlycommontoolcalledagrammar.
Grammar,whetheritdefinesEnglishsentencesorHTMLdocuments,isjustaset
ofrulesthatindicatestheorderoflanguageelements.Theselanguageelements
canbedividedintotwosets:terminal(theactualwordsofthelanguage)and
nonterminal(allothergrammaticalrules).InHTMLandXHTML,thewords
correspondtotheembeddedmarkuptagsandtextinadocument.
Tousethegrammartocreateavaliddocument,followtheorderoftherulesto
seewherethetagsandtextmaybeplacedtocreateavaliddocument.
A.1.GrammaticalConventions
Weuseanumberoftypographicandpunctuationconventionstomakeour
grammareasytounderstand.
A.1.1.TypographicandNamingConventions
Forourgrammar,wedenotetheterminalswithamonospacedtypeface.The
nonterminalsappearinitalicizedtext.
Wealsouseasimplenamingconventionforthemajorityofournonterminals:ifa
nonterminaldefinesthesyntaxofaspecifictag,itsnameisthetagnamefollowed
by_tag.Ifanonterminaldefinesthevariouslanguageelementsthatmaybe
nestedwithinacertaintag,itsnameisthetagnamefollowedby_content.
Forexample,ifyouarewonderingexactlywhichelementsareallowedwithinan
<a>tag,youcanlookforthea_contentrulewithinthegrammar.Similarly,to
determinethecorrectsyntaxofadefinitionlistcreatedwiththe<dl>tag,lookfor
thedl_tagrule.
A.1.2.PunctuationConventions
Eachruleinthegrammarstartswiththerule'sname,followedbythe
replacementsymbol(::=)andtherule'svalue.We'veintentionallykeptthe
grammarsimple,butwedousethreepunctuationelementstodenotealternation,
repetition,andoptionalelementsinthegrammar.
A.1.2.1.Alternation
Alternationindicatesarulemayactuallyhaveseveraldifferentvalues,ofwhich
youmustchooseexactlyone.Pipes(|)separatethealternativesfortherule.
Forexample,theheadingruleisequivalenttoanyoneofsixHTMLheadingtags,so
itappearsinthetableas:
heading::=h1_tag
|h2_tag
|h3_tag
|h4_tag
|h5_tag
|h6_tag
Theheadingruletellsusthatwherevertheheadingnonterminalappearsinarule,
youcanreplaceitwithexactlyoneoftheactualheadingtags.
A.1.2.2.Repetition
Repetitionindicatesthatanelementwithinarulemayberepeatedsomenumber
oftimes.Repeatedelementsareenclosedincurlybraces({...}).Theclosingbrace
hasasubscriptednumberotherthan1iftheelementmustberepeateda
minimumnumberoftimes.
Forexample,the<ul>tagmaycontainonly<li>tags,oritmaybeempty.The
rule,therefore,is:
ul_tag::=<ul>
{li_tag}0
</ul>
Thisrulesaysthatthesyntaxofthe<ul>tagrequiresthe<ul>tagandzeroor
more<li>tags,followedbyaclosing</ul>tag.Wespreadthisruleacrossseveral
linesandindentedsomeoftheelementstomakeitmorereadable;your
documentsneednotactuallybeformattedthisway.
A.1.2.3.Optionalelements
Someelementsmayappearinadocumentbutarenotrequired.Optional
elementsareenclosedinsquarebrackets([...]).The<table>tag,forexample,
hasanoptionalcaption:
table_tag::=<table>
[caption_tag]
{tr_tag}0
</table>
Inaddition,therulesaysthatatablebeginswiththe<table>tag,followedbyan
optionalcaptionandzeroormoretable-rowtags,andendswiththe</table>tag.
A.1.3.MoreDetails
Ourgrammarstopsatthetaglevel;itdoesnotdelvefurthertoshowthesyntax
ofeachtag,includingtagattributes.Forthesedetails,refertothequick-
referencecardincludedwiththisbook.
A.1.4.PredefinedNonterminals
TheHTMLandXHTMLstandardsdefineafewspecifickindsofcontentthat
correspondtovarioustypesoftext.Weusethesecontenttypesthroughoutthe
grammar.Theyare:
literal_text
Textisinterpretedexactlyasspecified;nocharacterentitiesorstyletagsare
recognized.
plain_text
Regularcharactersinthedocumentcharacterencoding,alongwithcharacter
entitiesdenotedbytheampersandcharacter,arerecognized.
style_text
Likeplain_text,withphysicalandcontent-basedstyletagsallowed.
A.2.TheGrammar
ThegrammarisacompositeoftheHTML4.01andXHTML1.0standardtagsand
specialextensionstothelanguageascurrentlysupportedbythepopular
browsers.
Therulesareinalphabeticalorder.Thestartingruleforanentiredocumentis
namedhtml_document.
a_content[a] ::= heading
|text
a_tag ::= <a>
{a_content}0
</a>
abbr_tag ::= <abbr>text</abbr>
acronym_tag ::= <acronym>text</acronym>
address_content ::= p_tag
|text
address_tag ::= <address>
{address_content}0
</address>
applet_content ::= {<param>}0
body_content
applet_tag ::= <applet>applet_content</applet>
b_tag ::= <b>text</b>
basefont_tag ::= <basefont>body_content</basefont>
bdo_tag ::= <bdo>text</bdo>
big_tag ::= <big>text</big>
blink_tag ::= <blink>text</blink>
block ::= {block_content}0
block_content ::= <isindex>
|basefont_tag
|blockquote_tag
|center_tag
|dir_tag
|div_tag
|dl_tag
|form_tag
|listing_tag
|menu_tag
|multicol_tag
|nobr_tag
|ol_tag
|p_tag
|pre_tag
|table_tag
|ul_tag
|xmp_tag
blockquote_tag ::= <blockquote>body_content</blockquote>
body_content ::= <bgsound>
| <hr>
|address_tag
|block
|del_tag
|heading
|ins_tag
|layer_tag
|map_tag
|marquee_tag
|text
body_tag ::= <body>
{body_content}0
</body>
caption_tag ::= <caption>body_content</caption>
center_tag ::= <center>body_content</center>
cite_tag ::= <cite>text</cite>
code_tag ::= <code>text</code>
colgroup_content ::= {<col>}0
colgroup_tag ::= <colgroup>
colgroup_content
content_style ::= abbr_tag
|acronym_tag
|cite_tag
|code_tag
|dfn_tag
|em_tag
|kbd_tag
|q_tag
|strong_tag
|var_tag
dd_tag ::= <dd>flow</dd>
del_tag ::= <del>flow</del>
dfn_tag ::= <dfn>text</dfn>
dir_tag[b] ::= <dir>
{li_tag}
</dir>
div_tag ::= <div>body_content</div>
dl_content ::= dt_tagdd_tag
dl_tag ::= <dl>
{dl_content}
</dl>
dt_tag ::= <dt>
text
</dt>
em_tag ::= <em>text</em>
fieldset_tag ::= <fieldset>
[legend_tag]
{form_content}0
</fieldset>
flow ::= {flow_content}0
flow_content ::= block
|text
font_tag ::= <font>style_text</font>
form_content[c] ::= <input>
| <keygen>
|body_content
|fieldset_tag
|label_tag
|select_tag
|textarea_tag
form_tag ::= <form>
{form_content}0
</form>
frameset_content ::= <frame>
|noframes_tag
frameset_tag ::= <frameset>
{frameset_content}0
</frameset>
h1_tag ::= <h1>text</h1>
h2_tag ::= <h2>text</h2>
h3_tag ::= <h3>text</h3>
h4_tag ::= <h4>text</h4>
h5_tag ::= <h5>text</h5>
h6_tag ::= <h6>text</h6>
head_content ::= <base>
| <isindex>
| <link>
| <meta>
| <nextid>
|style_tag
|title_tag
head_tag ::= <head>
{head_content}0
</head>
heading ::= h1_tag
|h2_tag
|h3_tag
|h4_tag
|h5_tag
|h6_tag
html_content ::= head_tagbody_tag
|head_tagframeset_tag
html_document ::= html_tag
html_tag ::= <html>html_content</html>
i_tag ::= <i>text</i>
ilayer_tag ::= <ilayer>body_content</ilayer>
ins_tag ::= <ins>flow</ins>
kbd_tag ::= <kbd>text</kbd>
label_content[d] ::= <input>
|body_content
|select_tag
|textarea_tag
label_tag ::= <label>
{label_content}0
</label>
layer_tag ::= <layer>body_content</layer>
legend_tag ::= <legend>text</legend>
li_tag ::= <li>flow</li>
listing_tag ::= <listing>literal_text</listing>
map_content ::= {<area>}0
map_tag ::= <map>map_content</map>
marquee_tag ::= <marquee>style_text</marquee>
menu_tag[e] ::= <menu>
{li_tag}0
</menu>
multicol_tag ::= <multicol>body_content</multicol>
nobr_tag ::= <nobr>text</nobr>
noembed_tag ::= <noembed>text</noembed>
noframes_tag ::= <noframes>
{body_content}0
</noframes>
noscript_tag ::= <noscript>text</noscript>
object_content ::= {<param>}0
body_content
object_tag ::= <object>object_content</object>
ol_tag ::= <ol>
{li_tag}
</ol>
optgroup_tag ::= <optgroup>
{option_tag}0
</optgroup>
option_tag ::= <option>plain_text</option>
p_tag ::= <p>text</p>
physical_style ::= b_tag
|bdo_tag
|big_tag
|blink_tag
|font_tag
|i_tag
|s_tag
|small_tag
|span_tag
|strike_tag
|sub_tag
|sup_tag
|tt_tag
|u_tag
pre_content ::= <br>
| <hr>
|a_tag
|style_text
pre_tag ::= <pre>
{pre_content}0
</pre>
q_tag ::= <q>text</q>
s_tag ::= <s>text</s>
samp_tag ::= <samp>text</samp>
script_tag[f] ::= <script>plain_text</script>
select_content ::= optgroup_tag
|option_tag
select_tag ::= <select>
{select_content}0
</select>
server_tag[g] ::= <server>plain_text</server>
small_tag ::= <small>text</small>
span_tag ::= <span>text</span>
strike_tag ::= <strike>text</strike>
strong_tag ::= <strong>text</strong>
style_tag ::= <style>plain_text</style>
sub_tag ::= <sub>text</sub>
sup_tag ::= <sup>text</sup>
table_cell ::= td_tag
|th_tag
table_content ::= <tbody>
| <tfoot>
| <thead>
|tr_tag
table_tag ::= <table>
[caption_tag]
{colgroup_tag}0
{table_content}0
</table>
td_tag ::= <td>body_content</td>
text ::= {text_content}0
text_content ::= <br>
| <embed>
| <iframe>
| <img>
| <spacer>
| <wbr>
|a_tag
|applet_tag
|content_style
|ilayer_tag
|noembed_tag
|noscript_tag
|object_tag
|physical_style
|plain_text
textarea_tag ::= <textarea>plain_text</textarea>
th_tag ::= <th>body_content</th>
title_tag ::= <title>plain_text</title>
tr_tag ::= <tr>
{table_cell}0
</tr>
tt_tag ::= <tt>text</tt>
u_tag ::= <u>text</u>
ul_tag ::= <ul>
{li_tag}
</ul>
var_tag ::= <var>text</var>
xmp_tag ::= <xmp>literal_text</xmp>
[a]
[b]
[c]
[d]
[e]
[f]
[g]
[a]a_contentmaynotcontaina_tags;youmaynotnest<a>tagswithinother<a>tags.
[b]Theli_tagwithinthedir_tagmaynotcontainanyelementfoundinablock.
[c]form_contentmaynotcontainform_tags;youmaynotnestone<form>withinanother<form>.
[d]Aswiththe<form>tag,youcannotembed<form>or<label>tagswithina<label>tag.
[e]Theli_tagwithinthemenu_tagmaynotcontainanyelementfoundinablock.
[f]Ascript_tagmaybeplacedanywherewithinanHTMLdocument,withoutregardtosyntacticrules.
[g]Aserver_tagmaybeplacedanywherewithinanHTMLdocument,withoutregardtosyntacticrules.
AppendixB.HTML/XHTMLTagQuickReference
Inthisappendix,welistinalphabeticalorderalltheknown(andsome
undocumented)HTMLandXHTMLtagsandattributescurrentlysupportedbyone
ormoreoftoday'spopularbrowsers.
B.1.CoreAttributes
PriortoHTML4.0,fewattributescouldbeusedconsistentlyforalltheHTMLtags.
HTML4.0changedthis,definingasetof16coreattributesthatyoucanapplyto
almostalltheelementsinbothHTML4.01andXHTML1.0.Forbrevity,welist
thesecoreattributesinthissectionandspareyoutheredundanciesinthetable
thatfollows:
class=name Specifyastyleclasscontrollingtheappearanceofthetag'scontents.
dir=dir Specifytherenderingdirectionfortexteitherlefttoright(ltr)orrighttoleft(rtl).
id=name Defineareferencenameforthetagthatisuniqueinthedocument.
lang=language Specifythehumanlanguageforthetag'scontentswithanInternationalOrganizationfor
Standardization(ISO)639standardtwo-characternameandoptionaldialectsubcode.
onclick=applet Specifyanapplettobeexecutedwhentheuserclicksthemouseonthetag'scontentdisplayarea.
ondblclick=applet Specifyanapplettobeexecutedwhentheuserdouble-clicksthemousebuttononthetag's
contentdisplayarea.
onkeydown=applet Specifyanapplettobeexecutedwhentheuserpressesdownonakeywhilethetag'scontents
haveinputfocus.
onkeypress=applet Specifyanapplettobeexecutedwhentheuserpressesandreleasesakeywhilethetag's
contentshavefocus.
onkeyup=applet Specifyanapplettobeexecutedwhentheuserreleasesapressedkeywhilethetag'scontents
havefocus.
onmousedown=applet Specifyanapplettobeexecutedwhentheuserpressesdownonthemousebuttonwhilepointing
tothetag'scontentdisplayarea.
onmousemove=applet Specifyanapplettobeexecutedwhentheusermovesthemouseinthetag'scontentdisplay
area.
onmouseout=applet Specifyanapplettobeexecutedwhentheusermovesthemouseoffthetag'scontentdisplay
area.
onmouseover=applet Specifyanapplettobeexecutedwhentheusermovesthemouseintothetag'scontentdisplay
area.
onmouseup=applet Specifyanapplettobeexecutedwhentheuserreleasesthemousebuttonwhileinthetag's
contentdisplayarea.
style=style Specifyaninlinestyleforthetag.
title=string Specifyatitleforthetag.
Onlyasmallhandfuloftagsacceptnoneoronlysome,butnotall,ofthese
attributes.Theyare:
<applet> <base> <basefont>
<bdo> <br> <comment>
<embed> <font><frame>
<frameset> <head> <hr>
<html> <iframe> <isindex>
<keygen> <marquee><meta>
<nextid><nobr> <noembed>
<param> <script> <server>
<spacer> <style> <title>
<wbr>
Forconvenience,we'vemarkedeachofthesetagswithanasterisk(*)inthe
followingtable,andwelistalloftheattributessupportedbythesespecialtags,
includingthecommonones.Forallothertags(thosewithoutanasterisk),assume
thatthecommonattributeslistedpreviouslyapply.Donote,however,thatthe
popularbrowsersdonotsupportalloftheHTML4.0standardattributes,common
ornot.Pleaserefertothemaintextfordetails.
B.2.HTMLQuickReference
Weusethealerticon tothefarrightofeachitemtoindicatetagsand
attributesthatareextensionstotheHTML4.01andXHTML1.0standards.Weuse
theInternetExplorericon toidentifythoseextensiontagsandattributesthat
areuniquetoInternetExplorerandarenotwellsupportedbytheotherpopular
browsers.Eventhoughweincludetheminthemaintext,wehavenotincluded
hereanyoftheantiquatedorobsoleteelementsorattributesthatareexplicitly
notpartofthestandardsandarenolongersupportedbyanybrowser.
Weincludethepossibleattributes(somerequired)indentedbelowtheir
respectivetags.Inthedescription,wegivepossibleattributevaluesaseithera
rangeofintegernumbersoradefinitivelistofoptions,wherepossible.
<a>...</a> Createahyperlinkanchor(hrefattribute)orfragmentidentifier(idattribute).
accesskey=char Definethehot-keycharacterforthisanchor.
charset=encoding Specifythecharactersetusedtoencodethetarget.
coords=list Specifyalistofshape-dependentcoordinates.
href=url SpecifytheURLofahyperlinktarget.
HReflang=language Specifythelanguageencodingforthetarget.
name=name Specifythenameofafragmentidentifier.
rel=relationship Indicatetherelationshipofthisdocumenttothetarget.
rev=relationship Indicatethereverserelationshipofthetargettothisdocument.
shape=shape Definetheregion'sshapetobecirc,circle,poly,polygon,rect,orrectangle.
tabindex=value Definethepositionofthisanchorinthedocument'stabbingorder.
target=name Definethenameoftheframeorwindowtoreceivethereferenceddocument.
type=type SpecifytheMultipurposeInternetMailExtension(MIME)typeofthetarget.
<abbr>...</abbr> Theenclosedtextisanabbreviation.
<acronym>... Theenclosedtextisanacronym.
</acronym>
<address>...
</address> Theenclosedtextisanaddress.
<applet>...</applet> Defineanexecutableappletwithinatextflow. *
align=position Alignthe<applet>regiontoeitherthetop,middle,bottom(default),left,right,absmiddle,
baseline,orabsbottomofthetextintheline.
alt=string Specifyalternativetexttoreplacethe<applet>regionwithinbrowsersthatsupportthe
<applet>tagbutcannotexecutetheapplication.
archive=url Specifyaclassarchivetobedownloadedtothebrowserandthensearchedforcodeclass.
class=name Specifyastyleclasscontrollingtheappearanceofthistag.
code=class Specifytheclassnameofthecodetobeexecuted(required).
codebase=url SpecifytheURLfromwhichthecodeisretrieved.
height=nSpecifytheheight,inpixels,ofthe<applet>region.
hspace=nSpecifyadditionalspace,inpixels,toallowtotheleftandrightofthe<applet>region.
id=name Defineanameforthisappletthatisuniquetothisdocument.
mayscript AllowtheapplettoaccessJavaScriptwithinthepage.
name=name Specifythenameofthisparticularinstanceoftheapplet.
object=data Specifyarepresentationoftheobject'sexecutionstate.
style=style Specifyaninlinestyleforthistag.
title=string Provideatitlefortheapplet.
vspace=nSpecifyadditionalspace,inpixels,toallowaboveandbelowthe<applet>region.
width=nSpecifythewidth,inpixels,ofthe<applet>region.
<area> Defineamouse-sensitiveareainaclient-sideimagemap.
accesskey=char Definethehot-keycharacterforthisarea.
alt=string Providealternativetexttobedisplayedbynongraphicalbrowsers.
coords=list Specifyacomma-separatedlistofshape-dependentcoordinatesthatdefinetheedgeof
thisarea.
HRef=url SpecifytheURLofahyperlinktargetassociatedwiththisarea.
nohref Indicatethatnodocumentisassociatedwiththisarea;clickingintheareahasnoeffect.
notab Donotincludethisareainthetabbingorder.
onblur=applet Specifyanapplettoberunwhenthemouseleavesthearea.
onfocus=applet Specifyanapplettoberunwhenthemouseentersthearea.
shape=shape Definetheregion'sshapetobecirc,circle,poly,polygon,rect,orrectangle.
tabindex=value Definethepositionofthisareainthedocument'stabbingorder.
taborder=nSpecifythisarea'spositioninthetabbingorder.
target=name Specifytheframeorwindowtoreceivethedocumentlinkedbythisarea.
<b>...</b> Formattheenclosedtextusingaboldtypeface.
<base> SpecifythebaseURLforallrelativeURLsinthisdocument. *
href=url SpecifythebaseURL(required).
target=name Definethedefaulttargetofall<a>linksinthedocument.
<basefont> Specifythefontsizeforsubsequenttext(deprecated;donotuse). *
color=color Specifythebasefont'scolor.
face=name Specifythelocalfonttobeusedforthebasefont.
id=name Defineanameforthistagthatisuniquetothisdocument.
name=name Specifythelocalfonttobeusedforthebasefont.
size=value Setthebasefontsize,from1to7(required;defaultis3).
<bdo>...</bdo> Bidirectionaloverride,changingtherenderingdirectionoftheenclosedtext. *
class=name Specifyastyleclasscontrollingtheappearanceofthistag.
dir=dir Specifytherenderingdirectionfortexteitherlefttoright(ltr)orrighttoleft(rtl).
id=name Defineanameforthistagthatisuniquetothisdocument.
lang=language Specifythelanguageusedforthistag'scontentsusingastandardtwo-characterISO
languagename.
style=style Specifyaninlinestyleforthistag.
title=string Specifyatitleforthistag.
<bgsound> Definebackgroundaudioforthedocument.
loop=value Setthenumberoftimestoplaytheaudio;valuemaybeanintegerorthevalueinfinite.
src=url ProvidetheURLoftheaudiofiletobeplayed.
<big>...</big> Formattheenclosedtextusingabiggertypeface.
<blink>...</blink> Causetheenclosedcontenttoblink.
<blockquote>...
</blockquote> Theenclosedtextisablockquotation.
cite=url SpecifytheURLofthesourceofthequotedmaterial.
<body>...</body> Delimitthebeginningandendofthedocumentbody.
alink=color Setthecolorofactivehypertextlinksinthedocument.
background=url SpecifytheURLofanimagetobetiledinthedocumentbackground.
bgcolor=color Setthebackgroundcolorofthedocument.
bgproperties=value Withvaluesettofixed,preventthebackgroundimagefromscrollingwiththedocument
content.
leftmargin=value Setthesize,inpixels,ofthedocument'sleftmargin.
link=color Setthecolorofunvisitedhypertextlinksinthedocument.
onblur=applet Specifyanapplettoberunwhenthemouseleavesthedocumentwindow.
onfocus=applet Specifyanapplettoberunwhenthemouseentersthedocumentwindow.
onload=applet Specifyanapplettoberunwhenthedocumentisloaded.
onunload=applet Specifyanapplettoberunwhenthedocumentisunloaded.
text=color Setthecolorofregulartextinthedocument.
topmargin=value Setthesize,inpixels,ofthedocument'stopmargin.
vlink=color Setthecolorofvisitedlinksinthedocument.
<br> Breakthecurrenttextflow,resumingatthebeginningofthenextline. *
class=name Specifyastyleclasscontrollingtheappearanceofthistag.
clear=margin Breaktheflowandmovedownwarduntilthedesiredmargin,eitherleft,right,none,or
all,isclear.
id=name Defineanameforthistagthatisuniquetothisdocument.
style=style Specifyaninlinestyleforthistag.
title=string Specifyatitleforthistag.
<button> Createapush-buttonelementwithina<form>.
accesskey=char Definethehot-keycharacterforthisbutton.
disabled Disablethebutton,preventingtheuserfromclickingit.
name=name Specifythenameoftheparametertobepassedtotheforms-processingapplicationifthe
inputelementisselected(required).
onblur=applet Specifyanapplettoberunwhenthemousemovesoutofthebutton.
onfocus=applet Specifyanapplettoberunwhenthemousemovesintothebutton.
tabindex=nSpecifythiselement'spositioninthetabbingorder.
type=type Specifythebuttontypeeitherbutton,submit,orreset.
value=string Specifythevalueoftheparametersenttotheforms-processingapplicationifthisform
elementisselected(required).
<caption>...
</caption> Defineacaptionforatable.
align=position Setthehorizontalalignmentofthecaptiontoleft,center,orright.
valign=position Settheverticalpositionofthecaptiontoeithertoporbottom.
<center>...</center> Centertheenclosedtext.
<cite>...</cite> Theenclosedtextisacitation.
<code>...</code> Theenclosedtextisacodesample.
<col> Defineacolumnwithina<colgroup>.
align=position Setthecolumnalignmenttoleft,center,orright.
char=character Specifythealignmentcharacterfortextinthesecells.
charoff=value Settheoffsetwithinthecellatwhichthealignmentcharacterisplaced.
span=nDefinethenumberofcolumnsaffectedbythis<col>tag.
valign=position Settheverticalalignmentoftextwithinthecolumntotop,middle,orbottom.
width=nSetthewidth,inpixelsorasapercentage,ofthecolumn.
<colgroup> Defineacolumngroupwithinatable.
align=position Setthehorizontalalignmentoftextwithinthecolumnstoleft,center,orright.
char=character Specifythealignmentcharacterfortextinthesecells.
charoff=value Settheoffsetwithinthecellatwhichthealignmentcharacterisplaced.
span=nDefinethenumberofcolumnsinthegroup.
valign=position Settheverticalalignmentoftextwithinthecolumnstotop,middle,orbottom.
width=nSetthewidth,inpixelsorasapercentage,ofeachcolumninthegroup.
<comment>...
</comment> Placeacommentinthedocument(commentsarevisibleinallotherbrowsers). *
<dd>...</dd> Definethedefinitionportionofanelementinadefinitionlist.
<del>...</del> Delineateadeletedsectionofadocument.
cite=url Citeadocumentjustifyingthedeletion.
datetime=date Specifythedateandtimeofthedeletion.
<dfn>...</dfn> Formattheenclosedtextasadefinition.
<dir>...</dir> Createadirectorylistcontaining<li>tags.
type=bullet Setthebulletstyleforthislisttocircle,disc(default),orsquare.
<div>...</div> Createadivisionwithinadocument.
align=type Alignthetextwithinthedivisiontoleft,center,orright.
nowrap Suppresswordwrappingwithinthisdivision.
<dl>...</dl> Createadefinitionlistcontaining<dt>and<dd>tags.
compact Makethelistmorecompactifpossible.
<dt>...</dt> Definethedefinitiontermportionofanelementinadefinitionlist.
<em>...</em> Formattheenclosedtextwithadditionalemphasis.
<embed> Embedanapplicationinadocument. *
align=position Aligntheappletareatoeitherthetoporbottomoftheadjacenttext,ortotheleftorright
marginofthepage,withsubsequenttextflowingaroundtheapplet.
border=nSpecifythesize,inpixels,oftheborderaroundtheapplet.
height=nSpecifytheheight,inpixels,oftheapplet.
hidden Ifpresent,hidetheappletonthepage.
hspace=nDefine,inpixels,additionalspacetobeplacedtotheleftandrightoftheapplet.
name=name Provideanamefortheapplet.
palette=value
InNetscapeandOpera,avalueofforegroundcausestheapplettousetheforeground
palette(inWindowsonly),andbackgroundusesthebackgroundpalette;withInternet
ExplorerandFirefox,providetheforegroundandbackgroundcolorsfortheapplet,
specifiedastwocolorvaluesseparatedbyapipe(|).
src=url SupplytheURLofthedatatobefedtotheapplet.
type=type SpecifytheMIMEtypeoftheplug-intobeused.
units=type Settheunitsfortheheightandwidthattributestoeitherpixels(thedefault)oren(half
thetextpointsize).
vspace=nDefine,inpixels,additionalspacetobeplacedaboveandbelowtheapplet.
width=nSpecifythewidth,inpixels,oftheapplet.
<fieldset>...
</fieldset> Createagroupofelementsinaform.
<font>...</font> Setthesizeorcoloroftheenclosedtext(deprecated;donotuse). *
class=name Specifyastyleclasscontrollingtheappearanceofthistag.
color=color Setthecoloroftheenclosedtexttothedesiredcolor.
dir=dir Specifytherenderingdirectionfortexteitherlefttoright(ltr)orrighttoleft(rtl).
face=list Setthetypefaceoftheenclosedtexttothefirstavailablefontinthecomma-separatedlist
offontnames.
id=name Defineanameforthistagthatisuniquetothisdocument.
lang=language Specifythelanguageusedforthistag'scontentsusingastandardtwo-characterISO
languagename.
size=value Setthesizetoanabsolutesize,from1to7,orrelativetothe<basefont>size,using+nor
-n(required).
style=style Specifyaninlinestyleforthistag.
title=string Specifyatitleforthistag.
<form>...</form> Delimitaform.
accept-charset=list Specifyalistofcharactersetsacceptedbytheserverprocessingthisform.
action=url SpecifytheURLoftheapplicationthatprocessestheform(required).
enctype=encoding Specifyhowtheformelementvaluesareencoded.
method=style Specifytheparameter-passingstyleeithergetorpost(required).
name=name SupplyanameforthisformforusebyJavaScript.
onreset=applet Specifyanapplettoberunwhentheformisreset.
onsubmit=applet Specifyanapplettoberunwhentheformissubmitted.
target=name Specifythenameoftheframeorwindowtoreceivetheresultsoftheformafter
submission.
<frame>...</frame> Defineaframewithinaframeset. *
bordercolor=color Setthecoloroftheframe'sborder.
class=name Specifyastyleclasscontrollingtheappearanceofthistag.
frameborder=nIfvalueis1,enableframeborders;ifvalueis0,disableframeborders
id=name Defineanameforthistagthatisuniquetothisdocument.
longdesc=url ProvidetheURLofadocumentdescribingthecontentsoftheframe.
marginheight=nPlacenpixelsofspaceaboveandbelowtheframecontents.
marginwidth=nPlacenpixelsofspacetotheleftandrightoftheframecontents.
name=name Definethenameoftheframe.
noresize Disableuserresizingoftheframe.
scrolling=type Alwaysaddscrollbars(yes),neveraddscrollbars(no),or,forNetscapeonly,addscroll
barswhenneeded(auto).
src=url DefinetheURLofthesourcedocumentforthisframe.
style=style Specifyaninlinestyleforthistag.
title=string Specifyatitleforthistag.
<frameset>...
</frameset> Defineacollectionofframesorotherframesets. *
border=nSetthethicknessoftheframebordersinthisframeset.
bordercolor=color Definethecolorofthebordersinthisframeset.
cols=list Specifythenumberandwidthofframeswithinthisframeset.
frameborder=value Ifvalueis1,enableframeborders;ifvalueis0,disableframeborders.
framespacing=nDefinethethicknessoftheframebordersinthisframeset.
onblur=applet Defineanapplettoberunwhenthemouseleavesthisframeset.
onfocus=applet Defineanapplettoberunwhenthemouseentersthisframeset.
onload=applet Defineanapplettoberunwhenthisframesetisloaded.
onunload=applet Defineanapplettoberunwhenthisframesetisremovedfromthedisplay.
rows=list Specifythenumberandheightofframeswithinaframeset.
<hn>...</hn>Theenclosedtextisalevel-nheader,forlevelnfrom1to6.
align=type Specifytheheadingalignmentasleft(default),center,orright.
<head>...</head> Delimitthebeginningandendofthedocumenthead. *
dir=dir Specifytherenderingdirectionfortexteitherlefttoright(ltr)orrighttoleft(rtl).
lang=language Specifythelanguageusedforthistag'scontentsusingastandardtwo-characterISO
languagename.
profile=url ProvidetheURLofaprofileforthisdocument.
<hr> Breakthecurrenttextflowandinsertahorizontalrule. *
align=type Specifytherulealignmentasleft,center(default),orright.
class=name Specifyastyleclasscontrollingtheappearanceoftherule.
color=color Definethecoloroftherule.
dir=dir Specifytherenderingdirectionfortexteitherlefttoright(ltr)orrighttoleft(rtl).
id=name Defineanameforthistagthatisuniquetothisdocument.
lang=language
Specifythelanguageusedforthistag'scontentsusingastandardtwo-characterISO
languagename.
noshade Donotuse3Dshadingtorendertherule.
onclick=applet Specifyanapplettobeexecutedwhenthemousebuttonisclickedonthistag.
ondblclick=applet Specifyanapplettobeexecutedwhenthemousebuttonisdouble-clickedonthistag.
onkeydown=applet Specifyanapplettobeexecutedwhenakeyispresseddownwhilethistaghasinput
focus.
onkeypress=applet Specifyanapplettobeexecutedwhenakeyispressedandreleasedwhilethistaghas
focus.
onkeyup=applet Specifyanapplettobeexecutedwhenakeyisreleasedwhilethistaghasfocus.
onmousedown=applet Specifyanapplettobeexecutedwhenamousebuttonispresseddownonthistag.
onmousemove=applet Specifyanapplettobeexecutedwhenthemouseismovedoverthistag.
onmouseout=applet Specifyanapplettobeexecutedwhenthemousemovesoutofthistag'sdisplayarea.
onmouseover=applet Specifyanapplettobeexecutedwhenthemousemovesintothistag'sdisplayarea.
onmouseup=applet Specifyanapplettobeexecutedwhenamousebuttonisreleasedwhileoverthistag.
size=pixels Setthethicknessoftheruletoanintegernumberofpixels.
style=style Specifyaninlinestyleforthistag.
title=string Specifyatitleforthistag.
width=valueor%Setthewidthoftheruletoeitheranintegernumberofpixelsorapercentageofthepage
width.
<html>...</html> DelimitthebeginningandendoftheentireHypertextMarkupLanguage(HTML)document. *
dir=dir Specifytherenderingdirectionfortexteitherlefttoright(ltr)orrighttoleft(rtl).
lang=language Specifythelanguageusedforthistag'scontentsusingastandardtwo-characterISO
languagename.
version=string IndicatetheHTMLversionusedtocreatethisdocument.
<i>...</i> Formattheenclosedtextinanitalictypeface.
<iframe>...</iframe> Defineaninlineframe. *
align=position Setthepositionoftheframealignedtothetop,center,orbottomofthesurroundingtext,
orflushagainsttheleftorrightmarginswithsubsequenttextflowingaroundtheframe.
class=name Specifyastyleclasscontrollingtheappearanceoftheframe.
frameborder=value Ifvalueis1,enableframeborders;ifvalueis0,disableframeborders.
height=nSettheheight,inpixels,oftheframe.
id=name Defineanameforthistagthatisuniquetothisdocument.
longdesc=url ProvidetheURLofadocumentdescribingthecontentsoftheframe.
marginheight=nPlacenpixelsofspaceaboveandbelowtheframecontents.
marginwidth=nPlacenpixelsofspacetotheleftandrightoftheframecontents.
name=name Definethenameoftheframe.
scrolling=type Alwaysaddscrollbars(yes)orneveraddscrollbars(no).
src=url DefinetheURLofthesourcedocumentforthisframe.
style=style Specifyaninlinestyleforthistag.
title=string Specifyatitleforthistag.
width=nSetthewidth,inpixels,oftheframe.
<img> Insertanimageintothecurrenttextflow.
align=type Aligntheimagetothetop,middle,bottom(default),left,right,absmiddle,baseline,or
absbottomofthetext.
alt=text Providealternativetextfornonimage-capablebrowsers.
border=nSetthepixelthicknessoftheborderaroundimagescontainedwithinhyperlinks.
controls Addplaybackcontrolsforembeddedvideoclips.
dynsrc=url SpecifytheURLofavideocliptobedisplayed.
height=nSpecifytheheightoftheimageinscanlines.
hspace=nSpecifythespace,inpixels,tobeaddedtotheleftandrightoftheimage.
ismap Indicatethattheimageismouse-selectablewhenusedwithinan<a>tag.
longdesc=url ProvidetheURLofadocumentdescribingtheimage.
loop=value Setthenumberoftimestoplaythevideo;valuemaybeanintegerorthevalueinfinite.
lowsrc=url Specifyalow-resolutionimagetobeloadedbythebrowserfirst,followedbytheimage
specifiedbythesrcattribute.
name=name ProvideanamefortheimageforusebyJavaScript.
onabort=applet Provideanapplettoberunifimageloadingisaborted.
onerror=applet Provideanapplettoberunifimageloadingisunsuccessful.
onload=applet Provideanapplettoberunifimageloadingissuccessful.
src=url SpecifythesourceURLoftheimagetobedisplayed(required).
start=start Specifywhentoplaythevideoclipeitherfileopenormouseover.
usemap=url Specifythemapofcoordinatesandlinksthatdefinethehypertextlinkswithinthisimage.
vspace=nSpecifytheverticalspace,inpixels,addedatthetopandbottomoftheimage.
width=nSpecifythewidthoftheimageinpixels.
<inputtype=button> Createapush-buttonelementwithina<form>.
accesskey=char Definethehot-keycharacterforthiselement.
disabled Disablethiscontrol,makingitinactive.
name=name Specifythenameoftheparametertobepassedtotheforms-processingapplicationifthe
inputelementisselected(required).
notab Specifythatthiselementisnotpartofthetabbingorder.
onblur=applet Specifyanapplettoberunwhenthemouseleavesthiscontrol.
onfocus=applet Specifyanapplettoberunwhenthemouseentersthiscontrol.
tabindex=nSpecifythiselement'spositioninthetabbingorder.
taborder=nSpecifythiselement'spositioninthetabbingorder.
value=string Specifythevalueoftheparametersenttotheforms-processingapplicationifthisform
elementisselected(required).
<input
type=checkbox> Createacheckboxinputelementwithina<form>.
accesskey=char Definethehot-keycharacterforthiselement.
checked Marktheelementasinitiallyselected.
disabled Disablethiscontrol,makingitinactive.
name=string Specifythenameoftheparametertobepassedtotheforms-processingapplicationifthe
inputelementisselected(required).
notab Specifythatthiselementisnotpartofthetabbingorder.
readonly Preventusermodificationofthiselement.
tabindex=nSpecifythiselement'spositioninthetabbingorder.
taborder=nSpecifythiselement'spositioninthetabbingorder.
value=string Specifythevalueoftheparametersenttotheforms-processingapplicationifthisform
elementisselected(required).
<inputtype=file> Createafile-selectionelementwithina<form>.
accept=list SpecifyalistofMIMEtypesthatcanbeacceptedbythiselement.
accesskey=char Definethehot-keycharacterforthiselement.
disabled Disablethiscontrol,makingitinactive.
maxlength=nSpecifythemaximumnumberofcharacterstoacceptforthiselement.
name=name Specifythenameoftheparameterthatispassedtotheforms-processingapplicationfor
thisinputelement(required).
notab Specifythatthiselementisnotpartofthetabbingorder.
onblur=applet Specifyanapplettoberunwhenthemouseleavesthiscontrol.
onchange=applet Specifyanapplettoberunwhentheuserchangesthevalueofthiselement.
onfocus=applet Specifyanapplettoberunwhenthemouseentersthiscontrol.
readonly Preventusermodificationofthiselement.
size=nSpecifythenumberofcharacterstodisplayforthiselement.
tabindex=nSpecifythiselement'spositioninthetabbingorder.
taborder=nSpecifythiselement'spositioninthetabbingorder.
value=string Specifythevalueoftheparametersenttotheforms-processingapplicationifthisform
elementisselected(required).
<inputtype=hidden> Createahiddenelementwithina<form>.
name=name Specifythenameoftheparameterthatispassedtotheforms-processingapplicationfor
thisinputelement(required).
value=string Specifythevalueofthiselementthatispassedtotheforms-processingapplication.
<inputtype=image> Createanimageinputelementwithina<form>.
accesskey=char Definethehot-keycharacterforthiselement.
align=type Aligntheimagetothetop,middle,orbottomoftheformelement'stext.
alt=string Provideanalternativedescriptionfortheimage.
border=nSetthepixelthicknessoftheborderoftheimage.
disabled Disablethiscontrol,makingitinactive.
name=name Specifythenameoftheparametertobepassedtotheforms-processingapplicationfor
thisinputelement(required).
notab Specifythatthiselementisnotpartofthetabbingorder.
src=url SpecifythesourceURLoftheimage(required).
tabindex=nSpecifythiselement'spositioninthetabbingorder.
taborder=nSpecifythiselement'spositioninthetabbingorder.
usemap=url SpecifytheURLofamaptobeusedwiththisimage.
<input
type=password> Createacontent-protectedtext-inputelementwithina<form>.
accesskey=char Definethehot-keycharacterforthiselement.
disabled Disablethiscontrol,makingitinactive.
maxlength=nSpecifythemaximumnumberofcharacterstoacceptforthiselement.
name=name Specifythenameoftheparametertobepassedtotheforms-processingapplicationfor
thisinputelement(required).
notab Specifythatthiselementisnotpartofthetabbingorder.
onblur=applet Specifyanapplettoberunwhenthemouseleavesthiselement.
onchange=applet Specifyanapplettoberunwhentheuserchangesthevalueofthiselement.
onfocus=applet Specifyanapplettoberunwhenthemouseentersthiselement.
onselect=applet Specifyanapplettoberuniftheuserclicksthiselement.
readonly Preventusermodificationofthiselement.
size=nSpecifythenumberofcharacterstodisplayforthiselement.
tabindex=nSpecifythiselement'spositioninthetabbingorder.
taborder=nSpecifythiselement'spositioninthetabbingorder.
value=string Specifytheinitialvalueforthiselement.
<inputtype=radio> Createaradio-buttoninputelementwithina<form>.
accesskey=char Definethehot-keycharacterforthiselement.
checked Marktheelementasinitiallyselected.
disabled Disablethiscontrol,makingitinactive.
name=string Specifythenameoftheparametertobepassedtotheforms-processingapplicationifthe
inputelementisselected(required).
notab Specifythatthiselementisnotpartofthetabbingorder.
readonly Preventusermodificationofthiselement.
tabindex=nSpecifythiselement'spositioninthetabbingorder.
taborder=nSpecifythiselement'spositioninthetabbingorder.
value=string Specifythevalueoftheparametersenttotheforms-processingapplicationifthisform
elementisselected(required).
<inputtype=reset> Createaresetbuttonwithina<form>.
accesskey=char Definethehot-keycharacterforthiselement.
disabled Disablethiscontrol,makingitinactive.
notab Specifythatthiselementisnotpartofthetabbingorder.
tabindex=nSpecifythiselement'spositioninthetabbingorder.
taborder=nSpecifythiselement'spositioninthetabbingorder.
value=string Specifyanalternatelabelfortheresetbutton(defaultis"Reset").
<inputtype=submit> Createasubmitbuttonwithina<form>.
accesskey=char Definethehot-keycharacterforthiselement.
disabled Disablethiscontrol,makingitinactive.
name=name Specifythenameoftheparameterthatispassedtotheforms-processingapplicationfor
thisinputelement(required).
notab Specifythatthiselementisnotpartofthetabbingorder.
tabindex=nSpecifythiselement'spositioninthetabbingorder.
taborder=nSpecifythiselement'spositioninthetabbingorder.
value=string Specifyanalternatelabelforthesubmitbutton,aswellasthevaluepassedtotheforms-
processingapplicationforthisparameterifthisbuttonisclicked.
<inputtype=text> Createatext-inputelementwithina<form>.
accesskey=char Definethehot-keycharacterforthiselement.
disabled Disablethiscontrol,makingitinactive.
maxlength=nSpecifythemaximumnumberofcharacterstoacceptforthiselement.
name=name Specifythenameoftheparameterthatispassedtotheforms-processingapplicationfor
thisinputelement(required).
notab Specifythatthiselementisnotpartofthetabbingorder.
onblur=applet Specifyanapplettoberunwhenthemouseleavesthiselement.
onchange=applet Specifyanapplettoberunwhentheuserchangesthevalueofthiselement.
onfocus=applet Specifyanapplettoberunwhenthemouseentersthiselement.
onselect=applet Specifyanapplettoberuniftheuserclicksthiselement.
readonly Preventusermodificationofthiselement.
size=nSpecifythenumberofcharacterstodisplayforthiselement.
tabindex=nSpecifythiselement'spositioninthetabbingorder.
taborder=nSpecifythiselement'spositioninthetabbingorder.
value=string Specifytheinitialvalueforthiselement.
<ins>...</ins> Delineateaninsertedsectionofadocument.
cite=url Citeadocumentdissatisfyingtheinsertion.
datetime=date Specifythedateandtimeoftheinsertion.
<isindex> Createa"searchable"HTMLdocument(deprecated;donotuse). *
action=url ForInternetExploreronly,providetheURLoftheprogramthatperformsthesearching
action.
class=name Specifyastyleclasscontrollingtheappearanceofthistag.
dir=dir Specifytherenderingdirectionfortexteitherlefttoright(ltr)orrighttoleft(rtl).
id=name Defineanameforthistagthatisuniquetothisdocument.
lang=language Specifythelanguageusedforthistag'scontentsusingastandardtwo-characterISO
languagename.
prompt=string Provideanalternatepromptfortheinputfield.
style=style Specifyaninlinestyleforthistag.
title=string Specifyatitleforthistag.
<kbd>...</kbd> Theenclosedtextiskeyboard-likeinput.
<keygen> Generatekeyinformationinaform. *
challenge=string Provideachallengestringtobepackagedwiththekey.
name=name Provideanameforthekey.
<label>...</label> Definealabelforaformcontrol.
accesskey=char Definethehot-keycharacterforthislabel.
for=id Specifytheformelementassociatedwiththislabel.
onblur=applet Specifyanapplettoberunwhenthemouseleavesthislabel.
onfocus=applet Specifyanapplettoberunwhenthemouseentersthislabel.
<legend>...</legend> Definealegendforaformfieldset.
accesskey=char Definethehot-keycharacterforthislegend.
align=position Alignthelegendtothetop,bottom,left,orrightofthefieldset.
<li>...</li> Delimitalistiteminanordered(<ol>)orunordered(<ul>)list.
type=format
Setthetypeofthislistelementtothedesiredformatfor<li>within<ol>:A(capital
letters),a(lowercaseletters),I(capitalRomannumerals),i(lowercaseRomannumerals),
or1(Arabicnumerals;default);for<li>within<ul>:circle,disc(default),orsquare.
value=nSetthenumberforthislistitemton.
<link> Definealinkbetweenthisdocumentandanotherdocumentinthedocument<head>.
charset=charset Specifythecharactersetusedtoencodethetargetofthislink.
HRef=url SpecifythehypertextreferenceURLofthetargetdocument.
HReflang=language Specifythelanguageusedforthetarget'scontentsusingastandardtwo-characterISO
languagename.
media=list Specifyalistofmediatypesuponwhichthisobjectcanberendered.
rel=relation Indicatetherelationshipfromthisdocumenttothetarget.
rev=relation Indicatethereverserelationshipfromthetargettothisdocument.
type=string SpecifytheMIMEtypeforthelinkeddocument.Usuallyusedinconjunctionwithlinksto
stylesheets,whenthetypeissettotext/css.
<map>...</map> Defineamapcontaininghotspotsinaclient-sideimagemap.
name=name Definethenameofthismap(required).
<marquee>...
</marquee> Createascrolling-textmarquee(InternetExploreronly). *
align=position Alignthemarqueetothetop,middle,orbottomofthesurroundingtext.
behavior=style Definethemarqueestyletobescroll,slide,oralternate.
bgcolor=color Setthebackgroundcolorofthemarquee.
class=name Specifyastyleclasscontrollingtheappearanceofthistag.
direction=dir Definethedirection,leftorright,inwhichthetextistoscroll.
height=nDefinetheheight,inpixels,ofthemarqueearea.
hspace=nDefinethespace,inpixels,tobeinsertedtotheleftandrightofthemarquee.
loop=value Setthenumberoftimestoanimatethemarquee;valueisanintegerorinfinite.
scrollamount=value Setthenumberofpixelstomovethetextforeachscrollmovement.
scrolldelay=value Specifythedelay,inmilliseconds,betweensuccessivemovementsofthemarqueetext.
style=style Specifyaninlinestyleforthistag.
vspace=nDefinethespace,inpixels,tobeinsertedaboveandbelowthemarquee.
width=nDefinethewidth,inpixels,ofthemarqueearea.
<menu>...</menu> Defineamenulistcontaining<li>tags.
type=bullet Setthebulletstyleforthislisttocircle,disc(default),orsquare.
<meta> Provideadditionalinformationaboutadocument. *
content=string Specifythevalueforthemeta-information(required).
dir=dir Specifytherenderingdirectionfortexteitherlefttoright(ltr)orrighttoleft(rtl).
http-equiv=string
SpecifytheHTTPequivalentnameforthemeta-informationandcausetheserverto
includethenameandcontentintheHTTPheaderforthisdocumentwhenitistransmitted
totheclient.
lang=language Specifythelanguageusedforthistag'scontentsusingastandardtwo-characterISO
languagename.
name=string Specifythenameofthemeta-information.
scheme=scheme Specifytheprofileschemeusedtointerpretthisproperty.
<nextid> Definethenextvaliddocumententityidentifier(obsolete;donotuse). *
n=nSetthenextIDnumber.
<nobr>...</nobr> Nobreaksallowedintheenclosedtext. *
<noembed>...
</noembed> Definecontenttobepresentedbybrowsersthatdonotsupportthe<embed>tag. *
<noframes>...
</noframes> Definecontenttobepresentedbybrowsersthatdonotsupportframes.
<noscript>...
</noscript> Definecontenttobepresentedbybrowsersthatdonotsupportthe<script>tag.
<object> Insertanobjectintoadocument.
align=position
Aligntheobjectwiththesurroundingtext(texttop,middle,textmiddle,baseline,textbottom,
orcenter)oragainstthemarginwithsubsequenttextflowingaroundtheobject(leftor
right).
archive=list SpecifyalistofURLsofarchivescontainingresourcesusedbythisobject.
border=nDefine,inpixels,theobject'sborderwidth.
classid=url SupplytheURLoftheobject.
codebase=url SupplytheURLoftheobject'scodebase.
codetype=type SpecifytheMIMEtypeofthecodebase.
data=url Supplydatafortheobject.
declare Declarethisobjectwithoutinstantiatingit.
height=nDefine,inpixels,theheightoftheobject.
hspace=nProvideextraspace,inpixels,totherightandleftoftheobject.
name=name Definethenameofthisobject.
notab Donotmakethisobjectpartofthetabbingorder.
shapes Specifythatthisobjecthasshapedhyperlinks.
standby=string Defineamessagetodisplaywhiletheobjectloads.
tabindex=nSpecifythisobject'spositioninthedocumenttaborder.
type=type SpecifytheMIMEtypefortheobjectdata.
usemap=url Defineanimagemapforusewiththisobject.
vspace=nProvideextraspace,inpixels,aboveandbelowtheobject.
width=nDefine,inpixels,thewidthoftheobject.
<ol>...</ol> Defineanorderedlistcontainingnumbered(ascending)<li>elements.
compact Presentthelistinamorecompactmanner.
start=nStartnumberingthelistatnratherthan1.
type=format SetthenumberingformatforthislisttoA(capitalletters),a(lowercaseletters),I(capital
Romannumerals),i(lowercaseRomannumerals),or1(Arabicnumerals;default).
<optgroup>...
</optgroup>
Defineagroupofoptionswithina<select>element.
disabled Disablethisgroup,makingitinactive.
label=string Providealabelforthisgroup.
<option>...</option> Defineanoptionwithina<select>itemina<form>.
disabled Disablethisoption,makingitinactive.
label=string Providealabelforthisoption.
selected Makethisiteminitiallyselected.
value=string Returnthespecifiedvaluetotheforms-processingapplicationinsteadofthe<option>
contents.
<p>...</p> Startandendaparagraph.
align=type Alignthetextwithintheparagraphtoleft,center,orright.
<param>...</param> Supplyaparametertoacontaining<applet>. *
id=name Definetheuniqueidentifierforthisparameter.
name=name Definethenameoftheparameter.
type=type SpecifytheMIMEtypeoftheparameter.
value=string Definethevalueoftheparameter.
valuetype=type Definethetypeofthevalueattribute,eitherasdata,ref(thevalueisaURLpointingtothe
data),orobject(thevalueisthenameofanobjectinthisdocument).
<pre>...</pre> Rendertheenclosedtextinitsoriginal,preformattedstyle,honoringlinebreaksand
spacingverbatim.
width=nSizethetext,ifpossible,sothatncharactersfitacrossthedisplaywindow.
<q>...</q> Theenclosedtextisaninlinequotation(notsupportedbyInternetExplorer).
cite=url SpecifytheURLofthesourceofthequotedmaterial.
<s>...</s> Sameas<strike>;theenclosedtextisstruckthroughwithahorizontalline.
<samp>...</samp> Theenclosedtextisasample.
<script>...</script> Defineascriptwithinadocument. *
charset=encoding Specifythecharactersetusedtoencodethescript.
defer Deferexecutionofthisscript.
language=encoding Specifythelanguageusedtocreatethescript.
src=url ProvidetheURLofthedocumentcontainingthescript.
type=encoding SpecifytheMIMEtypeofthescript.
<select>...</select> Defineamultiple-choicemenuorscrollinglistwithina<form>,containingoneormore
<option>tags.
disabled Disablethiscontrol,makingitinactive.
multiple Allowtheusertoselectmorethanone<option>withinthe<select>.
name=name Definethenamefortheselected<option>valuesthat,ifselected,arepassedtotheforms-
processingapplication(required).
onblur=applet Specifyanapplettoberunwhenthemouseleavesthiselement.
onchange=applet Specifyanapplettoberunwhentheuserchangesthevalueofthiselement.
onfocus=applet Specifyanapplettoberunwhenthemouseentersthiselement.
size=nDisplaynitemsusingapull-downmenuforsize=1(withoutmultiplespecified)anda
scrollinglistofnitemsotherwise.
tabindex=nSpecifythiselement'spositioninthetabbingorder.
<small>...</small> Formattheenclosedtextusingasmallertypeface.
<span>...</span> Defineaspanoftextforstyleapplication.
<strike>...</strike> Strikethroughtheenclosedtextwithahorizontalline.
<strong>...</strong> Stronglyemphasizetheenclosedtext.
<style>...</style> Defineoneormoredocument-levelstyles. *
Specifytherenderingdirectionforthetitletexteitherlefttoright(ltr)orrighttoleft
dir=dir (rtl).
lang=language Specifythelanguageusedforthistag'stitleusingastandardtwo-characterISOlanguage
name.
media=list Specifyalistofmediatypesuponwhichthisobjectcanberendered.
title=string Specifyatitleforthistag.
type=type Definetheformatofthestyles(alwaystext/css).
<sub>...</sub> Formattheenclosedtextassubscript.
<sup>...</sup> Formattheenclosedtextassuperscript.
<table>...</table> Defineatable.
align=position Alignthetableinthecenterandflowthesubsequenttextaroundthetable.
background=url Defineabackgroundimageforthetable.
bgcolor=color Defineabackgroundcolorfortheentiretable.
border=nCreateaborderthatisnpixelswide.
bordercolor=color Definethebordercolorfortheentiretable.
bordercolordark=color Definethedarkborder-highlightingcolorfortheentiretable.
bordercolorlight=color Definethelightborder-highlightingcolorfortheentiretable.
cellpadding=nPlacenpixelsofpaddingaroundeachcell'scontents.
cellspacing=nPlacenpixelsofspacingbetweencells.
cols=nSpecifythenumberofcolumnsinthistable.
frame=type Definewheretablebordersaredisplayedborder(default),void,above,below,hsides,lhs,rhs,
vsides,orbox.
height=nDefinetheheightofthetableinpixels.
hspace=nSpecifythehorizontalspace,inpixels,addedattheleftandrightofthetable.
nowrap Suppresstextwrappingintablecells.
rules=edges Determinewhereinnerdividersaredrawnall(default),groups(onlyaroundrowandcolumn
groups),rows,cols,ornone.
summary=string Provideasummarydescriptionofthistable.
valign=position Aligntextinthetabletothetop,center,bottom,orbaseline.
vspace=nSpecifytheverticalspace,inpixels,addedatthetopandbottomofthetable.
width=nSetthewidthofthetabletonpixelsorapercentageofthewindowwidth.
<tbody>...</tbody> Createarowgroupwithinatable.
align=position Alignthetablebodycells'contentstotheleft,center,orright.
char=char Specifythebodygroupcellalignmentcharacter.
charoff=value Specifytheoffsetwithinthecellsofthealignmentposition.
valign=position Verticallyalignthebodygroupcells'contentstothetop,center,bottom,orbaselineofthe
cell.
<td>...</td> Defineatabledatacell.
abbr=string Specifyanabbreviationforthecell'scontents.
align=position Alignthecellcontentstotheleft,center,orright.
axis=string Provideanameforarelatedgroupofcells.
background=url Defineabackgroundimageforthiscell.
bgcolor=color Definethebackgroundcolorforthecell.
bordercolor=color Definethebordercolorforthecell.
bordercolordark=color Definethedarkborder-highlightingcolorforthecell.
bordercolorlight=color Definethelightborder-highlightingcolorforthecell.
char=char Specifythecellalignmentcharacter.
charoff=value Specifytheoffsetofthealignmentpositionwithinthecell.
colspan=nHavethiscellstraddlenadjacentcolumns.
headers=list ProvidealistofheadercellIDsassociatedwiththiscell.
height=nDefinetheheight,inpixels,forthiscell.
nowrap Donotautomaticallywrapandfilltextinthiscell.
rowspan=nHavethiscellstraddlenadjacentrows.
scope=scope Definethescopeofthisheadercellrow,col,rowgroup,orcolgroup.
valign=position Verticallyalignthiscell'scontentstothetop,center,bottom,orbaselineofthecell.
width=nSetthewidthofthiscelltonpixelsorapercentageofthetablewidth.
<textarea>...
</textarea>
Defineamultilinetext-inputareawithina<form>;thecontentofthe<textarea>tagisthe
initial,defaultvalue.
accesskey=char Definethehot-keycharacterforthiselement.
cols=nDisplayncolumns(characters)oftextwithinthetextarea.
disabled Disablethiscontrol,makingitinactive.
name=string Definethenameforthetext-areavaluethatispassedtotheforms-processingapplication
(required).
onblur=applet Specifyanapplettoberunwhenthemouseleavesthiselement.
onchange=applet Specifyanapplettoberunwhentheuserchangesthevalueofthiselement.
onfocus=applet Specifyanapplettoberunwhenthemouseentersthiselement.
onselect=applet Specifyanapplettoberuniftheuserclicksthiselement.
readonly Preventusermodificationofthiselement.
rows=nDisplaynrowsoftextwithinthetextarea.
tabindex=nSpecifythiselement'spositioninthetabbingorder.
<tfoot>...</tfoot> Defineatablefooter.
align=position Alignthefootercells'contentstotheleft,center,orright.
char=char Specifythecellalignmentcharacter.
charoff=value Specifytheoffsetwithinthecellofthealignmentposition.
valign=position Verticallyalignthefootercells'contentstothetop,center,bottom,orbaselineofthecell.
<th>...</th> Defineatableheadercell.
abbr=string Specifyanabbreviationforthecell'scontents.
align=position Alignthecellcontentstotheleft,center,orright.
axis=string Provideanameforarelatedgroupofcells.
background=url Defineabackgroundimageforthiscell.
bgcolor=color Definethebackgroundcolorforthecell.
bordercolor=color Definethebordercolorforthecell.
bordercolordark=color Definethedarkborder-highlightingcolorforthecell.
bordercolorlight=color Definethelightborder-highlightingcolorforthecell.
char=char Specifythecellalignmentcharacter.
charoff=value Specifytheoffsetofthealignmentpositionwithinthecell.
colspan=nHavethiscellstraddlenadjacentcolumns.
headers=list ProvidealistofheadercellIDsassociatedwiththiscell.
height=nDefinetheheight,inpixels,forthiscell.
nowrap Donotautomaticallywrapandfilltextinthiscell.
rowspan=nHavethiscellstraddlenadjacentrows.
scope=scope Definethescopeofthisheadercellrow,col,rowgroup,orcolgroup.
valign=position Verticallyalignthiscell'scontentstothetop,center,bottom,orbaselineofthecell.
width=nSetthewidthofthiscelltonpixelsorapercentageofthetablewidth.
<thead>...</thead> Defineatableheading.
align=position Definethehorizontaltextalignmentintheheadingleft,center,right,orjustify.
char=char Specifythecellalignmentcharacterforheadingcells.
charoff=value Specifytheoffsetwithinthecellsofthealignmentposition.
valign=position Definetheverticaltextalignmentintheheadingleft,center,right,orjustify.
<title>...</title> DefinetheHTMLdocument'stitle. *
dir=dir Specifytherenderingdirectionfortexteitherlefttoright(ltr)orrighttoleft(rtl).
lang=language Specifythelanguageusedforthistag'scontentsusingastandardtwo-characterISO
languagename.
<tr>...</tr> Definearowofcellswithinatable.
align=type Alignthecellcontentsinthisrowtotheleft,center,orright.
background=url Defineabackgroundimageforthiscell.
bgcolor=color Definethebackgroundcolorforthisrow.
bordercolor=color ForInternetExplorer,definethebordercolorforthisrow.
bordercolordark=color ForInternetExplorer,definethedarkborder-highlightingcolorforthisrow.
bordercolorlight=color ForInternetExplorer,definethelightborder-highlightingcolorforthisrow.
char=char Specifythecellalignmentcharacterforthisrow.
charoff=value Specifytheoffsetofthealignmentpositionwithinthecellsofthisrow.
nowrap Disablewordwrapforallcellsinthisrow.
valign=position Verticallyalignthecellcontentsinthisrowtothetop,center,bottom,orbaselineofthecell.
<tt>...</tt> Formattheenclosedtextinteletype-style(monospaced)font.
<u>...</u> Underlinetheenclosedtext.
<ul>...</ul> Defineanunorderedlistofbulleted<li>elements.
compact Displaythelistinamorecompactmanner,ifpossible.
type=bullet Setthebulletstyleforthislisttocircle,disc(default),orsquare.
<var>...</var> Theenclosedtextisavariable'sname.
<wbr> Indicateapotentialwordbreakpointwithina<nobr>section. *
AppendixC.CascadingStyleSheetPropertiesQuick
Reference
Inthefollowingtable,welist,inalphabeticalorder,allthepropertiesdefinedin
theWorldWideWebConsortium's(W3C's)RecommendedSpecificationfor
CascadingStyleSheets(CSS),Level2(http://www.w3.org/pub/WWW/TR/REC-
CSS2).Weincludeeachproperty'spossiblevalues,definedaseitheranexplicit
keyword(showninconstantwidth)orasoneofthesevalues:
angle
Anumericvaluefollowedbydeg,grad,orrad.
color
EitheracolornameorhexadecimalRGBvalue,asdefinedinAppendixG,or
anRGBtripleoftheform:
rgb(red,green,blue)
wherered,green,andblueareeithernumbersintherange0to255or
percentagevaluesindicatingthebrightnessofthatcolorcomponent.Valuesof
255or100%indicatethatthecorrespondingcolorcomponentisatitsbrightest;
valuesof0or0%indicatethatthecorrespondingcolorcomponentisturnedoff
completely.Forexample:
rgb(27,119,207)
rgb(50%,75%,0%)
arebothvalidcolorspecifications.
frequency
Anumericvaluefollowedbyhzorkhz,indicatinghertzorkilohertz.
length
Anoptionalsign(either+or-),immediatelyfollowedbyanumber(withor
withoutadecimalpoint),immediatelyfollowedbyatwo-characterunit
identifier.Forvaluesof0,theunitidentifiermaybeomitted.
Theunitidentifiersemandexrefertotheoverallheightofthefontandtothe
heightoftheletter"x,"respectively.Theunitidentifierpxisequaltoasingle
pixelonthedisplaydevice.Theunitidentifiersin,cm,mm,pt,andpcreferto
inches,centimeters,millimeters,points,andpicas,respectively.Thereare
72.27pointsinaninchand12pointsinapica.
number
Anoptionalsign,immediatelyfollowedbyanumber(withorwithouta
decimalpoint).
percent
Anoptionalsign,immediatelyfollowedbyanumber(withorwithouta
decimalpoint),immediatelyfollowedbyapercentsign.Theactualvalueis
computedasapercentageofsomeotherelementproperty,usuallythe
element'ssize.
shape
Ashapekeyword,followedbyaparentheses-enclosedlistofcomma-
separated,shape-specificparameters.Currently,theonlysupportedshape
keywordisrect,whichexpectsfournumericparametersdenotingtheoffsets
ofthetop,right,bottom,andleftedgesoftherectangle.
time
Anumericvaluefollowedbysorms,designatingatimeinsecondsorin
milliseconds.
url
Thekeywordurl,immediatelyfollowed(nospaces)byaleftparenthesis,
followedbyaURLoptionallyenclosedinsingleordoublequotes,followedbya
matchingrightparenthesis.Forexample:
url("http://www.oreilly.com/catalog")
isavalidURLvalue.
Finally,somevaluesarelistsofothervaluesandaredescribedasa"listof"some
othervalue.Inthesecases,alistconsistsofoneormoreoftheallowedvalues,
separatedbycommas.
Ifseveraldifferentvaluesareallowedforaproperty,thesealternativechoicesare
separatedbypipes(|).
Ifthestandarddefinesadefaultvaluefortheproperty,thatvalueisunderlined.
azimuth
angle|left-side|far-left|left|center-
left|center|center-right|right|far-
right|right-side
Determinesthepositionaroundthelisteneratwhicha
soundisplayed. 8.4.12.7
background
Compositepropertyforthebackground-attachment,
background-color,background-image,background-position,
andbackground-repeatproperties;valueisanyofthese
properties'values,inanyorder.
8.4.5.6
background-
attachment scroll|fixed Determineswhetherthebackgroundimageisfixedinthe
windoworscrollsasthedocumentscrolls. 8.4.5.3
background-
color color|transparent Setsthebackgroundcolorofanelement. 8.4.5.1
background-
image url|none Setsthebackgroundimageofanelement. 8.4.5.2
background-
position
percent|length|top|center|bottom|
left|right
Setstheinitialpositionoftheelement'sbackground
image,ifspecified;valuesnormallyarepairedto
provideX,Ypositions;defaultpositionis0%0%.8.4.5.4
background-
repeat repeat|repeat-x|repeat-y|no-repeat Determineshowthebackgroundimageisrepeated(tiled)
acrossanelement. 8.4.5.5
border
Setsallfourofanelement'sborders;valueisoneor
moreofacolor,avalueforborder-width,andavalue
forborder-style.8.4.7.6
border-
bottom
Setsanelement'sbottomborder;valueisoneormore
ofacolor,avalueforborder-bottom-width,andavalue
forborder-style.8.4.7.6
border-
bottom-
width
length|thin|medium|thick Setsthethicknessofanelement'sbottomborder. 8.4.7.4
border-
collapse collapse|separate Setsthetableborderrenderingalgorithm. 8.4.9.1
border-
color color Setsthecolorofallfourofanelement'sborders;
defaultisthecoloroftheelement. 8.4.7.3
border-left
Setsanelement'sleftborder;valueisoneormoreof
acolor,avalueforborder-left-width,andavaluefor
border-style.8.4.7.6
border-
left-width length|thin|medium|thick Setsthethicknessofanelement'sleftborder 8.4.7.4
border-
right
Setsanelement'srightborder;valueisoneormoreof
acolor,avalueforborder-right-width,andavaluefor
border-style.8.4.7.6
border-
right-width length|thin|medium|thick Setsthethicknessofanelement'srightborder. 8.4.7.4
border-
spacing
Withseparateborders,setsthespacingbetween
bordersonevaluesetsverticalandhorizontalspacing;
twovaluessethorizontalandverticalspacing,
respectively.
8.4.9.1
border-
style
dashed|dotted|double|groove|inset|
none|outset|ridge|solid Setsthestyleofallfourofanelement'sborders. 8.4.7.5
border-top
Setsanelement'stopborder;valueisoneormoreofa
color,avalueforborder-top-width,andavaluefor
border-style.8.4.7.6
border-top-
width length|thin|medium|thick Setsthethicknessofanelement'stopborder. 8.4.7.4
border-
width length|thin|medium|thick Setsthethicknessofallfourofanelement'sborders. 8.4.7.4
bottom length|percent Usedwiththepositionpropertytoplacethebottom
edgeofanelement. 8.4.7.14
caption-
side top|bottom|left|right Setsthepositionforatablecaption. 8.4.9.2
clear both|left|none|right
Setswhichmarginsofanelementmustnotbeadjacent
toafloatingelement;theelementismoveddownuntil
thatmarginisclear.
8.4.7.7
clip shape Setstheclippingmaskforanelement. 8.4.7.8
color color Setsthecolorofanelement. 8.4.5.7
content Insertsgeneratedcontentaroundanelement;seetext 8.4.11.2
fordetails.
counter-
increment Incrementsacounterby1;valueisalistofcounter
names,witheachnameoptionallyfollowedbyavalueby
whichitisincremented.
8.4.11.4
counter-
reset Resetsacountertozero;valueisalistofcounter
names,witheachnameoptionallyfollowedbyavalueto
whichitisreset.
8.4.11.4
cue-after url|none Playsthedesignatedsoundafteranelementisspoken. 8.4.12.5
cue-before url|none Playsthedesignatedsoundbeforeanelementisspoken. 8.4.12.5
display block|inline|list-item|marker|none Controlshowanelementisdisplayed. 8.4.10.1
elevation angle|below|level|above|higher|lower Setstheheightatwhichasoundisplayed. 8.4.12.7
empty-cells hide|show Withseparateborders,hidesemptycellsinatable. 8.4.9.1
float left|none|right
Determineswhetheranelementfloatstotheleftor
right,allowingtexttowraparounditorbedisplayed
inline(usingnone). 8.4.7.9
font
Setsallfontattributesforanelement;valueisany
ofthevaluesforfont-style,font-variant,font-weight,
font-size,line-height,andfont-family,inthatorder. 8.4.3.8
font-family Listoffontnames
Definesthefontforanelement,eitherasaspecific
fontorasoneofthegenericfontsserif,sans-serif,
cursive,fantasy,andmonospace.8.4.3.1
font-size
xx-small|x-small|small|medium|large|
x-large|xx-large|larger|smaller|length
|percent
Definesthefontsize. 8.4.3.2
font-size-
adjust none|ratio Adjuststhecurrentfont'saspectratio. 8.4.3.4
font-
stretch
wider|normal|narrower|ultra-condensed
|extra-condensed|condensed|semi-
condensed|semi-expanded|expanded|
extra-expanded|ultra-expanded
Determinestheamounttostretchthecurrentfont. 8.4.3.3
font-style normal|italic|oblique Definesthestyleoftheface,eithernormalorsome
typeofslantedstyle. 8.4.3.5
font-
variant normal|small-caps Definesafonttobeinsmallcaps. 8.4.3.6
font-weight normal|bold|bolder|lighter|number
Definesthefontweightifanumberisused,itmustbea
multipleof100between100and900;400isnormal,
700isthesameasthekeywordbold.
8.4.3.7
height length|auto Definestheheightofanelement. 8.4.7.10
left length|percent Usedwiththepositionpropertytoplacetheleftedge
ofanelement. 8.4.7.14
letter-
spacing length|normal Insertsadditionalspacebetweentextcharacters. 8.4.6.1
line-height length|number|percent|normal Setsthedistancebetweenadjacenttextbaselines. 8.4.6.2
list-style
Defineslist-relatedstylesusinganyofthevaluesfor
list-style-image,list-style-position,andlist-style-
type.8.4.8.4
list-style-
image url|none Definesanimagetobeusedasalistitem'smarker,in
lieuofthevalueforlist-style-type.8.4.8.1
list-style-
position inside|outside Indentsorextends(default)alistitem'smarkerwith
respecttotheitem'scontent. 8.4.8.2
list-style-
type
circle|disc|square|decimal|lower-alpha
|lower-roman|none|upper-alpha|upper-
roman
Definesalistitem'smarkereitherforunorderedlists
(circle,disc,orsquare)orfororderedlists(decimal,
lower-alpha,lower-roman,none,upper-alpha,orupper-
roman).
8.4.8.3
margin length|percent|auto Definesallfourofanelement'smargins. 8.4.7.11
margin-
bottom length|percent|auto Definesthebottommarginofanelement;defaultvalue
is0.8.4.7.11
margin-left length|percent|auto Definestheleftmarginofanelement;defaultvalueis
0.8.4.7.11
margin-
right length|percent|auto Definestherightmarginofanelement;defaultvalue
is0.8.4.7.11
margin-top length|percent|auto Definesthetopmarginofanelement;defaultvalueis
0.8.4.7.11
orphans number Setstheminimumnumberoflinesallowedinanorphaned
paragraphfragment. 8.4.13.5
overflow auto|hidden|scroll|visible Determineshowoverflowcontentisrendered. 8.4.7.13
padding Definesallfourpaddingamountsaroundanelement. 8.4.7.12
padding-
bottom length|percent Definesthebottompaddingofanelement;defaultvalue
is0.8.4.7.12
padding-
left length|percent Definestheleftpaddingofanelement;defaultvalue
is0.8.4.7.12
padding-
right length|percent Definestherightpaddingofanelement;defaultvalue
is0.8.4.7.12
padding-top length|percent Definesthetoppaddingofanelement;defaultvalueis
0.8.4.7.12
page name Associatesanamedpagelayoutwithanelement. 8.4.13.3
page-break-
after auto|always|avoid|left|right Forcesorsuppressespagebreaksafteranelement. 8.4.13.4
page-break-
before auto|always|avoid|left|right Forcesorsuppressespagebreaksbeforeanelement. 8.4.13.4
page-break-
inside auto|avoid Suppressespagebreakswithinanelement. 8.4.13.4
pause-after percent|time Pausesafterspeakinganelement. 8.4.12.4
pause-
before percent|time Pausesbeforespeakinganelement. 8.4.12.4
pitch frequency|x-low|low|medium|high|x-
high Setstheaveragepitchofanelement'sspokencontent. 8.4.12.3
pitch-range number Setstherangeofthepitch,from0(flat)to100
(broad);defaultis50.8.4.12.3
play-during url|mix|none|repeat
IfaURLisprovided,itisplayedduringanelement's
spokencontentspecifyingrepeatloopstheaudio;mix
causesittomixwith,ratherthanreplace,other
backgroundaudio.
8.4.12.6
position absolute|fixed|relative|static Setsthepositioningmodelforanelement. 8.4.7.14
quotes Listofstrings Setsthequotesymbolsusedtoquotetext. 8.4.11.3
richness number Setstherichnessofthevoice,from0(flat)to100
(mellifluous);defaultis50.8.4.12.3
right length|percent Usedwiththepositionpropertytoplacetherightedge
ofanelement. 8.4.7.14
speak normal|none|spell-out Determineshowanelement'scontentisspoken. 8.4.12.2
speak-
header always|once Determineswhethertableheadersarespokenoncefor
eachroworcolumnoreachtimeacellisspoken. 8.4.9.3
speak-
numeral continuous|digits Determineshownumeralsarespoken. 8.4.12.2
speak-
punctuation code|none Determineswhetherpunctuationisspokenorusedfor
inflection. 8.4.12.2
speech-rate number|x-slow|slow|medium|fast|x-
fast|faster|slower
Setstherateofspeech;anumbersetstheratein
wordsperminute. 8.4.12.3
stress number Setsthestressofthevoice,from0(catatonic)to100
(hyperactive);defaultis50.8.4.12.3
table-
layout auto|fixed Determinesthetable-renderingalgorithm. 8.4.9.4
text-align center|justify|left|right Setsthetextalignmentstyleforanelement. 8.4.6.3
text-
decoration
blink|line-through|none|overline|
underline
Definesanydecorationforthetext;valuesmaybe
combined. 8.4.6.4
text-indent length|percent Definestheindentationofthefirstlineoftextinan
element;defaultis0.8.4.6.5
text-shadow Seetext Createstextdropshadowsofvaryingcolorsand
offsets. 8.4.6.6
text-
TRansform capitalize|lowercase|none|uppercase transformsthetextintheelementaccordingly. 8.4.6.7
top length|percent Usedwiththepositionpropertytoplacethetopedge
ofanelement. 8.4.7.14
vertical-
align
percent|baseline|bottom|middle|sub|
super|text-bottom|text-top|top Setstheverticalpositioningofanelement. 8.4.6.8
visibility collapse|hidden|visible Determineswhetheranelementisvisibleinthe
documentortable. 8.4.7.15
voice-
family Listofvoices Selectsanamedvoicefamilytospeakanelement's
content. 8.4.12.3
volume number|percent|silent|x-soft|soft|
medium|loud|x-loud
Setsthevolumeofspokencontent;numericvaluesrange
from0to100. 8.4.12.1
white-space normal|nowrap|pre Defineshowwhitespacewithinanelementishandled. 8.4.10.2
widows number Setstheminimumnumberoflinesallowedinawidowed
paragraphfragment. 8.4.13.5
width length|percent|auto Definesthewidthofanelement. 8.4.7.16
word-
spacing length|normal Insertsadditionalspacebetweenwords. 8.4.6.9
z-index number Setstherenderinglayerforthecurrentelement. 8.4.7.17
AppendixD.TheHTML4.01DTD
TheHTML4.01standardisformallydefinedasthreeStandardGeneralized
MarkupLanguage(SGML)DocumentTypeDefinitions(DTDs):theStrictDTD,the
TransitionalDTD,andtheFramesetDTD.TheStrictDTDdefinesonlythose
elementsthatarenotdeprecatedinthe4.0standard.Ideally,everyonewould
createHTMLdocumentsthatconformtotheStrictDTD.TheTransitionalDTD
includesallthosedeprecatedelementsandmoreaccuratelyreflectstheHTMLin
usetoday,withmanyolderelementsstillincommonuse.TheFramesetDTDis
identicaltotheTransitionalDTD,withtheexceptionthatthedocument<body>is
replacedbythe<frameset>tag.
SincetheTransitionalDTDprovidesthebroadestcoverageofallHTMLelements
currentlyinuse,itistheDTDuponwhichthisbookisbasedandtheonewe
reproducehere.NotethatwehavereprintedthisDTDverbatimandhavenot
attemptedtoaddextensionstoit.WhereourdescriptionandtheDTDdeviate,
assumetheDTDiscorrect:
<!--
ThisistheHTML4.01TransitionalDTD,whichincludes
presentationattributesandelementsthatW3Cexpectstophaseout
assupportforstylesheetsmatures.AuthorsshouldusetheStrict
DTDwhenpossible,butmayusetheTransitionalDTDwhensupport
forpresentationattributesandelementsisrequired.
HTML4includesmechanismsforstylesheets,scripting,
embeddingobjects,improvedsupportforrighttoleftandmixed
directiontext,andenhancementstoformsforimproved
accessibilityforpeoplewithdisabilities.
Draft:$Date:2006/10/2517:08:45$
Authors:
DaveRaggett<dsr@w3.org>
ArnaudLeHors<lehors@w3.org>
IanJacobs<ij@w3.org>
FurtherinformationaboutHTML4.01isavailableat:
http://www.w3.org/TR/1999/REC-html401-19991224
TheHTML4.01specificationincludesadditional
syntacticconstraintsthatcannotbeexpressedwithin
theDTDs.
-->
<!ENTITY%HTML.Version"-//W3C//DTDHTML4.01Transitional//EN"
--Typicalusage:
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
...
</head>
<body>
...
</body>
</html>
TheURIusedasasystemidentifierwiththepublicidentifierallows
theuseragenttodownloadtheDTDandentitysetsasneeded.
TheFPIfortheStrictHTML4.01DTDis:
"-//W3C//DTDHTML4.01//EN"
ThisversionofthestrictDTDis:
http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd
AuthorsshouldusetheStrictDTDunlesstheyneedthe
presentationcontrolforuseragentsthatdon't(adequately)
supportstylesheets.
Ifyouarewritingadocumentthatincludesframes,use
thefollowingFPI:
"-//W3C//DTDHTML4.01Frameset//EN"
ThisversionoftheframesetDTDis:
http://www.w3.org/TR/1999/REC-html401-19991224/frameset.dtd
Usethefollowing(relative)URIstoreferto
theDTDsandentitydefinitionsofthisspecification:
"strict.dtd"
"loose.dtd"
"frameset.dtd"
"HTMLlat1.ent"
"HTMLsymbol.ent"
"HTMLspecial.ent"
-->
<!--==================ImportedNames====================================-->
<!--FeatureSwitchforframesetdocuments-->
<!ENTITY%HTML.Frameset"IGNORE">
<!ENTITY%ContentType"CDATA"
--mediatype,asper[RFC2045]
-->
<!ENTITY%ContentTypes"CDATA"
--comma-separatedlistofmediatypes,asper[RFC2045]
-->
<!ENTITY%Charset"CDATA"
--acharacterencoding,asper[RFC2045]
-->
<!ENTITY%Charsets"CDATA"
--aspace-separatedlistofcharacterencodings,asper[RFC2045]
-->
<!ENTITY%LanguageCode"NAME"
--alanguagecode,asper[RFC1766]
-->
<!ENTITY%Character"CDATA"
--asinglecharacterfrom[ISO10646]
-->
<!ENTITY%LinkTypes"CDATA"
--space-separatedlistoflinktypes
-->
<!ENTITY%MediaDesc"CDATA"
--singleorcomma-separatedlistofmediadescriptors
-->
<!ENTITY%URI"CDATA"
--aUniformResourceIdentifier,
see[URI]
-->
<!ENTITY%Datetime"CDATA"--dateandtimeinformation.ISOdateformat-->
<!ENTITY%Script"CDATA"--scriptexpression-->
<!ENTITY%StyleSheet"CDATA"--stylesheetdata-->
<!ENTITY%FrameTarget"CDATA"--renderinthisframe-->
<!ENTITY%Text"CDATA">
<!--ParameterEntities-->
<!ENTITY%head.misc"SCRIPT|STYLE|META|LINK|OBJECT"--repeatableheadelements-->
<!ENTITY%heading"H1|H2|H3|H4|H5|H6">
<!ENTITY%list"UL|OL|DIR|MENU">
<!ENTITY%preformatted"PRE">
<!ENTITY%Color"CDATA"--acolorusingsRGB:#RRGGBBasHexvalues-->
<!--Therearealso16widelyknowncolornameswiththeirsRGBvalues:
Black=#000000Green=#008000
Silver=#C0C0C0Lime=#00FF00
Gray=#808080Olive=#808000
White=#FFFFFFYellow=#FFFF00
Maroon=#800000Navy=#000080
Red=#FF0000Blue=#0000FF
Purple=#800080Teal=#008080
Fuchsia=#FF00FFAqua=#00FFFF
-->
<!ENTITY%bodycolors"
bgcolor%Color;#IMPLIED--documentbackgroundcolor--
text%Color;#IMPLIED--documenttextcolor--
link%Color;#IMPLIED--coloroflinks--
vlink%Color;#IMPLIED--colorofvisitedlinks--
alink%Color;#IMPLIED--colorofselectedlinks--
">
<!--================Charactermnemonicentities=========================-->
<!ENTITY%HTMLlat1PUBLIC
"-//W3C//ENTITIESLatin1//EN//HTML"
"HTMLlat1.ent">
%HTMLlat1;
<!ENTITY%HTMLsymbolPUBLIC
"-//W3C//ENTITIESSymbols//EN//HTML"
"HTMLsymbol.ent">
%HTMLsymbol;
<!ENTITY%HTMLspecialPUBLIC
"-//W3C//ENTITIESSpecial//EN//HTML"
"HTMLspecial.ent">
%HTMLspecial;
<!--===================GenericAttributes===============================-->
<!ENTITY%coreattrs
"idID#IMPLIED--document-wideuniqueid--
classCDATA#IMPLIED--space-separatedlistofclasses--
style%StyleSheet;#IMPLIED--associatedstyleinfo--
title%Text;#IMPLIED--advisorytitle--"
>
<!ENTITY%i18n
"lang%LanguageCode;#IMPLIED--languagecode--
dir(ltr|rtl)#IMPLIED--directionforweak/neutraltext--"
>
<!ENTITY%events
"onclick%Script;#IMPLIED--apointerbuttonwasclicked--
ondblclick%Script;#IMPLIED--apointerbuttonwasdoubleclicked--
onmousedown%Script;#IMPLIED--apointerbuttonwaspresseddown--
onmouseup%Script;#IMPLIED--apointerbuttonwasreleased--
onmouseover%Script;#IMPLIED--apointerwasmovedonto--
onmousemove%Script;#IMPLIED--apointerwasmovedwithin--
onmouseout%Script;#IMPLIED--apointerwasmovedaway--
onkeypress%Script;#IMPLIED--akeywaspressedandreleased--
onkeydown%Script;#IMPLIED--akeywaspresseddown--
onkeyup%Script;#IMPLIED--akeywasreleased--"
>
<!--ReservedFeatureSwitch-->
<!ENTITY%HTML.Reserved"IGNORE">
<!--Thefollowingattributesarereservedforpossiblefutureuse-->
<![%HTML.Reserved;[
<!ENTITY%reserved
"datasrc%URI;#IMPLIED--asingleortabularDataSource--
datafldCDATA#IMPLIED--thepropertyorcolumnname--
dataformatas(plaintext|html)plaintext--textorhtml--"
>
]]>
<!ENTITY%reserved"">
<!ENTITY%attrs"%coreattrs;%i18n;%events;">
<!ENTITY%align"align(left|center|right|justify)#IMPLIED"
--defaultisleftforltrparagraphs,rightforrtl--
>
<!--===================TextMarkup======================================-->
<!ENTITY%fontstyle
"TT|I|B|U|S|STRIKE|BIG|SMALL">
<!ENTITY%phrase"EM|STRONG|DFN|CODE|
SAMP|KBD|VAR|CITE|ABBR|ACRONYM">
<!ENTITY%special
"A|IMG|APPLET|OBJECT|FONT|BASEFONT|BR|SCRIPT|
MAP|Q|SUB|SUP|SPAN|BDO|IFRAME">
<!ENTITY%formctrl"INPUT|SELECT|TEXTAREA|LABEL|BUTTON">
<!--%inline;coversinlineor"text-level"elements-->
<!ENTITY%inline"#PCDATA|%fontstyle;|%phrase;|%special;|%formctrl;">
<!ELEMENT(%fontstyle;|%phrase;)--(%inline;)*>
<!ATTLIST(%fontstyle;|%phrase;)
%attrs;--%coreattrs,%i18n,%events--
>
<!ELEMENT(SUB|SUP)--(%inline;)*--subscript,superscript-->
<!ATTLIST(SUB|SUP)
%attrs;--%coreattrs,%i18n,%events--
>
<!ELEMENTSPAN--(%inline;)*--genericlanguage/stylecontainer-->
<!ATTLISTSPAN
%attrs;--%coreattrs,%i18n,%events--
%reserved;--reservedforpossiblefutureuse--
>
<!ELEMENTBDO--(%inline;)*--I18NBiDiover-ride-->
<!ATTLISTBDO
%coreattrs;--id,class,style,title--
lang%LanguageCode;#IMPLIED--languagecode--
dir(ltr|rtl)#REQUIRED--directionality--
>
<!ELEMENTBASEFONT-OEMPTY--basefontsize-->
<!ATTLISTBASEFONT
idID#IMPLIED--document-wideuniqueid--
sizeCDATA#REQUIRED--basefontsizeforFONTelements--
color%Color;#IMPLIED--textcolor--
faceCDATA#IMPLIED--comma-separatedlistoffontnames--
>
<!ELEMENTFONT--(%inline;)*--localchangetofont-->
<!ATTLISTFONT
%coreattrs;--id,class,style,title--
%i18n;--lang,dir--
sizeCDATA#IMPLIED--[+|-]nne.g.size="+1",size="4"--
color%Color;#IMPLIED--textcolor--
faceCDATA#IMPLIED--comma-separatedlistoffontnames--
>
<!ELEMENTBR-OEMPTY--forcedlinebreak-->
<!ATTLISTBR
%coreattrs;--id,class,style,title--
clear(left|all|right|none)none--controloftextflow--
>
<!--==================HTMLcontentmodels===============================-->
<!--
HTMLhastwobasiccontentmodels:
%inline;characterlevelelementsandtextstrings
%block;block-likeelementse.g.paragraphsandlists
-->
<!ENTITY%block
"P|%heading;|%list;|%preformatted;|DL|DIV|CENTER|
NOSCRIPT|NOFRAMES|BLOCKQUOTE|FORM|ISINDEX|HR|
TABLE|FIELDSET|ADDRESS">
<!ENTITY%flow"%block;|%inline;">
<!--===================DocumentBody====================================-->
<!ELEMENTBODYOO(%flow;)*+(INS|DEL)--documentbody-->
<!ATTLISTBODY
%attrs;--%coreattrs,%i18n,%events--
onload%Script;#IMPLIED--thedocumenthasbeenloaded--
onunload%Script;#IMPLIED--thedocumenthasbeenremoved--
background%URI;#IMPLIED--texturetilefordocumentbackground--
%bodycolors;--bgcolor,text,link,vlink,alink--
>
<!ELEMENTADDRESS--((%inline;)|P)*--informationonauthor-->
<!ATTLISTADDRESS
%attrs;--%coreattrs,%i18n,%events--
>
<!ELEMENTDIV--(%flow;)*--genericlanguage/stylecontainer-->
<!ATTLISTDIV
%attrs;--%coreattrs,%i18n,%events--
%align;--align,textalignment--
%reserved;--reservedforpossiblefutureuse--
>
<!ELEMENTCENTER--(%flow;)*--shorthandforDIValign=center-->
<!ATTLISTCENTER
%attrs;--%coreattrs,%i18n,%events--
>
<!--==================TheAnchorElement================================-->
<!ENTITY%Shape"(rect|circle|poly|default)">
<!ENTITY%Coords"CDATA"--comma-separatedlistoflengths-->
<!ELEMENTA--(%inline;)*-(A)--anchor-->
<!ATTLISTA
%attrs;--%coreattrs,%i18n,%events--
charset%Charset;#IMPLIED--charencodingoflinkedresource--
type%ContentType;#IMPLIED--advisorycontenttype--
nameCDATA#IMPLIED--namedlinkend--
href%URI;#IMPLIED--URIforlinkedresource--
hreflang%LanguageCode;#IMPLIED--languagecode--
target%FrameTarget;#IMPLIED--renderinthisframe--
rel%LinkTypes;#IMPLIED--forwardlinktypes--
rev%LinkTypes;#IMPLIED--reverselinktypes--
accesskey%Character;#IMPLIED--accessibilitykeycharacter--
shape%Shape;rect--forusewithclient-sideimagemaps--
coords%Coords;#IMPLIED--forusewithclient-sideimagemaps--
tabindexNUMBER#IMPLIED--positionintabbingorder--
onfocus%Script;#IMPLIED--theelementgotthefocus--
onblur%Script;#IMPLIED--theelementlostthefocus--
>
<!--==================Client-sideimagemaps============================-->
<!--Thesecanbeplacedinthesamedocumentorgroupedina
separatedocumentalthoughthisisn'tyetwidelysupported-->
<!ELEMENTMAP--((%block;)|AREA)+--client-sideimagemap-->
<!ATTLISTMAP
%attrs;--%coreattrs,%i18n,%events--
nameCDATA#REQUIRED--forreferencebyusemap--
>
<!ELEMENTAREA-OEMPTY--client-sideimagemaparea-->
<!ATTLISTAREA
%attrs;--%coreattrs,%i18n,%events--
shape%Shape;rect--controlsinterpretationofcoords--
coords%Coords;#IMPLIED--comma-separatedlistoflengths--
href%URI;#IMPLIED--URIforlinkedresource--
target%FrameTarget;#IMPLIED--renderinthisframe--
nohref(nohref)#IMPLIED--thisregionhasnoaction--
alt%Text;#REQUIRED--shortdescription--
tabindexNUMBER#IMPLIED--positionintabbingorder--
accesskey%Character;#IMPLIED--accessibilitykeycharacter--
onfocus%Script;#IMPLIED--theelementgotthefocus--
onblur%Script;#IMPLIED--theelementlostthefocus--
>
<!--==================TheLINKElement==================================-->
<!--
Relationshipvaluescanbeusedinprinciple:
a)fordocumentspecifictoolbars/menuswhenused
withtheLINKelementindocumentheade.g.
start,contents,previous,next,index,end,help
b)tolinktoaseparatestylesheet(rel=stylesheet)
c)tomakealinktoascript(rel=script)
d)bystylesheetstocontrolhowcollectionsof
htmlnodesarerenderedintoprinteddocuments
e)tomakealinktoaprintableversionofthisdocument
e.g.apostscriptorpdfversion(rel=alternatemedia=print)
-->
<!ELEMENTLINK-OEMPTY--amedia-independentlink-->
<!ATTLISTLINK
%attrs;--%coreattrs,%i18n,%events--
charset%Charset;#IMPLIED--charencodingoflinkedresource--
href%URI;#IMPLIED--URIforlinkedresource--
hreflang%LanguageCode;#IMPLIED--languagecode--
type%ContentType;#IMPLIED--advisorycontenttype--
rel%LinkTypes;#IMPLIED--forwardlinktypes--
rev%LinkTypes;#IMPLIED--reverselinktypes--
media%MediaDesc;#IMPLIED--forrenderingonthesemedia--
target%FrameTarget;#IMPLIED--renderinthisframe--
>
<!--===================Images===========================================-->
<!--LengthdefinedinstrictDTDforcellpadding/cellspacing-->
<!ENTITY%Length"CDATA"--nnforpixelsornn%forpercentagelength-->
<!ENTITY%MultiLength"CDATA"--pixel,percentage,orrelative-->
<![%HTML.Frameset;[
<!ENTITY%MultiLengths"CDATA"--comma-separatedlistofMultiLength-->
]]>
<!ENTITY%Pixels"CDATA"--integerrepresentinglengthinpixels-->
<!ENTITY%IAlign"(top|middle|bottom|left|right)"--center?-->
<!--Toavoidproblemswithtext-onlyUAsaswellas
tomakeimagecontentunderstandableandnavigable
tousersofnon-visualUAs,youneedtoprovide
adescriptionwithALT,andavoidserver-sideimagemaps-->
<!ELEMENTIMG-OEMPTY--Embeddedimage-->
<!ATTLISTIMG
%attrs;--%coreattrs,%i18n,%events--
src%URI;#REQUIRED--URIofimagetoembed--
alt%Text;#REQUIRED--shortdescription--
longdesc%URI;#IMPLIED--linktolongdescription
(complementsalt)--
nameCDATA#IMPLIED--nameofimageforscripting--
height%Length;#IMPLIED--overrideheight--
width%Length;#IMPLIED--overridewidth--
usemap%URI;#IMPLIED--useclient-sideimagemap--
ismap(ismap)#IMPLIED--useserver-sideimagemap--
align%IAlign;#IMPLIED--verticalorhorizontalalignment--
border%Pixels;#IMPLIED--linkborderwidth--
hspace%Pixels;#IMPLIED--horizontalgutter--
vspace%Pixels;#IMPLIED--verticalgutter--
>
<!--USEMAPpointstoaMAPelementwhichmaybeinthisdocument
oranexternaldocument,althoughthelatterisnotwidelysupported-->
<!--====================OBJECT======================================-->
<!--
OBJECTisusedtoembedobjectsaspartofHTMLpages
PARAMelementsshouldprecedeothercontent.SGMLmixedcontent
modeltechnicalityprecludesspecifyingthisformally...
-->
<!ELEMENTOBJECT--(PARAM|%flow;)*
--genericembeddedobject-->
<!ATTLISTOBJECT
%attrs;--%coreattrs,%i18n,%events--
declare(declare)#IMPLIED--declarebutdon'tinstantiateflag--
classid%URI;#IMPLIED--identifiesanimplementation--
codebase%URI;#IMPLIED--baseURIforclassid,data,archive--
data%URI;#IMPLIED--referencetoobject'sdata--
type%ContentType;#IMPLIED--contenttypefordata--
codetype%ContentType;#IMPLIED--contenttypeforcode--
archiveCDATA#IMPLIED--space-separatedlistofURIs--
standby%Text;#IMPLIED--messagetoshowwhileloading--
height%Length;#IMPLIED--overrideheight--
width%Length;#IMPLIED--overridewidth--
usemap%URI;#IMPLIED--useclient-sideimagemap--
nameCDATA#IMPLIED--submitaspartofform--
tabindexNUMBER#IMPLIED--positionintabbingorder--
align%IAlign;#IMPLIED--verticalorhorizontalalignment--
border%Pixels;#IMPLIED--linkborderwidth--
hspace%Pixels;#IMPLIED--horizontalgutter--
vspace%Pixels;#IMPLIED--verticalgutter--
%reserved;--reservedforpossiblefutureuse--
>
<!ELEMENTPARAM-OEMPTY--namedpropertyvalue-->
<!ATTLISTPARAM
idID#IMPLIED--document-wideuniqueid--
nameCDATA#REQUIRED--propertyname--
valueCDATA#IMPLIED--propertyvalue--
valuetype(DATA|REF|OBJECT)DATA--Howtointerpretvalue--
type%ContentType;#IMPLIED--contenttypeforvalue
whenvaluetype=ref--
>
<!--===================JavaAPPLET==================================-->
<!--
Oneofcodeorobjectattributesmustbepresent.
PlacePARAMelementsbeforeothercontent.
-->
<!ELEMENTAPPLET--(PARAM|%flow;)*--Javaapplet-->
<!ATTLISTAPPLET
%coreattrs;--id,class,style,title--
codebase%URI;#IMPLIED--optionalbaseURIforapplet--
archiveCDATA#IMPLIED--comma-separatedarchivelist--
codeCDATA#IMPLIED--appletclassfile--
objectCDATA#IMPLIED--serializedappletfile--
alt%Text;#IMPLIED--shortdescription--
nameCDATA#IMPLIED--allowsappletstofindeachother--
width%Length;#REQUIRED--initialwidth--
height%Length;#REQUIRED--initialheight--
align%IAlign;#IMPLIED--verticalorhorizontalalignment--
hspace%Pixels;#IMPLIED--horizontalgutter--
vspace%Pixels;#IMPLIED--verticalgutter--
>
<!--===================HorizontalRule==================================-->
<!ELEMENTHR-OEMPTY--horizontalrule-->
<!ATTLISTHR
%attrs;--%coreattrs,%i18n,%events--
align(left|center|right)#IMPLIED
noshade(noshade)#IMPLIED
size%Pixels;#IMPLIED
width%Length;#IMPLIED
>
<!--===================Paragraphs=======================================-->
<!ELEMENTP-O(%inline;)*--paragraph-->
<!ATTLISTP
%attrs;--%coreattrs,%i18n,%events--
%align;--align,textalignment--
>
<!--===================Headings=========================================-->
<!--
TherearesixlevelsofheadingsfromH1(themostimportant)
toH6(theleastimportant).
-->
<!ELEMENT(%heading;)--(%inline;)*--heading-->
<!ATTLIST(%heading;)
%attrs;--%coreattrs,%i18n,%events--
%align;--align,textalignment--
>
<!--===================PreformattedText================================-->
<!--excludesmarkupforimagesandchangesinfontsize-->
<!ENTITY%pre.exclusion"IMG|OBJECT|APPLET|BIG|SMALL|SUB|SUP|FONT|BASEFONT">
<!ELEMENTPRE--(%inline;)*-(%pre.exclusion;)--preformattedtext-->
<!ATTLISTPRE
%attrs;--%coreattrs,%i18n,%events--
widthNUMBER#IMPLIED
>
<!--=====================InlineQuotes==================================-->
<!ELEMENTQ--(%inline;)*--shortinlinequotation-->
<!ATTLISTQ
%attrs;--%coreattrs,%i18n,%events--
cite%URI;#IMPLIED--URIforsourcedocumentormsg--
>
<!--===================Block-likeQuotes================================-->
<!ELEMENTBLOCKQUOTE--(%flow;)*--longquotation-->
<!ATTLISTBLOCKQUOTE
%attrs;--%coreattrs,%i18n,%events--
cite%URI;#IMPLIED--URIforsourcedocumentormsg--
>
<!--===================Inserted/DeletedText============================-->
<!--INS/DELarehandledbyinclusiononBODY-->
<!ELEMENT(INS|DEL)--(%flow;)*--insertedtext,deletedtext-->
<!ATTLIST(INS|DEL)
%attrs;--%coreattrs,%i18n,%events--
cite%URI;#IMPLIED--infoonreasonforchange--
datetime%Datetime;#IMPLIED--dateandtimeofchange--
>
<!--===================Lists============================================-->
<!--definitionlists-DTforterm,DDforitsdefinition-->
<!ELEMENTDL--(DT|DD)+--definitionlist-->
<!ATTLISTDL
%attrs;--%coreattrs,%i18n,%events--
compact(compact)#IMPLIED--reducedinteritemspacing--
>
<!ELEMENTDT-O(%inline;)*--definitionterm-->
<!ELEMENTDD-O(%flow;)*--definitiondescription-->
<!ATTLIST(DT|DD)
%attrs;--%coreattrs,%i18n,%events--
>
<!--Orderedlists(OL)numberingstyle
1arablicnumbers1,2,3,...
aloweralphaa,b,c,...
AupperalphaA,B,C,...
ilowerromani,ii,iii,...
IupperromanI,II,III,...
Thestyleisappliedtothesequencenumberwhichbydefault
isresetto1forthefirstlistiteminanorderedlist.
Thiscan'tbeexpresseddirectlyinSGMLduetocasefolding.
-->
<!ENTITY%OLStyle"CDATA"--constrainedto:"(1|a|A|i|I)"-->
<!ELEMENTOL--(LI)+--orderedlist-->
<!ATTLISTOL
%attrs;--%coreattrs,%i18n,%events--
type%OLStyle;#IMPLIED--numberingstyle--
compact(compact)#IMPLIED--reducedinteritemspacing--
startNUMBER#IMPLIED--startingsequencenumber--
>
<!--UnorderedLists(UL)bulletstyles-->
<!ENTITY%ULStyle"(disc|square|circle)">
<!ELEMENTUL--(LI)+--unorderedlist-->
<!ATTLISTUL
%attrs;--%coreattrs,%i18n,%events--
type%ULStyle;#IMPLIED--bulletstyle--
compact(compact)#IMPLIED--reducedinteritemspacing--
>
<!ELEMENT(DIR|MENU)--(LI)+-(%block;)--directorylist,menulist-->
<!ATTLISTDIR
%attrs;--%coreattrs,%i18n,%events--
compact(compact)#IMPLIED--reducedinteritemspacing--
>
<!ATTLISTMENU
%attrs;--%coreattrs,%i18n,%events--
compact(compact)#IMPLIED--reducedinteritemspacing--
>
<!ENTITY%LIStyle"CDATA"--constrainedto:"(%ULStyle;|%OLStyle;)"-->
<!ELEMENTLI-O(%flow;)*--listitem-->
<!ATTLISTLI
%attrs;--%coreattrs,%i18n,%events--
type%LIStyle;#IMPLIED--listitemstyle--
valueNUMBER#IMPLIED--resetsequencenumber--
>
<!--================Forms===============================================-->
<!ELEMENTFORM--(%flow;)*-(FORM)--interactiveform-->
<!ATTLISTFORM
%attrs;--%coreattrs,%i18n,%events--
action%URI;#REQUIRED--server-sideformhandler--
method(GET|POST)GET--HTTPmethodusedtosubmittheform--
enctype%ContentType;"application/x-www-form-urlencoded"
accept%ContentTypes;#IMPLIED--listofMIMEtypesforfileupload--
nameCDATA#IMPLIED--nameofformforscripting--
onsubmit%Script;#IMPLIED--theformwassubmitted--
onreset%Script;#IMPLIED--theformwasreset--
target%FrameTarget;#IMPLIED--renderinthisframe--
accept-charset%Charsets;#IMPLIED--listofsupportedcharsets--
>
<!--EachlabelmustnotcontainmorethanONEfield-->
<!ELEMENTLABEL--(%inline;)*-(LABEL)--formfieldlabeltext-->
<!ATTLISTLABEL
%attrs;--%coreattrs,%i18n,%events--
forIDREF#IMPLIED--matchesfieldIDvalue--
accesskey%Character;#IMPLIED--accessibilitykeycharacter--
onfocus%Script;#IMPLIED--theelementgotthefocus--
onblur%Script;#IMPLIED--theelementlostthefocus--
>
<!ENTITY%InputType
"(TEXT|PASSWORD|CHECKBOX|
RADIO|SUBMIT|RESET|
FILE|HIDDEN|IMAGE|BUTTON)"
>
<!--attributenamerequiredforallbutsubmitandreset-->
<!ELEMENTINPUT-OEMPTY--formcontrol-->
<!ATTLISTINPUT
%attrs;--%coreattrs,%i18n,%events--
type%InputType;TEXT--whatkindofwidgetisneeded--
nameCDATA#IMPLIED--submitaspartofform--
valueCDATA#IMPLIED--specifyforradiobuttonsandcheckboxes--
checked(checked)#IMPLIED--forradiobuttonsandcheckboxes--
disabled(disabled)#IMPLIED--unavailableinthiscontext--
readonly(readonly)#IMPLIED--fortextandpasswd--
sizeCDATA#IMPLIED--specifictoeachtypeoffield--
maxlengthNUMBER#IMPLIED--maxcharsfortextfields--
src%URI;#IMPLIED--forfieldswithimages--
altCDATA#IMPLIED--shortdescription--
usemap%URI;#IMPLIED--useclient-sideimagemap--
ismap(ismap)#IMPLIED--useserver-sideimagemap--
tabindexNUMBER#IMPLIED--positionintabbingorder--
accesskey%Character;#IMPLIED--accessibilitykeycharacter--
onfocus%Script;#IMPLIED--theelementgotthefocus--
onblur%Script;#IMPLIED--theelementlostthefocus--
onselect%Script;#IMPLIED--sometextwasselected--
onchange%Script;#IMPLIED--theelementvaluewaschanged--
accept%ContentTypes;#IMPLIED--listofMIMEtypesforfileupload--
align%IAlign;#IMPLIED--verticalorhorizontalalignment--
%reserved;--reservedforpossiblefutureuse--
>
<!ELEMENTSELECT--(OPTGROUP|OPTION)+--optionselector-->
<!ATTLISTSELECT
%attrs;--%coreattrs,%i18n,%events--
nameCDATA#IMPLIED--fieldname--
sizeNUMBER#IMPLIED--rowsvisible--
multiple(multiple)#IMPLIED--defaultissingleselection--
disabled(disabled)#IMPLIED--unavailableinthiscontext--
tabindexNUMBER#IMPLIED--positionintabbingorder--
onfocus%Script;#IMPLIED--theelementgotthefocus--
onblur%Script;#IMPLIED--theelementlostthefocus--
onchange%Script;#IMPLIED--theelementvaluewaschanged--
%reserved;--reservedforpossiblefutureuse--
>
<!ELEMENTOPTGROUP--(OPTION)+--optiongroup-->
<!ATTLISTOPTGROUP
%attrs;--%coreattrs,%i18n,%events--
disabled(disabled)#IMPLIED--unavailableinthiscontext--
label%Text;#REQUIRED--foruseinhierarchicalmenus--
>
<!ELEMENTOPTION-O(#PCDATA)--selectablechoice-->
<!ATTLISTOPTION
%attrs;--%coreattrs,%i18n,%events--
selected(selected)#IMPLIED
disabled(disabled)#IMPLIED--unavailableinthiscontext--
label%Text;#IMPLIED--foruseinhierarchicalmenus--
valueCDATA#IMPLIED--defaultstoelementcontent--
>
<!ELEMENTTEXTAREA--(#PCDATA)--multi-linetextfield-->
<!ATTLISTTEXTAREA
%attrs;--%coreattrs,%i18n,%events--
nameCDATA#IMPLIED
rowsNUMBER#REQUIRED
colsNUMBER#REQUIRED
disabled(disabled)#IMPLIED--unavailableinthiscontext--
readonly(readonly)#IMPLIED
tabindexNUMBER#IMPLIED--positionintabbingorder--
accesskey%Character;#IMPLIED--accessibilitykeycharacter--
onfocus%Script;#IMPLIED--theelementgotthefocus--
onblur%Script;#IMPLIED--theelementlostthefocus--
onselect%Script;#IMPLIED--sometextwasselected--
onchange%Script;#IMPLIED--theelementvaluewaschanged--
%reserved;--reservedforpossiblefutureuse--
>
<!--
#PCDATAistosolvethemixedcontentproblem,
perspecificationonlywhitespaceisallowedthere!
-->
<!ELEMENTFIELDSET--(#PCDATA,LEGEND,(%flow;)*)--formcontrolgroup-->
<!ATTLISTFIELDSET
%attrs;--%coreattrs,%i18n,%events--
>
<!ELEMENTLEGEND--(%inline;)*--fieldsetlegend-->
<!ENTITY%LAlign"(top|bottom|left|right)">
<!ATTLISTLEGEND
%attrs;--%coreattrs,%i18n,%events--
accesskey%Character;#IMPLIED--accessibilitykeycharacter--
align%LAlign;#IMPLIED--relativetofieldset--
>
<!ELEMENTBUTTON--
(%flow;)*-(A|%formctrl;|FORM|ISINDEX|FIELDSET|IFRAME)
--pushbutton-->
<!ATTLISTBUTTON
%attrs;--%coreattrs,%i18n,%events--
nameCDATA#IMPLIED
valueCDATA#IMPLIED--senttoserverwhensubmitted--
type(button|submit|reset)submit--foruseasformbutton--
disabled(disabled)#IMPLIED--unavailableinthiscontext--
tabindexNUMBER#IMPLIED--positionintabbingorder--
accesskey%Character;#IMPLIED--accessibilitykeycharacter--
onfocus%Script;#IMPLIED--theelementgotthefocus--
onblur%Script;#IMPLIED--theelementlostthefocus--
%reserved;--reservedforpossiblefutureuse--
>
<!--=======================Tables=======================================-->
<!--IETFHTMLtablestandard,see[RFC1942]-->
<!--
TheBORDERattributesetsthethicknessoftheframearoundthe
table.Thedefaultunitsarescreenpixels.
TheFRAMEattributespecifieswhichpartsoftheframearound
thetableshouldberendered.Thevaluesarenotthesameas
CALStoavoidanameclashwiththeVALIGNattribute.
Thevalue"border"isincludedforbackwardscompatibilitywith
<TABLEBORDER>whichyieldsframe=borderandborder=implied
For<TABLEBORDER=1>yougetborder=1andframe=implied.Inthis
case,itisappropriatetotreatthisasframe=borderforbackwards
compatibilitywithdeployedbrowsers.
-->
<!ENTITY%TFrame"(void|above|below|hsides|lhs|rhs|vsides|box|border)">
<!--
TheRULESattributedefineswhichrulestodrawbetweencells:
IfRULESisabsentthenassume:
"none"ifBORDERisabsentorBORDER=0otherwise"all"
-->
<!ENTITY%TRules"(none|groups|rows|cols|all)">
<!--horizontalplacementoftablerelativetodocument-->
<!ENTITY%TAlign"(left|center|right)">
<!--horizontalalignmentattributesforcellcontents-->
<!ENTITY%cellhalign
"align(left|center|right|justify|char)#IMPLIED
char%Character;#IMPLIED--alignmentchar,e.g.char=':'--
charoff%Length;#IMPLIED--offsetforalignmentchar--"
>
<!--verticalalignmentattributesforcellcontents-->
<!ENTITY%cellvalign
"valign(top|middle|bottom|baseline)#IMPLIED"
>
<!ELEMENTTABLE--
(CAPTION?,(COL*|COLGROUP*),THEAD?,TFOOT?,TBODY+)>
<!ELEMENTCAPTION--(%inline;)*--tablecaption-->
<!ELEMENTTHEAD-O(TR)+--tableheader-->
<!ELEMENTTFOOT-O(TR)+--tablefooter-->
<!ELEMENTTBODYOO(TR)+--tablebody-->
<!ELEMENTCOLGROUP-O(COL)*--tablecolumngroup-->
<!ELEMENTCOL-OEMPTY--tablecolumn-->
<!ELEMENTTR-O(TH|TD)+--tablerow-->
<!ELEMENT(TH|TD)-O(%flow;)*--tableheadercell,tabledatacell-->
<!ATTLISTTABLE--tableelement--
%attrs;--%coreattrs,%i18n,%events--
summary%Text;#IMPLIED--purpose/structureforspeechoutput--
width%Length;#IMPLIED--tablewidth--
border%Pixels;#IMPLIED--controlsframewidtharoundtable--
frame%TFrame;#IMPLIED--whichpartsofframetorender--
rules%TRules;#IMPLIED--rulingsbetweenrowsandcols--
cellspacing%Length;#IMPLIED--spacingbetweencells--
cellpadding%Length;#IMPLIED--spacingwithincells--
align%TAlign;#IMPLIED--tablepositionrelativetowindow--
bgcolor%Color;#IMPLIED--backgroundcolorforcells--
%reserved;--reservedforpossiblefutureuse--
datapagesizeCDATA#IMPLIED--reservedforpossiblefutureuse--
>
<!ENTITY%CAlign"(top|bottom|left|right)">
<!ATTLISTCAPTION
%attrs;--%coreattrs,%i18n,%events--
align%CAlign;#IMPLIED--relativetotable--
>
<!--
COLGROUPgroupsasetofCOLelements.Itallowsyoutogroup
severalsemanticallyrelatedcolumnstogether.
-->
<!ATTLISTCOLGROUP
%attrs;--%coreattrs,%i18n,%events--
spanNUMBER1--defaultnumberofcolumnsingroup--
width%MultiLength;#IMPLIED--defaultwidthforenclosedCOLs--
%cellhalign;--horizontalalignmentincells--
%cellvalign;--verticalalignmentincells--
>
<!--
COLelementsdefinethealignmentpropertiesforcellsin
oneormorecolumns.
TheWIDTHattributespecifiesthewidthofthecolumns,e.g.
width=64widthinscreenpixels
width=0.5*relativewidthof0.5
TheSPANattributecausestheattributesofone
COLelementtoapplytomorethanonecolumn.
-->
<!ATTLISTCOL--columngroupsandproperties--
%attrs;--%coreattrs,%i18n,%events--
spanNUMBER1--COLattributesaffectNcolumns--
width%MultiLength;#IMPLIED--columnwidthspecification--
%cellhalign;--horizontalalignmentincells--
%cellvalign;--verticalalignmentincells--
>
<!--
UseTHEADtoduplicateheaderswhenbreakingtable
acrosspageboundaries,orforstaticheaderswhen
TBODYsectionsarerenderedinscrollingpanel.
UseTFOOTtoduplicatefooterswhenbreakingtable
acrosspageboundaries,orforstaticfooterswhen
TBODYsectionsarerenderedinscrollingpanel.
UsemultipleTBODYsectionswhenrulesareneeded
betweengroupsoftablerows.
-->
<!ATTLIST(THEAD|TBODY|TFOOT)--tablesection--
%attrs;--%coreattrs,%i18n,%events--
%cellhalign;--horizontalalignmentincells--
%cellvalign;--verticalalignmentincells--
>
<!ATTLISTTR--tablerow--
%attrs;--%coreattrs,%i18n,%events--
%cellhalign;--horizontalalignmentincells--
%cellvalign;--verticalalignmentincells--
bgcolor%Color;#IMPLIED--backgroundcolorforrow--
>
<!--Scopeissimplerthanheadersattributeforcommontables-->
<!ENTITY%Scope"(row|col|rowgroup|colgroup)">
<!--THisforheaders,TDfordata,butforcellsactingasbothuseTD-->
<!ATTLIST(TH|TD)--headerordatacell--
%attrs;--%coreattrs,%i18n,%events--
abbr%Text;#IMPLIED--abbreviationforheadercell--
axisCDATA#IMPLIED--comma-separatedlistofrelatedheaders--
headersIDREFS#IMPLIED--listofid'sforheadercells--
scope%Scope;#IMPLIED--scopecoveredbyheadercells--
rowspanNUMBER1--numberofrowsspannedbycell--
colspanNUMBER1--numberofcolsspannedbycell--
%cellhalign;--horizontalalignmentincells--
%cellvalign;--verticalalignmentincells--
nowrap(nowrap)#IMPLIED--suppresswordwrap--
bgcolor%Color;#IMPLIED--cellbackgroundcolor--
width%Length;#IMPLIED--widthforcell--
height%Length;#IMPLIED--heightforcell--
>
<!--==================DocumentFrames===================================-->
<!--
ThecontentmodelforHTMLdocumentsdependsonwhethertheHEADis
followedbyaFRAMESETorBODYelement.Thewidespreadomissionof
theBODYstarttagmakesitimpracticaltodefinethecontentmodel
withouttheuseofamarkedsection.
-->
<![%HTML.Frameset;[
<!ELEMENTFRAMESET--((FRAMESET|FRAME)+&NOFRAMES?)--windowsubdivision-->
<!ATTLISTFRAMESET
%coreattrs;--id,class,style,title--
rows%MultiLengths;#IMPLIED--listoflengths,default:100%(1row)--
cols%MultiLengths;#IMPLIED--listoflengths,default:100%(1col)--
onload%Script;#IMPLIED--alltheframeshavebeenloaded--
onunload%Script;#IMPLIED--alltheframeshavebeenremoved--
>
]]>
<![%HTML.Frameset;[
<!--reservedframenamesstartwith"_"otherwisestartswithletter-->
<!ELEMENTFRAME-OEMPTY--subwindow-->
<!ATTLISTFRAME
%coreattrs;--id,class,style,title--
longdesc%URI;#IMPLIED--linktolongdescription
(complementstitle)--
nameCDATA#IMPLIED--nameofframefortargetting--
src%URI;#IMPLIED--sourceofframecontent--
frameborder(1|0)1--requestframeborders?--
marginwidth%Pixels;#IMPLIED--marginwidthsinpixels--
marginheight%Pixels;#IMPLIED--marginheightinpixels--
noresize(noresize)#IMPLIED--allowuserstoresizeframes?--
scrolling(yes|no|auto)auto--scrollbarornone--
>
]]>
<!ELEMENTIFRAME--(%flow;)*--inlinesubwindow-->
<!ATTLISTIFRAME
%coreattrs;--id,class,style,title--
longdesc%URI;#IMPLIED--linktolongdescription
(complementstitle)--
nameCDATA#IMPLIED--nameofframefortargetting--
src%URI;#IMPLIED--sourceofframecontent--
frameborder(1|0)1--requestframeborders?--
marginwidth%Pixels;#IMPLIED--marginwidthsinpixels--
marginheight%Pixels;#IMPLIED--marginheightinpixels--
scrolling(yes|no|auto)auto--scrollbarornone--
align%IAlign;#IMPLIED--verticalorhorizontalalignment--
height%Length;#IMPLIED--frameheight--
width%Length;#IMPLIED--framewidth--
>
<![%HTML.Frameset;[
<!ENTITY%noframes.content"(BODY)-(NOFRAMES)">
]]>
<!ENTITY%noframes.content"(%flow;)*">
<!ELEMENTNOFRAMES--%noframes.content;
--alternatecontentcontainerfornonframe-basedrendering-->
<!ATTLISTNOFRAMES
%attrs;--%coreattrs,%i18n,%events--
>
<!--================DocumentHead=======================================-->
<!--%head.misc;definedearlieronas"SCRIPT|STYLE|META|LINK|OBJECT"-->
<!ENTITY%head.content"TITLE&ISINDEX?&BASE?">
<!ELEMENTHEADOO(%head.content;)+(%head.misc;)--documenthead-->
<!ATTLISTHEAD
%i18n;--lang,dir--
profile%URI;#IMPLIED--nameddictionaryofmetainfo--
>
<!--TheTITLEelementisnotconsideredpartoftheflowoftext.
Itshouldbedisplayed,forexampleasthepageheaderor
windowtitle.Exactlyonetitleisrequiredperdocument.
-->
<!ELEMENTTITLE--(#PCDATA)-(%head.misc;)--documenttitle-->
<!ATTLISTTITLE%i18n>
<!ELEMENTISINDEX-OEMPTY--singlelineprompt-->
<!ATTLISTISINDEX
%coreattrs;--id,class,style,title--
%i18n;--lang,dir--
prompt%Text;#IMPLIED--promptmessage-->
<!ELEMENTBASE-OEMPTY--documentbaseURI-->
<!ATTLISTBASE
href%URI;#IMPLIED--URIthatactsasbaseURI--
target%FrameTarget;#IMPLIED--renderinthisframe--
>
<!ELEMENTMETA-OEMPTY--genericmetainformation-->
<!ATTLISTMETA
%i18n;--lang,dir,forusewithcontent--
http-equivNAME#IMPLIED--HTTPresponseheadername--
nameNAME#IMPLIED--metainformationname--
contentCDATA#REQUIRED--associatedinformation--
schemeCDATA#IMPLIED--selectformofcontent--
>
<!ELEMENTSTYLE--%StyleSheet--styleinfo-->
<!ATTLISTSTYLE
%i18n;--lang,dir,forusewithtitle--
type%ContentType;#REQUIRED--contenttypeofstylelanguage--
media%MediaDesc;#IMPLIED--designedforusewiththesemedia--
title%Text;#IMPLIED--advisorytitle--
>
<!ELEMENTSCRIPT--%Script;--scriptstatements-->
<!ATTLISTSCRIPT
charset%Charset;#IMPLIED--charencodingoflinkedresource--
type%ContentType;#REQUIRED--contenttypeofscriptlanguage--
languageCDATA#IMPLIED--predefinedscriptlanguagename--
src%URI;#IMPLIED--URIforanexternalscript--
defer(defer)#IMPLIED--UAmaydeferexecutionofscript--
eventCDATA#IMPLIED--reservedforpossiblefutureuse--
for%URI;#IMPLIED--reservedforpossiblefutureuse--
>
<!ELEMENTNOSCRIPT--(%flow;)*
--alternatecontentcontainerfornonscript-basedrendering-->
<!ATTLISTNOSCRIPT
%attrs;--%coreattrs,%i18n,%events--
>
<!--================DocumentStructure==================================-->
<!ENTITY%version"versionCDATA#FIXED'%HTML.Version;'">
<![%HTML.Frameset;[
<!ENTITY%html.content"HEAD,FRAMESET">
]]>
<!ENTITY%html.content"HEAD,BODY">
<!ELEMENTHTMLOO(%html.content;)--documentrootelement-->
<!ATTLISTHTML
%i18n;--lang,dir--
%version;
>
AppendixE.TheXHTML1.0DTD
TheXHTML1.0standardisformallydefinedasthreeExtensibleMarkupLanguage
(XML)DocumentTypeDefinitions(DTDs):theStrictDTD,theTransitionalDTD,
andtheFramesetDTD.TheseDTDscorrespondtotherespectiveHTML4.01DTDs,
definingthesameelementsandattributesusingXMLratherthantheStandard
GeneralizedMarkupLanguage(SGML)astheDTDauthoringlanguage.
TheStrictDTDdefinesonlythoseelementsthatarenotdeprecatedintheHTML
4.01standard.Ideally,everyonewouldcreateXHTMLdocumentsthatconformto
theStrictDTD.TheTransitionalDTDincludesallthosedeprecatedelementsand
moreaccuratelyreflectstheHTMLinusetoday,withmanyolderelementsstillin
commonuse.TheFramesetDTDisidenticaltotheTransitionalDTD,withthe
exceptionthatthedocument<body>isreplacedbythe<frameset>element.
SincetheHTMLTransitionalDTDistheoneuponwhichthisbookisbased,itis
onlyappropriatethatweincludethecorrespondingXHTMLDTD.Notethatwe
havereprintedthisDTDverbatimandhavenotattemptedtoaddextensionstoit.
WhereourdescriptionandtheDTDdeviate,assumetheDTDiscorrect:
<!--
ExtensibleHTMLversion1.0TransitionalDTD
ThisisthesameasHTML4.0Transitionalexceptfor
changesduetothedifferencesbetweenXMLandSGML.
Namespace=http://www.w3.org/1999/xhtml
Forfurtherinformation,see:http://www.w3.org/TR/xhtml1
Copyright(c)1998-2000W3C(MIT,INRIA,Keio),
AllRightsReserved.
ThisDTDmoduleisidentifiedbythePUBLICandSYSTEMidentifiers:
PUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
SYSTEM"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
$Revision:1.2$
$Date:2006/10/2517:08:45$
-->
<!--================Charactermnemonicentities=========================-->
<!ENTITY%HTMLlat1PUBLIC
"-//W3C//ENTITIESLatin1forXHTML//EN"
"xhtml-lat1.ent">
%HTMLlat1;
<!ENTITY%HTMLsymbolPUBLIC
"-//W3C//ENTITIESSymbolsforXHTML//EN"
"xhtml-symbol.ent">
%HTMLsymbol;
<!ENTITY%HTMLspecialPUBLIC
"-//W3C//ENTITIESSpecialforXHTML//EN"
"xhtml-special.ent">
%HTMLspecial;
<!--==================ImportedNames====================================-->
<!ENTITY%ContentType"CDATA">
<!--mediatype,asper[RFC2045]-->
<!ENTITY%ContentTypes"CDATA">
<!--comma-separatedlistofmediatypes,asper[RFC2045]-->
<!ENTITY%Charset"CDATA">
<!--acharacterencoding,asper[RFC2045]-->
<!ENTITY%Charsets"CDATA">
<!--aspaceseparatedlistofcharacterencodings,asper[RFC2045]-->
<!ENTITY%LanguageCode"NMTOKEN">
<!--alanguagecode,asper[RFC1766]-->
<!ENTITY%Character"CDATA">
<!--asinglecharacterfrom[ISO10646]-->
<!ENTITY%Number"CDATA">
<!--oneormoredigits-->
<!ENTITY%LinkTypes"CDATA">
<!--space-separatedlistoflinktypes-->
<!ENTITY%MediaDesc"CDATA">
<!--singleorcomma-separatedlistofmediadescriptors-->
<!ENTITY%URI"CDATA">
<!--aUniformResourceIdentifier,see[RFC2396]-->
<!ENTITY%UriList"CDATA">
<!--aspaceseparatedlistofUniformResourceIdentifiers-->
<!ENTITY%Datetime"CDATA">
<!--dateandtimeinformation.ISOdateformat-->
<!ENTITY%Script"CDATA">
<!--scriptexpression-->
<!ENTITY%StyleSheet"CDATA">
<!--stylesheetdata-->
<!ENTITY%Text"CDATA">
<!--usedfortitlesetc.-->
<!ENTITY%FrameTarget"NMTOKEN">
<!--renderinthisframe-->
<!ENTITY%Length"CDATA">
<!--nnforpixelsornn%forpercentagelength-->
<!ENTITY%MultiLength"CDATA">
<!--pixel,percentage,orrelative-->
<!ENTITY%MultiLengths"CDATA">
<!--comma-separatedlistofMultiLength-->
<!ENTITY%Pixels"CDATA">
<!--integerrepresentinglengthinpixels-->
<!--theseareusedforimagemaps-->
<!ENTITY%Shape"(rect|circle|poly|default)">
<!ENTITY%Coords"CDATA">
<!--commaseparatedlistoflengths-->
<!--usedforobject,applet,img,inputandiframe-->
<!ENTITY%ImgAlign"(top|middle|bottom|left|right)">
<!--acolorusingsRGB:#RRGGBBasHexvalues-->
<!ENTITY%Color"CDATA">
<!--Therearealso16widelyknowncolornameswiththeirsRGBvalues:
Black=#000000Green=#008000
Silver=#C0C0C0Lime=#00FF00
Gray=#808080Olive=#808000
White=#FFFFFFYellow=#FFFF00
Maroon=#800000Navy=#000080
Red=#FF0000Blue=#0000FF
Purple=#800080Teal=#008080
Fuchsia=#FF00FFAqua=#00FFFF
-->
<!--===================GenericAttributes===============================-->
<!--coreattributescommontomostelements
iddocument-wideuniqueid
classspaceseparatedlistofclasses
styleassociatedstyleinfo
titleadvisorytitle/amplification
-->
<!ENTITY%coreattrs
"idID#IMPLIED
classCDATA#IMPLIED
style%StyleSheet;#IMPLIED
title%Text;#IMPLIED"
>
<!--internationalizationattributes
langlanguagecode(backwardscompatible)
xml:langlanguagecode(asperXML1.0spec)
dirdirectionforweak/neutraltext
-->
<!ENTITY%i18n
"lang%LanguageCode;#IMPLIED
xml:lang%LanguageCode;#IMPLIED
dir(ltr|rtl)#IMPLIED"
>
<!--attributesforcommonUIevents
onclickapointerbuttonwasclicked
ondblclickapointerbuttonwasdoubleclicked
onmousedownapointerbuttonwaspresseddown
onmouseupapointerbuttonwasreleased
onmousemoveapointerwasmovedontotheelement
onmouseoutapointerwasmovedawayfromtheelement
onkeypressakeywaspressedandreleased
onkeydownakeywaspresseddown
onkeyupakeywasreleased
-->
<!ENTITY%events
"onclick%Script;#IMPLIED
ondblclick%Script;#IMPLIED
onmousedown%Script;#IMPLIED
onmouseup%Script;#IMPLIED
onmouseover%Script;#IMPLIED
onmousemove%Script;#IMPLIED
onmouseout%Script;#IMPLIED
onkeypress%Script;#IMPLIED
onkeydown%Script;#IMPLIED
onkeyup%Script;#IMPLIED"
>
<!--attributesforelementsthatcangetthefocus
accesskeyaccessibilitykeycharacter
tabindexpositionintabbingorder
onfocustheelementgotthefocus
onblurtheelementlostthefocus
-->
<!ENTITY%focus
"accesskey%Character;#IMPLIED
tabindex%Number;#IMPLIED
onfocus%Script;#IMPLIED
onblur%Script;#IMPLIED"
>
<!ENTITY%attrs"%coreattrs;%i18n;%events;">
<!--textalignmentforp,div,h1-h6.Thedefaultis
align="left"forltrheadings,"right"forrtl-->
<!ENTITY%TextAlign"align(left|center|right)#IMPLIED">
<!--===================TextElements====================================-->
<!ENTITY%special
"br|span|bdo|object|applet|img|map|iframe">
<!ENTITY%fontstyle"tt|i|b|big|small|u
|s|strike|font|basefont">
<!ENTITY%phrase"em|strong|dfn|code|q|sub|sup|
samp|kbd|var|cite|abbr|acronym">
<!ENTITY%inline.forms"input|select|textarea|label|button">
<!--thesecanoccuratblockorinlinelevel-->
<!ENTITY%misc"ins|del|script|noscript">
<!ENTITY%inline"a|%special;|%fontstyle;|%phrase;|%inline.forms;">
<!--%Inline;coversinlineor"text-level"elements-->
<!ENTITY%Inline"(#PCDATA|%inline;|%misc;)*">
<!--==================Blocklevelelements==============================-->
<!ENTITY%heading"h1|h2|h3|h4|h5|h6">
<!ENTITY%lists"ul|ol|dl|menu|dir">
<!ENTITY%blocktext"pre|hr|blockquote|address|center|noframes">
<!ENTITY%block
"p|%heading;|div|%lists;|%blocktext;|isindex|fieldset|table">
<!ENTITY%Block"(%block;|form|%misc;)*">
<!--%Flow;mixesBlockandInlineandisusedforlistitemsetc.-->
<!ENTITY%Flow"(#PCDATA|%block;|form|%inline;|%misc;)*">
<!--==================Contentmodelsforexclusions=====================-->
<!--aelementsuse%Inline;excludinga-->
<!ENTITY%a.content
"(#PCDATA|%special;|%fontstyle;|%phrase;|%inline.forms;|%misc;)*">
<!--preuses%Inlineexcludingimg,object,applet,big,small,
sub,sup,font,orbasefont-->
<!ENTITY%pre.content
"(#PCDATA|a|br|span|bdo|map|tt|i|b|u|s|
%phrase;|%inline.forms;)*">
<!--formuses%Flow;excludingform-->
<!ENTITY%form.content"(#PCDATA|%block;|%inline;|%misc;)*">
<!--buttonuses%Flow;butexcludesa,form,formcontrols,iframe-->
<!ENTITY%button.content
"(#PCDATA|p|%heading;|div|%lists;|%blocktext;|
table|br|span|bdo|object|applet|img|map|
%fontstyle;|%phrase;|%misc;)*">
<!--================DocumentStructure==================================-->
<!--thenamespaceURIdesignatesthedocumentprofile-->
<!ELEMENThtml(head,body)>
<!ATTLISThtml
%i18n;
xmlns%URI;#FIXED'http://www.w3.org/1999/xhtml'
>
<!--================DocumentHead=======================================-->
<!ENTITY%head.misc"(script|style|meta|link|object|isindex)*">
<!--contentmodelis%head.misc;combinedwithasingle
titleandanoptionalbaseelementinanyorder-->
<!ELEMENThead(%head.misc;,
((title,%head.misc;,(base,%head.misc;)?)|
(base,%head.misc;,(title,%head.misc;))))>
<!ATTLISThead
%i18n;
profile%URI;#IMPLIED
>
<!--Thetitleelementisnotconsideredpartoftheflowoftext.
Itshouldbedisplayed,forexampleasthepageheaderor
windowtitle.Exactlyonetitleisrequiredperdocument.
-->
<!ELEMENTtitle(#PCDATA)>
<!ATTLISTtitle%i18n;>
<!--documentbaseURI-->
<!ELEMENTbaseEMPTY>
<!ATTLISTbase
href%URI;#IMPLIED
target%FrameTarget;#IMPLIED
>
<!--genericmetainformation-->
<!ELEMENTmetaEMPTY>
<!ATTLISTmeta
%i18n;
http-equivCDATA#IMPLIED
nameCDATA#IMPLIED
contentCDATA#REQUIRED
schemeCDATA#IMPLIED
>
<!--
Relationshipvaluescanbeusedinprinciple:
a)fordocumentspecifictoolbars/menuswhenused
withthelinkelementindocumentheade.g.
start,contents,previous,next,index,end,help
b)tolinktoaseparatestylesheet(rel="stylesheet")
c)tomakealinktoascript(rel="script")
d)bystylesheetstocontrolhowcollectionsof
htmlnodesarerenderedintoprinteddocuments
e)tomakealinktoaprintableversionofthisdocument
e.g.aPostScriptorPDFversion(rel="alternate"media="print")
-->
<!ELEMENTlinkEMPTY>
<!ATTLISTlink
%attrs;
charset%Charset;#IMPLIED
href%URI;#IMPLIED
hreflang%LanguageCode;#IMPLIED
type%ContentType;#IMPLIED
rel%LinkTypes;#IMPLIED
rev%LinkTypes;#IMPLIED
media%MediaDesc;#IMPLIED
target%FrameTarget;#IMPLIED
>
<!--styleinfo,whichmayincludeCDATAsections-->
<!ELEMENTstyle(#PCDATA)>
<!ATTLISTstyle
%i18n;
type%ContentType;#REQUIRED
media%MediaDesc;#IMPLIED
title%Text;#IMPLIED
xml:space(preserve)#FIXED'preserve'
>
<!--scriptstatements,whichmayincludeCDATAsections-->
<!ELEMENTscript(#PCDATA)>
<!ATTLISTscript
charset%Charset;#IMPLIED
type%ContentType;#REQUIRED
languageCDATA#IMPLIED
src%URI;#IMPLIED
defer(defer)#IMPLIED
xml:space(preserve)#FIXED'preserve'
>
<!--alternatecontentcontainerfornonscript-basedrendering-->
<!ELEMENTnoscript%Flow;>
<!ATTLISTnoscript
%attrs;
>
<!--=======================Frames=======================================-->
<!--inlinesubwindow-->
<!ELEMENTiframe%Flow;>
<!ATTLISTiframe
%coreattrs;
longdesc%URI;#IMPLIED
nameNMTOKEN#IMPLIED
src%URI;#IMPLIED
frameborder(1|0)"1"
marginwidth%Pixels;#IMPLIED
marginheight%Pixels;#IMPLIED
scrolling(yes|no|auto)"auto"
align%ImgAlign;#IMPLIED
height%Length;#IMPLIED
width%Length;#IMPLIED
>
<!--alternatecontentcontainerfornonframe-basedrendering-->
<!ELEMENTnoframes%Flow;>
<!ATTLISTnoframes
%attrs;
>
<!--===================DocumentBody====================================-->
<!ELEMENTbody%Flow;>
<!ATTLISTbody
%attrs;
onload%Script;#IMPLIED
onunload%Script;#IMPLIED
background%URI;#IMPLIED
bgcolor%Color;#IMPLIED
text%Color;#IMPLIED
link%Color;#IMPLIED
vlink%Color;#IMPLIED
alink%Color;#IMPLIED
>
<!ELEMENTdiv%Flow;><!--genericlanguage/stylecontainer-->
<!ATTLISTdiv
%attrs;
%TextAlign;
>
<!--===================Paragraphs=======================================-->
<!ELEMENTp%Inline;>
<!ATTLISTp
%attrs;
%TextAlign;
>
<!--===================Headings=========================================-->
<!--
Therearesixlevelsofheadingsfromh1(themostimportant)
toh6(theleastimportant).
-->
<!ELEMENTh1%Inline;>
<!ATTLISTh1
%attrs;
%TextAlign;
>
<!ELEMENTh2%Inline;>
<!ATTLISTh2
%attrs;
%TextAlign;
>
<!ELEMENTh3%Inline;>
<!ATTLISTh3
%attrs;
%TextAlign;
>
<!ELEMENTh4%Inline;>
<!ATTLISTh4
%attrs;
%TextAlign;
>
<!ELEMENTh5%Inline;>
<!ATTLISTh5
%attrs;
%TextAlign;
>
<!ELEMENTh6%Inline;>
<!ATTLISTh6
%attrs;
%TextAlign;
>
<!--===================Lists============================================-->
<!--Unorderedlistbulletstyles-->
<!ENTITY%ULStyle"(disc|square|circle)">
<!--Unorderedlist-->
<!ELEMENTul(li)+>
<!ATTLISTul
%attrs;
type%ULStyle;#IMPLIED
compact(compact)#IMPLIED
>
<!--Orderedlistnumberingstyle
1arabicnumbers1,2,3,...
aloweralphaa,b,c,...
AupperalphaA,B,C,...
ilowerromani,ii,iii,...
IupperromanI,II,III,...
Thestyleisappliedtothesequencenumberwhichbydefault
isresetto1forthefirstlistiteminanorderedlist.
-->
<!ENTITY%OLStyle"CDATA">
<!--Ordered(numbered)list-->
<!ELEMENTol(li)+>
<!ATTLISTol
%attrs;
type%OLStyle;#IMPLIED
compact(compact)#IMPLIED
start%Number;#IMPLIED
>
<!--singlecolumnlist(DEPRECATED)-->
<!ELEMENTmenu(li)+>
<!ATTLISTmenu
%attrs;
compact(compact)#IMPLIED
>
<!--multiplecolumnlist(DEPRECATED)-->
<!ELEMENTdir(li)+>
<!ATTLISTdir
%attrs;
compact(compact)#IMPLIED
>
<!--LIStyleisconstrainedto:"(%ULStyle;|%OLStyle;)"-->
<!ENTITY%LIStyle"CDATA">
<!--listitem-->
<!ELEMENTli%Flow;>
<!ATTLISTli
%attrs;
type%LIStyle;#IMPLIED
value%Number;#IMPLIED
>
<!--definitionlists-dtforterm,ddforitsdefinition-->
<!ELEMENTdl(dt|dd)+>
<!ATTLISTdl
%attrs;
compact(compact)#IMPLIED
>
<!ELEMENTdt%Inline;>
<!ATTLISTdt
%attrs;
>
<!ELEMENTdd%Flow;>
<!ATTLISTdd
%attrs;
>
<!--===================Address==========================================-->
<!--informationonauthor-->
<!ELEMENTaddress%Inline;>
<!ATTLISTaddress
%attrs;
>
<!--===================HorizontalRule==================================-->
<!ELEMENThrEMPTY>
<!ATTLISThr
%attrs;
align(left|center|right)#IMPLIED
noshade(noshade)#IMPLIED
size%Pixels;#IMPLIED
width%Length;#IMPLIED
>
<!--===================PreformattedText================================-->
<!--contentis%Inline;excluding
"img|object|applet|big|small|sub|sup|font|basefont"-->
<!ELEMENTpre%pre.content;>
<!ATTLISTpre
%attrs;
width%Number;#IMPLIED
xml:space(preserve)#FIXED'preserve'
>
<!--===================Block-likeQuotes================================-->
<!ELEMENTblockquote%Flow;>
<!ATTLISTblockquote
%attrs;
cite%URI;#IMPLIED
>
<!--===================Textalignment===================================-->
<!--centercontent-->
<!ELEMENTcenter%Flow;>
<!ATTLISTcenter
%attrs;
>
<!--===================Inserted/DeletedText============================-->
<!--
ins/delareallowedinblockandinlinecontent,butits
inappropriatetoincludeblockcontentwithinaninselement
occurringininlinecontent.
-->
<!ELEMENTins%Flow;>
<!ATTLISTins
%attrs;
cite%URI;#IMPLIED
datetime%Datetime;#IMPLIED
>
<!ELEMENTdel%Flow;>
<!ATTLISTdel
%attrs;
cite%URI;#IMPLIED
datetime%Datetime;#IMPLIED
>
<!--==================TheAnchorElement================================-->
<!--contentis%Inline;exceptthatanchorsshouldn'tbenested-->
<!ELEMENTa%a.content;>
<!ATTLISTa
%attrs;
charset%Charset;#IMPLIED
type%ContentType;#IMPLIED
nameNMTOKEN#IMPLIED
href%URI;#IMPLIED
hreflang%LanguageCode;#IMPLIED
rel%LinkTypes;#IMPLIED
rev%LinkTypes;#IMPLIED
accesskey%Character;#IMPLIED
shape%Shape;"rect"
coords%Coords;#IMPLIED
tabindex%Number;#IMPLIED
onfocus%Script;#IMPLIED
onblur%Script;#IMPLIED
target%FrameTarget;#IMPLIED
>
<!--=====================InlineElements================================-->
<!ELEMENTspan%Inline;><!--genericlanguage/stylecontainer-->
<!ATTLISTspan
%attrs;
>
<!ELEMENTbdo%Inline;><!--I18NBiDiover-ride-->
<!ATTLISTbdo
%coreattrs;
%events;
lang%LanguageCode;#IMPLIED
xml:lang%LanguageCode;#IMPLIED
dir(ltr|rtl)#REQUIRED
>
<!ELEMENTbrEMPTY><!--forcedlinebreak-->
<!ATTLISTbr
%coreattrs;
clear(left|all|right|none)"none"
>
<!ELEMENTem%Inline;><!--emphasis-->
<!ATTLISTem%attrs;>
<!ELEMENTstrong%Inline;><!--strongemphasis-->
<!ATTLISTstrong%attrs;>
<!ELEMENTdfn%Inline;><!--definitional-->
<!ATTLISTdfn%attrs;>
<!ELEMENTcode%Inline;><!--programcode-->
<!ATTLISTcode%attrs;>
<!ELEMENTsamp%Inline;><!--sample-->
<!ATTLISTsamp%attrs;>
<!ELEMENTkbd%Inline;><!--somethinguserwouldtype-->
<!ATTLISTkbd%attrs;>
<!ELEMENTvar%Inline;><!--variable-->
<!ATTLISTvar%attrs;>
<!ELEMENTcite%Inline;><!--citation-->
<!ATTLISTcite%attrs;>
<!ELEMENTabbr%Inline;><!--abbreviation-->
<!ATTLISTabbr%attrs;>
<!ELEMENTacronym%Inline;><!--acronym-->
<!ATTLISTacronym%attrs;>
<!ELEMENTq%Inline;><!--inlinedquote-->
<!ATTLISTq
%attrs;
cite%URI;#IMPLIED
>
<!ELEMENTsub%Inline;><!--subscript-->
<!ATTLISTsub%attrs;>
<!ELEMENTsup%Inline;><!--superscript-->
<!ATTLISTsup%attrs;>
<!ELEMENTtt%Inline;><!--fixedpitchfont-->
<!ATTLISTtt%attrs;>
<!ELEMENTi%Inline;><!--italicfont-->
<!ATTLISTi%attrs;>
<!ELEMENTb%Inline;><!--boldfont-->
<!ATTLISTb%attrs;>
<!ELEMENTbig%Inline;><!--biggerfont-->
<!ATTLISTbig%attrs;>
<!ELEMENTsmall%Inline;><!--smallerfont-->
<!ATTLISTsmall%attrs;>
<!ELEMENTu%Inline;><!--underline-->
<!ATTLISTu%attrs;>
<!ELEMENTs%Inline;><!--strike-through-->
<!ATTLISTs%attrs;>
<!ELEMENTstrike%Inline;><!--strike-through-->
<!ATTLISTstrike%attrs;>
<!ELEMENTbasefontEMPTY><!--basefontsize-->
<!ATTLISTbasefont
idID#IMPLIED
sizeCDATA#REQUIRED
color%Color;#IMPLIED
faceCDATA#IMPLIED
>
<!ELEMENTfont%Inline;><!--localchangetofont-->
<!ATTLISTfont
%coreattrs;
%i18n;
sizeCDATA#IMPLIED
color%Color;#IMPLIED
faceCDATA#IMPLIED
>
<!--====================Object======================================-->
<!--
objectisusedtoembedobjectsaspartofHTMLpages.
paramelementsshouldprecedeothercontent.Parameters
canalsobeexpressedasattribute/valuepairsonthe
objectelementitselfwhenbrevityisdesired.
-->
<!ELEMENTobject(#PCDATA|param|%block;|form|%inline;|%misc;)*>
<!ATTLISTobject
%attrs;
declare(declare)#IMPLIED
classid%URI;#IMPLIED
codebase%URI;#IMPLIED
data%URI;#IMPLIED
type%ContentType;#IMPLIED
codetype%ContentType;#IMPLIED
archive%UriList;#IMPLIED
standby%Text;#IMPLIED
height%Length;#IMPLIED
width%Length;#IMPLIED
usemap%URI;#IMPLIED
nameNMTOKEN#IMPLIED
tabindex%Number;#IMPLIED
align%ImgAlign;#IMPLIED
border%Pixels;#IMPLIED
hspace%Pixels;#IMPLIED
vspace%Pixels;#IMPLIED
>
<!--
paramisusedtosupplyanamedpropertyvalue.
InXMLitwouldseemnaturaltofollowRDFandsupportan
abbreviatedsyntaxwheretheparamelementsarereplaced
byattributevaluepairsontheobjectstarttag.
-->
<!ELEMENTparamEMPTY>
<!ATTLISTparam
idID#IMPLIED
nameCDATA#REQUIRED
valueCDATA#IMPLIED
valuetype(data|ref|object)"data"
type%ContentType;#IMPLIED
>
<!--===================Javaapplet==================================-->
<!--
Oneofcodeorobjectattributesmustbepresent.
Placeparamelementsbeforeothercontent.
-->
<!ELEMENTapplet(#PCDATA|param|%block;|form|%inline;|%misc;)*>
<!ATTLISTapplet
%coreattrs;
codebase%URI;#IMPLIED
archiveCDATA#IMPLIED
codeCDATA#IMPLIED
objectCDATA#IMPLIED
alt%Text;#IMPLIED
nameNMTOKEN#IMPLIED
width%Length;#REQUIRED
height%Length;#REQUIRED
align%ImgAlign;#IMPLIED
hspace%Pixels;#IMPLIED
vspace%Pixels;#IMPLIED
>
<!--===================Images===========================================-->
<!--
Toavoidaccessibilityproblemsforpeoplewhoaren't
abletoseetheimage,youshouldprovideatext
descriptionusingthealtandlongdescattributes.
Inaddition,avoidtheuseofserver-sideimagemaps.
-->
<!ELEMENTimgEMPTY>
<!ATTLISTimg
%attrs;
src%URI;#REQUIRED
alt%Text;#REQUIRED
nameNMTOKEN#IMPLIED
longdesc%URI;#IMPLIED
height%Length;#IMPLIED
width%Length;#IMPLIED
usemap%URI;#IMPLIED
ismap(ismap)#IMPLIED
align%ImgAlign;#IMPLIED
border%Length;#IMPLIED
hspace%Pixels;#IMPLIED
vspace%Pixels;#IMPLIED
>
<!--usemappointstoamapelementwhichmaybeinthisdocument
oranexternaldocument,althoughthelatterisnotwidelysupported-->
<!--==================Client-sideimagemaps============================-->
<!--Thesecanbeplacedinthesamedocumentorgroupedina
separatedocumentalthoughthisisn'tyetwidelysupported-->
<!ELEMENTmap((%block;|form|%misc;)+|area+)>
<!ATTLISTmap
%i18n;
%events;
idID#REQUIRED
classCDATA#IMPLIED
style%StyleSheet;#IMPLIED
title%Text;#IMPLIED
nameCDATA#IMPLIED
>
<!ELEMENTareaEMPTY>
<!ATTLISTarea
%attrs;
shape%Shape;"rect"
coords%Coords;#IMPLIED
href%URI;#IMPLIED
nohref(nohref)#IMPLIED
alt%Text;#REQUIRED
tabindex%Number;#IMPLIED
accesskey%Character;#IMPLIED
onfocus%Script;#IMPLIED
onblur%Script;#IMPLIED
target%FrameTarget;#IMPLIED
>
<!--================Forms===============================================-->
<!ELEMENTform%form.content;><!--formsshouldn'tbenested-->
<!ATTLISTform
%attrs;
action%URI;#REQUIRED
method(get|post)"get"
nameNMTOKEN#IMPLIED
enctype%ContentType;"application/x-www-form-urlencoded"
onsubmit%Script;#IMPLIED
onreset%Script;#IMPLIED
accept%ContentTypes;#IMPLIED
accept-charset%Charsets;#IMPLIED
target%FrameTarget;#IMPLIED
>
<!--
EachlabelmustnotcontainmorethanONEfield
Labelelementsshouldn'tbenested.
-->
<!ELEMENTlabel%Inline;>
<!ATTLISTlabel
%attrs;
forIDREF#IMPLIED
accesskey%Character;#IMPLIED
onfocus%Script;#IMPLIED
onblur%Script;#IMPLIED
>
<!ENTITY%InputType
"(text|password|checkbox|
radio|submit|reset|
file|hidden|image|button)"
>
<!--thenameattributeisrequiredforallbutsubmit&reset-->
<!ELEMENTinputEMPTY><!--formcontrol-->
<!ATTLISTinput
%attrs;
type%InputType;"text"
nameCDATA#IMPLIED
valueCDATA#IMPLIED
checked(checked)#IMPLIED
disabled(disabled)#IMPLIED
readonly(readonly)#IMPLIED
sizeCDATA#IMPLIED
maxlength%Number;#IMPLIED
src%URI;#IMPLIED
altCDATA#IMPLIED
usemap%URI;#IMPLIED
tabindex%Number;#IMPLIED
accesskey%Character;#IMPLIED
onfocus%Script;#IMPLIED
onblur%Script;#IMPLIED
onselect%Script;#IMPLIED
onchange%Script;#IMPLIED
accept%ContentTypes;#IMPLIED
align%ImgAlign;#IMPLIED
>
<!ELEMENTselect(optgroup|option)+><!--optionselector-->
<!ATTLISTselect
%attrs;
nameCDATA#IMPLIED
size%Number;#IMPLIED
multiple(multiple)#IMPLIED
disabled(disabled)#IMPLIED
tabindex%Number;#IMPLIED
onfocus%Script;#IMPLIED
onblur%Script;#IMPLIED
onchange%Script;#IMPLIED
>
<!ELEMENToptgroup(option)+><!--optiongroup-->
<!ATTLISToptgroup
%attrs;
disabled(disabled)#IMPLIED
label%Text;#REQUIRED
>
<!ELEMENToption(#PCDATA)><!--selectablechoice-->
<!ATTLISToption
%attrs;
selected(selected)#IMPLIED
disabled(disabled)#IMPLIED
label%Text;#IMPLIED
valueCDATA#IMPLIED
>
<!ELEMENTtextarea(#PCDATA)><!--multi-linetextfield-->
<!ATTLISTtextarea
%attrs;
nameCDATA#IMPLIED
rows%Number;#REQUIRED
cols%Number;#REQUIRED
disabled(disabled)#IMPLIED
readonly(readonly)#IMPLIED
tabindex%Number;#IMPLIED
accesskey%Character;#IMPLIED
onfocus%Script;#IMPLIED
onblur%Script;#IMPLIED
onselect%Script;#IMPLIED
onchange%Script;#IMPLIED
>
<!--
Thefieldsetelementisusedtogroupformfields.
Onlyonelegendelementshouldoccurinthecontent
andifpresentshouldonlybeprecededbywhitespace.
-->
<!ELEMENTfieldset(#PCDATA|legend|%block;|form|%inline;|%misc;)*>
<!ATTLISTfieldset
%attrs;
>
<!ENTITY%LAlign"(top|bottom|left|right)">
<!ELEMENTlegend%Inline;><!--fieldsetlabel-->
<!ATTLISTlegend
%attrs;
accesskey%Character;#IMPLIED
align%LAlign;#IMPLIED
>
<!--
Contentis%Flow;excludinga,form,formcontrols,iframe
-->
<!ELEMENTbutton%button.content;><!--pushbutton-->
<!ATTLISTbutton
%attrs;
nameCDATA#IMPLIED
valueCDATA#IMPLIED
type(button|submit|reset)"submit"
disabled(disabled)#IMPLIED
tabindex%Number;#IMPLIED
accesskey%Character;#IMPLIED
onfocus%Script;#IMPLIED
onblur%Script;#IMPLIED
>
<!--single-linetextinputcontrol(DEPRECATED)-->
<!ELEMENTisindexEMPTY>
<!ATTLISTisindex
%coreattrs;
%i18n;
prompt%Text;#IMPLIED
>
<!--=======================Tables=======================================-->
<!--DerivedfromIETFHTMLtablestandard,see[RFC1942]-->
<!--
Theborderattributesetsthethicknessoftheframearoundthe
table.Thedefaultunitsarescreenpixels.
Theframeattributespecifieswhichpartsoftheframearound
thetableshouldberendered.Thevaluesarenotthesameas
CALStoavoidanameclashwiththevalignattribute.
-->
<!ENTITY%TFrame"(void|above|below|hsides|lhs|rhs|vsides|box|border)">
<!--
Therulesattributedefineswhichrulestodrawbetweencells:
Ifrulesisabsentthenassume:
"none"ifborderisabsentorborder="0"otherwise"all"
-->
<!ENTITY%TRules"(none|groups|rows|cols|all)">
<!--horizontalplacementoftablerelativetodocument-->
<!ENTITY%TAlign"(left|center|right)">
<!--horizontalalignmentattributesforcellcontents
charalignmentchar,e.g.char=':'
charoffoffsetforalignmentchar
-->
<!ENTITY%cellhalign
"align(left|center|right|justify|char)#IMPLIED
char%Character;#IMPLIED
charoff%Length;#IMPLIED"
>
<!--verticalalignmentattributesforcellcontents-->
<!ENTITY%cellvalign
"valign(top|middle|bottom|baseline)#IMPLIED"
>
<!ELEMENTtable
(caption?,(col*|colgroup*),thead?,tfoot?,(tbody+|tr+))>
<!ELEMENTcaption%Inline;>
<!ELEMENTthead(tr)+>
<!ELEMENTtfoot(tr)+>
<!ELEMENTtbody(tr)+>
<!ELEMENTcolgroup(col)*>
<!ELEMENTcolEMPTY>
<!ELEMENTtr(th|td)+>
<!ELEMENTth%Flow;>
<!ELEMENTtd%Flow;>
<!ATTLISTtable
%attrs;
summary%Text;#IMPLIED
width%Length;#IMPLIED
border%Pixels;#IMPLIED
frame%TFrame;#IMPLIED
rules%TRules;#IMPLIED
cellspacing%Length;#IMPLIED
cellpadding%Length;#IMPLIED
align%TAlign;#IMPLIED
bgcolor%Color;#IMPLIED
>
<!ENTITY%CAlign"(top|bottom|left|right)">
<!ATTLISTcaption
%attrs;
align%CAlign;#IMPLIED
>
<!--
colgroupgroupsasetofcolelements.Itallowsyoutogroup
severalsemanticallyrelatedcolumnstogether.
-->
<!ATTLISTcolgroup
%attrs;
span%Number;"1"
width%MultiLength;#IMPLIED
%cellhalign;
%cellvalign;
>
<!--
colelementsdefinethealignmentpropertiesforcellsin
oneormorecolumns.
Thewidthattributespecifiesthewidthofthecolumns,e.g.
width=64widthinscreenpixels
width=0.5*relativewidthof0.5
Thespanattributecausestheattributesofone
colelementtoapplytomorethanonecolumn.
-->
<!ATTLISTcol
%attrs;
span%Number;"1"
width%MultiLength;#IMPLIED
%cellhalign;
%cellvalign;
>
<!--
Usetheadtoduplicateheaderswhenbreakingtable
acrosspageboundaries,orforstaticheaderswhen
tbodysectionsarerenderedinscrollingpanel.
Usetfoottoduplicatefooterswhenbreakingtable
acrosspageboundaries,orforstaticfooterswhen
tbodysectionsarerenderedinscrollingpanel.
Usemultipletbodysectionswhenrulesareneeded
betweengroupsoftablerows.
-->
<!ATTLISTthead
%attrs;
%cellhalign;
%cellvalign;
>
<!ATTLISTtfoot
%attrs;
%cellhalign;
%cellvalign;
>
<!ATTLISTtbody
%attrs;
%cellhalign;
%cellvalign;
>
<!ATTLISTtr
%attrs;
%cellhalign;
%cellvalign;
bgcolor%Color;#IMPLIED
>
<!--Scopeissimplerthanheadersattributeforcommontables-->
<!ENTITY%Scope"(row|col|rowgroup|colgroup)">
<!--thisforheaders,tdfordataandforcellsactingasboth-->
<!ATTLISTth
%attrs;
abbr%Text;#IMPLIED
axisCDATA#IMPLIED
headersIDREFS#IMPLIED
scope%Scope;#IMPLIED
rowspan%Number;"1"
colspan%Number;"1"
%cellhalign;
%cellvalign;
nowrap(nowrap)#IMPLIED
bgcolor%Color;#IMPLIED
width%Pixels;#IMPLIED
height%Pixels;#IMPLIED
>
<!ATTLISTtd
%attrs;
abbr%Text;#IMPLIED
axisCDATA#IMPLIED
headersIDREFS#IMPLIED
scope%Scope;#IMPLIED
rowspan%Number;"1"
colspan%Number;"1"
%cellhalign;
%cellvalign;
nowrap(nowrap)#IMPLIED
bgcolor%Color;#IMPLIED
width%Pixels;#IMPLIED
height%Pixels;#IMPLIED
>
AppendixF.CharacterEntities
Thefollowingtableliststhedefinedstandardandproposedcharacterentitiesfor
HTMLandXHTML,aswellasseveralthatarenonstandardbutgenerally
supported.
Entitynames,ifdefined,appearfortheirrespectivecharactersandcanbeusedin
thecharacter-entitysequence&name;todefineanycharacterfordisplaybythe
browser.Otherwise,oralternativelyfornamedcharacters,usethecharacter's
three-digitnumeralvalueinthesequence&#nnn;tospeciallydefineacharacter
entity.Actualcharacters,however,mayormaynotbedisplayedbythebrowser,
dependingonthecomputerplatformanduser-selectedfontfordisplay.
Notall256charactersintheInternationalOrganizationforStandardization(ISO)
charactersetappearinthetable.Missingonesarenotrecognizedbythebrowser
aseithernamedornumericentities.
TobesurethatyourdocumentsarefullycompliantwiththeHTML4.0andXHTML
1.0standards,useonlythosenamedcharacterentitieswithnoentriesinthe
Conformancecolumn.Characterswithavalueof"!!!"intheConformancecolumn
arenotformallydefinedbythestandards;usethematyourownrisk.
Numericentity Namedentity Symbol Description Conformance
	 Horizontaltab

 Linefeed

 Carriagereturn
  Space
! ! Exclamationpoint
" " " Quotationmark
# # Hashmark
$ $ Dollarsign
% % Percentsign
& & & Ampersand
' ' Apostrophe
( ( Leftparenthesis
) ) Rightparenthesis
* * Asterisk
+ + Plussign
, , Comma
- - Hyphen
. . Period
/ / Slash
0-9 09 Digits09
: : Colon
; ; Semicolon
< < < Lessthansign
= = Equalssign
> > > Greaterthansign
? ? Questionmark
@ @ Commercialatsign
A-Z A-Z LettersA-Z
[ [ Leftsquarebracket
\ \ Backslash
] ] Rightsquarebracket
^ Caret
_ _ Underscore
` ` Graveaccent
a-z a-z Lettersa-z
{ { Leftcurlybrace
| | Verticalbar
} } Rightcurlybrace
~ ~ Tilde
‚ , Lowleftsinglequote !!!
ƒ Florin !!!
„ " Lowleftdoublequote !!!
… ... Ellipsis !!!
† Dagger !!!
‡ Doubledagger !!!
ˆ ^ Circumflex !!!
‰ Permil !!!
Š CapitalS,caron !!!
‹ < Lessthansign !!!
Œ Œ CapitalOEligature !!!
Ž CapitalZ,caron !!!
‘ ' Leftsinglequote !!!
’ ' Rightsinglequote !!!
“ " Leftdoublequote !!!
” " Rightdoublequote !!!
• • Bullet !!!
– Endash !!!
— Emdash !!!
˜ ~ Tilde !!!
™ ™ Trademark !!!
š Smalls,caron !!!
› > Greaterthansign !!!
œ œ Smalloeligature !!!
ž Smallz,caron !!!
Ÿ CapitalY,umlaut !!!
  Nonbreakingspace
¡ ¡ ¡ Invertedexclamationpoint
¢ ¢ ¢ Centsign
£ £ £ Poundsign
¤ ¤ ¤ Generalcurrencysign
¥ ¥ ¥ Yensign
¦ ¦ Brokenverticalbar
§ § § Sectionsign
¨ ¨ ¨ Umlaut
© © © Copyright
ª ª ª Feminineordinal
« « « Leftanglequote
¬ ¬ ¬ Notsign
­ ­ Softhyphen
® ® ® Registeredtrademark
¯ ¯ ¯ Macronaccent
° ° ° Degreesign
± ± ± Plusorminus
² ² 2Superscript2
³ ³ 3Superscript3
´ ´ ´ Acuteaccent
µ µ μ Microsign(Greekmu)
¶ ¶ ¶ Paragraphsign
· · · Middledot
¸ ¸ , Cedilla
¹ ¹ 1Superscript1
º º º Masculineordinal
» » » Rightanglequote
¼ ¼ ¼ Fractionone-fourth
½ ½ ½; Fractionone-half
¾ ¾ ¾ Fractionthree-fourths
¿ ¿ ¿ Invertedquestionmark
À À À CapitalA,graveaccent
Á Á Á CapitalA,acuteaccent
   CapitalA,circumflexaccent
à à à CapitalA,tilde
Ä Ä Ä CapitalA,umlaut
Å Å Å CapitalA,ring
Æ Æ Æ CapitalAEligature
Ç Ç Ç CapitalC,cedilla
È È È CapitalE,graveaccent
É É É CapitalE,acuteaccent
Ê Ê Ê CapitalE,circumflexaccent
Ë Ë Ë CapitalE,umlaut
Ì Ì Ì CapitalI,graveaccent
Í Í í CapitalI,acuteaccent
Î Î Î CapitalI,circumflexaccent
Ï Ï Ï CapitalI,umlaut
Ð Ð Capitaleth,Icelandic
Ñ Ñ Ñ CapitalN,tilde
Ò Ò Ò CapitalO,graveaccent
Ó Ó Ó CapitalO,acuteaccent
Ô Ô Ô CapitalO,circumflexaccent
Õ Õ Õ CapitalO,tilde
Ö Ö Ö CapitalO,umlaut
× × x Multiplysign
Ø Ø Ø CapitalO,slash
Ù Ù Ù CapitalU,graveaccent
Ú Ú Ú CapitalU,acuteaccent
Û Û û CapitalU,circumflexaccent
Ü Ü Ü CapitalU,umlaut
Ý Ý Ý CapitalY,acuteaccent
Þ Þ Capitalthorn,Icelandic
ß ß ß Smallszligature,German
à à à Smalla,graveaccent
á á á Smalla,acuteaccent
â â â Smalla,circumflexaccent
ã ã ã Smalla,tilde
ä ä ä Smalla,umlaut
å å å Smalla,ring
æ æ æ Smallaeligature
ç ç ç Smallc,cedilla
è è è Smalle,graveaccent
é é é Smalle,acuteaccent
ê ê ê Smalle,circumflexaccent
ë ë ë Smalle,umlaut
ì ì ì Smalli,graveaccent
í í í Smalli,acuteaccent
î î î Smalli,circumflexaccent
ï ï î Smalli,umlaut
ð ð Smalleth,Icelandic
ñ ñ ñ Smalln,tilde
ò ò ò Smallo,graveaccent
ó ó ó Smallo,acuteaccent
ô ô ô Smallo,circumflexaccent
õ õ õ Smallo,tilde
ö ö ö Smallo,umlaut
÷ ÷ ÷ Divisionsign
ø ø Smallo,slash
ù ù ù Smallu,graveaccent
ú ú ú Smallu,acuteaccent
û û Û Smallu,circumflexaccent
ü ü ü Smallu,umlaut
ý ý y Smally,acuteaccent
þ þ Smallthorn,Icelandic
ÿ ÿ ÿ Smally,umlaut
AppendixG.ColorNamesandValues
Withthepopularbrowsers,andaccordingtotheCascadingStyleSheets(CSS)
standard,youmayprescribethedisplaycolorforvariouselementsinyour
documents.Youdosobyspecifyingacolorvalueorastandardname.Theuser
mayoverridethesecolorspecificationsthroughherbrowserpreferences.
G.1.ColorValues
Inallcases,youmaysetthecolorvalueforanHTMLelement,suchas<body>text,
<table>background,andsoon,asasix-digithexadecimalnumberthatrepresents
thered,green,andblue(RGB)componentsofthecolor.Thefirsttwodigits
correspondtotheredcomponentofthecolor,thenexttwoarethegreen
component,andthelasttwoarethebluecomponent.Avalueof00correspondsto
acomponentbeingcompletelyoff;thehexadecimalvalueofFF(decimal255)
correspondstothecomponentbeingcompletelyon.Thus,brightredisFF0000,
brightgreenis00FF00,andbrightblueis0000FF.Otherprimarycolorsaremixtures
ofthecomponents,suchasyellow(FFFF00),magenta(FF00FF),andcyan(00FFFF).
White(FFFFFF)andblack(000000)alsoareeasytofigureout.
YouusethesevaluesinatagbyreplacingthecolorwiththeRGBtriple,preceded
byapoundsign(#).Thus,tomakeallvisitedlinksdisplayasmagenta,usethis
bodytag:
<bodyvlink="#FF00FF">
G.2.ColorNames
DeterminingtheRGB-triplevalueforanythingotherthanthesimplestcolors(you
tryfiguringoutesotericcolorslike"papayawhip"or"navajowhite")isnoteasy.
YoucangocrazytryingtoadjusttheRGBtripleforacolortogettheshadejust
right,especiallywheneachadjustmentrequiresloadingadocumentintoyour
browsertoviewtheresult.
Tomakelifeeasier,thestandardsdefine16standardcolornamesthatyoucan
useanywhereyoucanuseanumericcolorvalue.Forexample,youcanmakeall
visitedlinksinthedisplaymagentawiththefollowingattributeandvalueforthe
bodytag:
<bodyvlink="magenta">
ThecolornamesandRGBvaluesdefinedintheHTML/XHTMLstandardsare:
aqua(#00FFFF) gray(#808080) navy(#000080) silver(#C0C0C0)
black(#000000) green(#008000) olive(#808000) teal(#008080)
blue(#0000FF) lime(#00FF00) purple(#800080) yellow(#FFFF00)
fuchsia(#FF00FF) maroon(#800000) red(#FF0000) white(#FFFFFF)
Thepopularbrowsersgowellbeyondthestandardandsupporttheseveral
hundredcolornamesdefinedforuseintheXWindowSystem.Notethatthese
colornamesmaycontainnospaces;also,thewordgraymaybespelledgreyin
anycolorname.
Thosecolorsmarkedwithanasterisk(*)actuallyrepresentafamilyofcolors
numberedonethroughfour.Thus,thereareactuallyfourvariantsofblue,named
"blue1,""blue2,""blue3,"and"blue4,"alongwithplainold"blue."Blue1isthe
lightestofthefour;blue4isthedarkest.Theunnumberedcolornameisthesame
colorasthefirst;thus,blueandblue1areidentical.
Finally,ifallthatisn'tenough,thereare100variantsofgray(andgrey),
numbered1through100."Gray1"isthedarkest,"gray100"isthelightest,and
"gray"isverycloseto"gray75."
Theextendedcolornamesare:
aliceblue darkturquoise lightseagreen palevioletred*
antiquewhite* darkviolet lightskyblue* papayawhip
aquamarine* deeppink* lightslateblue peachpuff*
azure* deepskyblue* lightslategray peru
beige dimgray lightsteelblue* pink*
bisque* dodgerblue* lightyellow* plum*
black firebrick* limegreen powderblue
blanchedalmond floralwhite linen purple*
blue* forestgreen magenta* red*
blueviolet gainsboro maroon* rosybrown*
brown* ghostwhite mediumaquamarine royalblue*
burlywood* gold* mediumblue saddlebrown
cadetblue* goldenrod* mediumorchid* salmon*
chartreuse* gray mediumpurple* sandybrown
chocolate* green* mediumseagreen seagreen*
coral* greenyellow mediumslateblue seashell*
cornflowerblue honeydew* mediumspringgreen sienna*
cornsilk* hotpink* mediumturquoise skyblue*
cyan* indianred* mediumvioletred slateblue*
darkblue ivory* midnightblue slategray*
darkcyan khaki* mintcream snow*
darkgoldenrod* lavender mistyrose* springgreen*
darkgray lavenderblush* moccasin steelblue*
darkgreen lawngreen navajowhite* tan*
darkkhaki lemonchiffon* navy thistle*
darkmagenta lightblue* navyblue tomato*
darkolivegreen* lightcoral oldlace turquoise*
darkorange* lightcyan* olivedrab* violet
darkorchid* lightgoldenrod* orange* violetred*
darkred lightgoldenrodyellow orangered* wheat*
darksalmon lightgray orchid* white
darkseagreen* lightgreen palegoldenrod whitesmoke
darkslateblue lightpink* palegreen* yellow*
darkslategray* lightsalmon* paleturquoise* yellowgreen
G.3.TheStandardColorMap
SupportinghundredsofcolornamesandmillionsofRGBtriplesisnice,butthe
realityisthatalarge(albeitshrinking)populationofuserscandisplayonly256
colorsontheirsystems.Whenconfrontedwithacolornotdefinedinthissetof
256,thebrowserhastwochoices:convertthecolortooneoftheexistingcolors,
orditherthecolorusingtheavailablecolorsinthecolormap.
Conversioniseasy;thecoloriscomparedtoalltheothercolorsinthecolormap
andisreplacedbytheclosestcolorfound.Ditheringismoredifficult.Usingtwoor
morecolorsinthecolormap,theerrantcolorisapproximatedbymixingdifferent
ratiosoftheavailablecolors.Whenyouviewthemupclose,you'llseeapattern
ofalternatingpixelsusingtheavailablecolors.Atadistance,thepixelsblendto
formacolorclosetotheoriginalcolor.
Ingeneral,yourimageswilllookbestifyoucanavoidbothconversionand
dithering.Conversionwillmakeyourcolorsappear"off";ditheringmakesthem
lookfuzzy.Howtoavoidtheseproblems?Easy:usecolorsinthestandardcolor
mapwhencreatingyourimages.
Thestandardcolormapactuallyhas216valuesinit.Therearesixvariantsof
red,sixofgreen,andsixofbluethatarecombinedinallpossiblewaystocreate
these216(6x6x6)colors.Thesevariantshavedecimalbrightnessvaluesof0,
51,102,153,204,and255,correspondingtohexadecimalvaluesof00,33,66,
99,CC,andFF.Colorssuchas003333(darkcyan)and999999(mediumgray)
existdirectlyinthecolormapandwon'tbeconvertedordithered.
Keepinmindthatmanyoftheextendedcolornamesarenotinthestandardcolor
mapandwillbeconvertedorditheredtoa(hopefully)similarcolor.Usingcolor
names,whileconvenient,doesnotguaranteethatthebrowserwillusethe
desiredcolor.
Whencreatingimages,trytousecolorsinthestandardcolormap.When
selectingcolorsfortext,links,orbackgrounds,makesureyouselectcolorsinthe
standardcolormap.Yourpageswilllookbetterandwillbemoreconsistentwhen
viewedwithdifferentbrowsers.
AppendixH.NetscapeLayoutExtensions
Fromthestartoftheirenterprisebeforetheturnofthecentury,thedevelopersat
Netscapewereattheforefrontofbrowserdesignthataddressedtheneedsof
commercialinterests.Duringthoseheadyyears,NetscapeextendedHTMLto
provideauthorswithfarmoresophisticatedpage-layoutcapabilitiesthan
otherwiseavailableinanyotherbrowser.Andtheywereverysuccessfulinthat
enterprise.NetscapeNavigatorwasthedominantbrowserbyfaruntiltheearly
2000swiththeadventofCascadingStyleSheets(CSS)andotherstandards.
Microsoftfinallycaughton,too.
Inthisappendix,wedocumentforhistoricalpurposesthreefeaturesthatwere
uniquetoNetscapeversions4andearlierandnootherbrowserssincethen:
spacers,multiplecolumns,andlayers.Thesetagslurethedesignerwithexciting
page-layoutcapabilities.Playwiththemasyouwill,butwewarnyou:theywon't
everbecomepartofHTML/XHTMLstandards.Theyaren'tevensupportedbythe
latestversionofNetscapeNavigator.
H.1.CreatingWhitespace
Oneofthesimplestelementsinanypagedesignistheemptyspacesurrounding
content.Emptyspaceisoftenjustasimportanttothelookandfeelofapageas
theareasfilledwithtextandimages.Commonlyknownaswhitespace,these
emptyareasshapeandcontainthecontentofyourpage.
NativeHTMLhasnowaytocreateemptyspaceonyourpage,shortofusinga
<pre>tagfilledwithblanklinesoranemptyimage.Infact,browsersacting
accordingtotheHTML/XHTMLstandardsremoveleading,trailing,andanyother
extraspacesintextandignoreextralinefeeds.Netscape4fillsthisvoidwiththe
<spacer>tag.[The<br>Tag,4.6.1]
H.1.1.The<spacer>Tag(Antiquated)
Usethe<spacer>tagtocreatehorizontal,vertical,andrectangularwhitespacein
documentsrenderedbyNetscape4.
<spacer>
Function Definesablankareainadocument
Attributes align,height,size,type,width
Endtag NoneinHTML
Contains Nothing
Usedin text
H.1.1.1.Creatinghorizontalspace
Themostcommonuseofthe<spacer>tagistoindentalineoftext.Toachievethis
effect,setthevalueofthetypeattributetohorizontal,andusethesizeattributeto
definethewidth,inpixels(nottextcharacters),ofthehorizontalarea.For
example:
<spacertype=horizontalsize=100>
inserts100pixelsofspaceinlinewiththecurrentlineoftext.Netscape4
appendssubsequentcontentattheendofthespacerifsufficientspaceremains
onthecurrentline.Otherwise,itplacesthenextelementontothenextline,
followingitsnormalword-wrapbehavior.
Ifthereisnotenoughroomtoplacetheentire<spacer>tag'swhitespaceonthe
currentline,thebrowsershortensthespacetofitonthecurrentline.Inasense,
thesizeofthespacerissoft,tellingthebrowsertoinsertuptothespecified
numberofpixelsuntiltheendofthecurrentlineisreached.
Forexample,ifaspaceris100pixelswide,andonly75pixelsofspaceremainon
thecurrentlinewithinthebrowser'sdisplaywindow,Netscape4inserts75pixels
ofspaceintothelineandplacesthenextelementatthebeginningofthenext
lineinthedisplay.Accordingly,ahorizontalspacerisneverbrokenacrossaline,
creatingspaceattheendofonelineandthebeginningofthenext.
Byfar,themostcommonapplicationofthehorizontalspaceristoindentthefirst
lineofaparagraph.Simplyplaceahorizontalspaceratthestartofaparagraph
togetthedesiredresult:
<spacertype=horizontalsize=50>
Theeffectsofcoolerweatheronthekumquat'sripeningprocess
varybaseduponthetemperature.Temperaturesabove28°
sweetenthefruit,whilefourormorehoursbelow28°will
damagethetree.
FigureH-1showstheresults.
FigureH-1.Indentingaparagraphwithahorizontalspacer
(Netscape4only)
Ofcourse,youalsocanusehorizontalspacerstoinsertadditionalspacebetween
lettersorwordsinalineoftext.Thismightbeusefulfordisplayingpoetryor
specializedadcopy.Butdon'tuseaspacertocreateanindentedblockoftextyou
cannotpredictthesizeoftheuser'sbrowserwindow,fontsizes,andsoforth,and,
hence,whereitwillbreakaparticularlineoftext.Instead,usethe<blockquote>tag
oradjusttheparagraph'sleftmarginwithanappropriatestyle.
H.1.1.2.Creatingverticalspace
Youmayinsertextrawhitespacebetweenlinesoftextandparagraphsinyour
documentsbysettingthetypeattributeinthe<spacer>tagtovertical.Youalso
mustincludethesizeattribute.Makeitsvalueapositiveintegerequaltothe
amountofwhitespace,inpixels.
Theverticalspaceractsjustlikethe<br>tag.Bothtagscauseanimmediateline
break.Thedifferenceisthatwiththeverticalspacer,youcontrolhowfarbelow
thecurrentlineoftextNetscape4shouldstartthesubsequentline.The
whitespaceisaddedtoandthereforeisneverlessthanthenormalamountofspace
thatwouldappearbelowthecurrentlineoftextasaresultoftheparagraph'sline
spacing.
BecauseHTMLpagesareinfinitelytall,theverticalspacemaybeanynumberof
pixelshigh.Ofcourse,it'dbesophomorictobeexcessive(oh,OK,try
size=100000000).Mostoftoday'smonitorshaveaverticalscanofnomorethan
1,024lines,soaverticalpixelsizevalueof1,025ensuresthatthenextlineof
textisplacedofftheuser'sscreen,ifthatistheeffectyoudesire.
Verticalspacersaren'tquiteascommonashorizontalspacers,buttheycanstill
beuseful.Inthefollowingtext,we'veusedaverticalspacertoprovideabitmore
separationbetweenthedocument'sheaderandtheregulartext:
<h1align=right>TemperatureEffects</h1>
<spacertype=verticalsize=50>
Theeffectsofcoolerweatheronthekumquat'sripeningprocess
varybaseduponthetemperature.Temperaturesabove28°
sweetenthefruit,whilefourormorehoursbelow28°will
damagethetree.
FigureH-2showstheresults.
FigureH-2.Usingaverticalspacertoseparateaheaderfromthe
text(Netscape4only)
H.1.1.3.Creatingblocksofspace
Thethirdspacertypecreatesarectangularblockofblankspace,muchlikea
blankimage.Setthetypeattributetoblockandincludethreeotherattributesto
fullydefinethespace:width,height,andalign.
Thewidthandheightattributesspecifythesizeofthespacerinpixelsorasa
percentageoftheelementcontainingthespacer.Theseattributesareusedonly
whenthetypeattributeissettoblockandotherwiseareignored.Similarly,thesize
attributeisignoredwhenthe<spacer>typeisblock.Ifspecifyingasizeinpixels,
youmustgiveapositiveintegervaluetoboththewidthandheightattributes;their
defaultvalueis0.
Thethirdrequiredblockspacerattribute,align,controlshowNetscape4places
theemptyblockrelativetothesurroundingtext.Thevaluesforthisattributeare
identicaltothoseforthealignattributeinthe<img>tag.Usethetop,texttop,middle,
absmiddle,baseline,bottom,andabsbottomvaluestoobtainthedesiredvertical
alignmentoftheblockspacer.Usetheleftandrightvaluestoforcetheblock
spacertotheindicatedmarginandcausethefollowingtexttoflowupandaround
thespacer.Thedefaultvalueisbottom.Foracompletedescriptionofthealign
attributeanditsvalues,seesection4.1.1.1.
ThisHTMLfragmentplacesthecompasspointsaroundanemptyarea:
<center>
North
<br>
West
<spacertype=blockwidth=50height=50align=absmiddle>
East
<br>
South
</center>
FigureH-3showstheresultingdocument.
FigureH-3.Usingablockspacertocreatespaceinadocument
(Netscape4only)
H.1.2.Mimickingthe<spacer>Tag
BecauseonlyNetscapeversions4andearliersupportthe<spacer>tag,other
browsersignoreit,ruiningyourcarefullycontrivedlayout.Westronglysuggest
thatyouinsteadusetheCSSstandardtext-indentpropertyforidenticalresults.
Youmightalsoemulatethe<spacer>tagwiththe<img>tagandaspecial,small
image.Thisway,youcanachieve<spacer>-likeeffectsevenwithbrowsersthat
don'tsupportCSS.Foranimagetoemulate<spacer>,you'llneedaGIFthatis
completelytransparent.Becausenopartoftheimageiseverseen,youcanmake
itassmallasyouwant;werecommenda1x1-pixelGIFimage.Inthefollowing
examples,ourtiny1x1-pixeltransparentimageisnamedsmall.gif.
Toemulateahorizontalspaceroftheform:
<spacertype=horizontalsize=n>
usethis<img>tag:
<imgsrc=small.gifwidth=nheight=1>
Replacenwiththedesiredpixelwidth.Keepinmind,however,thatthewidthof
the<img>tagisfixedandmaynotintegrateintothetextflowexactlylikethe
<spacer>tagwould,especiallyifthe<img>tagfallsatorneartheendofalineof
text.
Toemulateaverticalspaceroftheform:
<spacertype=verticalsize=n>
usethisHTMLfragment:
<br>
<imgsrc=small.gifwidth=1height=n>
<br>
The<br>tagsareneededintheexampletoemulatetheline-breakingbehaviorof
theverticalspacer.Again,replacenwiththedesiredheight.
Toemulateablockspaceroftheform:
<spacertype=blockwidth=wheight=halign=a>
usethis<img>tag:
<imgsrc=small.gifwidth=wheight=halign=a>
Replacew,h,andawiththedesiredwidth,height,andalignmentvalues.
H.2.MulticolumnLayout
Multicolumntextformattingisoneofthemostcommonfeaturesofdesktop
publishing.Inadditiontocreatingattractivepagesinavarietyofformats,
multiplecolumnsletyoupresentyourtextusingshorter,easier-to-readlines.
HTMLpagedesignershavelongedfortheabilitytoeasilycreatemultipletext
columnsinasinglepage,buttheyhavebeenforcedtousevarioustricks,suchas
multicolumntables(seeChapter17).
Netscape4neatlysolvedthisproblemwiththeunique<multicol>tag.Whilefancy
unbalancedcolumnsandstraddlingarenotpossiblewiththistag,astheyarewith
tables,conventionallybalancedtextcolumnsareeasytocreatewith<multicol>.
AndwhilethiscapabilityisavailableonlywithNetscape4,the<multicol>tag
degradesnicelyinotherbrowsers.
H.2.1.The<multicol>Tag(Antiquated)
The<multicol>tagcreatesmultiplecolumnsoftextandletsyoucontrolthesize
andnumberofcolumns.
<multicol>(Antiquated)
Function Formatstextwithmultiplecolumns
Attributes class,cols,gutter,style,width
Endtag </multicol>;neveromitted
Contains body_content
Usedin block
The<multicol>tagcancontainanyotherHTMLcontent,muchlikethe<div>tag.All
ofthecontentwithinthe<multicol>tagisdisplayedjustlikeconventionalcontent,
exceptthatNetscape4placesthecontentsintomultiplecolumnsratherthanjust
one.
The<multicol>tagcreatesabreakinthetextflowandinsertsablanklinebefore
renderingitscontentintomultiplecolumns.Afterthetag,anotherblanklineis
addedandthetextflowresumesusingthepreviouslayoutandformatting.
Netscape4automaticallybalancesthecolumns,makingeachapproximatelythe
samelength.Wherepossible,thebrowsermovestextbetweencolumnsto
accomplishthebalancing.Insomecases,thecolumnscannotbebalanced
perfectlybecauseofembeddedimages,tables,orotherlargeelements.
Youcannest<multicol>tags,embeddingonesetofcolumnswithinanothersetof
columns.Whileinfinitenestingissupported,morethantwolevelsofnestingare
generallyimpracticalandresultsinunattractivetextflows.
H.2.1.1.Thecolsattribute
Thecolsattributeisrequiredbythe<multicol>tagtodefinethenumberof
columns.Ifthisattributeisomitted,Netscape4createsjustonecolumn,as
thoughthe<multicol>tagisn'tthereatall.Youmaycreateanynumberof
columns,butinpractice,morethanthreeorfourcolumnsmaketextunreadable
onmostdisplays.
Thefollowingexamplecreatesathree-columnlayout:
<h1align=right>TemperatureEffects</h1>
<multicolcols=3>
Theeffectsofcoolerweatheronthekumquat'sripeningprocess
varybaseduponthetemperature.Temperaturesabove28°
sweetenthefruit,whilefourormorehoursbelow28°will
damagethetree.Thesavvyquatfarmerwillcarefullymonitor
thetemperature,especiallyinthepredawnhourswhenthemercury
dipstoitslowestpoint.Smudgepotsandgroveheatersmaybe
requiredtokeepthetreeswarm;manygrowerswillspraythetrees
withwatertocreateaninsulatinglayeroficeoverthefruitand
leaves.
<p>
Ifadisastrousfrostispredicted,below20°,theonlyrecourse
maybetoharvestthefruitearlytosaveitfromanassureddisaster.
Kumquatsmaysubsequentlyberipenedusinganyofthepopularmethane
andcyanoacrylateinjectionsystemsusedforothercitrusfruits.
Usedcorrectly,thesesystemswillproducefruitwhosetasteis
indistinguishablefromtree-ripenedkumquats.
</multicol>
FigureH-4showstheresults.
FigureH-4.Athree-column<multicol>documentsegment
(Netscape4only)
YoucanseeinFigureH-4howNetscape4hasbalancedthecolumnsto
approximatelyequallengths.Youalsocanseehowseverallineswithinthe
columnsappearshorterbecauselongerwordswerewrappedtothenextlineof
text.Theseoverlyraggedrightmarginswithinthecolumnsareunavoidableand
servetoemphasizethatyoushouldn'tcreatemorethanfourorfivecolumnsina
flow.Ourexampleisstillbarelyreadableifdisplayedasfivecolumns;itbreaks
downcompletelyandeveninducesrenderingerrorsifcolsissetto7,asshownin
FigureH-5.
FigureH-5.Toomanycolumnscreateunreadablepages
(Netscape4only)
H.2.1.2.Thegutterattribute
Thespacebetweencolumnsisknownasthegutter.Bydefault,Netscapecreates
agutterthatis10pixelswidebetweeneachofyourcolumns.Tochangethis,set
thegutterattribute'svaluetothedesiredwidthinpixels.Netscape4reservesthis
muchspacebetweenyourcolumns;theremainingspaceisusedforthecolumns
themselves.
FigureH-6showstheeffectthiscanhaveonyourcolumns.Inthisfigure,we've
reformattedoursampletextusing<multicolcols=3gutter=50>.Contrastthiswith
FigureH-4,whichusesthedefault10-pixelgutters.
FigureH-6.Changegutterwidthswiththe<multicol>gutter
attribute(Netscape4only)
H.2.1.3.Thewidthattribute
Normally,the<multicol>tagfillsthecurrentwidthofthecurrenttextflow.Tohave
yourmultiplecolumnsoccupyathinnerspace,ortoextendthembeyondthe
visiblewindow,usethewidthattributetospecifytheoverallwidthofthe<multicol>
tag.Thecolumnsareresizedsothatthecolumnsplustheguttersfillthewidth
you'vespecified.[*]Thewidthmaybespecifiedasanabsolutenumberofpixelsor
asapercentageofthewidthofthecurrenttextflow.
[*]Tobeexact,eachcolumnis(w-g(n-1))/npixelswide,wherewisthewidthofthe<multicol>tag,gisthewidthof
agutter,andnisthenumberofcolumns.Thus,using<multicolcols=3gutter=10width=500>creates
columnsthatare160pixelswide.
FigureH-7showstheeffectsofaddingwidth="75%"toourcolumnexample,
retainingthedefaultgutterwidthof10pixels.
FigureH-7.Changingthewidthof<multicol>columns
(Netscape4only)
Ifyourcolumnsincludeimagesorotherfixed-widthelements,becarefulwhen
youreducetheirsize.Netscape4doesnotwraptextaroundimagesthatextend
beyondtheboundariesofacolumn.Instead,theimagecoverstheadjacent
columns,ruiningyourdocument.
Alwaysmakesurethatembeddedelementsincolumnsaresmallenoughtofit
withinyourcolumns,evenonfairlysmallbrowserdisplays.
H.2.1.4.Thestyleandclassattributes
Usethestyleattributewiththe<multicol>tagtocreateaninlinestyleforallthe
contentinsidethetag.Theclassattributeletsyoulabelthesectionwithaname
thatreferstoapredefinedclassofthe<multicol>tagdeclaredinsomedocument-
levelorexternallydefinedstylesheet.[InlineStyles:ThestyleAttribute,8.1.1]
[StyleClasses,8.3]
H.2.2.MultipleColumnsandOtherBrowsers
Aswe'venoted,the<multicol>tagissupportedonlybyNetscapeversions4and
earlier.Fortunately,whenotherbrowsersencounterthe<multicol>tag,theyignore
itandrendertheenclosedtextaspartofthenormaltextflow,usuallywithlittle
consequentdisruptiontothedocument.
Theonlyproblemisthatthecontentsofthe<multicol>tagflowupintothe
previousflow,withoutaninterveningbreak.Thus,youmightconsiderpreceding
every<multicol>tagwitha<p>tag.Netscape4won'tmind,andotherbrowsersat
leastperformaparagraphbreakbeforerenderingyourmulticolumntextina
singlecolumn.
Itispossibletoemulatethe<multicol>tagusingtables,buttheresultsarecrude
anddifficulttomanageacrossmultiplebrowsers.Todoso,createasingle-row
tablewithacellforeachcolumn.Placeanappropriateamountofthetextflowin
eachcelltoachievebalancedcolumns.Thedifficulty,ofcourse,isthatthe
"appropriateamount"varieswildlybetweenbrowsers,makingitalmostimpossible
tocreatemultiplecolumnsthatareattractiveonseveraldifferentbrowsers.
Ifyoumusthavemultiplecolumnsandcantolerateyourcolumnsrevertingtoa
singlecolumnonincompatiblebrowsers,werecommendthatyouuse<multicol>.
H.2.3.EffectiveMulticolumnLayouts
We'veofferedadviceoncolumnsthroughoutthesesections.Hereisaquickrecap
ofourtipsforcreatingeffectivecolumnlayouts:
Useasmallnumberofcolumns.
Don'tuseexcessivelywidegutters.
Ensurethatembeddedelementssuchasimagesandtablesfitinyourcolumns
onmostdisplays.
Precedeeach<multicol>tagwitha<p>tagtoimproveyourdocument's
appearanceonotherbrowsers.
Avoidnesting<multicol>tagsmorethantwodeep.
H.3.Layers
SpacersandmultiplecolumnsarenaturalextensionstoconventionalHTML,
existingwithinadocument'snormalflow.Withversion4,NetscapetookHTML
intoanentirelynewdimensionwithlayers.Ittransformsthesingle-element
documentmodelintoonecontainingmanylayeredelementsthatarecombinedto
formthefinaldocument.Regrettably,layersarenotsupportedbyNetscape6or
anyversionofInternetExplorer.
LayerssupplythelayoutartistwithacriticalelementmissinginstandardHTML:
absolutepositioningofcontentwithinthebrowserwindow.Layersletyoudefinea
self-containedunitofHTMLcontentthatcanbepositionedanywhereinthe
browserwindow,placedaboveorbelowotherlayers,andmadetoappearand
disappearasyoudesire.Documentlayoutsthatwereimpossiblewithconventional
HTMLaretrivialwithlayers.
Ifyouthinkofyourdocumentasasheetofpaper,layersarelikesheetsofclear
plasticplacedontopofyourdocument.Foreachlayer,youdefinethecontentof
thelayer,itspositionrelativetothebasedocument,andtheorderinwhichitis
placedonthedocument.Layerscanbetransparentoropaque,visibleorhidden,
providinganendlesscombinationoflayoutoptions.
H.3.1.The<layer>Tag(Antiquated)
EachHTMLdocumentcontentlayerisdefinedwiththe<layer>tag.Alayercanbe
thoughtofasaminiatureHTMLdocumentwhosecontentisdefinedbetweenthe
<layer>and</layer>tags.Alternatively,thecontentofthelayercanberetrieved
fromanotherHTMLdocumentbyusingthesrcattributewiththe<layer>tag.
<layer>(Antiquated)
Function Definesalayerofcontentwithinadocument
Attributes above,background,below,bgcolor,class,clip,left,name,src,style,top,visibility,
width,z-index
Endtag </layer>;neveromitted
Contains body_content
Usedin block
Regardlessofitsorigin,Netscape4formatsalayer'scontentexactlylikea
conventionaldocument,exceptthattheresultiscontainedwithinthatseparate
layer,apartfromtherestofyourdocument.Youcontrolthepositionandvisibility
ofthislayerusingtheattributesofthe<layer>tag.
Layerscanbenested,too.Nestedlayersmovewiththecontaininglayerandare
visibleonlyifthecontaininglayeritselfisvisible.
H.3.1.1.Thenameattribute
Ifyouplanoncreatingalayerandneverreferringtoit,youneedn'tgiveita
name.However,ifyouplantostackotherlayersrelativetothecurrentlayer,as
wedemonstratelaterinthisappendix,ortomodifyyourlayerusingJavaScript,
you'llneedtonameyourlayersusingthenameattribute.Thevalueyougivenameis
atextstring,whosefirstcharactermustbealetter,notanumberorsymbol.
Onceyounamethelayer,youcanrefertoitelsewhereinthedocumentand
changeitwhiletheuserinteractswithyourpage.Forexample,thisbitofHTML:
<layername="warning"visibility=hide>
Warning!Yourinputparameterswerenotvalid!
</layer>
createsalayernamedwarningthatisinitiallyhidden.Ifinthecourseofvalidating
aformusingaJavaScriptroutine,youfindanerrorandwanttodisplaythe
warning,youwouldusethiscommand:
warning.visibility="show";
Netscape4thenmakesthelayervisibletotheuser.
H.3.1.2.Theleftandtopattributes
Withoutattributes,alayergetsplacedinthedocumentwindowasthoughitwere
partofthenormaldocumentflow.Layersattheverybeginningofadocumentget
putatthetopoftheNetscape4window;layersthatarebetweenconventional
documentcontentgetplacedinlinewiththatcontent.
Thepoweroflayers,however,isthatyoucanplacethemanywhereinthe
document.Usethetopandleftattributesforthe<layer>tagtospecifyitsabsolute
positioninthedocumentdisplay.
Bothattributesacceptanintegervalueequaltothenumberofpixelsoffsetfrom
thetop-left(0,0)edgeofthedocument'sdisplayspaceor,ifnestedinsideanother
layer,thecontaininglayer'sdisplayspace.Aswithotherdocumentelements
whosesizeorpositionextendspasttheedgeofthebrowser'swindow,Netscape
givestheuserscrollbarstoaccesslayeredelementsoutsidethecurrentviewing
area.
Thefollowingisasimplelayerexamplethatstaggersthreewordsdiagonallydown
thedisplaynotsomethingyoucandoeasily,andcertainlynotwiththesame
precision,inconventionalHTML:
<layerleft=10top=10>
Upperleft!
</layer>
<layerleft=50top=50>
Middle!
</layer>
<layerleft=90top=90>
Lowerright!
</layer>
FigureH-8showstheresult.
FigureH-8.Simpletextpositioningwiththe<layer>tag
Admittedly,thisexampleisabitdull.Here'sabetteronethatcreatesadrop
shadowbehindaheading:
<layer>
<layerleft=2top=2>
<h1><fontcolor=gray>IntroductiontoKumquatLore</font></h1>
</layer>
<layerleft=0top=0>
<h1>IntroductiontoKumquatLore</h1>
</layer>
</layer>
<h1> </h1>
Earlyinthehistoryofman,thekumquatplayedavitalroleinthe
formationofreligiousbeliefs.Centraltoannualharvestcelebrations
wasthedayuponwhichkumquatsripened.Likenedtothesun(<i>
sol</i>),thegoldenfruitwastaken(<i>stisus</i>)fromthetreeson
thedaythesunstoodhighestinthesky.Wecarrythisdayforward
eventoday,asoursummer<i>solstice</i>.
FigureH-9showstheresult.FigureH-10demonstrateswhathappenswithlayers
whenviewedwithabrowserotherthanNetscape4.
FigureH-9.Creatingdrop-shadoweffectswithmultiplelayers
(Netscape4only)
FigureH-10.InternetExplorerdoesn'tsupportmultiplelayers
Weusedafewtrickstocreatethedrop-shadoweffectfortheexampleheader.
Netscape4coverslayerscreatedearlierinthedocumentwithlaterlayers.Hence,
wecreatethegrayshadowfirst,followedbytheactualheading,sothatitappears
ontop,abovetheshadow.Wealsoenclosedthesetwolayersinaseparate
containinglayer.Thisway,theshadowandheaderpositionsarerelativetothe
containinglayer,notthedocumentitself.Thecontaininglayer,lackinganexplicit
position,isplacedintothedocumentflowasthoughitwerenormalcontentand
windsupwhereaconventionalheadingwouldappearinthedocument.
Normalcontent,however,stillstartsatthetopofthedocumentandcouldendup
behindthefancyheadinginourexample.Topushcontentbelowourlayered
heading,weincludeanemptyheading(saveforanonbreakingspace )
beforeincludingourconventionaldocumenttext.
Thisisimportantenoughtorepeat:normaldocumentcontentfollowinga<layer>
tagispositioneddirectlyunderthelayeritfollows.Youcancircumventthiseffect
usinganinlinelayer,describedin"The<ilayer>Tag(Antiquated)"sectionlaterin
thischapter.
H.3.1.3.Theabove,below,andz-indexattributes
Layersexistinthreedimensions,occupyingspaceonthepageandstackedontop
ofoneanotheraswellasontopofconventionaldocumentcontent.Aswe
mentionedearlier,layersnormallyarestackedinorderoftheirappearanceinthe
document:layersatthebeginninggetcoveredbylaterlayersinthesamedisplay
area.
Youcancontrolthestackingorderofthelayerswiththeabove,below,andz-index
attributesforthe<layer>tag.Theseattributesaremutuallyexclusive;useonly
oneperlayer.
Thevaluefortheaboveorbelowattributeisthenameofanotherlayerinthe
currentdocument.Ofcourse,thatreferencedlayermusthaveanameattribute
whosevalueisthesamenameyouusewiththeaboveorbelowattributeinthe
referring<layer>tag.Youalsomusthavecreatedthereferencedlayerearlierin
thedocument;youcannotrefertoalayerthatcomeslater.
Indirectcontradictionwithwhatyoumightexpect,Netscape4putsthecurrent
layerbelowtheabove-namedlayerandabovethebelow-namedlayer.[*]Oh,well.
Notethatthelayersmustoccupythesamedisplayspaceforyoutoseeany
effects.
[*]Onecannothelpbutimaginethattheaboveandbelowattributeswereimplementedintheweehours.
Let'suseourdrop-shadowlayerexampleagaintoillustratetheaboveattribute:
<layer>
<layername=textleft=0top=0>
<h1>IntroductiontoKumquatLore</h1>
</layer>
<layername=shadowabove=textleft=2top=2>
<h1><fontcolor=gray>IntroductiontoKumquatLore</font></h1>
</layer>
</layer>
TheaboveattributeinthelayernamedshadowtellsNetscape4topositionthe
shadowlayersothatthelayernamedtextisaboveit.Theeffectisidenticalto
FigureH-9.
Theaboveandbelowattributescangetconfusingwhenyoustackseverallayers.We
finditsomewhateasiertousethez-indexattributeforkeepingtrackofwhich
layersgooverwhich.Withz-index,youspecifytheorderinwhichNetscapestacks
thelayers:higherz-indexvaluelayersareputontopoflowerz-indexvaluelayers.
Forexample,tocreateourdropshadowusingthez-indexattribute,wewoulduse
thefollowing:
<layer>
<layerleft=0top=0z-index=2>
<h1>IntroductiontoKumquatLore</h1>
</layer>
<layerleft=2top=2z-index=1>
<h1><fontcolor=gray>IntroductiontoKumquatLore</font></h1>
</layer>
</layer>
Again,theeffectisidenticaltoFigureH-9.Normally,Netscape4woulddisplaythe
secondlayerthegrayoneinthiscaseontopofthefirstlayer.Butbecausewe've
giventhegraylayeralowerz-indexvalue,itisplacedbehindthefirstlayer.
Thez-indexvaluesneednotbesequential,althoughtheymustbeintegers,sowe
couldhaveusedthevalues99and2,respectively,andgottenthesameresultin
thepreviousexample.Andyouneednotspecifyaz-indexforallthelayersthat
occupythesamedisplayspaceyouneedspecifyitonlyforthosethatyouwantto
raiseorlowerinrelationtootherlayers.However,beawarethattheorderof
precedencemaygetconfusingifyoudon'tz-indexallrelatedlayers.
Forinstance,whatorderofprecedencebycolorwouldyoupredictwhenNetscape
4rendersthefollowingsequenceoflayers?
<layerleft=0top=0z-index=3>
<h1><fontcolor=red>IntroductiontoKumquatLore</font></h1>
</layer>
<layerleft=4top=4>
<h1><fontcolor=green>IntroductiontoKumquatLore</font></h1>
</layer>
<layerleft=8top=8z-index=2>
<h1><fontcolor=blue>IntroductiontoKumquatLore</font></h1>
</layer>
Giveyourselfastarifyousaidthatthegreenheadergoesontopofthered
header,whichgoesontopoftheblueheader.Why?Becausetheredheaderisof
lowerprioritythanthegreenheaderbasedonorderofappearance,andweforced
thebluelayerbelowtheredonebygivingitalowerz-indexvalue.Netscape4
displaysz-indexedlayersaccordingtotheirgivenorderandnon-z-indexedlayers
accordingtotheirorderofappearanceinthedocument.Precedencebasedon
orderofappearancealsoappliesforlayersthathavethesamez-indexvalue.If
younestlayers,allthelayersatthesamenestinglevelareorderedaccordingto
theirz-indexattributes.Thisgroupisthenorderedasasinglelayeramongallthe
layersatthecontaininglevel.Inshort,layersnestedwithinalayercannotbe
interleavedamonglayersatadifferentlevel.
Forexample,considerthesenestedlayerswiththeircontentandendtagsomitted
forclarity(indentationindicatesnestlevel):
<layername=az-index=20>
<layername=a1z-index=5>
<layername=a2z-index=15>
<layername=bz-index=30>
<layername=b1z-index=10>
<layername=b2z-index=25>
<layername=b3z-index=20>
<layername=cz-index=10>
Layersa,b,andcareatthesamelevel,withlayersa1anda2nestedwithinaand
b1,b2,andb3nestedwithinb.Althoughthez-indexnumbersmight,atfirstglance,
appeartocauseNetscape4tointerleavethevariousnestedlayers,theactual
orderingofthelayers,frombottomtotop,isc,a,a1,a2,b,b1,b3,andb2.
Iftwolayersarenestedwithinthesamelayerandtheyhavethesamez-index
value,thelayerdefinedlaterinthedocumentisplacedontopofthepreviously
definedlayer.[*]
[*]This,ofcourse,appliestolayersinsidethesamecontainingnestonly.
H.3.1.4.Thebackgroundandbgcolorattributes
Aswiththecorrespondingattributesforthe<body>tag,youcandefinethe
backgroundcolorandanimageforaNetscape4layerwiththebgcolorand
backgroundattributes,respectively.[ ]Bydefault,thebackgroundofalayeris
transparent,allowinglowerlayerstoshowthrough.
[ ]Notethatyoucancontrolthebackgroundcolor(aswellasmanyotherdisplayfeatures)ofnotjustasingletagbutall
<DEFANGED_layer>tagswithinyourdocumentusingstylesheets.Seesection5.3.1.8,"Thestyleandclass
attributes."
ThebgcolorattributeacceptsacolornameorRGBtripleasitsvalue,asdefinedin
AppendixG.Ifspecified,Netscapesetstheentirebackgroundofthelayertothis
color,renderingthelayeropaque.Thisattributeishandyforcreatingacolored
boxbehindtext,asahighlightingorattention-gettingmechanism.Itdoes,
however,hideanylayersbelowit,includingconventionalHTMLcontent.
ThebackgroundattributeacceptstheURLofanimageasitsvalue.Theimageis
tiledtofilltheareaoccupiedbythelayer.Ifportionsoftheimageare
transparent,thoseportionsofthelayeraretransparent,andunderlyinglayers
showthrough.
Ifyouincludebothattributes,thebackgroundcolorshowsthroughthe
transparentspotsinthebackgroundimage.Thewholelayerisopaque.
Thebackgroundattributeisusefulforplacingatexturebehindtext,butitfails
miserablywhenthegoalistorendertextinfrontofafixedimage.Becausethe
sizeofalayerisdictatedbyitscontents,notthebackgroundimage,usingthe
imageasthebackgroundcausesittobeclippedortiled,dependingonthesizeof
thetext.
Toplacetextreliablyontopofanimage,useonelayernestedwithinanother:
<layer>
<imgsrc="sunset.gif">
<p>
<layertop=75>
<h2align=center>Andtheylivedhappilyeverafter...</h2>
</layer>
</layer>
Netscape4setsasidespacefortheentireimageintheouterlayer.Theinner
layeroccupiesthesamespace,exceptthatweshiftitdown75pixelstoalignthe
textbetterovertheimage.FigureH-11showstheresult.
FigureH-11.Placingtextoveranimageusinglayers(Netscape4
only)
H.3.1.5.Thevisibilityattribute
Bydefault,layersusuallyarevisible.Youcanchangethatbysettingthevisibility
attributetoshow,hide,orinherit.Asexpected,showforcesthelayertobeseen,hide
hidesitfromview,andinheritexplicitlydeclaresthatyouwantthelayertoinherit
itsparent'svisibility.Thedefaultvalueforthisattributeisinherit.Layersthatare
notnestedareconsideredtobechildrenofthemaindocument,whichisalways
visible.Thus,non-nestedlayerslackingthevisibilityattributeareinitiallyvisible.
Itmakeslittlesensetohidelayersunlessyouplantorevealthemlater.In
general,youshouldusethisattributeonlywhenyouincludesomeJavaScript
routineswithyourdocumentthatrevealthehiddenlayersasaresultofsome
userinteraction.[JavaScriptEventHandlers,12.3.3]
Layersthatarehiddendonotblocklayersbelowthemfromview.Instead,a
hiddenlayercanbestbethoughtofasbeingtransparent.Onewaytohide
contentinthemaindocumentistoplaceanopaquelayeroverthecontent.To
displaythehiddencontext,hidetheopaquelayer,revealingthecontent
underneath.
H.3.1.6.Thewidthattribute
Layersareonlyasbigasnecessarytocontaintheircontent.Theinitialwidthofa
layerisdefinedtobethedistancefromthepointatwhichthelayeriscreatedin
thecurrenttextflowtotherightmargin.Netscape4thenformatsthelayer's
contentstothatwidthandmakestheheightofthelayertallenoughtocontainall
ofthelayer'scontents.Ifthecontentsofthelayerwindupsmallerthantheinitial
width,thelayer'swidthisreducedtothissmalleramount.
Youcanexplicitlysetthewidthofalayerusingthewidthattribute.Thevalueof
thisattributedefinesthewidthofthelayerinpixelsorasapercentageofthe
containinglayer.Asexpected,Netscape4thensetstheheightbaseduponthe
sizeofthelayer'scontents,wrappedtothespecifiedwidth.Ifelementsinthe
layersuchasimagescannotbewrappedandinsteadextendpasttherightmargin
ofthelayer,onlyaportionoftheelementisshown.Theremainderisclippedby
theedgeofthelayerandisnotshown.Thisissimilartothebehaviorofanimage
inthemaindocumentwindow.Iftheimageextendsbeyondtheedgeofthe
browserwindow,onlyaportionoftheimageisdisplayed.Unlikethebrowser
window,however,layerscannotsportscrollbarsallowingtheusertoscrollaround
inthelayer'scontents.
H.3.1.7.Thesrcattribute
Thecontentsofalayerarenotrestrictedtowhatyoutypebetweenits<layer>and
</layer>tags;youcanalsorefertoandautomaticallyloadthecontentsofanother
documentintothelayerwiththesrcattribute.Thevalueofthesrcattributeisthe
URLofthedocumentcontainingthelayer'scontent.
Notethatthelayersrc'ddocumentshouldnotbeafull-fledgedHTMLdocument.In
particular,itshouldnotcontain<body>or<head>tags,althoughotherHTMLcontent
isallowed.
Youcancombineconventionallayercontentwithcontenttakenfromanotherfile
byusingthesrcattributeandplacingcontentwithinthe<layer>tag.Inthiscase,
thecontentfromthefileisplacedinthelayerfirst,followedbyanyinlinecontent
withinthetagitself.Ifyouchoosetousethesrcattributewithoutsupplying
additionalinlinecontent,youstillmustsupplytheclosing</layer>tagtoendthe
definitionofthelayer.
Thesrcattributeprovides,forthefirsttime,asourceinclusioncapabilityinHTML.
Previously,toinsertcontentfromoneHTMLdocumentintoanother,youhadto
relyonaserver-basedcapabilitytoreadtheotherfileandinsertitintoyour
documentatthecorrectlocation.Becauselayersarepositioned,bydefault,at
theirdefiningpointwithinthecurrentflow,includinganotherfileinyour
documentissimple:
...othercontent...<layersrc="boilerplate"></layer>...morecontent...
BecausealayerisrenderedasaseparateHTMLentity,thecontentoftheincluded
fileisnotflowedintothecontainingtext.Instead,itisasthoughtheinsertedtext
werecontainedwithina<div>tagorotherblock-levelHTMLelement.
H.3.1.8.Theclipattribute
Normally,usersseetheentirelayerunlessitisobscuredbyacoveringlayer.With
theclipattribute,youcanmaskoffportionsofalayer,revealingonlya
rectangularportionwithinthelayer.Theareaofthelayeroutsidethevisiblearea
ismadetransparent,allowingwhateverisunderthelayertoshowthrough.
Thevalueoftheclipattributeistwoorfourintegervalues,separatedbycommas,
definingpixeloffsetsintothelayercorrespondingtotheleft,top,right,and
bottomedgesofthecliparea.Ifonlytwovaluesaresupplied,theycorrespondto
therightandbottomedgesofthevisiblearea,andNetscapeassumesthetopand
leftvaluesare0.Therefore,clip="75,100"isequivalenttoclip="0,0,75,100".
Theclipattributeishandyforhidingportionsofalayer,orforcreatingfadeand
wipeeffectsusingJavaScriptfunctionstochangetheclippingwindowovertime.
H.3.1.9.Thestyleandclassattributes
Usethestyleattributewiththe<layer>tagtocreateaninlinestyleforallthe
contentinsidealayer.Theclassattributeletsyoulabelthelayerwithanamethat
referstoapredefinedclassofthe<layer>tagdeclaredinsomedocument-levelor
externallydefinedstylesheet.Accordingly,youmaychoosetouseastylesheet
ratherthanindividualandredundantbgcolortagattributestodefineabackground
colorforallyourdocumentlayersorforaparticularclassoflayers.[InlineStyles:
ThestyleAttribute,8.1.1][StyleClasses,8.3]
H.3.2.The<ilayer>Tag(Antiquated)
Whileyoucontrolthepositionofa<layer>usingtopandleftattributecoordinates
relativetothedocument'sentiredisplayspace,Netscape4providesaseparate
tag,<ilayer>,thatletsyoupositionindividuallayerswithrespecttothecurrent
flowofcontent,muchlikeaninlineimage.
<ilayer>(Antiquated)
Function Definesaninlinelayerofcontentwithinatextflow
Attributes above,background,below,bgcolor,class,clip,left,name,src,style,top,visibility,
width,z-index
Endtag </ilayer>;neveromitted
Contains body_content
Usedin text
An<ilayer>tagcreatesalayerthatoccupiesspaceinthecontainingtextflow.
Subsequentcontentisplacedafterthespaceoccupiedby<ilayer>.Thisisin
contrasttothe<layer>tag,whichcreatesalayerabovethecontainingtextflow,
allowingsubsequentcontenttobeplacedunderthelayerjustcreated.
The<ilayer>tagremovestheneedforanenclosing,attribute-free<layer>that
servestoputanestofspeciallypositionedlayersinlinewiththecontentflow,
muchlikewedidinmostoftheexamplesintheprevioussectionsofthis
appendix.Theattributesof<ilayer>arethesameasthoseforthe<layer>tag.
H.3.2.1.Thetopandleftattributes
Theonlyattributesthatdistinguishtheactionsofthe<ilayer>tagfromits<layer>
siblingaretopandleft:Netscape4renders<ilayer>contentdirectlyinthe
containingtextflow,offsetbythetopandleftattributevaluesfromtheupper-left
cornerofthatinlinepositionnotthedocument'supper-leftdisplaycorner,aswith
<layer>.Netscape4alsoacceptsnegativevaluesforthetopandleftattributesof
the<ilayer>tag,lettingyoushiftthecontentsaboveandtotheleftofthecurrent
flow.
Forexample,tosubscript,superscript,orshiftwordswithinthecurrentline,you
coulduse:
This<ilayertop=4>word</ilayer>isshifteddown,while
this<ilayerleft=10>one</ilayer>isshiftedover.Withanegative
value,wordscanbemoved<ilayertop=-4>up</ilayer>andto
the<ilayerleft=-10>left</ilayer>.
FigureH-12showstheresultingeffects.Noticehowtheshiftedwordsoverlapand
obscurethesurroundingtext.Netscape4makesnoefforttomakeroomforthe
shiftedelements;theyaresimplyplacedinadifferentspotonthepage.
FigureH-12.Movinginlinelayerswithrespecttotheadjacent
text(Netscape4only)
H.3.2.2.Combining<layer>and<ilayer>
Anythingyoucancreatewitharegularlayeryoucanusewithinaninlinelayer.
However,bearinmindthatthetopandleftattributeoffsetsareindeedfromthe
<ilayer>content'sallottedposition,notfromthedocumentdisplayspace.
Accordingly,use<ilayer>topositioncontentinlinewiththeconventionalHTML
documentflow,anduse<layer>topositionelementsandcontentpreciselyinthe
documentdisplayspace.
Also(andfortunately),Netscape4doesnotdistinguishbetween<ilayer>and
<layer>tagswhenitcomestoorderofappearance.Youmaydeclarethatan
<ilayer>appearbelowsome<layer>byusingthenameandaboveattributes:
<layername=me>I'montop</layer>
<ilayerabove=me>I'monthebottom</ilayer>
Similarly,youcanreordertheappearanceofbothabsoluteandinlinelayers
wheretheyoverlapbyassigningz-indexattributevaluestothevariouselements.
Nestingrulesapply,too.
AbouttheAuthors
ChuckMusciano(cmusciano@aol.com)acquiredaB.S.incomputersciencefrom
GeorgiaTechin1982.Hespent15yearsintheemployofHarrisCorporation,in
Melbourne,Florida,firstasacompilerwriterandcrafteroftoolsandlaterasa
memberofHarris'sAdvancedTechnologyGroup.HisfocusonUnix-and
Internetbasedtechnologyenabledhimtosupportearlywebinitiativeswithin
Harris.AftervariouspositionsofincreasingresponsibilityintheITindustry,he
currentlyservesastheVicePresidentofInformationServicesforMartinMarietta
MaterialsinRaleigh,NorthCarolina.Throughouthiscareerhehaswrittenfor
varioustradepublications,bothinprintandasanonlinecolumnist,includingthe
"Webmaster"columnforSunWorldandthe"TagoftheWeek"columnfor
WebReview.Inhissparetime,heenjoyslifeinNorthCarolinawithhiswifeCindy,
daughterCourtney,andsonCole.
BillKennedy(bkennedy@mobilerobots.com)iscurrentlyChiefTechnologyOfficer
forMobileRobots,Inc.,adeveloperandmanufacturerofintelligentmobilerobots
andothersmartmachines.HowhecametochasingAIrobotsaroundisnot
surprising,givenhismanyroundaboutcareers.BillhasaPh.D.inbiochemistry
andbiophysicsfromLoyolaUniversityofChicagoanddidover12yearsof
biomedicalresearchthroughthe1970sandearly'80s.InfectedbythePCbug
(32KAppleII;really!),hecreatedasoftwarecompanythatdevelopedcomputer
gamesandeducationalprograms.Needingarealjobwithbenefits,Billalso
servedastechnicaleditor,senioreditor,andeditor-in-chiefforvarious
InternationalDataGroupmagazines,includinginCider,SunTechnologyJournal,
SunWorld,andA+Publishing/MacComputing,amongothers,inthe'80sand'90s.
AnaviduseroftheInternetsincethemid'80s,Bill,withhiswifeJeanneDietsch,
foundedActivMediaResearch,thefirstmarket-researchfirmevertoformally
studybusinessesontheWeb.Theirfirstreport,publishedin1995,containeddata
gatheredbyactuallyvisitingeachandeverybusinesswebsiteinexistenceback
then,ifyoucanimagine.Alwaysreadytoembraceemergingtechnologies,Bill
andhispartnersformedActivMediaRoboticsin1996,whichnow,asMobileRobots
Inc.(http://www.mobilerobots.com),sellsmoreintelligentmobileplatformsto
moreartificialandmachine-intelligentresearchersaroundtheworldthananyone
else.Andthecompany'smobile-roboticsnavigationtechnologiesarequicklybeing
adoptedforcommercialandindustrialapplications.So,what'snext?
Colophon
TheanimalonthecoverofHTML&XHTML:TheDefinitiveGuideisakoala.The
koalaisanAustralianmarsupial,theonlymemberofthePhascolarctidaefamily.
Whentheyareborn,koalasaretiny,weighingapproximately0.5grams.Ayoung
koalastaysinitsmother'spouchforapproximatelysevenmonths.Unlikemost
marsupials,thekoala'spouchopensneartherear,notnearthehead.Koalashave
ahighmortalityrateandfaceextinctioninAustraliaduetoepidemicsin
18871889and19001903,andunrestrainedhuntingthroughoutthe20thcentury.
Theyareaprotectedspecies.Populationsarerebuilding,butatpresent,they
surviveonlyineasternAustralia.
Thecoverimageisa19th-centuryengravingfromtheDoverPictorialArchive.
ThecoverfontisAdobeITCGaramond.ThetextfontisLinotypeBirka;the
headingfontisAdobeMyriadCondensed;andthecodefontisLucasFont's
TheSansMonoCondensed.
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
<(less-thansign)
<!---->tag2nd
<a>tag2nd
hyperlinkstates
linkingexternaldocuments
nestingrestrictions
<abbr>tag
<acronym>tag
<address>tag
<applet>tag
<area>tag2nd3rd
<b>tag2nd
<base>tag2nd
<basefont>tag
<bdo>tag
<bgsound>tag
<big>tag
<blink>tag
<body>tag2nd3rd
colorextensions
<br>tag2nd3rd4th
vertical<spacer>vs.
<button>tag
nestingrestrictions
<caption>tag2nd
<center>tag
<cite>tag2nd
<code>tag2nd
filenames,usewith
<col>tag
<colgroup>tag
<dd>tag
<del>tag
<dfn>tag2nd
<dir>tag
<div>tag2nd
<dl>tag2nd
<dt>tag2nd
<em>tag2nd
<embed>tag
foraudio
<fieldset>tag
<font>tag
<form>tag2nd
nestingrestrictions
<frame>tag2nd
<frameset>tag2nd3rd
<h#>tag2nd
<head>tag2nd3rd
<hr>tag2nd
<html>tag2nd3rd
<i>tag2nd
<em>tagvs.
<iframe>tag
<ilayer>tag
<img>tag2nd
customimagebuttons(forms)
emulatingspacerswith
videoextensions
<input>tag
actionbuttons
checkboxes(type=checkbox)
file-selection(type=file)
hiddenfields(type=hidden)
maskedtext-entry(type=password)
radiobuttons(type=radio)
text-entry(type=text)
<ins>tag
<isindex>tag2nd3rd
<kbd>tag2nd
<label>tag
nestingrestrictions
<legend>tag
<li>tag2nd
<link>tag2nd3rd4th5th
webbrowserlimitations
<listing>tag
<map>tag2nd3rd
<marquee>tag
<menu>tag
<meta>tag2nd3rd
<multicol>tag2nd
<nextid>tag2nd
<nobr>tag2nd
centeredcontentand
<noembed>tag
<noframes>tag
<noscript>tag
<object>tag2nd
<ol>tag2nd
<optgroup>tag
<option>tag
<p>tag2nd3rd
<param>tag
<plaintext>tag
<pre>tag2nd
nestingrestrictions
<q>tag
<s>tag
<samp>tag2nd
<script>tag2nd
<select>tag
<server>tag
<small>tag
<spacer>tag
<span>tag
<strike>tag
<strong>tag2nd
<style>tag2nd3rd
@importat-rule
commentsin
dir,lang,andtitleattributes
<sub>tag
<sup>tag
<table>tag2nd
<tbody>tag
<td>tag2nd
<textarea>tag
<tfoot>tag
<th>tag2nd
<thead>tag
<title>tag2nd
<tr>tag2nd
<tt>tag2nd
<u>tag
<ul>tag2nd
<var>tag2nd
<wbr>tag
centeredcontentand
<xmp>tag
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
abbrattribute(<th>and<td>)
aboveattribute(<layer>)
absbottom,absmiddlevalues
absolutefontsize
absoluteURLs2nd
acceptattribute(<inputtype=file>)
accept-charsetattribute(<form>)
accesskeyattribute
<a>
<legend>
formcontrols
actionattribute
<form>
<isindex>
actionbuttons(forms)
ActiveXtechnology
addresses
IPaddresses2nd
XMLDTD,definingfor
adjacentselectors
AdvancedResearchProjectsAgency(ARPA)
alignattribute
<applet>
<caption>
<div>
<embed>
<h#>
<hr>
<iframe>
<img>2nd
<inputtype=image>
<legend>
<marquee>
<object>
<p>
<spacer>
<table>
<th>and<td>
<tr>
alignment
<center>tags
formelements2nd
frames
headings
horizontalrules
imagebuttons(forms)
images2nd3rd
layers2nd
sections
tables2nd3rd4th5th
text2nd3rd4th
whitespaceblocks
alinkattribute(<body>)
allvalue(stylemedia)
altattribute
<applet>
<area>
<img>
alternatevalue(marqueebehavior)
ampersand(&)
entities2nd3rd
inURLs
inXHTML
anchors2nd
animation
frame-by-frame(GIF)
oftext
annotatedlists
anonymousFTP
applets2nd3rd
application/x-www-form-urlencodedencoding
archiveattribute
<applet>
<object>
ARPA(AdvancedResearchProjectsAgency)
articles(newsgroups),identifiersfor
ASCIItextfileformat,savingHTML/XHTMLdocumentsin
at-rules
@font-face
@import
@media
@page
attributeselectors
supportingbrowsers
attributes
deprecated
for<body>tags
HTMLtags2nd
images,enablingJavaScriptmanipulation
XHTML2nd
XML2nd3rd
audience,designingfor
audio2nd
<bgsound>tags
client-pullfeaturefor
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
background
audio
colors2nd3rd4th5th6th7th8th
images2nd3rd4th5th6th7th8th9th10th
layers
stylepropertiesfor
backgroundattribute
<body>2nd
<layer>
<table>
<th>and<td>
backgroundproperty
background-attachmentproperty
background-colorproperty
background-imageproperty
background-positionproperty
background-repeatproperty
backslash(\\\\),CSS2escapecharactersand
baseURLs2nd
baselinedescriptor
bboxdescriptor
behaviorattribute(<marquee>)
belowattribute(<layer>)
bgcolorattribute
<body>2nd
<layer>
<marquee>
<table>
<th>and<td>
<tr>
bgpropertiesattribute(<body>)
bibliographiccitations
binaryfiles
blanklines
blindcarboncopy(bcc)field,mailmessages
blinkingtext2nd
blockitems
blockquotes
<blockquote>tags
<q>tags
blocksofwhitespace
bodycontent2nd
marginsfor
boilerplateHTMLdocuments
usesof<ins>and<del>tagsin
boldfacetext2nd
borderattribute
<embed>
<img>
<inputtype=image>
<object>
<table>2nd
border-collapseproperty
border-colorproperty
border-spacingproperty
border-styleproperty
border-widthproperty
bordercolorattribute
<frame>
<table>
<th>and<td>
<tr>
bordercolorlight,bordercolordarkattributes
<table>
<th>and<td>
<tr>
borders
colors
frame2nd
imagebuttons(forms)
images2nd
size
stylepropertiesfor2nd
tables2nd3rd
bottomvalue
boundarystring
boxstyleproperties
braillevalue(stylemedia)
browserextensions,XHTMLVersion1.1and
browsers
mobiledevices,constraints
bufferspace
bugs,<img>height/widthattributes
bulleted(unordered)lists
bulletshape
listmarkerstyleproperties
nesting
buttons
formactionbuttons
mouse
radiobuttons
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
cap-heightdescriptor
caption,table
caption-sideproperty
carboncopy(cc)field,mailmessages
carriagereturns
CascadingStyleSheets
casesensitivity2nd
elementsofstylerules
XHTMLtagsandattributenames2nd
case,transformingtextindocuments
CDATAsections
inXMLDTDs
JavaScriptandCSSdeclarations,enclosingwithin
cellpaddingattribute(<table>)
cells,table
cellspacingattribute(<table>)
cellularaccess
high-speed
lowspeed
WiFi
centerattribute(<img>)
centervalue(alignment)
centering
centerlinedescriptor
CGI(CommonGatewayInterface)programs
authorinabilitytocreateormanage
storing
charattribute
<th>and<td>
<tr>
characterentities2nd3rd4th5th
JavaScript
characters
letterspacing
reserved/unsafeinURLs
special
wordspacing
charoffattribute
<th>and<td>
<tr>
charsetattribute
<a>
<meta>
<script>
checkboxes
circularbullets
circularimagemapareas
citeattribute
<blockquote>
<ins>and<del>
<q>
classattribute2nd
<a>
<address>
<area>
<blockquote>
<body>
<caption>
<center>
<div>
<dl>,<dt>,and<dd>
<font>
<form>2nd
<frameset>
<isindex>
<layer>
<map>
<multicol>
<object>
<p>2nd
<pre>
<q>
<ul>,<ol>,and<li>
content-basedstyletags
formcontrols
physicalstyletags
tableattributes
classes,style2nd
inheritanceand2nd
classidattribute,<object>
classificationstyleproperties
clearattribute(<br>)
clearimages
clearproperty
clickableimagemaps
client-pulldocuments
client-sideimagemaps2nd3rd
exampleof
clients
clipattribute(<layer>)
clipproperty
codeattribute(<applet>)
codebaseattribute(<applet>)
codetypeattribute(<object>)
colon(:)andpseudoclasses
colorattribute
<basefont>
<font>
<hr>
colorproperty
colorvalues
colormaps
colors2nd3rd
<body>tagextensions
background2nd3rd4th5th6th
border
frameborders2nd
graphicsfileformatsand
horizontalrules
hyperlinks2nd
JavaScriptStyleSheets(JSS),specifyingvalues
names
performanceconsiderations
standardcolormap
stylepropertiesfor2nd
tables2nd3rd4th
text2nd3rd
transparentGIFs
colsattribute
<col>
<multicol>
<table>
<textarea>
colspanattribute(<td>and<th>)
columns
<multicol>tags
frames
multilinetext-entryareas
tables2nd3rd
textlayoutin2nd
whitespacebetween(gutter)
comma(,)instyles
comments2nd3rd
<comment>tags
in<style>tags
inXMLDTDs
CommonGatewayInterface
compactattribute
<dl>
<ol>
<ul>
conditionalsections,XMLDTD
contentattribute(<meta>)2nd
contentproperty
open-quoteandclose-quotevalues
contenttypes2nd
application/x-www-form-urlencoded
file-selectioncontrolsand
multipart/form-data
multipart/mixed
multipart/x-mixed-replace
text/css
text/plain
content-basedstyletags2nd3rd
tableof
Content-Dispositionheader2nd
Content-Typeheader2nd
contextualstyles2nd
controlsattribute(<img>)
controls,form
conventionsforHTMLprogramming
convergencesdevices
convertingHTMLdocumentstoXHTML
coordinatesinimagemaps
coordsattribute
<a>
<area>
counter-incrementproperty
counter-resetproperty
counters
CSS(CascadingStyleSheets)2nd
boxproperties
cascadingofeffects
classificationproperties
colorandbackgroundproperties
commentsin
CSS2standard
fontproperties
howtouse
listproperties2nd
rectangularboxmodelfor
styleproperties
stylesyntax
taglessstyles(<span>)
textproperties
CSS2standard2nd
@importand@mediaat-rules
audioproperties
bordershorthandproperties
boxproperties
browserversions,supportingandnon-supporting
classificationproperties
counters
escapeentities
fontproperties
font-matchingalgorithm
formattingmodel
generatedcontentproperties
listproperties
markers,creating
media-specificstylesheets,defining
paginationcontrolfeaturesforprinting
pseudoclasses
pseudoelementsdefinedin
selectors2nd
styleproperties
stylesyntax
tableproperties
cueproperties
custombullets
customimagebuttons(forms)
cyclingdocuments
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
dashedborders
dataattribute(<object>)
data,exchangingwithXML
connectingsystems
documentexchange
datetimeattribute(<ins>and<del>)
declareattribute(<object>)
declaringXMLentitiesandelements
deferattribute(<script>)
definitionlists2nd
usingappropriately
definitions-srcdescriptor
delay
documentrefresh
loading
marqueemovement
deprecatedattributes
align2nd3rd4th
background,<body>
bgcolor,<body>
border,<img>
class,forlists
compact,forlists2nd3rd
link,vlink,andalink,<body>
name,<a>
noshade,<hr>
size,<hr>
start,forlists
style,forlists
text,<body>
type2nd3rd
value,forlists
version,<html>tags
width,<hr>
deprecatedelements
HTML4.01standard,and
XHTMLand2nd
deprecatedtags
<applet>2nd
<basefont>
<center>2nd
<dir>
<font>
<isindex>2nd
<menu>
<s>
<span>
<strike>
<u>
font-handlingtags
foraudiosupport
designinginHTML
dirattribute2nd3rd
<a>
<address>
<area>
<bdo>,overridingwith
<blockquote>
<center>
<div>
<dl>,<dt>,and<dd>
<font>
<form>
<head>
<html>
<isindex>
<object>
<p>2nd
<pre>
<q>
<title>
<ul>,<ol>,and<li>
formcontrols
tabletags
directionattribute(<marquee>)
directorylists
disabledattribute(formcontrols)
discbullets
displayconstraints,mobiledevices
displayproperty
displayingXMLdocuments
displays,formcontentsand
document-levelstyles
advantagesanddisadvantagesofusing
document-relatedevents
documentation
<meta>tagsfor
forformelements
HTMLtagsquickreference
documents
aslayers
automation
embedding2nd
exchangingwithXMLapplications
HTML
pathnames
XHTML
domains2nd3rd
dottedborders
doubleborders
doublequotationmarks(")inXHTMLattributevalues
downloadingdelay
downloadingimages
DTDforHTML2nd3rd
HTML4.01standard
DTDforXHTML
creating
declaring
XHTML1.0standard
DTDforXML2nd
comments
conditionalsections
creating(example)
elements2nd3rd
entities2nd
dynamicdocuments
client-pull
server-push
dynsrcattribute(<img>)
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
elements,nesting
elevationproperty
email,mailtoURLfor2nd
definingmailheaderfields
sendingformdatavia
embeddedlinks
embeddedobjects2nd
<applet>tags
<embed>tags
<noembed>tags
<object>tags
<param>tags
embeddedtags
emphasis,tagsfor
<b>
<blink>
<dfn>
<em>
<i>
<strong>
emptyelementsinXHTMLdocuments
empty-cellsproperty
encoding
characters
file-selectioncontrolsand
enctypeattribute
<form>
<inputtype=file>
endingtags2nd
omittinginHTML
XHTMLvs.HTMLdocuments
entities2nd3rd4th
JavaScript
URLencodings
entityandelementdeclarations(XML)
equalssign(=)fortagattributes
=(equalssign)fortagattributes
escapeentities,CSS2standard
eventattributes
<a>
<address>
<area>(client-sideimagemaps)
<blockquote>
<center>
<div>
<form>
<h#>
<img>
<inputtype=button>(pushbuttons)
<map>
<p>
<pre>
<q>
<ul>
content-basedtags
formcontrols
framesand
objectsand
physicalstyletags
tabletags
eventhandlers,JavaScript
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
faceattribute
<basefont>
<font>
family,font
favorite_font_size()function
fileserver
FileTransferProtocol
file-selectioncontrols(forms)
files
fileURLs
HTML
listingindirectorylists
XHTML
fixedvalue(backgroundimageposition)
flashingtext2nd
floatproperty
floatingelements,rulesformargincollapsing
floatingframes
flood-fillingimages
flowingtext
fontproperty
font-familyproperty
font-sizeproperty
font-styleproperty
font-variantproperty
font-weightproperty
fonts
color
descriptors
fontsize
headingtagstochange
HTMLtagsfor2nd3rd
JavaScriptStyleSheets(JSS),tagsproperty
stylepropertiesfor
footers
ruleswith
table
forattribute(<label>)
foregroundcolors
format
alignment
encoding
graphicsformats2nd
HTMLdocuments
indentation
listitems
multimediafileformats
paragraphrendering
preformattedtext
forms2nd
<button>tags
exampleof
inputcontrols2nd3rd4th5th6th7th8th9th10th
layoutof2nd
mailtoURL,with
nestedtableswith
programming2nd
writingeffectively
FQDNs
fragmentidentifiers2nd
<a>tagsas
tablesofcontents,and
frameattribute(<table>)
frame-by-frameanimation
frameborderattribute
<frame>
frames2nd
<frame>tags2nd
<frameset>tags2nd3rd
<noframes>tags
alignment
ashyperlinktargets2nd3rd4th5th6th
borders
contentsof
inline
layout
marginsandborders
openingmultipleatonetime
scrolling
tipsandtricks
FramesetDTD2nd
framesets
FTP(FileTransferProtocol)
ftpURLs
obtainingbrowsersvia
fullyqualifieddomainnames
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
generalentities,XML
generatedcontentproperties
genericstyleclasses
GETmethod2nd
GIF(GraphicsInterchangeFormat)2nd
GIFanimation
gopherURLs
grammar,elements
nonterminalsandterminals
XML2nd
grammar,HTML
graphics2nd
groovedborders
groupingformelements
groupinggrammarrules,elements
gutterattribute(<multicol>)
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
handheldvalue(stylemedia)
hangingindents
headofHTMLdocuments2nd3rd4th
headers
ruleswith
table2nd
verticalspacerswith
headersattribute(<th>and<td>)
headings2nd
allowedcontent
imagesin
sideheads(tables)
straddleheads(tables)
textsizeand
heightattribute
<applet>
<embed>
<iframe>
<img>
<marquee>
<spacer>
<table>
<tr>
heightproperty
helperapplications2nd
hexadecimalcharacterequivalents,escapecharactersinCSS2
hexadecimalcolorvalues
hexadecimalRGBtriples
hiddenattribute(<embed>)
hiddenformfields
hiddentext-entryfields
hidevalue(layervisibility)
homepages2nd3rd
horizontal
margins
rules2nd3rd4th5th6th7th
whitespace
hotkeysforhyperlinks
hrefattribute
<a>2nd
<area>
<base>
<link>
hreflangattribute(<a>)
hspaceattribute
<embed>
<img>
<marquee>
HTML
creationof
documentsin
DTD(DocumentTypeDefinition)2nd3rd4th
extensionsto2nd3rd
grammarof
limitationsof
objectmodel
standardizingwithXML
tags
texteditorsfor2nd3rd4th5th
tipsandtricks2nd
Version4.0
Version4.01,xix
XHTMLvs.
HTMLattributes
HTMLdocuments
boilerplates
colorsin
columns
contentvs.appearance
content,typesof
convertingtoXHMTL
designingforyouraudience
documentautomation
document-levelstyles
document-relatedevents
dynamic
editorialmarkuptags
executablecontent
forms
frames
headingsin
homepages2nd3rd
imagesin
linkingto
marginsforbodycontent
myfirst.html(example)
pathnames
refreshingautomatically
relationshipsbetween
searchable2nd
sectioning2nd
structureof2nd3rd
stylesheets
styles
tables
tablesofcontents
titlesof2nd3rd
whitespacein
HTMLtags2nd3rd4th
attributesfor2nd
content-basedstyle2nd3rd4th
deprecated
empty,inXHTMLformat
fonthandling
foreditorialmarkup
grammarfor
nesting
obsolete
omitting
physicalstyle
quickreference
startingandendingtags2nd
taglessstyles(<span>)
HTTP(HypertextTransferProtocol)
Redirectheader
Refreshheader
httpservers
httpURLs
http-equivattribute(<meta>)2nd
hyperlinks2nd3rd4th
colorsfor
effectiveuseof
imagemaps,clickable2nd3rd4th5th6th7th
imagesand
linkingwithindocuments
navigatingwithTabandhotkeys
relationshipsbetween
statesof
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
idattribute2nd
<a>
<address>
<basefont>
<blockquote>
<center>
<div>2nd
<dl>,<dt>,and<dd>
<form>
<frameset>
<isindex>
<label>
<map>
<object>
<p>2nd
<q>
<ul>,<ol>,and<li>
forhyperlinktargets
forstyleclasses
formcontrols
tabletags
XHTMLdocuments
identifiers(IDs)
articlesinnewsgroups
messagesonnewsservers
IE
IETF(InternetEngineeringTaskForce)
ignoredHTMLtags
imagemaps
areas2nd
clickable2nd3rd4th5th6th
client-side2nd3rd4th
coordinates
HTMLdocumentsand
performance
server-side2nd
images2nd3rd
alignment2nd
aslistitemsignifiers
background2nd3rd4th5th6th7th8th9th10th
borders2nd
clickable
combiningattributesfor
customimagebuttons(forms)
downloadperformance
flowingtextaround
graphicsformats2nd
hyperlinksand
inheadings
marginsaround
preventingfromscrolling2nd
resizing
reusing
rules
size
textflowaround
textinplaceof
whentouse
wrappingtextaround
implicitlabelassociations(forms)
importedexternalstylesheets2nd
linkedvs.
inclusions
indentation
abusing<dt>for
blockquotes
nestedunorderedlists,usingfor
paragraphs,with<spacer>
text-indentpropertyfor
infinitevalue(marqueelooping)
inheritvalue(layervisibility)
inheritance,stylesand2nd
inline
frames
images
items
layers
references
styles2nd3rd
inputconstraints,mobiledevices
insetborders
interactionpseudoclasses
interlacing
internationalization
dirandlangattributes
dirattribute,overridingwith<bdo>
Internet
InternetEngineeringTaskForce(IETF)
InternetExplorer
<basefont>tags,and
<bgsound>tags
<comment>tag
<q>tagsand
actionattribute
Activetechnologyand
animatedtextsupport
audiofeatures
colorattribute
ExtendedFontModeltags,and
inlineaudio,and
leftmarginattribute
multimediasupport
notabattribute
nowrapattribute
obtaining
paletteattribute
tagsandline-breaking
text,directionandjustification
topmarginattribute
videoextensions
intranets
IP(Internetprotocol)
addresses
ismapattribute(<img>)2nd3rd
italic2nd
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
JavaScriptlanguage2nd
<img>attributes
<noscript>tags
<script>tags
eventhandlers2nd
framesand
JavaScriptpseudo-protocol
JavaScriptpseudo-URLs
overridinghyperlinktargets
stylesheetproperties
stylesheets(JSS)2nd
JPEGformat2nd
JSS(JavaScriptStyleSheets)2nd3rd
encodingof
stylesheetproperties
justification
justifyvalue(alignattribute)
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
labelattribute
<optgroup>
<option>
labelingformelements
langattribute2nd3rd
<a>
<address>
<area>
<blockquote>
<center>
<div>
<dl>,<dt>,and<dd>
<font>
<form>
<head>
<html>
<isindex>
<object>
<p>2nd
<pre>
<q>
<title>
<ul>,<ol>,and<li>
formcontrols
tabletags
XHTMLVersion1.1,absencefrom
languageattribute(<script>)
languages
computer,definingwithmetalanguages
pseudoclassesfor
layers
<ilayer>tags
<layer>tags
alignment2nd
visibilityof
leftattribute
<ilayer>
<layer>
leftmarginattribute(<body>)
length
lengthpropertyvalues
less-thansign(<)
letter-spacingproperty
linebreaks2nd3rd4th
allowingwith<wbr>
nowrapattributeand
suppressingwith<nobr>
vertical<spacer>
line-heightproperty
line-throughtextstyle
linkattribute(<body>)
linkedexternalstylesheets2nd
importedvs.
links
list-styleproperty2nd
list-style-imageproperty
list-style-positionproperty
list-style-typeproperty
lists2nd
definitionlists
directorylists
itemsof2nd
menulists
nesting2nd
ofhyperlinks
ordered(numbered)
selectionlists(forms)
stylepropertiesfor2nd
unordered(bulleted)
usingappropriately
loadingdelay
longdescattribute
<frame>
<img>
loopattribute
<img>
<marquee>
looping
marqueetext
video
lowsrcattribute(<img>)
Lynx
content-basedtags,and
images,substitutingtextfor
textdisplaylimitations
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
mailtoURLs2nd
definingmailheaderfields
formdatavia
maps
standardcolor
margincollapsing
marginheightattribute(<frame>)
margins
aroundCSSboxes
aroundtablecells
bodycontent
frames
images
marqueeareas
stylepropertiesfor
marginwidthattribute(<frame>)
markers
markupmetalanguage,XMLas
maskedtext-entryfields
mathlinedescriptor
maxlengthattribute
<inputtype=file>
<inputtype=text>
mayscriptattribute(<applet>)
mediaattribute(<style>)
menulists
messageIDs,newsservers
metalanguages,definingcomputerlanguageswith
methodattribute(<form>)
MicrosoftInternetExplorer
MicrosoftWord2000,creatingHTMLdocumentswith
middlevalue
MIMEtypes2nd
application/x-www-form-urlencoded
file-selectioncontrolsand
multipart/form-data
multipart/mixed
multipart/x-mixed-replace
text/css
text/plain
missingHTMLtags
mixkeyword
mobiledevices
browsers,constraints
convergencedevices
displayconstraints
inputconstraints
mobilewebdesign
networkconstraints
PDAs
phones
mobilephones
mobilewebdesign
forms
images
layout
links
navigating
presentation
monitor,formcontentsand
monospacedtext
<code>tags
<kbd>tags
<plaintext>tags
<tt>tags
<var>tags
Mosaicbrowser
mouse-relatedevents
pseudoclassesfor
mouse-sensitiveimages
movies
MSIE
multicolumnlayout
multilinetext-entryareas
multimedia2nd
audio
browserhandlingof
client-pullfeaturefor
commonfileformats
GIFanimation
images
textanimation
video,<img>extensionsfor
multipart/form-dataencoding
multipart/mixedencoding
multipart/x-mixed-replaceencoding
multipleattribute(<select>)
multiple-choiceelements(forms)
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
nattribute(<nextid>)
nameattribute
<a>
<applet>
<basefont>
<div>
<embed>
<form>
<frame>2nd
<img>
<label>
<layer>
<map>
<meta>
<object>
<param>
forminputelements
XHTMLdocuments
XHTMLVersion1.1,restrictionsin
nameservers
namedformparameters2nd
namedframes
namespaces,XHTMLDTDs
namingconventionsforHTML
navigatingwithhyperlinks
Navigator
NCSA(NationalCenterforSupercomputingApplications)
nesting
<frameset>tags
<multicol>tags
content-basedstyletags
contextualstylerules
HTMLtags
languagepseudoclassesand
layers
lists
physicalstyletags
tables
XHTMLdocuments,elementsin
Netscape2nd
plug-ins2nd
tagsandline-breaking
text,directionandjustification
networkconstraints,mobiledevices
newsURLs
newsgroups
nntpURLs
nohrefattribute(<area>)
nonterminals
noresizeattribute(<frame>)
noshadeattribute(<hr>)
notabattribute
<map>
<object>
formcontrols
nowrapattribute
<div>
<table>
<th>and<td>
<tr>
numbered(ordered)lists2nd
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
objectattribute(<applet>)
objectmodel(HTMLv4.0)
obsoletetags
offset
omittingHTMLtags
onAbortattribute2nd
onBlurattribute
onChangeattribute2nd
onClickattribute2nd
onDblClickattribute2nd
onErrorattribute
onFocusattribute
onKeyDownattribute2nd
onKeyPressattribute2nd
onKeyReleaseattribute
onKeyUpattribute
onLoadattribute2nd3rd
onMouseDownattribute2nd
onMouseMoveattribute2nd
onMouseOutattribute2nd3rd
onMouseOverattribute2nd3rd4th5th
onMouseUpattribute2nd
onResetattribute2nd3rd
onSelectattribute2nd
onSubmitattribute2nd3rd
onUnloadattribute2nd
ordered(numbered)lists2nd
listmarkerstyleproperties
nesting
numberingstyle
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
padding
paddingproperties
pageboxes
sizeproperty
pagelayout2nd
alignment
columns
designingforyouraudience
forms2nd
frames
HTMLtagsfor
layers
multiplecolumns
stylesheets
tables
wrappingtext
page-breakproperties
paletteattribute(<embed>)
panose-1descriptor
paragraphs2nd
indentingwith<spacer>
parameterentities,XML
parameters,form2nd
parsedandunparsedentities,XML
passwordinputfields
pathnames2nd
pauseproperties
PCDATA,XMLtags2nd
PDAs
percentsign(%)
forcharacterencoding
inURLencoding
percentagepropertyvalues
performance
applets
backgroundimages
client-pulldocuments
colors
flood-filling
imagemaps
imagesand
lowsrcattribute(<img>)for
marqueemovement
server-pushdocuments
text
physicalstyletags2nd
summaryof
tableof
physicaltextwrapping
play-duringproperty
plug-inaccessories2nd3rd4th
pluginspageattribute(<embed>)
plussign(+)inURLencoding
+(plussign)inURLencoding
polygonalimagemaparea
ports
ftpservers
gopherservers
nntp
telnet
webservers
positionproperties
positioninglistitemmarkers
POSTmethod2nd
poundsign(#)
forentities
fornameanchors
inURLs
precedenceofstyles
preformattedtext
<listing>tags
<pre>tags
<xmp>tags
printformattingforHTML/XHTMLdocuments
namedpages,using
paginationcontrolling2nd
tables
usingmultipleformats
printvalue(stylemedia)
privatewebs
profileattribute(<head>)
programmingforms
parametersinURLs
projectionvalue(stylemedia)
promptattribute(<isindex>)
properties,style
CascadingStyleSheets2nd3rd
JavaScriptStyleSheets
property:valuepairs,styles
protocols
pseudoclasses,style
:active
:first-child
:focus
:hover
:lang
:link
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
radiobuttons
randomURLgenerator
readability,whitespaceand
readonlyattribute(formcontrols)
rectangularimagemaparea
Redirectheader
redundantHTMLtags
references
inline
toexternalcontent
tomultimediaelements
Refreshheader
relattribute
<a>
<link>
relationships
betweenHTMLdocuments
betweenhyperlinks
relativefontsize
relativeframesizes
relativeURLs2nd
<base>tags
advantagesofusing
repeatkeyword
repetitiongrammarrules,elements
RequestsforComments(RFCs)
reservedcharacters
resetbuttons
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
schemeattribute(<meta>)
schemes,URL2nd
scopeattribute(<th>and<td>)
screenvalue(stylemedia)
scrollvalue(marqueebehavior)
scrollamountattribute(<marquee>)
scrolldelayattribute(<marquee>)
scrolling
<marquee>tagsand
fixingimagesagainst2nd
frames
scrollingattribute(<frame>)
searchparameterofURLs
searchabledocuments2nd
sections
document2nd
performanceand
table
security
ActiveXand
mailtoforms,problemswith
selectedattribute(<option>)
selectionlists
selectors
gopherURLs
stylerules2nd3rd4th
semicolon(;)incharacterentities
sequencegrammarrules,elements
server-pushdocuments2nd
server-sideapplications
server-sideimagemaps2nd
servers
<isindex>tagsand
datato/from
fileservers
formprogramming
ftpservers
gopherservers
httpservers
nntpservers
telnetservers
SGML(StandardGeneralizedMarkupLanguage)
<!DOCTYPE>commandinHTMLdocuments
limitationsof
SGMLDTD
shadowingtext
shapeattribute
<a>
<area>2nd
shapesattribute(<object>)
sharpsign
showvalue(layervisibility)
sideheads(tables)
size
applets
borders
columnwidth
CSSboxes2nd3rd
embeddedobjects2nd
fontsize
formentrycontrols
frames2nd3rd
horizontalrule
imagemapareas2nd
images
layers
lineheight
marqueearea
selectionlists
tablecells
tables
text2nd3rd4th5th
text-entryfields
whitespaceblocks
sizeattribute
<basefont>
<font>
<hr>
<inputtype=file>
<inputtype=text>
<multiple>
<spacer>
slash(/)
inendingtags
inURLs2nd
slidevalue(marqueebehavior)
slopedescriptor
software
fordesigners
forwritingHTMLdocuments
formattingcode
solidborders
sound
space
spanattribute
<col>
<colgroup>
speakproperty
speak-headerproperty
specialcharacters2nd3rd4th5th6th
inURLs
JavaScriptentities
XHTML,handlingin
specialprocessingdirectives,XML
speech-rateproperty
squarebrackets([])
squarebullets
srcattribute
<bgsound>
<embed>
<frame>
<img>2nd
<inputtype=image>
<layer>
<script>
srcdescriptor
stackinglayers
StandardGeneralizedMarkupLanguage
standardizingHTML2nd3rd4th5th
XHTMLstandard
standbyattribute(<object>)
startattribute
<img>
<ol>
startingtags2nd
state,hyperlink
stemvandstemhdescriptors
straddleheads(tables)
StrictDTD2nd
strike-throughtextstyle
structuraltags
styleattribute2nd3rd
<a>
<address>
<area>
<blockquote>
<body>
<caption>
<center>
<div>
<dl>,<dt>,and<dd>
<font>
<form>2nd
<frameset>
<isindex>
<layer>
<li>
<map>
<multicol>
<object>
<p>2nd
<pre>
<q>
<ul>,<ol>,and<li>
content-basedstyletags
formcontrols
physicalstyletags
tableattributes
style,text
styles
boxproperties
classesfor2nd
classificationproperties
colorandbackgroundproperties
contextualselectors2nd
CSSpropertiesfor
document-level2nd3rd
externalstylesheets2nd
fontstyleproperties
howtouse
inline2nd
JavaScriptStylesheets(JSS)2nd
listproperties
media-specific
precedence
property:valuepairs
pseudoclassesfor
pseudoelementsfor
stylesheets2nd3rd4th
taglessstyles(<span>)
textstyleproperties
webbrowserlimitations
subdomains2nd
submitbuttons
subscriptsandsuperscripts
summaryattribute(<table>)
systems,exchangingdatawithXML
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
Tabkey
navigatingformcontrols
navigatinghyperlinks
navigatingobjects
tabindexattribute
<a>
<map>
<object>
formcontrols
table-layoutproperty
tables2nd3rd4th
alignment2nd3rd
borders2nd3rd
captions
cells2nd3rd
colorsin2nd3rd4th
columns2nd3rd
controllingpagelayoutwith
exampleofbasicstructure
headersandfooters
HTMLv4.0tagsfor
nesting
rows2nd3rd
sectioning
sideheads
size
straddleheads
wrappingtextincells2nd3rd
tablesofcontents
taborderattribute
<map>
formcontrols
tabs
taglessstyles(<span>)
tags
tagsproperty(JavaScript)
targetattribute
<a>2nd3rd
<area>
<base>2nd
<form>
specialvaluesfor
telnetURLs
userandpassword
templatesforHTMLdocuments
terminals
terms,definitionlists
text
addresses
alignment2nd
animating
appearancetagsfor2nd
blockquotes
breakinglines
colorof2nd
flowingaroundimages
formfieldsfor
headings
inlinereferencesin
insteadofimages2nd
marginsforbodycontent
monospaced
multicolumnlayout2nd
multilinetext-entryareas(forms)
paragraphs
preformatted
sizeof
specialcharacters2nd3rd4th5th6th
structuraltags
stylepropertiesfor
text-onlybrowsers2nd
text/cssencoding
text/plainencoding
three-dimensionalappearance
whitespace
wrapping2nd
textattribute(<body>)
texteditors2nd
textsize
<basefont>tags
<big>tags
<font>tags
<small>tags
ExtendedFontModel
headingtagsfor
text-alignproperty
text-decorationproperty
text-entryfields(forms)
text-shadowproperty
text-transformproperty
text/cssencoding
text/plainencoding
texttopvalue
three-dimensionalappearance,text
TidyutilityforHTML-to-XHTMLconversions
tilde(~)inURLs
~(tilde)inURLs
tilingwithimages
titleattribute
<a>
<applet>
<area>
<div>
<dl>,<dt>,and<dd>
<form>
<frame>
<frameset>
<img>
<isindex>
<link>
<map>
<object>
<p>2nd
<ul>,<ol>,and<li>
formcontrols
tabletags
titles
bibliographic
choosing
document2nd3rd
forms
frames
hyperlinkeddocuments2nd
imagemaparea
sections
tablecaptions
topattribute
<ilayer>
<layer>
topvalue
toplinedescriptor
topmarginattribute(<body>)
TransitionalDTD2nd
transparentGIFs
troubleshootingbackgroundimages/colors
ttyvalue(stylemedia)
tvvalue(stylemedia)
typeattribute
<a>
<button>
<embed>
<input>
<li>2nd
<link>
<object>
<ol>
<param>
<script>
<spacer>2nd3rd
<style>
<ul>
typeingopherURLs
typecodesinftpURLs
typographicconventionsforHTML
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
underscoring2nd
unicode-rangedescriptor
uniformresourcelocators
uniqueidentifiers(IDs)
articlesinnewsgroups
messagesonnewsservers
unitsattribute(<embed>)
units-per-emdescriptor
universalchildselectors
unnamedformparameters
unorderedlists
bulleted2nd3rd4th5th
directorylists
unsafecharactersinURLs
URLs(uniformresourcelocators)2nd
absolutevs.relative2nd
asstylepropertyvalues
characterencodingsin
fileURLs
formparametersin2nd
ftpURLs
generatingrandomly
gopherURLs
httpURLs
JavaScriptpseudoprotocol
javascriptURLs
mailtoURLs2nd3rd
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
validXMLdocuments
valignattribute
<caption>
<table>
<th>and<td>
valueattribute
<li>
<option>
<param>
valuetypeattribute(<param>)
versionattribute(<html>)
vertical
margins
whitespace
vertical-alignproperty
video2nd
<img>extensions
client-pullfeaturefor
inline
virtualtextwrapping
visibilityattribute(<layer>)
visibilityproperty
vlinkattribute(<body>)
volumeproperty
vspaceattribute
<embed>
<img>
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
W3C(WorldWideWebConsortium)
Web
informationon
navigatingwithhyperlinks
webbrowsers
<link>tagsand
appletrendering
characterentities,rendering
client-pulldocuments
client-sideimagemapsand
executablecontent
formlimitations
HTMLdocuments,useinediting
HTMLtags2nd
imageborders
imagepresentation
images,rendering
incompatiblewithembeddedobjects
incompatiblewithexecutablecontent
incompatiblewithframes
JavaScript
leniencyindataacceptance
Mosaicbrowser
NetscapeNavigator
obtaining
styles
text-only2nd
webservers
<server>tags
server-pushdocuments
webs,private
weight,font
well-formeddocuments
XHTMLand
XML2nd
white-spaceproperty
whitespace
<img>tagsfor
<nobr>tags
<spacer>tags
aroundhorizontalrules
aroundtablecells
betweencolumns(gutters)
blocksof
framesand
handlinginblocktags
hangingindents
HTMLtagsfor
indentation
letterspacing
linebreaks
lineheight
margins2nd3rd
paragraphs
readabilityand
tabsinpreformattedtext
wordspacing
widows
widthattribute
<applet>
<embed>
<hr>
<iframe>
<img>
<layer>
<marquee>
<multicol>
<pre>
<spacer>
<table>
<th>and<td>
widthproperty
widthsdescriptor
WiFi
windows2nd
ashyperlinktargets2nd3rd4th5th6th
tipsandtricks
wordprocessors
wordwrap
word-spacingproperty
WorldWideWeb
WorldWideWebConsortium(W3C)
wrapattribute(<textarea>)
wrappingtext
<multicol>and
aroundimages2nd
in<textarea>entryareas
nowrapattribute(<div>)
tablecellcontents2nd3rd
writingHTMLdocuments
applets
dynamicdocuments
editorialmarkup
forms,howtouse2nd3rd4th
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R]
[S][T][U][V][W][X][Z]
x-heightdescriptor
XFrames
documents
URLs
XHTML2nd
authoringtools
case-sensitivityinstyleruleelements
decidingtouse
documentsin
DTDs2nd
HTMLconversionsoftware
HTMLvs.
machine-generatedcontentand
tags,quickreference
Version1.0andHTML4.01
Version1.12nd3rd
well-formeddocumentsand
XML,usingtodefine
XHTMLBasic
content-basedtags
coretags
design
documentheader
forms
images
lists
objects
scripting
stylesheets
tables
textstructuraltags
XHTMLdocuments
content2nd
creating2nd3rd
endingtagsin
nestingelementsin
XML(ExtensibleMarkupLanguage)2nd
asmarkupmetalanguage
DTDs
specialprocessingdirectives
usesfor2nd3rd
xmlnsattribute,definingnamespaceswith