HTML a Beginner's Tutorial by Chris Coremans
description
Transcript of HTML a Beginner's Tutorial by Chris Coremans
-
HTML
ABeginnersTutorial
ChrisCoremans
-
HTML:ABeginnersTutorial
FirstEdition:April2015
Allrightsreserved.Nopartofthisbookmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageandretrievalsystem,withoutwrittenpermissionfromthepublisher,exceptfortheinclusionofbriefquotationsinareview.
ISBN:9781771970181
Indexer:ChrisMayle
Trademarks
OracleandJavaareregisteredtrademarksofOracleand/oritsaffiliatesUNIXisaregisteredtrademarkoftheOpenGroupApacheisatrademarkofTheApacheSoftwareFoundation.FirefoxisaregisteredtrademarkoftheMozillaFoundation.GoogleisatrademarkofGoogle,Inc.
Throughoutthisbooktheprintingoftrademarkednameswithoutthetrademarksymbolisforeditorialpurposeonly.Wehavenointentionofinfringementofthetrademark.
WarningandDisclaimerEveryefforthasbeenmadetomakethisbookasaccurateaspossible.Theauthorandthepublishershallhaveneitherliabilitynorresponsibilitytoanypersonorentitywithrespecttoanylossordamagesarisingfromtheinformationinthisbook.
-
AbouttheAuthorChrisCoremansisasoftwareengineerspecializinginfront-enddevelopment.AnexpertinHTML5,JavaScript,JQueryandFlashdevelopmentwithActionScript,hehasmorethantenyearscommercialexperienceworkingforvariousorganizations.HeistheauthorofAJAXandFlashDevelopmentwithOpenLaszlo:ATutorial.
-
TableofContentsIntroduction
WhatisHTML?
WhoThisBookIsFor
AboutThisBook
DownloadingtheSampleApplications
Chapter1:GettingStarted
PreparingYourTools
YourFirstHTMLDocument
CreatingandOpeningAnHTMLDocument
Attributes
VoidElements
Comments
ViewingtheHTMLSourceCodeinABrowser
Chapter2:WorkingwithText
Paragraphs
Headings
WhiteSpaces
bandiElements
emandstrongElements
ThespanElement
codeandpreElements
EscapingHTMLCharacters
NamedCharacterReferences
SectioningElements
Chapter3:Links
WhatisaURL?
AbsoluteandRelativeURLs
CreatingALink
OpeningAWebPageinANewTab/Window
ThedownloadAttribute
-
Chapter4:Images
WheretoGetImagesforYourWebSite?
ImageEditingTools
TheimgElement
figureandfigcaptionElements
ChangingtheFavicon
Chapter5:Lists
Overview
UnorderedLists
OrderedLists
DefinitionLists
NestedLists
Chapter6:Tables
Overview
TableswithTwoHeadings
ThecolspanAttribute
TherowspanAttribute
Chapter7:Forms
Overview
TextInputFields
RadioButtons
Checkboxes
TheselectElement
SubmitandResetButtons
NumberandRange
Date-TimeFields
EmailandUrl
TheColorPicker
fieldsetandlegend
AutoFocus
InputValidation
Chapter8:Multimedia
-
Overview
VideoContainerFormats
UsingthevideoElement
TheaudioElement
EmbeddingYouTubeVideos
Chapter9:StylingwithCSS
Overview
ApplyingStyles
WebColors
Selectors
StylingText
StylingBoxes
StylingLinks
StylingLists
StylingTables
StylingForms
-
IntroductionHTMListhelanguageforcreatingwebpages.Today,HTMLisntjustforprofessionalwebdesignersanymore.AnyonewhoneedstopresentorpublishsomethingontheInternetneedstomasterHTML.TeacherswhoneedtoputassignmentsonlineneedHTML.Managerswhowanttofindnewemployeesadvertiseontheircorporatewebsites.TheytooneedHTML.JobseekerswishingtogetanedgebypublishingtheirprofilesontheWebdefinitelyneedtomasterHTML.AlmosteveryoneneedsHTMLskillsnowadays.
Fortunately,HTMLiseasy.Youdontneeda1000pagebooktolearnHTML.Youcandoitquicklywiththisbook.ItexplainshowtocreateHTMLdocuments,providespracticalexamplesandteachesbasictechniquestostyleplaindocumentsandturnthemtogoodlookingwebpages.
-
WhatisHTML?HTMLorHypertextMarkupLanguageisthestandardlanguageforbuildingwebpages.Hypertextistextdisplayedonacomputerdeviceandcontainslinkstonavigatetootherhypertextdocuments.Ahypertextdocumentmaydescribeobjectssuchaslists,tables,imagesandforms.
Asthenameimplies,HTMLisamarkuplanguage.Amarkuplanguageisalanguageforannotatingdocuments.Thetermmarkuporiginatesfromthepublishingindustrywhereitiscommonforeditorstomarkup(correctorproofread)manuscriptsbyaddingannotationsorcorrectionsfortheauthors.
ThemostcurrentversionisHTML5.Notethatitiswrittenasasingleword(HTML5)andnotHTML5.TableI.1summarizesthereleasedatesofallHTMLversions.
Year Version
1989 TimBerners-LeeproposedanInternet-basedhypertextsystem.TheWebwasborn.
1991 TimBerners-LeeinventedHTML.ThisearlyversioncanbeconsideredHTMLversion1andconsistsofonly18elements.
1993 DaveRaggett,acomputerscientist,proposedHTML+.
1995 TimBerners-LeepublishedHTML2.0asastandard.
January1997 ThepublicationofHTML3.2asaW3Crecommendation.
December1997 ThepublicationofHTML4.0asaW3Crecommendation.
1999 ThepublicationofHTML4.01asaW3Crecommendation.
2000 ThepublicationofXHTML1.0asaW3Crecommendation.
2001 ThepublicationofXHTML1.1asaW3Crecommendation.
2014 HTML5becameaW3Cstandard.
TableI.1:ThehistoryofHTML
HTML5onlybecameaW3CstandardonOctober28,2014.TheW3C,shortforWorldWideWebConsortium,isthemaininternationalstandardsorganizationfortheWorldWideWeb.ItiscurrentlyheadedbyTimBerners-Lee,thefatheroftheWebhimself.TheW3Cspecificationcanbeviewedhere:
-
http://www.w3.org/TR/html5/
Thespecificationisareferenceandisnotmeanttobealearningtool.Atthetimeofwriting,HTML5.1isbeingdraftedbythesamestandardsbody.ItisplannedtobethesuccessorofHTML5.
Longbeforeitbecameastandard,HTML5hadbeenapopularchoiceandsupportedbyallmajorbrowsers.Bymajorbrowsers,Imeanthesefivebrowsers:
ChromeInternetExplorerFirefoxSafariOpera
ItissafetouseHTML5inyourwebpagesasHTML5iswellunderstoodbyvirtuallyallbrowsersinusetoday.
-
WhoThisBookIsForThisbookisforanyonewishingtolearnHTML,eithertobecomeaprofessionalwebdesignerorforworkpurposeorahobby.Anyonewhohasaccesstoacomputershouldbeabletofollowthelessonsinthisbook.
-
AboutThisBookHereisthecontentofthisbook.
Chapter1,GettingStartedgetsyoustartedwithHTML.ItalsoexplainswhatanHTMLdocumentisandhowtocreateone.
Chapter2,WorkingwithTextteachesyouhowtouseHTMLelementstowriteandgrouptext.Italsodiscussesmanythingsrelatedtotext,suchaswhitespaces,specialcharactersequencesandthenewsectioningelementsinHTML5.
Chapter3,LinkscovershyperlinksandexplainswhataURLis.
Chapter4,Imagestalksabouthowtogetimagesforyourwebsiteandembedtheminwebpages.
Chapter5,Listsexplainshowtogroupsimilaritemswithalist.
Chapter6,TablesdiscussestheuseofHTMLtablestopresentdata.
Chapter7,FormsprovidesadiscussionofHTMLforms,ameansofcollectinguserinformation.
Chapter8,Multimediateachesyoutoplayaudioandvideoonawebpage.
Chapter9,StylingwithCSSintroducesCSSasthelanguageforarrangingandstylingHTMLelementsinawebpage.
-
DownloadingtheSampleApplicationsThesampleapplicationsforthisbookcanbedownloadedfromthepublisherswebsiteat
http://books.brainysoftware.com
-
Chapter1
GettingStartedThischaptergetsyoustarted.ItexplainshowyoucancreateHTMLdocumentsandopentheminawebbrowser.ItalsointroducesyoutothestructureofatypicalHTMLdocument.Tofollowthelessonsinthischapterandotherchapters,allyouneedisacomputerwiththeWindows,MacOSXorLinuxoperatingsystem.YoudontevenneedaccesstotheInternetorafastcomputer.Ifyouknowhowtoopenacomputerprogram,youcanfollowtheexamplesinthisbookeasily.
-
PreparingYourToolsTocreateHTMLdocumentsyouneedisatexteditorandtotestthemyouneedawebbrowser.AllWindowsorMaccomputerscomewithatexteditorandabrowser,sothereisnoneedforyoutopurchaseaspecialtoolordownloadaprogram.IfyouhappentobeusingaLinuxcomputerandithasagraphicaluserinterface,youshouldbefinetoo.Intheory,youcouldevenuseatabletorasmartphonetowriteHTMLdocuments,butIwouldnotrecommenditasitishardertotypeonthosesmalldevices.Adesktopcomputerisperfectforthistask.
Ofcourse,therearebettertoolsouttherethanwhatshippedwithyourcomputer.Atthisstage,however,theyarenotnecessary.
OnWindows,youcanuseNotepadorWordPadthatcomewithWindows.ForHTMLbeginners,IrecommendNotePadasitiseasiertosavedocumentsasHTMLfilesthanWordPad.
OnMacOSX,youcanuseTextEdit.SimplyopentheprogramfromtheApplicationsfolderorwithLaunchpad(OSXLionandMountainLion).
OnUbuntuLinux,youcanusegeditorvitoworkwithHTMLdocuments.ThesetwocomewithmostLinuxsystems.
OpenyourtexteditornowandyouarereadytocreateyourfirstHTMLdocument.
-
YourFirstHTMLDocumentAnHTMLdocumentorawebpageismadeupofHTMLelements.AnHTMLelementinturniscomposedofapairofHTMLtagsplussomecontent,eventhoughtherearealsoHTMLelementsthatconsistofasingleHTMLtagwithoutcontent.Listing1.1containsasimpleHTMLdocument.ItalsoshowsthestructureofanHTMLdocument.
Listing1.1:ThestructureofanHTMLdocument
ThetitleofthisdocumentAverysimpleHTMLdocument
ThedocumentinListing1.1iscomposedofanhtmlelement,aheadelement,atitleelementandabodyelement.Anhtmlelementstartswiththestarttagandisterminatedwiththeendtag.Betweenthestarttagandtheendtagisthecontentofthehtmlelement.Anelementmaycontainotherelements.Forexample,thehtmlelementinListing1.1containstwootherelements,aheadelementandabodyelement.Theheadelementitselfcontainsatitleelement.AnHTMLdocumentshouldcontainexactlyonehtmlelement,oneheadelementandonebodyelement.Theheadelementusuallycontainsonetitleelementandafewotherelements.Thebodyelementmaycontainanynumberofotherelements.
HereisthetitleelementintheHTMLdocumentinListing1.1.
Thetitleofthisdocument
Thetitleelementconsistsofthestarttag,somecontentthatsaysThetitleofthisdocumentandtheendtag.
Hereistheheadelement:
Thetitleofthisdocument
Andhereisthebodyelement.
AverysimpleHTMLdocument
AnHTMLstarttagiscomposedofthenameoftheelementenclosedwithinanglebrackets.Hereisthestarttagofthebodyelement.
-
Theendtaghasanextraforwardslashrightbeforethename:
TheelementnameinanHTMLtagisalwaysinlowercase,eventhoughyoucanalsousecapitalsormixedcases.Forexample,thisisvalidbutconsideredbad:
Thisisvalidbutnotrecommended.
YouwilllearnalotofHTMLelementsinthisbook.However,IneedtomentionsomethingimportantbeforeIstartexplainingtheseelements.AgoodHTMLdocumentbeginswithadocumenttypedeclarationorDOCTYPE.HereishowitlookslikeinanHTMLdocument:
TheDOCTYPEisarequiredpreamble.BrowsestendtobelenientinenforcingHTMLrulesandwillstillrenderapagewithoutaDOCTYPEdeclaration.However,itisnotguaranteedthepagewillberenderedcorrectly,whichexplainswhytheDOCTYPEisrequired.AlsonotethattheDOCTYPEiscase-insensitive.Forexample,itcanbewrittenwithalluppercase().However,theconventionistowritetheDOCTYPEpartinuppercaseandthehtmlpartinlowercase.
Listing1.2showsanHTMLdocumentwithaDOCTYPE.RememberitisgoodpracticetohaveaDOCTYPEineveryHTMLdocument.
Listing1.2:AnHTMLdocumentwithaDOCTYPE
ThetitleofthisdocumentAverysimpleHTMLdocument
Figure1.1showstherenderedpageofthecodeinListing1.2.
-
Figure1.1:TheheadandbodyofanHTMLpage
Thecontentofthetitleelementisshownasthetitleofthebrowsertaborwindow.Thebodyelementbecomesthedocumentbody.TheaddressbarcontainsthepathtotheHTMLdocument.Inthiscase,thefilenameisfirst.html.Mostofthetime,thewebaddresswillstartwithhttp://,buthereitstartswithfile:///becausethebrowserisshowingalocalfileandnotawebpagecomingfromtheInternet.
Tosavespace,otherscreenshotsinthisbookwillonlyshowthedocumentbody.
TheindentationandlinechangesinanHTMLpageareoptional.Forinstance,youcanre-writethedocumentinListing1.2likeso:
Thetitleofthisdocument
Thecontentgoeshere
However,properindentationmakestheHTMLdocumentmorereadable.Alwaysendeavortomakeyourpageseasytoread.Readablepagesareeasiertomaintainandyoucanfinderrorsmoreeasilyinawellformattedpagethaninamessypage,especiallyifyourpagesevergetmorecomplex.
-
CreatingandOpeningAnHTMLDocumentTocreateanHTMLdocument,typethecontentofListing1.2inyourtexteditorandsaveitasfirst.htmlinadirectory.Makedoublysurethefileextensionis.html.Thedirectoryyouchoosetosaveyourfileiscalledyourworkdirectory.
Afteryousavethedocument,double-clickonthedocumenticoninWindowsExplorer(onaWindowscomputer)orinFinder(onaMaccomputer).Itshouldopenawebbrowsershowingthedocument.Ifitdoesnotopen,openawebbrowseryourselfandopenthedocumentinthebrowser.
-
AttributesAnHTMLelementmayhaveattributesthatdescribeit.Forinstance,thefollowingbodytagusesthestyleattributetosetthetextcolorwithintheHTMLbodyareatored.
Thefollowingpelementusestheidattributeasauniqueidentifierwithinthecontainingdocument:
...
Thevalueofanattributecanbeanystring,includingtheemptystring.Thevaluecanbeenclosedwithdoublequotesorsinglequotes.Youcanalsoskipthequotesifthevalueconsistsofonlyoneword,howeveritisadvisabletousesinglequotesordoublequotes.
AnHTMLelementhasasetofattributesthatarevalidforthatelement.Someoftheseattributesareglobalattributesthatcanbeappliedtoanyelement.Otherattributesareonlyvalidwhenusedwithcertainelements.Forexample,thefollowingaresomeglobalattributes:
idstyleclasslang
Ontheotherhand,thehrefattribute,forexample,canonlybeusedwithanaelement.Itdoesnotmakesensetousehrefinabodyorpelement.
Youwilllearnmoreaboutattributesintheupcomingchapters.
-
VoidElementsNotallHTMLelementscanhavecontent.Voidelementscannothavecontent,eventhoughtheycanhaveattributes.Herearevoidelements:area,base,br,col,command,embed,hr,img,input,keygen,link,meta,param,source,trackandwbr.
Eachoftheseelementswillbediscussedinupcomingchapters.Fornow,justknowthatavoidelementcanbewrittenwithoutanendtag,suchas
or
-
CommentsIncomplexpages,itisagoodideatoaddcomments.Acommentstartswith.HTMLcommentsarenotrendered.Forexample,theHTMLdocumentinListing1.3hascomments:
Listing1.3:AnHTMLdocumentwithcomments
Welcome
-
ViewingtheHTMLSourceCodeinABrowserMostbrowsersallowyoutoviewthesourcecodeforawebpage.Therearetworeasonswhyyouwouldwanttodothat.
1.Tolearnfromothershowtheybuilttheirwebpages.
2.ToverifyHTMLtagsarebeinggeneratedcorrectlywhenusingaprogramminglanguagetodynamicallybuildwebpages.
InChromeandFirefox,youcanpresstheCTRL+UtoviewanHTMLsource.InInternetExplorer,right-clickonthepageandselectViewSource.
-
Chapter2
WorkingwithTextAlmostallHTMLdocumentscontaintext.PiecesoftextarenormallygroupedinparagraphsinthebodyelementofanHTMLdocument.ThetitleofasectionorsubsectioninanHTMLdocumentcanbewrittenasaheading.Usingparagraphsandheadingsmakesyourdocumentmorereadable.Inaddition,doingsoenableseachpieceoftexttobestyleddifferently.Forexample,youcanusedifferentfontsanddifferentcolorsindifferentparagraphsandprintheadingsindifferentfontsizes.
ThischapterexplainstheHTMLelementsforworkingwithtext.
-
ParagraphsYoucanaddtextdirectlyinthebodyelement,howeveryoushouldorganizeyourtextinparagraphstomakeitmorereadable.Aparagraphisrepresentedbythepelement.Herearetwoparagraphs:
Dolphinsaremammals,notfish.Theyliveinwaterbutbreathethroughablowhole.
Therenderingofparagraphsvariesfromonebrowsertotheother.However,generally,eachparagraphwillbeseparatedbyamargin,asshowninFigure2.1.YoucancontrolthelookandfeelofaparagraphusingCSS,asexplainedinChapter9,StylingwithCSS.
Figure2.1:Paragraphrendering
Listing2.1showsanHTMLdocumentwithtwopelements.pelementsmustalwaysbenestedwithinthebodyelement,eitherdirectlyunderitorindirectly.Listing2.1canbefoundintheparagraph-1.htmlfileunderthechapter-02directoryinthezipfilethataccompaniesthisbook.
Listing2.1:Usingpelements(chapter-02/paragraph-1.html)
Thedolphin
Dolphinsaremammals,notfish.Theyliveinwaterbutbreathethroughablowhole.
-
HeadingsAheadingisusedforatitleofasectionorsubsection.Therearesixlevelsofheadings:h1,h2,h3,h4,h5andh6.Listing2.2showsanHTMLdocumentwithheadings.Figure2.2showshowthedocumentisrendered.
Listing2.2:Usingheadings(chapter-02/heading-1.html)
Headings
Headinglevel1Headinglevel2Headinglevel3Headinglevel4Headinglevel5Headinglevel6
Figure2.2:HTMLheadings
-
WhiteSpacesWhitespacesorwhitespacecharactersrepresenthorizontalandverticalspaceintypography.Theseincludethespacecharacter,thetabcharacterandthelinebreak.
InmostHTMLelements,successivemultiplespacesareregardedasasinglespace.Successivetabcharactersandlinebreaksarerenderedasiftherewereasinglespace.Ifyouneedmorespacethanwhatasinglespacecharacterwouldrender,use.Also,ifyouwanteachspacecharacterinasequenceberenderedindividually,enclosethecharactersinapreelement.
ConsiderthecodeinListing2.3.
Listing2.3:Whitespaces(chapter-02/whitespace-1.html)
Whitespaces
WhitespacesPlaintextAnysuccessivewhitespacecharactersinthisparagrapharerenderedasasinglespacecharacter.
UsingspecialcharactersequencesYoucanusespecialcharactersequencesifyouneedmorespace
UsingthepreelementThisparagraphisrenderedwithmultiplespacesandlinebreaks.
Figure2.3showsthedocument.
-
Figure2.3:WhitespacesinHTML
First,takealookattherenderingofthefirstparagraphinFigure2.3.Multiplewhitespacesandlinebreaksinthefirstparagrapharenothonored.
Ontheotherhand,therenderingofthesecondparagraphshowsthatyoucanbuymorespaceusing,whichisaspecialcharactersequenceinHTML.Lookatthespacebetweenthewordmoreandspace.
Thethirdparagraphiswrittenwithapreelementandhasthemostdramaticeffect.Allwhitespacesandlinebreaksaretranslatedasis.Inaddition,thetextisprintedwithamonospacedfont.
-
bandiElementsPeoplehavealwaysbeenusingbandielementstopresenttextinboldanditalicizedformats,respectively.Afterall,bstandsforboldandiforitalic.HTML5redefinesbothelementstohavesomesemanticfunction,ratherthanapresentationalone.Thismeans,textenclosedwiththebelementwillnotalwaysbeprintedinboldandthereisnoguaranteetextenclosedwiththeielementwillbeitalicized,eventhough,atleastfornow,browserscontinuetosupportthepresentationalquickfix.
Forexample,considerthepelementintheHTMLdocumentinListing2.4.
Listing2.4:Usingbandi(chapter-02/bolditalic-1.html)
Dolphins
Whalesarenotfish.
Figure2.4showstherenderingofthebandielementsinListing2.4.
Figure2.4:Usingbandielements
Eventhoughitstillworks,youshouldusethespanelementandCSStomaketextboldandoritalic.Thespanelementisexplainedlaterinthischapter.
-
emandstrongElementsPriortoHTML5,theuseofemandstrongelementshasalwaysbeenpresentational.emwasusedtogiveemphasisandstrongtogivestrongemphasis.EventhoughemandstrongstillworkinmodernbrowsersthatsupportHTML5,HTML5redefinesemandstrongtohaveasemanticfunction.Assuch,youshouldavoidusingemandstrongasapresentationalfixandresorttospaninstead.Thespanelementisexplainedlaterinthischapter.
Asanexample,though,considertheHTMLdocumentinListing2.5,whichusesemandstrong.
Listing2.5:Usingemandstrong(chapter-02/emstrong-1.html)
Electriccars
Thesalesofelectriccarshavebeenontherise.Theywillbreaktherecordthisyear.
Figure2.5showshowtheemandstrongelementsarerendered.
Figure2.5:Usingemandstrongelements
-
ThespanElementYouusethespanelementtowrapapieceoftextsothatyoucanstylethetext.Forexample,thecodeinListing2.6showshowtousespan.Notonlycanyoumaketextboldanditalicized,youcangiveitadifferentcolorthantherestoftheparagraph,asshowninFigure2.6.
Listing2.6:Usingspan(chapter-02/span-1.html)
CharlesDarwin
ThemockingbirdsMimusthencacaughttheattentionofnaturalistCharlesDarwin.
Figure2.6:Usingspanisthebestwaytostyletext
ThespanelementsinListing2.6employthestyleattributetostylethecontent.YouwilllearnmoreaboutstylesinChapter9,StylingwithCSS.
-
codeandpreElementsManypeoplethinkcodeandprecanbeusedinterchangeably,buttheW3Cspecificationisveryclearonthis:theyaredifferent.Thecodeelementrepresentsafragmentofcomputercodewhereasthepreelementtellsthebrowserthattheenclosedcontentistoberenderedwithamonospacedfontandwhitespacesandlinebreaksareimportant.SeetheexampleinListing2.7.
Listing2.7:Usingcodeandpre(chapter-02/codepre-1.html)
Pre&Code
UsingpreandcodePayattentiontothefollowingtextThisisinsideapreThisismultilinecomputercode
Figure2.7showstherenderingoftheHTMLdocumentinListing2.7.
Figure2.7:Usingpreandcode
Thepreelementinterpretseverylinebreakandwhitespaceasis.Ontheotherhand,thecodeelementdoesnotcareaboutlinebreaksandwhitespaceseventhoughittooisprintedwithamonospacedfont.
-
EscapingHTMLCharactersThecharactersplayaspecialroleinHTML.WhatifyouwanttowritethosecharactersinHTML?Theansweris:Escapeorreplace.
Forinstance,considerthecodeinListing2.8.
Listing2.8:Usingescapecharacters(chapter-02/escape-1.html)
Escapecharacters
,&and"arespecialcharacters.
Thespecialcharactersequences,&and"arerenderedas,&and,respectively,asshowninFigure2.8.
Figure2.8:Escapecharacters
-
NamedCharacterReferencesSomecharactersareveryhardtoinputascomputerkeyboardshavealimitednumberofkeys.HowdoyouenterthecopyrightsymbolortheJapanesecurrencysymbolwithyourkeyboard?Fortunately,therearenamedcharacterreferencesthatmakeiteasytousespecialcharactersinHTMLdocuments.
Thecompletelistofnamedcharacterreferencescanbefoundhere:
http://www.w3.org/TR/html5/syntax.html#named-character-references
Figure2.9showssomeofthem.
Figure2.9:Namedcharacterreferences
Basically,touseanamedcharacterreference,youprefixitwith&andsuffixitwiththesemicolon(;).Forexample,thefollowingcharactersequencewillberenderedasthecopyrightsymbol.
supandsubElementssupandsubelementsdefinesuperscriptandsubscripttext,respectively.Listing2.10showsanHTMLdocumentthatusessupandsubelements.
Listing2.10:Usingsupandsub
Math
23+24=24y=x1+x2
Figure2.10showshowtheseelementsarerendered.
-
Figure2.10:Usingsupandsub
-
SectioningElementsAtthebeginningofthischapter,Imentionedthatyoucanorganizetextintoparagraphsusingthepelement.Inamorestructureddocument,however,paragraphscanbegroupedintosections.Forexample,awebpagemayhaveaheader,acontentandafootersections.Thecontentsectionmightbedividedfurtherintotwocolumns,theleftcolumnandtherightcolumn.
Traditionally,peopleusedthedivelementtocreateasection.Listing2.11showshowitmightlooklike.
Listing2.11:Usingdiv(chapter-02/div-1.html)
Usingdiv
HeaderThisisthemainsectionofthispageItconsistsoftwoparagraphswrappedinadivelement
2015mycompany
Figure2.11showshowthedifferentsectionsarerendered.
Figure2.11:Usingdiv
Youcanalsousedivtocreatemulti-columns,asillustratedinListing2.12.
Listing2.12:Multi-columnpage(chapter-02/div-2.html)
Multi-columns
div{margin:5px;float:left;background:lightgreen;
-
}
ThisistheleftcolumnofthispageThisistherightcolumnofthispage
Figure2.12showsthetwo-columnpage.NotethatIhaveusedCSSinastyleelementtoplacetheseconddivtotherightofthefirstdiv.CSSisexplainedinChapter9,StylingwithCSS.
Figure2.12:Multi-columnpagewithdiv
HTML5addsnewelementsforsectioningawebpage.Youcanstillusediv,butthereareothersectioningelementsthatincludeheader,footer,nav,main,article,asideandhgroupelements.
Listing2.13showsanexampleofapagethatusesheader,footer,main,articleandasideelements.
Listing2.13:UsingHTML5sectioningelements
Usingsectioningelements
Thisisaheader
-
FirstarticleSecondarticleSidenote2015mycompany
Figure2.13showsthepage.
Figure2.13:HTML5sectioningelements
ThereisnothingexceptionalinFigure2.13becausethenewsectioningelementsaresemanticelements,notpresentationalelements.YoustillneedCSStoarrangethemandmakethemlookgood.
-
Chapter3
LinksYouusehyperlinks,orsimplylinks,tonavigatetootherpagesinawebsite.Awebpageisaresource,andeachwebpagehasauniqueidentifierforpeopletolocatethepage.ThisuniqueidentifieristheURL,shortforUniformResourceLocator.
ThischapterexplainswhataURLisandhowtouselinksinyourwebpages.
-
WhatisaURL?AURLisawebaddress.Tolocateawebpage,whichisaresourceontheInternet,youwouldclickonalinkthatcontainsaUniformResourceLocator(URL)orenteroneintheAddressorLocationboxofyourbrowser.HerearetwoexamplesofURLs:
http://google.com/index.htmlhttp://facebook.com/index.html
ThefirstpartoftheURLsishttp,whichidentifiestheHTTPprotocol.HTTPstandsforHyperTextTransferProtocol.Asyoumayhaveguessed,itisaprotocolfortransferringwebpages.NotallURLsuseHTTP.Forinstance,thesetwoURLsarenotHTTP-basedURLs:
mailto:[email protected]://[email protected]
IngeneralaURLhasthisformat:
protocol://[host.]domain[:port][/context][/resource][?querystring]
or
protocol://IPaddress[:port][/context][/resource][?querystring]
Thepartsinsquarebracketsareoptional,thereforeaURLcanbeassimpleashttp://yahoo.comorhttp://192.168.1.9.AnInternetProtocol(IP)address,bytheway,isanumericallabelassignedtoacomputeroranotherdevice.Acomputermayhostmorethanonedomain,somultipledomainsmaysharethesameIPaddress.
Generally,whenyouwanttovisitawebsite,youenteritsdomainname,e.g.google.com.However,youcanalsousetheIPaddressofthecomputerthathoststhedomain.Inotherwords,insteadoftypinghttp://google.com,youcanuseitsIPaddress:http://74.125.226.98.TofindouttheIPaddressofadomain,usethepingprogramonyourcomputerconsole:
pinggoogle.com
IPaddressesarehardtoremember,sopeoplepreferdomainnames.And,didyouknowthatyoucantbuyexample.comandexample.orgbecausetheyarereservedfordocumentationpurpose?
ThehostpartmaybepresentandidentifyatotallydifferentlocationontheInternetoranintranet.Forinstance,http://yahoo.com(nohost)bringsyoutoadifferentlocationthanhttp://mail.yahoo.com(withahost).Overtheyearswwwhasbeenthemostpopularhostnameandbecomethedefault.Normally,http://www.domainNameismappedtohttp://domainName.
80isthedefaultportofHTTP.Therefore,ifawebserverisrunningonport80,you
-
dontneedtheportnumbertoreachtheserver.Ifnot,youneedtotypetheportnumber,likeso:
http://example.com:8080
ThecontextpartinaURLreferstotheapplicationname,butthisisalsooptional.Awebservercanrunmultiplecontexts(applications)andoneofthemcanbeconfiguredtobethedefaultcontext.Torequestaresourceinthedefaultcontext,youskipthecontextpartinaURL.
Finally,acontextcanhaveoneormoredefaultresources(ordinarilyindex.htmlorindex.htmordefault.htm).AURLwithoutaresourcenameisconsideredtoidentifyadefaultresource.Ofcourse,ifmorethanonedefaultresourceexistsinacontext,theonewiththehighestprioritywillalwaysbereturnedwhenaclientdoesnotspecifyaresourcename.
Afteraresourcenamecomeszeroormorequerystring.Aquerystringisakey/valuepairthatcanbepassedtotheservertobeprocessed.
-
AbsoluteandRelativeURLsAURLthatstartswithaprotocolandcontainsadomain,suchashttp://twitter.com,isanabsoluteURL.However,aURLcanalsobewrittenwithoutaprotocolandadomain.SuchaURLiscalledarelativeURL.
Relativetowhat?Youmayask.
RelativeURLscanbefoundinawebpage.InthiscasetheURLsarerelativetotheURLofthecurrentpage.Forexample,iftheURLofawebpageishttp://example.com/start.htmlandthepagecontainsarelativeURLnamednext.html,thentheabsoluteaddressofnext.htmlcanbefoundbyremovingthestringafterthelastforwardslash(/)andappendtherelativeURL.Inthiscase,theabsoluteURLofnext.htmlwouldbehttp://example.com/next.html.
TherearegoodreasonsforusingrelativeURLs.First,relativeURLsareshorter.Insteadofhttp://example.com/next.html,youcanjustwritenext.html.Moreimportantly,however,whenyouarecreatingawebpage,youmaynotknowexactlythenameofthedomainthatwillbeusedtohostthewebsite.YoucannotwriteanabsoluteURLwithoutadomainname.
-
CreatingALinkYoucreateahyperlinkusingtheaelement.Here,astandsforanchor.
Ahyperlinkcontainsareferencetoanotherresourceandtexttobedisplayed.Thereferencecanrefertoaresourceexternaltothecurrentwebsiteoraresourceinthesamewebsite.Itcanevenrefertoadifferentlocationonthesamepage.
HereisanexampleofahyperlinkthattakestheusertoGooglewhenclicked.Youusethehrefattributetospecifyatarget.Inthiscase,itishttp://google.com,theGooglewebsite.
SearchEngine
Figure3.1showsthehyperlinkinawebbrowser.
Figure3.1:Ahyperlinkthatreferencesanexternalresource
Thetextinahyperlinkcanbeanythingbutitshouldclearlydescribethetargetresource.ItshouldnotbejustClickHereorsomeothernon-descriptivetext.
Theresourcethatahyperlinkreferencescanbeanotherwebpageoranyotherresourcetypeavailableonthetargetwebsite.Theseincludeanimage,aPDFfile,avideoandsoon.
-
OpeningAWebPageinANewTab/WindowBydefault,whenahyperlinkisclicked,thebrowseropensthetargetresourceinthesamewindowasthecurrentpage.Modernbrowsersallowtheusertoopenaresourceinanewtaboranewwindow,normallybyright-clickingthelink.Forexample,Figure3.2showsapopupmenuwhenyouright-clickalinkinChrome.
Figure3.2:Openingaresourceinanewtaborwindowmanually
Ifyouwantalinktoopeninanewtaborwindowautomatically,withouttheuserhavingtochoosetodoit,youcanusethetargetattributeoftheaelement.Hereisanexample:
SearchEngine
Thevalueoftargetis_blank.Whetheritwillopeninanewtaboranewwindowisuptothebrowser.Theusercanconfigurethis,howeveryou,thepageauthor,cannotenforceit.
-
ThedownloadAttributeInveryrareoccasions,youmaywantthebrowsertodownloadaresourceinsteadoftryingtoopenit.Inthiscase,thedownloadattributeiswhatyouneed.Forexample,whentheuserclicksonthislink,thebrowserwilldownloadtheresourceinsteadofopeningit.
SearchEngine
-
Chapter4
ImagesWebpagesoftencontainphotosandotherimages.YoucanembedanimageinanHTMLdocumentbycreatingalinktotheimagefileusingtheimgelement.
Thischapterexplainshowtoworkwithimages.
-
WheretoGetImagesforYourWebSite?Todayitiseasytogetimagesforyourwebsite.Evenaninexpensivedigitalcameracanproducebrilliantandartisticallypalatablepictures.Ifyoudecidetotakeyourownpictures,youwillbethankfultoknowthatmostdigitalcamerascansaveimagesasjpgfiles,oneoftheimageformatsthatcanbedisplayedinabrowser.
AnothersourceofgreatpicturesistheInternet.Therearemanywebsitesthatprovideexcellentphotosandotherimages,bothfreeandforafee.
Forfreeimages,checkthefollowingwebsites.
Wikimediaathttp://commons.wikimedia.org.Therearealotofgemstobefound,eventhoughadmittedlytherearemanythatwillstrikeyouasnon-professional.Beforeyoudownloadanimage,makesureyouunderstanditstermsofuse.Someallowyoutouseanimageforbothcommercialandnon-commercialpurposessomeonlyallownon-commercialuse.Inmostcases,youmustattributetheimagesinthemannerspecifiedbythephotographers.Flickr.Aleadingphoto-sharingsite.YouwillbeparticularlyinterestedinthesectioncalledTheCommons(https://www.flickr.com/commons).TheCommonsisalibraryofpublicly-heldphotographycollectionsfromdozensofmuseumsaroundtheworld.Thesephotographsarefreeeitherbecausethecopyrightshaveexpiredorthemuseumsownthem.Again,makesureyouunderstandthetermsofuseofanimageyouareplanningtouse.UnrestrictedStock(http://unrestrictedstock.com).Providesacollectionofphotosandvectorimages.Allfreetouseonwebsitesbutyoucannotresellthem.freedigitalphotos.net.Thesmallversionoftheirimagesarefree,withattributionrequired.Thehigherresolutionphotosarenotfree.
Ifyouneedmoreprofessionaltouches,thenyoucanpurchaseimagesfromonlinewebsites,including:
www.dollarphotoclub.comwww.istockphoto.comwww.gettyimages.comwww.fotolia.com
DollarPhotoClubisparticularlyinterestingthankstotheirlowprices.
-
ImageEditingToolsImagesyoutookusingyourowndigitalcameraorboughtfromanonlinegallerymaynotbeinstantlyreadyforuse.Oftentimes,youneedtoedittheimagesbeforeinsertingtheminawebpage.
Herearetoolsyoucanusetoeditimages.
MicrosoftPaint.AprogramthatcomeswithWindows.Arudimentaryimageeditingtoolthatallowsyoutoresizeanimage,addtextandshapes(circle,rectangle,etc)toanimageaswellasmanipulateeachindividualpixelofanimage.Picasa(http://picasa.google.com).AfreeonlinephotoeditingtoolfromGoogle.GIMP(http://gimp.org).Afreeimagemanipulationprogram.Admittedly,noteasytouse.AdobePhotoshop.Consideredthebest,butcomeswithaprice.
-
TheimgElementTheimgelementrepresentsanimage.Webbrowserscandisplayimagesinthefollowingformats:
gifjpgorjpegpng
Somebrowsersareabletorenderimagesinbmp,butthereisnoguaranteeallbrowserscan.
Table4.1showsthemoreimportantattributesofimg.
Attribute Description
src TheURLoftheimagefile.
width Theimagewidthinpixels.
height Theimageheightinpixels.
alt Thealternatetextthatwillbedisplayediftheimagecannotbedisplayed.
title Thelabelthatwillbedisplayedasatooltipwhentheuserhoversovertheimage.
Table4.1:Themoreimportantattributesofimg
Table4.1doesnotincludeattributesthatarenolongersupported,suchasalignandborder.
Thewidthandheightattributescanstillbeused,howeveritisbettertouseCSS.SeeChapter9,StylingwithCSS.
Asanexample,theHTMLdocumentinListing4.1usesanimage.
Listing4.1:Usinganimage(chapter-04/image-1.html)
Image
Thisisanimage.
Youcandownloadanduseit.
-
Figure4.1showsthedocumentwiththeimage.
Figure4.1:AnimageinanHTMLdocument
-
figureandfigcaptionElementsBothfigureandfigcaptionelementsarenewadditionsinHTML5.Thefigureelementisusedtomarkupanimageandusedchieflytonestafigcaptionelement.Thelatterisusedtogiveanimageacaption.
Listing4.2showsanHTMLdocumentthatusesfigureandfigcaptionelements.
Listing4.2:Usingfigureandfigcaption(chapter-04/image-figure1.html)
figureandfigcaption
Figure1:Amazingscenery
Figure4.2showshowthefigureandfigcaptionelementsarerendered.
Figure4.2:Usingfigureandfigcaption
-
ChangingtheFaviconAfavicon(shortforfavoriteicon)isaniconassociatedwithawebsiteorawebpage.Itisusedbymanywebdesignerstogivetheirsitesdistinguishinglooks.Afaviconcanbedisplayedintheaddressbarofthebrowserornexttothetitleofthebrowsertab.
Inthepasttheonlywaytodisplayafaviconisbyusinganicoimageandalinkelementtoreferencetheimage:
Thiswasimpracticalandnotalwayseasytodo,sinceyouhadtofindaconvertertoconvertyourimage,whichnormallycomesinjpgorbitmap,toico.
Fortunately,nowyoucanuseanyoftheseformats:jpg,png,gif.Youstillneedalinkelementwithtwoattributes,relandhref.TherelattributemusthavethevalueiconandthehrefattributebeassignedtheimageURL.
Listing4.3showsanexample.
Listing4.3:Specifyingafavicon(chapter-04/icon-1.html)
Favicon
Figure4.3showsthefaviconinChrome.
Figure4.3:AfavoriteiconinChrome
-
Chapter5
ListsInHTMLdocuments,similaritemsarebestputinalist.Listoffavoritecars.Listofmostlivablecities.Shoppinglists.TheHTMLspecificationallowsthreetypesoflistsandeachtypecanbecustomizedandstyledusingCSS.Inaddition,listscanalsobenested.
Thischapterexplainshowtoworkwithlists.
-
OverviewTherearethreetypesoflistsintheHTMLspecification:
Unorderedlists.Inanunorderedlist,eachitemisnotnumberedandismarkedwithabulletpoint.Orderedlists.Inanorderedlist,eachitemisnumbered.Definitionlists.Adefinitionlistdisplayspairsoftermsanddescriptionsorotherkey/valuepairs.
Thetypesareexplainedinthefollowingsections.
-
UnorderedListsYouusetheulelementtocreateanunorderedlistandthelielementforeachlistitem.Listing5.1showsanHTMLdocumentthatcontainsanunorderedlistofsomeEuropeancountries.
Listing5.1:Anunorderedlist(chapter-05/unordered-list-1.html)
UnorderedList
EuropeancountriesGermanyUnitedKingdomFranceGreece
Figure5.1showsthelist.
Figure5.1:Anunorderedlist
Bydefault,acircleisusedasthemarkerforeachlistitem.ThiscanbechangedusingCSSandyouwilllearnhowtodothisinChapter9,StylingwithCSS.
-
OrderedListsYouusetheolelementtocreateanorderedlistandthelielementforeachlistitem.Listing5.1showsanHTMLdocumentthatcontainsanorderedlistofthemostpopulartouristdestinationsintheUSA.
Listing5.2:Anorderedlist(chapter-05/ordered-list-1.html)
OrderedList
10MostPopularTouristDestinationsintheUSANewYorkCityLosAngelesChicagoWashington,DCLasVegasSanFranciscoHawaiiGrandCanyonFloridaNewOrleans
Figure5.2showstheorderedlist.
Figure5.2:Anorderedlist
ThenumberingcanbecustomizedusingCSS.SeeChapter9,StylingwithCSS.
Inaddition,youcanusethereversedattributetoreversethelist.Listing5.3showsareversedorderedlist.
Listing5.3:Areversedorderedlist(chapter-05/ordered-list-2.html)
-
ReversedOrderedList
Top10TouristDestinationsinReverseOrderNewOrleansFloridaGrandCanyonHawaiiSanFranciscoLasVegasWashington,DCChicagoLosAngelesNewYorkCity
Notethat,asyoucanseeinFigure5.3,theitemsarenotreversed,theyarestilldisplayedintheordertheyappearinthelist.Onlythenumbersarereversed.
Figure5.3:Areversedorderedlist
-
DefinitionListsAdefinitionlistisalistoftermswithadescriptionforeachterm.Youusethedlelementtocreateadefinitionlist.Adlelementcontainsdtandddelementpairs.Thedtelementisusedtocreateatermandtheddelementtocreateadescription.
Asanexample,considerthedefinitionlistinListing5.4.Itcontainstermsanddescriptionsrelatedtowebdesign.
Listing5.4:Adefinitionlistofwebdesignskills(chapter-05/definition-list-1.html)
DefinitionList
RequiredwebdesignskillsHTMLHyperTextMarkupLanguage,theuniversallanguageoftheWeb.CSSCascadeStyleSheets.StyleHTMLcontentJavaScriptApopularscriptinglanguageforaddingdynamicitytowebpages.
ThedefinitionlistispresentedinFigure5.4.
Figure5.4:Adefinitionlist
-
NestedListsAlistcanbenestedwithinanotherlist.Forexample,theHTMLdocumentinListing5.5containsalistofcountries.Eachcountryinturnhasalistofmajorcities.
Listing5.5:Nestedlists(chapter-05/nested-list-1.html)
NestedList
CountriesandTheirMajorCitiesAustraliaSydneyMelbourneCanadaTorontoVancouverMontrealUnitedKingdomLondonBirmingham
ThenestedlistsinListing5.5isshowninFigure5.5.
-
Figure5.5:Nestedlists
-
Chapter6
TablesAlotofinformationcanbepresentedinatable.Datasuchassportresults,traintimetables,stockpricesaregoodcandidatesforatable.ThischapterexplainshowtoworkwithHTMLtables.
-
OverviewAnHTMLtableisagridofcolumnsandrowsandcanhaveahorizontalheadingandaverticalone.Atablecanalsohaveanynumberofrowsandeachblockinthetableisreferredtoasatablecell.Atablecellcanspanmultiplecolumnsandrows.Headingsinatableareoptional.
Youusethetableelementtocreateatable.Atableelementmaycontainanynumberofrows,eachcreatedusingthetrelement.Atrelementthatcontainsaheadingmaycontainanynumberofthelements.Atrelementthatcontainsnormalrowsmaycontainanynumberoftdelements.
Hereisasimpletablethatdisplaysacoupleoftechstockprices.
Listing6.1:Asimpletable(chapter-06/table-1.html)
TechStocks
FavoriteTechStockPricesSymbolCompanyClosingpriceAAPLAppleInc.$109.14GOOGGoogleInc.$518.63NFLXNetflixInc.$454.17TSLATeslaMotorsInc.$205.98
-
Figure6.1showsthetableinListing6.1.
Figure6.1:Asimpletable
-
TableswithTwoHeadingsMosttableshaveoneheading.However,itispossibletocreateatablewithtwoheadings,onehorizontalheadingandoneverticalheading.Insuchatable,thetdelementsofthecolumnthatisaverticalheadingarereplacedbythelements.
Asanexample,thetableinListing6.2hastwoheadings.Thetdelementofitsfirstcolumnarereplacedbythelements.
Listing6.2:Atablewithtwoheadings(chapter-06/table-1.html)
FinancialStatement
FinancialStatementQ1Q2Q3Q4Income100,000110,000130,000110,000Expenses100,000100,000100,00090,000Profit010,00030,00020,000
Figure6.2showsthetableinListing6.2.
-
Figure6.2:Atablewithtwoheadings
-
ThecolspanAttributeAcellthatspansmultiplecolumnsorrowsisalsopossibleinHTML.Tocreateatablecellthatspansmultiplecolumns,usethecolspanattributeinthecellthatshouldspanmultiplecolumns.Thevalueofcolspanisthenumberofcolumnstospan.
Forexample,thetableinListing6.3usesthecolspanattribute.
Listing6.3:Usingcolspan(chapter-06/table-3.html)
PrimetimeWeekendPrograms
td,th{border:2pxsolidteal;padding:8px;text-align:center;}
PrimetimeWeekendPrograms8.00p.m.8.30p.m.9.00p.m.9.30p.m.10.00p.m.10.30p.m.SaturdayE.E.TTonightWeekendComedyCollegeBasketballSundaySundayMovieSurprise!!!Newsrecap
ThetableisshowninFigure6.3.
-
Figure6.3:Usingcolspan
-
TherowspanAttributeYoucanalsocreateacellthatspansmultiplerows.Toachievethis,usetherowspanattributeinthecellthatshouldspanmultiplerows.Theattributeshouldbeassignedthenumberofrowsthecellshouldspan.
Asanexample,thetableinListing6.4showstheuseofrowspan.
Listing6.4:Usingrowspan(chapter-06/table-4.html)
Agenda
td,th{border:1pxsolidblue;padding:8px;}
AgendaDateTimeEventJanuary12,201510:00-11:00Teachkarate11:00-11:30MeetingwithparentsJanuary13,2015alldayNewteachertraining
Figure6.4showsthetable.
-
Figure6.4:Usingrowspan
-
Chapter7
FormsAnHTMLformcanbeusedtocollectinformationfromtheuser.Aformnormallycontainsoneormorefieldsandasubmitbutton.Theroleofthelatterisobvious.Youcannotsubmitaformwithoutasubmitbutton.Aformwouldalsospecifyanaction,whichisnormallyanInternetresource,tohandletheformdata.
Thischapterdiscussesformsandformfields.
-
OverviewPriortoHTML5,thefieldsthatcouldbeusedinaformweresomewhatlimited.Thereweretextfields,radiobuttons,checkboxesanddrop-downlists.ThisdramaticallychangedwhenHTML5wasreleased.Thereisnowmorevariety,fromdate-timefieldstoemailandurlfieldstoacolorpicker.Betterstill,HTML5formsarevalidateduponsubmission,whichmeansthebrowseritselfwouldenforcethetypecorrectnessofeachfield.
Tocreateaform,youusetheformelement.Aformelementmaycontainzeroormoreinputfields.Thestructureofaformelementisasfollows.
...
Eachinputelementrepresentsadataunit.Forexample,ifyouneedtheusersfirstnameandlastname,thenyouwouldhaveaformwithtwoinputfields,oneforthefirstnameandoneforthelastname.
Aformelementmayalsohaveattributes.Table7.1showsthelistofallvalidattributes.Ofthese,themethodandactionattributesarethemostcommon.ThemethodattributespecifiestheHTTPmethodtousewhensubmittingtheform.Chancesareyouwillusethepostmethod,sothevalueofthisattributeshouldbepost.TheactionattributespecifiesaURLtowhichtheformdatawillbesubmitted.Ifyouareawebdesignerworkinginateam,youshouldgettheformactionfromyourteamleadoraprogrammerworkingontheback-endthatwillhandletheformontheserver.
Attribute Description
accept-charset Thecharacterencodingstouseforformsubmission.
action TheURLtosubmitthisformto.
autocompleteIndicateswhetherornotthebrowsershouldattempttofilltheformcontrolswithpreviouslyenteredvalues.Thevalueiseitheronoroff.
enctype Theformdatasetencodingtype.
method TheHTTPmethodtouse.
name Thenameoftheform.
-
novalidate Indicateswhetherornottobypassformcontrolvalidation.
target Specifieswheretodisplaytheresponsereceiveduponformsubmission.
Table7.1:Formattributes
Table7.2showsinputfieldsthatcanbeaddedtoaform.
Forminput Description
Textbox.
Passwordbox
Hiddenfield.
Radiobutton
Checkbox
Buttontoenablefileselection
Buttontosubmittheform.
Buttontoclearallotherfieldsintheform.
Dropdownbox
Multilinetextfield.
Emailbox
URLbox
Numberbox
Arangewithaminimumandamaximum.
Datefield.
Datetimefieldwithtimezone.
Datetimefieldwithnotimezone.
Monthoftheyear.
Weekintheyear.
-
Timefield.
Searchfield.
Colorfield.
Telephonenumber.
Table7.2:Forminputfields
Youdonothavetomemorizealltheattributesandinputtypes.TheywillcomeeasilyasyougetmorefamiliarwithHTML.Justbearinmindthatmostformswillhaveasubmitbutton.Otherwise,theuserwouldnotbeabletosubmittheform.Withoutasubmitbutton,aformcanonlybesubmittedusingJavaScript.However,JavaScriptisbeyondthescopeofthisbook.
CreatinganHTMLformiseasy,youjustneedaformelementandacoupleofinputelements.Makingtheformlookgoodisalwaysthedifficultpart.
Asasidenote,longagopeopleusedtolayoutaformusingatable,likethefollowing.Donotdothis.
Username:Password:
ItsnowatabootouseatabletoarrangeHTMLelementsbecausetablesarefordisplayingdata,notforlayingoutcontrols.Instead,useapelementforarowandalabelelementforaninputlabel.
Thelabelelementrepresentsacaptioninaform.Alabelcanbeassociatedwithaformfield,knownasthelabelelementslabeledcontrol,eitherbyusingtheforattributeorbyputtingtheformcontrolinsidethelabelelementitself.
Hereisanexampleofusingtheforattribute.
Username:
-
Thevalueofformustmatchthevalueoftheidattributeofthelabeledcontrol.
Hereisanexampleofthesameinputfieldenclosedinalabel.Noforattributeisnecessary.
Username:
Foreachrow,youcanuseapelement,likethis:
Username:
Password:
However,ifyoudecidetouseCSStostyleyourform,nopelementisrequired:
Username:Password:
Inthischapter,Iwillusepelementstocreaterows.RefertoChapter9,StylingwithCSSforinformationabouthowtostyleaform.
Notethatsomewebdesignersmayusedivelementsinsteadofp,whichisalsonotwrong.However,inmyopinion,itsbesttouseCSSandomitthepordivelementsaltogether.
Figure7.1showsaformstyledwithCSS.YouwilllearnhowtodothisinChapter9,StylingwithCSS.Justknowthatyoucanmakeformsbeautiful.
Figure7.1:AformstyledwithCSS
-
Youcanviewhowthecodetomakethisformbyopeningthechapter-07/example.htmlfileinthezipfilethataccompaniesthisbook.
-
TextInputFieldsTherearefourinputfieldsforcarryingtextdata:textfield,passwordfield,hiddenfieldandtextarea.Thetextfieldisanordinarytextfield.Apasswordfieldislikeatextfield,butallcharactersenteredaremasked.Itisusedforenteringapasswordsothenosycolleaguesittingnexttoyouwontbeabletoseeyourpasswordeverytimeyoulogintocheckyourpersonalmail.
Thehiddenfieldisalsosimilar,exceptthatitishidden.Normallyyouneedthistopasscertaininformation,suchasacountrycode,totheserver.Itisnotuncommontodynamicallygeneratethevalueofahiddenfield.
Atextareaisuniqueasititamultilineinputfield.Youcandecidehowmanycolumnsorrowsitcantake.
ThecodeinListing7.1showsanHTMLformwiththreefields.
Listing7.1:Usingtextfields(chapter-07/text-fields-1.html)
ContactUs
ContactUsYourName:YourEmail:Message:
-
Figure7.2showstheform.Fornow,dontworrywithitsunattractiveappearance.YoucanmakeitprettyafteryouhavelearnedCSSinChapter9,StylingwithCSS.
Figure7.2:Textfields
-
RadioButtonsRadiobuttonsareusedtoprovidetheuserwithaselectionofchoices.Itisuncommontouseasingleradiobuttoninaformasforthisyoucanuseacheckbox.
Youconstructaradiobuttonbyusingtheinputelement,specifyingradioasitstype.Rememberthatyoualmostalwaysneedmultipleinstances.Hereisanexample:
IndividualBusiness
Inadditiontothetypeattribute,youalsoneedthenameandvalueattributes.Agroupofradiobuttonsthatmakeupaselectionofchoicesmusthavethesamenametotellthebrowserthatonlyoneinthegroupcanbeselected.Thevalueattributespecifiesthevaluethatwillbesubmittediftheradiobuttonisselected.
Asanexample,theHTMLdocumentinListing7.2usestworadiobuttonstospecifytheorganizationtype.
Listing7.2:Usingradiobuttons(chapter-07/radio-1.html)
RadioButtonDemo
RegisterYourEmail:Organizationtype:IndividualBusiness
-
Figure7.3showstheformand,ofcourse,theradiobuttons.
Figure7.3:Usingradiobuttons
-
CheckboxesYouuseacheckboxtoposeayes/noquestion.Ayesisindicatedbythecheckboxbeingcheckedandanootherwise.
Hereishowyoucreateacheckbox.
Bydefault,acheckboxisunchecked.Ifacheckboxmustbeshowncheckedwhentheformisloaded,usethecheckedattributelikethis.
Listing7.3showsaformwithacheckbox.
Listing7.3:Usingacheckbox(chapter-07/checkbox-1.html)
CheckboxDemo
SubscribeYourEmail:Subscribetoournewsletter?
Figure7.4showstheform.
-
Figure7.4:Usingthecheckbox
-
TheselectElementTheselectelementrepresentsadrop-downlist.Functionally,itworksliketheradiobuttoninthesensethatitcanbeusedtoasktheusertochoosefromagroupofchoices.Unliketheradiobutton,however,theselectelementallowsmultipleselections.
Tocreateadrop-downlist,useaselectelementwithoptionelements.Eachoptionelementrepresentsachoice.Hereisthestructureoftheselectelement.
Label1Label2...labeln
Thevalueattributeinanoptionelementisoptional.Ifnovalueattributeispresentintheselectedoption,thelabelforthatoptionwillbesubmitted.
Toallowmultipleoptionstobeselected,usethemultipleattribute.
...
Asanexample,theHTMLdocumentinListing7.4containsaselectelementthatallowstheusertochooseoneoftwovalues.
Listing7.4:Usingtheselectelement(chapter-07/select-1.html)
SelectDemo
RegisterYourEmail:Organizationtype:IndividualBusiness
-
Figure7.5showsthedrop-downlist.
Figure7.5:Aselectelementwithtwooptions
-
SubmitandResetButtonsYouhaveusedthesubmitbuttoninthepreviousexamples.Asyouhavelearned,itisaninputfieldwithtypesubmit.Aresetbuttonlookssimilarwhenrendered.Itisusedtoresetallothercontrolsinthecontainingform.
Theresetbuttonisnotasimportantasthesubmitbutton,butaresetbuttoncanbeuseful.Forexample,itcanbeusedinaformthatcontainsradiobuttonstounselectaselectedradiobutton.Thereisnowaytounselectaradiobuttonwithoutaresetbutton.
Youcreatearesetbuttonbyusingtheinputelement:
Listing7.5showsaformthatcontainsaresetbutton.
Listing7.5:Usingtheradiobutton(chapter-07/reset-1.html)
ResetButtonDemo
RegisterYourEmail:Organizationtype:IndividualBusiness
Figure7.6showstheform.
-
Figure7.6:Usingtheresetbutton
-
NumberandRangeAnumberfieldisatextfieldthatshouldcontaindigitsonly.Implementationsinwebbrowsersdonotrestrictenteringnon-digitsinanumberfield,howeveritsvaluewillbevalidatedwhenthecontainingformissubmitted.
Youcreateanumberfieldusingtheinputelement.
Youcanspecifyaminimumandamaximumvaluesusingtheminandmaxattributes,respectively.
Arangefieldallowstheusertoselectanumberfromarange.Itcanbecreatedusingtheinputelementandtheminandmaxattributesareusedtospecifytheminimumandmaximumvalues,respectively.
Listing7.6showsanHTMLdocumentwithanumberfieldandarangecontrol.
Listing7.6:Usingnumberandrange(chapter-07/number-1.html)
Form
Number:Range:
Figure7.7showstheinputfieldandrangefield.
-
Figure7.7:NumberandRange
-
Date-TimeFieldsHTML5bringswithitanumberofdate-timefields.Asalways,youcreateadate-timefieldusingtheinputelement.Thevalueforthetypeattributescanbeoneofthefollowing:
datedatetimedatetime-localmonthweektime
Date-timefieldsareimplementedtolooklikeatextfield.However,adate-timefieldcanshowacalendarfromwhichtheusercanselectadate.
Thedatefieldcanbeusedtoenteradate.Adatetimefieldandadatetime-localfieldcanbeusedforbothadateandatime.Thedifferencebetweendatetimeanddatetime-localisthatdatetimeincludesthetimezoneanddatetime-localdoesnot.
Themonthfieldletsyouselectamonthfromacalendar.Theweekfieldisforselectingaweek.Thetimefieldallowsyoutoenterorselectatime.
Listing7.7showsanHTMLformformakinganappointment.Theformcontainsadatetime-localfieldfortheusertochoosetheappointmentdate.
Listing7.7:Usingthedate-timefield(chapter-07/datetime-1.html)
Appointmentform
Selectadate/timethatsuitsyouYourName:
Prefereddate/time:
-
Figure7.8showstheformandFigure7.9thedatepickerthatwillappearwhenyouclickonthedatetime-localfield.
Figure7.8:Adatetime-localfield
Figure7.9:Adatepicker
Listing7.8showsanotherexample.ItcontainsanHTMLdocumentwithaformthatletstheuserchooseareportingmonth.Theformhasamonthfieldforchoosingathemonth.
Listing7.8:Usingthedate-timefield(chapter-07/datetime-2.html)
Monthlyreport
SalesreportReporttype:SalesDetailsSalesSummary
-
Reportingmonth:
Figure7.10showstheformandthemonthpicker.
Figure7.10:Themonthfield
-
EmailandUrlTheemailfieldisatextfieldforenteringanemailaddress.AurlfieldisalsoatextfieldsuitableforaURL.
Youcreateanemailfieldandaurlfieldusingtheinputelement.
TheHTMLdocumentinListing7.9containsaformthathasanemailandaurlfields.
Listing7.9:Usingemailandurl(chapter-07/email-url-1.html)
EmailandURL
Pleasetellusaboutyourcompany
Youremail:Yourwebsite:
Figure7.11showstheemailandurlfields.Atafirstglance,theylooklikeanordinarytextfield.However,thebrowserwillmakesuretheycontainthecorrectdatatypewhenyousubmittheform.
Figure7.11:emailandurl
-
TheColorPickerYoucanusethecolorfieldbyspecifying.Acompliantbrowserwillrenderitasacolorfieldthatopensupacolorpickerwhenclicked.
Listing7.10showsaformwithacolorfield.
Listing7.10:Usingthecolorfield(chapter-07/color-1.html)
Color
Color:
Figure7.12showsthecolorfield.
Figure7.12:Acolorfield
Whentheuserclicksthecolorfield,adialogwillopenthatlooksliketheonepresentedinFigure7.13.Theimplementationofthecolordialogisbrowser-specific.Therefore,youmayseeadifferentdialoginyourbrowser.
Figure7.13:ThecolorselectiondialoginChrome
Youcanselectacolorbyclickingonthecolorbox.Thestringvalueoftheselectedcolorwillbeshowninthetextfieldinthelower-leftcorner.InFigure7.13thevalueoftheselectedcoloris#10290c.Acolorvaluemustconsistsofexactlysevencharactersandthe
-
firstcharacteristhenumbersigncharacter(#).Characters2and3representtheredcomponentofthecolor.Characters4and5representthegreencomponentofthecolorinhexadecimalandcharacters6and7thebluecomponent.Eachcolorcomponentisahexadecimalrangingfrom00toff.Fordetails,seethediscussionofwebcolorsinChapter9,StylingwithCSS.
Whenthecontainingformissubmitted,thestringrepresentationofthecolorissenttotheserver.
-
fieldsetandlegendThefieldsetelementgroupscontrolsandlabelsinaform.Thelegendelementisusedtodrawalegendforthegroup.Theirusesarebestdescribedinanexample(SeeListing7.11).
Listing7.11:Usingfieldsetandlegend(chapter-07/fieldset-demo1.html)
Registrationform
RegistrationCredentialsEmail:Password:
OptionalInfoYourName:Phone:
-
Figure7.14showstheformwithfieldsetsandlegends.
Figure7.14:Usingfieldsetandlegend
-
AutoFocusTheautofocusattributeofaninputfieldcanbeusedtofocustheformcontrolwhenthepageisloaded.Theadvantageofusingautofocusissothattheusercanstarttypingwhentheformisready.Heorshedoesnotneedtoclickthefield.Onlyonefieldinaformcanhavetheautofocusattribute.
Asanexample,thedocumentinListing7.12usestheautofocusatributeononeoftheformfields.
Listing7.12:Usingautofocus(chapter-07/autofocus-demo1.html)
Loginform
LoginEmail:Password:
-
InputValidationPriortoHTML5,client-sideinputvalidationhadtobedoneusingJavaScript.Client-sideinputvalidationtakesplaceinthebrowserbeforeaformissubmitted.Theserver,uponreceivingtheform,normallyperformsserver-sideinputvalidation.
UsingJavaScriptforclient-sideinputvalidationisnothard,butitdoesrequireeffort.Thankfully,HTML5letsyouoffloadthatburdentothebrowser.
HTML5inputvalidationcancheckifarequiredfieldhasbeenfilledandifthevalueofaninputfieldisinaccordancewithitsfieldtype.Forexample,thebrowserwillinvalidateanumberfieldcontainingnon-digits.
Tomakeafieldrequired,usetherequiredattribute,likeso:
Otherthanthat,thereisnothingelseyouneedtodotoenjoyHTML5client-sideinputvalidation.
Listing7.13showsaformthatcontainsarequiredfield.
Listing7.13:Formvalidation(chapter-07/validation-1.html)
Appointmentform
Selectadate/timethatsuitsyouYourName:Prefereddate/time:
-
Ifyousubmittheformwithoutenteringavalueintherequiredfield,thebrowserwillstepinandshowyouanerrormessagelikethatinFigure7.15.Theformsubmissionwillbecanceledtoo.
Figure7.15:Inputvalidation
Toturnoffformvalidation,usethenovalidateattributeinaform.
...
-
Chapter8
MultimediaHTML5comeswithastandardforplayingaudioandvideoontheWeb.Thischaptershowsyouhowtoplayaudioandvideoonyourwebsite.Inaddition,thelastsectionofthischapterexplainshowyoucanembedaYouTubevideoinanHTMLdocument.
-
OverviewBeforeHTML5,therewereFlash,QuickTimeandRealPlayerforplayingvideosinthebrowser.Allrequiredsomebrowserplug-inbeinstalledandtherewasnostandard.Ofallthetechnologies,Flashappearedtobethedefactostandardforwebvideoandanimation.Eventoday,therearestilltonsofwebsitesthatuseFlash.Timehaschanged.Flashisnowadyingtechnology.Forexample,inJanuary2015YouTube,thelargestvideosharingsitedumpedFlashinfavorofHTML5asitsdefaultvideoformat.HTML5isthepresentandthe(near)future.
YoushoulduseHTML5foryourmultimedianeedsandtriedtoforgetFlash.
-
VideoContainerFormatsDigitalvideoisstoredinacontainerfilethatactslikeaziportarfile.Avideofilecontainsmultipleresources,includingthevideodata,theaudiocomponents,synchronizationinformation,subtitlesandothermetadata.Inaddition,tosavespace,thevideoandaudiodataisoftencompressed.
Therearemorethantwentyvideofileformats.Youcaneasilytellavideofilebyitsextension.Table8.1showssomevideoformatsthatarepopulartoday.
Format Fileextension(s) Description
WebM .webm FreeformatcreatedespeciallyforHTML5video.
Ogg .ogv Anopenstandard,unencumberedbyanyknownpatents.
Flash .flv Flashmovies.
AVI .avi IntroducedbyMicrosoftin1992asthevideoformatfortheWindowsoperatingsystems.
WindowsMediaVideo .wmv AlsocreatedbyMicrosoft.
QuickTime .mov,.qt DevelopedbyApple.VideotakenwithaniPad/iPhoneisstoredina.movfile.
RealMedia .rm DevelopedbyRealNetworks.
MPEG-4 .mp4,.m4p,.m4vFormatusedbyAndroidphones/tabletsandotherstostorevideo.
Table8.1:Popularvideoformats
Alltheseformatsarenotcompatiblewitheachother.Forexample,aplayerthatcanplayAVIfilesisnotnecessarilyabletoplayWebMorOggfiles.Themainreasonforthisisbecausethevideoandaudiocontentsinafileformatareencodeddifferently.Encoding,orsimplycoding,referstohowrawvideooraudiodataisstored.Asmentionedearlier,videocodingalgorithmsalsocompressesthevideodatatosavespace.Thesameholdstrueforaudiocodingalgorithms.Whenvideodataisstored,itiscoded.Whentheencodedvideodataneedstobeplayed,itfirstneedstobedecoded.Therefore,avideoplayertechnicallyisaprogramthatcandecodevideodata.
Table8.2showstheaudioandvideocodingformats.
-
Format Audiocodingformat(s)
Videocodingformat(s)
WebM Vorbis,Opus VP8,VP9
Ogg Vorbis Theora
Flash MP3,ADPCM,AAC VP6,SorensonSpark,H.264
AVI any any
WindowsMediaVideo
WindowsMediaAudio,SiproACELP.net
WindowsMediaVideo,WindowsMediaVideoScreen,WindowsMediaVideoImage
QuickTime MP3,AAC many
RealMedia RealAudio RealVideo
MPEG-4 MPEG-4Part12 H.264,MPEG-4Part2,MPEG-2,MPEG-1
Table8.2:Videoandaudiocodingformats
-
UsingthevideoElementYouusethevideoelementtoembedavideoinawebpage.Thevideofilemustbeuploadedtothesamewebsiteoravailablefromanotherwebsite.Tousethevideoelement,specifytheURLtothevideosourceinthesrcattribute.
Table8.3presentstheattributesofthevideoelement.
Attribute Description
autoplay Specifiesthatthevideoshouldplayassoonasitloads.Thisattributedoesnotneedavalue.
controls Specifiesthatvideocontrols,suchasplayandpausebuttons,shouldbedisplayed.Thisattributedoesnotneedavalue.
height Theheightofthevideoplayerinpixels.
loop Indicatesthatthevideoshouldplayrepeatedly.Thisattributedoesnotneedavalue.
muted Indicatesthatthevideoshouldbemuted.Thisattributedoesnotneedavalue.
posterSpecifiesaURLtoanimagethatshouldbedisplayedwhilethevideofileisbeingdownloaded.Theimageshouldbedisplayeduntiltheuserclickstheplaybutton.
preload Specifiesthatthevideoshouldbeloadedassoonasthepageloads.Validvaluesareauto,metadataandnone.
src TheURLreferencingthevideosource.
width Thewidthofthevideoplayerinpixels.
Table8.3:Theattributesofthevideoelement
Thewidthandheightattributesspecifythedimensionofthescreeninthewebpage.Theautoplayattribute,ifpresent,tellsthebrowsertostartplayingthevideoassoonastheitfinishedloading.Thecontrolsattributeindicatesthatthebrowsershoulddisplayvideocontrolssuchastheplayandstopbuttons.
Currently,notallvideoformatsaresupportedbythemajorbrowsers.Table8.4showstheformatssupported.Forinstance,allmajorbrowserscanplayMPEG-4.Chrome,FireFoxandOperacanplayWebMandOggvideos.
-
Browser MPEG-4 WebM Ogg
Chrome Yes Yes Yes
FireFox Yes Yes Yes
InternetExplorer Yes No No
Safari Yes No No
Opera Yes Yes Yes
Table8.4:Videoformatssupportedbythemajorbrowsers
Thezipfileaccompanyingthisbookcontainsavideofileinmp4format.Listing8.1showsawebpagethatembedsthisvideo.
Listing8.1:Embeddingavideo(chapter-08/video-1.html)
Video
Acarvideo
Figure8.1showsthevideoinabrowser.
Figure8.1:Embeddingavideo
-
TheaudioElementYouusetheaudioelementtoplayaudio.Table8.5showstheattributesthatcanbeusedinanaudioelement.Theonlyrequiredattributeissrc,whichmustpointtoanaudiosource.
Attribute Description
autoplay Specifiesthattheaudioshouldplayassoonasitloads.Thisattributedoesnotneedavalue.
controls Specifiesthataudiocontrols,suchasplayandpausebuttons,shouldbedisplayed.Thisattributedoesnotneedavalue.
loop Indicatesthattheaudioshouldplayrepeatedly.Thisattributedoesnotneedavalue.
muted Indicatesthattheaudioshouldbemuted.Thisattributedoesnotneedavalue.
preload Specifiesthattheaudioshouldbeloadedassoonasthepageloads.Validvaluesareauto,metadataandnone.
src TheURLreferencingtheaudiosource.
Table8.5:Theattributesoftheaudioelement
Audiofilescomeindifferentformats,whichareshowninTable8.2.Table8.6showstheaudioformatssupportedbythemajorbrowsers.AsyoucanseeinTable8.6allthemajorbrowserscanplayMP3.Inaddition,Chrome,FireFoxandOperacanplayWavandOgg.
Browser MP3 Wav Ogg
Chrome Yes Yes Yes
FireFox Yes Yes Yes
InternetExplorer Yes No No
Safari Yes Yes No
Opera Yes Yes Yes
Table8.6:Audioformatssupportedbythemajorbrowsers
Asanexample,Listing8.2showsanHTMLdocumentthatembedsanaudiofile.Theaudiofilecanbefoundinthezipfileaccompanyingthisbook.
-
Listing8.2:Embeddinganaudiofile(chapter-08/audio-1.html)
Audio
Asoundsample
Figure8.2showstheaudioelementwithcontrols.ClickonthePlaybuttontoplaytheaudio.
Figure8.2:Embeddingaudio
YoucandomuchmorewithaudiosupportinHTML5.However,mostofitrequiresJavaScriptprogramming.Listing8.3showssomeJavaScriptcodethatcanplaytwosongsinsuccession.IwrotesomethinglikethiscodesoIcouldplaysongssavedinasharedlocation(myroutersUSBstorage)fromanydeviceconnectedtomyhomenetwork.AsJavaScriptisbeyondthescopeofthisbook,IwillnotbeexplaininghowthecodeinListing8.3works.
Listing8.3:Playingmultiplesongsinsuccession(chapter-08/audio-2.html)
Video
Playmultiplesongs
vari=1;varaudio=document.getElementsByTagName("audio")[0];audio.addEventListener("ended", function(){ varsource; if(i==1){ source='test2.wav'; i=2; }else{ source='test1.wav'; i=1; } document.getElementsByTagName("audio")[0].src=source; document.getElementsByTagName("audio")[0].play(); },true);
-
EmbeddingYouTubeVideosYouTubeisthelargestvideosharingsiteanditallowsyoutoembeditsvideosinyourownwebsite.Tothisend,youusetheiframeelementinsteadofvideo.Thisishowyoudoit.
Replacethevideo-idpartwiththeactualvideoidentifier.
Youmayask,Howdoyougettheidentifierofthevideoyouwanttoembed?Itseasy.Justgotoyoutube.comandclickonthevideoyouwanttoembed.LookattheURLinthebrowsersAddress/URLbox.Itwillhavethisformat:
https://www.youtube.com/watch?v=[video-id]
Thestringafterwatch?v=isthevideoid.
Listing8.4showsanHTMLdocumentwithanembeddedvideofromYouTube.Youstillhavetoreplacethe[video-id]partofthesrcattributewithyourownvideoid.
Listing8.4:EmbedingaYouTubevideo(chapter-08/youtube-1.html)
Embedyoutubevideo
YoucanfinddetailsonembeddingYouTubevideoshere.
https://developers.google.com/youtube/player_parameters
-
Chapter9
StylingwithCSSCSSisanabbreviationforCascadingStyleSheets.ItisalanguageforformattingdocumentswritteninamarkuplanguagesuchasHTML.CSSallowsfortheseparationofdocumentcontentandpresentationandiscurrentlyatversion3.Unlikepreviousversionswhichareonelargesingledocuments,CSS3consistsofseveralmodules.
ThischapterisabrieftutorialofCSSandexplainshowyoucanuseCSStoformatHTMLdocuments.
-
OverviewThestudyofCSSnormallytouchesontwomajorthings:
1.GettingfamiliarwithCSSproperties,suchascolor,background,border,andsoon.Therearemanyofthemandthischapterexplainsthemorepopularones.
2.HowtouseselectorstoapplyCSSpropertiestoanelementoragroupofelements.
ToapplystylestoanHTMLelement,youspecifyaCSSpropertyfollowedbyacolonandavalue:
property:value
Thespacesbeforeandafterthecolonareoptional.Forexample:
background-color:green
Astylemaybeaffectedbymultipleproperties.Inthiscase,twopropertiesareseparatedbyasemicolonandoralinebreak.Forexample,thisstyleconsistsoftwoproperties.
color:red;padding:10px;
Itcanalsobewrittenlikeso
color:redpadding:10px
or
color:red;/*endswithsemicolon*/padding:10px;
Asyoucansee,youcanaddcommentstoastyledeclaration.Acommentstartswith/*andendswith*/.
-
ApplyingStylesTherearethreewaystoapplyastyletoanHTMLelement.
1.Usethestyleattributeoftheelementtobestyled.
2.Usethestyleelementwithintheheadelementofawebpagetodefinestyles.Astyleinthestyleelementmayapplytoallinstancesofaparticularelementtypeoranelementhavingamatchingidentifier.Youcanalsocreatestylesthatcanbeusedbyreferencingthemintheclassattributeoftheelementtobestyled.
3.Isolatestylesina.cssfileandloadthefilefromtheHTMLdocument.
Thethreeapproachesareexplainedinthesesubsections.
-
UsingthestyleAttributeThesimplestwaytoaddastyleisbydefiningthestyleintheelementitself,usingthestyleattribute.Forexample,thebody,pandspanelementsintheHTMLdocumentin9.1arestyledthisway.
Listing9.1:UsingthestyleAttribute(chapter-09/style-attribute-1.html)
Usingthestyleattribute
Loremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam,quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.Duisauteiruredolorinreprehenderitinvoluptatevelitessecillumdoloreeufugiatnullapariatur.Excepteursintoccaecatcupidatatnonproident,suntinculpaquiofficiadeseruntmollitanimidestlaborum.
Figure9.1showshowitlookslike.
Figure9.1:Usingthestyleattribute
-
UsingthestyleElementListing9.2:UsingthestyleElement(chapter-09/style-element-1.html)
Usingthestyleelement
body{background:#abbaca;}p{font-size:14px;}#intro{color:red;font-style:italic;}.teal-with-border{color:teal;border:1pxsolidgreen;}.bold{font-weight:bold;color:cyan;}
Loremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam,quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.Duisauteiruredolorinreprehenderitinvoluptatevelitessecillumdoloreeufugiatnullapariatur.Excepteursintoccaecatcupidatatnonproident,suntinculpaquiofficiadeseruntmollitanimidestlaborum.Loremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam,quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.Duisauteiruredolorinreprehenderitinvoluptatevelitessecillumdoloreeufugiatnullapariatur.Excepteursintoccaecatcupidatatnonproident,suntinculpaquiofficiadeseruntmollitanimidestlaborum.
-
Figure9.2:Usingthestyleelement
-
UsingaCSSFileWiththisapproach,youisolateallstylesinaseparateCSSfileandlinkthefilefromanyHTMLdocumentthatneedstousethestyles.ACSSfilenormallyhas.cssextension,butitdoesnthaveto.YoucanusethesametexteditoryouusetowriteHTMLdocumentstocreateCSSfiles.
AnexampleisprovidedinListing9.3.
Listing9.3:LinkingaCSSfile(chapter-09/css-demo1.html)
UsingCSSfile
Loremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmod
TheHTMLdocumentinListing9.3referencesaCSSfilecalledstyle.cssusingthelinkelement,specifyingtheURLoftheCSSfilewithitshrefattribute:
Listing9.4showstheCSSfile.NotethatstylesinaCSSfilearenotembeddedinastyleelement.IexplaintheCSSfilelaterinthischapter.
Listing9.4:TheCSSfile(chapter-09/style.css)
body{background:#abbaca;}p{font-size:14px;}#intro{color:red;font-style:italic;}.teal-with-border{color:teal;border:1pxsolidgreen;}.bold{font-weight:bold;color:cyan;}
-
WhichMethodtoUse?Ofthethreemethods,thestyleattributeisthequickestwaytoformatanelement.However,itdoesnotpromoteseparationofcontentfrompresentation.Inaddition,styleswrittenthiswayarenotreusable.Youshouldnotusethismethodexceptforverysimpledocuments.
Bycontrast,stylesinaCSSfilecanbelinkedbymultipledocumentsthatsharethesametheme.ChangingavalueintheCSSfileaffectsallthedocuments.ThisisthebestwayofusingCSSandyoushouldalwayschoosethisapproachwhenpossible.Thearedrawbacksareyouendupwithoneextrafile,theCSSfile,andthereissomeperformancepenaltybecausebrowsershavetodownloadanadditionfile.Thisperformancehitisusuallynegligible.
Usingthestyleelementinadocumentisacompromisebetweenthetwoothermethods.ItdoesnotcreateanuntidyjumbleofHTMLtagsandstylesthusitstillpromotesseparationofcontentandpresentation.However,stylesarecannotbeusedbyotherdocumentsthanthedocumentwheretheyaredeclared.
InthischapterIusethestyleelementsotheCSSandHTMLelementscanbeshowninthesamecodelisting.
-
WebColorsLetsstartthediscussionofCSSwithcolors.Afterall,attractivecolorsprobablyhaveagreaterwowfactorthananyotherCSSproperties.
Inprogramming,acolorisrepresentedbyitsthreecomponents:red,greenandblue.Infact,acoloristheintensityandproportionofeachofthethreecolorcomponents.Thestrength/intensity/valueofacolorcomponentrangesfromzeroto255.Why255?Becausethereare256numbersbetween0to255and256canbeconvenientlyrepresentedbyabyte(8bits).Thevalueofacolorcomponentmustbewrittenintwo-digithexadecimal,hence00toFF.
Acolorcanbeexpressedinthisformat:
#rrggbb
whererr,ggandbbarethevaluesofthered,greenandbluecomponentsinhexadecimal,respectively.Forinstance,thecolor#FF0000ispureredandsois#EE0000albeitwithlessintensity.Ontheotherhand,#00FF00ispuregreenand#0000FFispureblue.#AAAAAAisgrayishasitisamixofallcomponents.
Ifyourenotcomfortableworkingwithhexadecimal,youcanusethefollowingformatandwritethevaluesindecimal:
rgb(r,g,b)
wherer,gandbarered,greenandbluecolorcomponentvalues,respectively.Therangeforr,gandbisbetween0and255.Forexample,thefollowingarevalidcolors:
rgb(200,0,190)rgb(255,255,255)rgb(0,0,0)
Thenumberofcolorsavailableis256x256x256=16,777,216or16,7millioncolors.
Colorcodesinhexadecimalordecimalarehardtomemorize.Fortunately,thereisamucheasierwayofusingcolorsbecauseHTMLdefinesnamesforthemostpopularcolors.Forexample,youcansimplyusegreen,orange,yellow,crimson,tealandsalmonastheyaredefinedcolornames.
Tables9.1to9.11listthecolornamesyoucanuseinHTML.Colornamesarecase-insensitive.YoucanwriteYelloworYELLOWoryellow.
-
Table9.1:Pinkcolors
Table9.2:Redcolors
Table9.3:Orangecolors
Table9.4:Yellowcolors
-
Table9.5:Browncolors
Table9.6:Greencolors
-
Table9.7:Cyancolors
Table9.8:Bluecolors
-
Table9.9:Purplecolors
Table9.10:Whitecolors
-
Table9.11:Graycolors
-
SelectorsSelectorsarekeytoapplyingstylestoHTMLelements.Aselectormeansexactlythat,itselectsanHTMLelementormultipleHTMLelementstoapplystylesto.Therearemanytypesofselectors.
Themoreimportantselectorsareexplainedinthissection.
-
TheUniversalSelectorTheuniversalselector,representedbytheasterisk,selectsalltheelementsinthedocument.Listing9.5showsanexample.
Listing9.5:Usingtheuniversalselector
Universalselector
*{margin:0px;}
Paragraph1Paragraph2
Theselector*inthedocumentinListing9.5appliesthestyletoallelements.Asaresult,allelementswillhaveamarginofzero,whichmeansthereisnospacebetweentwoelements.
-
TheElementTypeSelectorAnothercommonselectoristheelementtypeselector,whichappliesstylestoallinstancesofthedefinedelement.Forexample,thedocumentinListing9.6definesastyleforallpelements.
Listing9.6:Usingelementtypeselectors
Elementtypeselector
h1{color:teal;}header{text-align:center;font-size:150%;}article{padding:10px;margin-bottom:20px;background:#dedefe;border:1pxsolidpurple;}
NewsUpdatesArticle1HereisaveryinterestingarticleaboutArticle2Anotherarticleaboutbiodiversity
Figure9.3showsthedocumentinListing9.6.Allarticleelementshavegraybackgroundandallh1elementsareshowninteal.Inaddition,thetextintheheaderelementiscenter-justified.
-
Figure9.3:Usingelementtypeselectors
-
TheIDSelectorAnidselectorappliesstylestoelementswithamatchingid.Youdeclareanidselectorbyspecifyingtheidentifierprefixedwithahash.Forexample,thedocumentinListing9.7declaresanidselectornamedfirstParagraph.Asaresult,thefirstpelementinthedocumentwillbeprintedinteal.
Listing9.7:Usinganidselector
IDselector
#firstParagraph{color:teal;}
Ifyoudonotagreewithyournoticeofassessment,youcancontactus.Youmustsubmityourobjectioninwriting.
-
TheClassSelectorAclassselectorselectelementsthathavetheirclassattributeassignedthesamevalueastheselector.Youdeclareaclassselectorbyprefixinganamewithadot.
Asanexample,thedocumentinListing9.8usesaclassselectornamedredBlock.ItappliestothesecondpelementasitsclassatributeisgiventhevalueredBlock.
Listing9.8:Usingaclassselector
Classselector
.redBlock{border:1pxdashedred;}
Werespecttheconfidentialityoftheinformationyouprovidetous.Yourdataisstoredandusedonlyasallowedbylaw.
-
GroupingSelectorsTosavespace,youcangroupsimilarselectorstogether.Useacommatojointwoselectors.Forexample,ifyouhaveapelementselectorandaclassselectorwiththesamestyleslikethis:
p{color:red;text-align:center;}.redText{color:red;text-align:center;}
Youcanrewriteitasfollows.
p,.redText{color:red;text-align:center;}
Iftwoselectorsshareonlysomestyles,youcanstillcombinethem.Considerthefollowing:
ul{background:salmon;text-align:center;}article{background:salmon;text-align:center;}#container{background:salmon;text-align:center;border:1pxsolidcyan;}
Youcangroupthesamestylesanddefineanextraselectorthatcontainsstylesthatarenotshared.Inthiscase:
ul,article,#container{background:salmon;text-align:center;}#container{border:1pxsolidcyan;}
-
TheDescendantSelectorYoucanusethedescendantselectortodefineamoreselectiveselector.Thedescendantselectorbasicallyselectsanelementtypethatisadirectorindirectchildofanotherelementtype.
Forinstance,thefollowingselectorselectsallpelementsthatarenestedinanarticleelement.
articlep{...}
-
StylingTextMostofthetime,youstyletextbymanipulatingthefontusedtoprintit.ThefollowingCSSpropertiescanbeusedtostyletext.
font-family.Specifiesthefontfamily.font-size.Specifiesthefontsizeinpixelorpercentage.font-weight.Specifiesthethickness.Validvaluesarenormal,bold,bolder,lighter,initial,inherit.Inaddition,thefollowingnumberspecifyingthicknesscanbeused:100,200,300,400,500,600,700,800,900.font-style.Specifiesthefontstyle.Validvaluesarenormal,italic,oblique,intialandinherit.
Inaddition,the::first-letterand::first-linepseudo-elementscanbeusedtoselectthefirstletterandfirstlineofanelement,respectively.
Listing9.9showsanexampleofstylingtext.
Listing9.9:Stylingtext(chapter-09/styling-text-1.html)
Stylingtext
.firstPara::first-letter{font-size:300%;}.bold{font-weight:900;}.italic{font-style:italic;}
Werespecttheconfidentialityoftheinformationyouprovidetous.Yourdataisstoredandusedonlyasallowedbylaw.
Figure9.4showsthetextstyling.
-
Figure9.4:Stylingtext
-
StylingBoxesThetermboxmodelisoftenusedwhentalkingaboutHTMLdocumentlayout.Inthismodel,anHTMLelementisbasicallyaboxwithmargins,borders,paddingandcontent.Themarginisthespacebetweentheelementsborderandthenextelementsmargin.Thepaddingisthespacebetweentheelementscontentanditsborder.
width.Thewidthoftheboxinpixels,percentage,emetc.height.Theheightoftheboxinpixels,percentage,emetc.margin.Themarginofthebox.Itsvaluecanbeasingleunitthatrepresentsthefourmarginsorfourunitsseparatedbyspaces,e.g.10px20px10px20px.Inthelattercase,thefourunitsrepresentthevaluesofthetopmargin,rightmargin,bottommarginandleftmargin,respectively.Alternatively,youcanspecifyindividualmarginsusingthemargin-top,margin-right,margin-bottomandmargin-leftproperties.padding.Thepaddingofthebox.Itsvaluecanbeasingleunitthatrepresentsthefoursidesorfourunitsseparatedbyspaces,e.g.10px20px10px20px.Inthelattercase,thefourunitsrepresentthevaluesofthetoppadding,rightpadding,bottompaddingandleftpadding,respectively.Alternatively,youcanspecifyindividualpaddingsusingthepadding-top,padding-right,padding-bottomandpadding-leftproperties.border.Specifiesthewidth,typeandcoloroftheborders.Forexample:1pxsolidred.overflow.Indicateswhatshouldhappenwhenthecontentexceedstheboxsperimeter.Itsvalueisoneofthese:visible,hidden,scroll,auto,initialandinherit.border-radius.Specifiestheradiusofroundedborders.float.Usethispropertytofloatanelement.Itsvalueiseitherleftorright.clear.Resetsthefloat.Itsvalueisoneofthese:none,left,right,both,initialandinherit.
Thefloatpropertyisparticularlyinterestingbecauseyoucancreateatwo-columnpageorplaceoneboxtotherightofanotherbox,notjustbelowit.SeetheexampleinListing9.10.
Listing9.10:Stylingabox(chapter-09/styling-box-1.html)
StylingBox
table,div{background:#dedede;width:140px;height:100px;margin:10px;float:left;}
-
div{border-radius:6px;text-align:center;padding-top:10px;/*overridesthevalueintable,div*/background:lightgreen;}
Table1(1,2)(2,1)(2,2)Table2(1,2)(2,1)(2,2)
Box3,resetfloat(clear:both)
Box4
Figure9.5:Stylingabox
-
StylingLinksAhyperlinkcanbeoneofthefollowingfourstates:
a:link.Normal,unvisitedlink.a:visited.Alinkthattheuserhasvisited.a:hover.Theuserismousingoverthelink.a:active.Thelinkisbeingclicked.
Browsersnormallyusedifferentcolorsfordifferentstates.Youcancustomizethese.Inaddition,youcanpreventthebrowserfromdrawinganlineunderalinkusingthetext-decorationproperty
Listing9.11showsanexample.
Listing9.11:Stylingalink(chapter-09/styling-link-1.html)
Stylinglinks
a:link{color:red;text-decoration:none;}a:visited{color:red;text-decoration:none;}a:hover{color:cyan;text-decoration:underline;}a:active{color:tomato;font-weight:bold;text-decoration:underline;}
HereisourResearchteam
-
StylingListsYoucanusethelist-style-typeandlist-style-positionpropertiestostylealist.Thevalidvaluesforlist-style-typeisasfollows.
disccircledecimaldecimal-leading-zerolower-alphalower-latinlower-romannonesquareupper-alphaupper-latinupper-romaninitialinherit
Thelist-style-positionpropertycanhaveoneofthesevalues.Thedefaultvalueisoutside.
insideoutsideinitialinherit
Asanexample,considerthelistsintheHTMLdocumentinListing9.12.
Listing9.12:Stylinglists(chapter-09/styling-list-1.html)
Stylinglists
.decimal{list-style-type:decimal-leading-zero;}.inside{list-style-type:circle;list-style-position:inside;}.outside{list-style-type:disc;list-style-position:outside;}
-
OneTwoLoremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam,quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.Duisauteiruredolorinreprehenderitinvoluptatevelitessecillumdoloreeufugiatnullapariatur.Loremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam,quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.Duisauteiruredolorinreprehenderitinvoluptatevelitessecillumdoloreeufugiatnullapariatur.
Figure9.6showsthestyledlists.
Figure9.6:Stylinglists
-
StylingTablesBydefault,atablehasnobordersurroundingitselforarounditscells.ItiseasytogiveitborderswithCSS.Listing9.13showsatablewithborders.
Listing9.13:Atablewithborders(chapter-09/styling-table-1.html)
TechStocks
table,th,td{border:1pxsolidblack}
FavoriteTechStockPricesSymbolCompanyClosingpriceAAPLAppleInc.$109.14GOOGGoogleInc.$518.63
Figure9.7showsatablewithborders.
Figure9.7:Atablewithborders
Youcanalsocollapsetheborderusingtheborder-collapsepropertytomakethetablelookdifferent.Listing9.14showshowtodoit.Inaddition,usingthe:last-childpseudo-class,thelasttdelementineachrowisright-aligned.
Listing9.14:Atablewithborders(chapter-09/styling-table-1.html)
-
TechStocks
table{border-collapse:collapse;}table,th,td{border:1pxsolidblack;padding:7px;}td:last-child{text-align:right;}
SymbolCompanyClosingpriceAAPLAppleInc.$109.14GOOGGoogleInc.$518.63
Figure9.8showsthetablewithcollapsedborders.
Figure9.8:Atablewithcollapsedbordersandpaddings.
-
StylingFormsFieldsinaformdonotneedtobenestedwithinapelementiftheformistobestyledwithCSS.Thekeytodoingthisistomakesurethateverylabelisdisplayedasablockelement.Thisway,thenextelementwillbeshownbelowthelabel.Asaresult,allfieldsintheformwillbeshownindifferentrows.
Todisplayanelementasablockelement,usethedisplaypropertyandassignthevalueblocktoit.Listing9.15showsaformthatisstyledwithCSS.
Listing9.15:Styingaform(chapter-09/styling-form-1.html)
ContactUs
form{margin-left:auto;margin-right:auto;max-width:450px;background:palegreen;padding:25px15px25px10px;border:1pxsolid#dedede;font:12pxArial;}h1{padding:20px;display:block;border-bottom:1pxsolidgrey;margin:-20px0px20px0px;color:mediumpurple;}h1>span{display:block;font-size:13px;}label{display:block;}label>span{float:left;width:20%;text-align:right;margin:14px;color:mediumpurple;font-weight:bold;}input[type="text"],input[type="email"],textarea{border:1pxsolid#dedede;height:30px;width:70%;font-size:12px;border-radius:3px;
-
margin:5px;}textarea{height:120px;}input[type="submit"]{background:mediumseagreen;font-weight:bold;border:none;padding:8px20px8px20px;color:black;border-radius:5px;cursor:pointer;margin-left:4px;}input[type="submit"]:hover{background:red;color:yellow;}
ContactUsPleaseusethisformtosendusamessageYourName:YourEmail:Message:
Figure9.9showsthestyledform.
-
Figure9.9:Stylingaform
IntroductionWhat is HTML?Who This Book Is ForAbout This BookDownloading the Sample Applications
Chapter 1: Getting StartedPreparing Your ToolsYour First HTML DocumentCreating and Opening An HTML DocumentAttributesVoid ElementsCommentsViewing the HTML Source Code in A Browser
Chapter 2: Working with TextParagraphsHeadingsWhite Spacesb and i Elementsem and strong ElementsThe span Elementcode and pre ElementsEscaping HTML CharactersNamed Character ReferencesSectioning Elements
Chapter 3: LinksWhat is a URL?Absolute and Relative URLsCreating A LinkOpening A Web Page in A New Tab/WindowThe download Attribute
Chapter 4: ImagesWhere to Get Images for Your Web Site?Image Editing ToolsThe img Elementfigure and figcaption ElementsChanging the Favicon
Chapter 5: ListsOverviewUnordered ListsOrdered ListsDefinition ListsNested Lists
Chapter 6: TablesOverviewTables with Two HeadingsThe colspan AttributeThe rowspan Attribute
Chapter 7: FormsOverviewText Input FieldsRadio ButtonsCheckboxesThe select ElementSubmit and Reset ButtonsNumber and RangeDate-Time FieldsEmail and UrlThe Color Pickerfieldset and legendAuto FocusInput Validation
Chapter 8: MultimediaOverviewVideo Container FormatsUsing the video ElementThe audio ElementEmbedding YouTube Videos
Chapter 9: Styling with CSSOverviewApplying StylesWeb ColorsSelectorsStyling TextStyling BoxesStyling LinksStyling ListsStyling TablesStyling Forms