HTML:
ABeginner’sGuide
About the Author
WendyWillardisafreelanceconsultantofferingdesignandart directionservicestoclients.Shealsoteachesandwritesonthese topics,andistheauthorofseveralotherbooksincludingWeb Design:ABeginner’sGuide(alsopublishedbyMcGraw-Hill). SheholdsadegreeinIllustrationfromArtCenterCollegeof DesigninPasadena,California,whereshefirstlearnedHTML in1995.
Wendyenjoysallaspectsofdigitaldesign,reading,cooking, andanythingrelatedtotheWeb.ShelivesandworksinMaryland withherhusband,Wyeth,andtheirtwodaughters.
About the Technical Editor
HTML:
ABeginner’sGuide
FourthEdition
WendyWillard
NewYorkChicagoSanFrancisco LisbonLondonMadridMexicoCity MilanNewDelhiSanJuan
ISBN: 978-0-07-161144-2
MHID: 0-07-161144-4
The material in this eBook also appears in the print version of this title: ISBN: 978-0-07-161143-5, MHID: 0-07-161143-6.
All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark. Where such designations appear in this book, they have been printed with initial caps.
McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs. To contact a representative please e-mail us at bulksales@mcgraw-hill.com.
Information has been obtained by McGraw-Hill from sources believed to be reliable. However, because of the possibility of human or mechanical error by our sources, McGraw-Hill, or others, McGraw-Hill does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from the use of such information.
TERMS OF USE
This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGraw-Hill”) and its licensors reserve all rights in and to the work. Use of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohib-ited. Your right to use the work may be terminated if you fail to comply with these terms.
vii
Contents at a Glance
PARTI HTMLBasics
1GettingStarted . . . 3
2BasicPageStructure . . . 21
3Color . . . 45
4WorkingwithText . . . 55
5WorkingwithLinks . . . 91
6WorkingwithImages . . . 119
7WorkingwithMultimedia . . . 157
8CreatingLists . . . 171
9UsingTables . . . 195
10DevelopingFrames . . . 237
12PositioningPageElements . . . 301
13HTMLforE-Mail . . . 329
PARTII BeyondHTML 14CreatingYourOwnWebGraphics . . . 359
15WebContent . . . 383
16DynamicContent . . . 395
17MakingPagesAvailabletoOthers . . . 415
PARTIII Appendixes AAnswerstoSelfTest . . . 437
BHTML/CSSReferenceTable . . . 465
CTroubleshooting(FAQs) . . . 483
DSpecialCharacters . . . 493
EFileTypes . . . 499
ix
Contents
ACKNOWLEDGMENTS. . . xix
INTRODUCTION. . . xxi
PARTI HTMLBasics 1GettingStarted . . . 3
UnderstandtheInternetasaMediumforDisseminatingInformation . . . 4
TheAnatomyofaWebSite . . . 4
WebBrowsers . . . 7
InternetServiceProviders . . . 8
BeAwareoftheCurrentVersionofHTML . . . 8
PlanfortheAudience,Goals,Structure,Content,andNavigationofYourSite . . . 9
IdentifytheTargetAudience . . . 9
SetGoals . . . 11
CreatetheStructure . . . 11
OrganizeContent . . . 11
DevelopNavigation . . . 11
IdentifytheBestHTMLEditorforYou . . . 14
WhichIsBest? . . . 16
LearnfromtheProsUsingtheViewSourceCommandofPopularWebBrowsers . . . . 17
2BasicPageStructure . . . 21
IdentifytheWaysinWhichColorIsReferencedinWebDevelopment . . . 47
Test,Test,Test . . . 351
UnderstandtheConceptandUsesofJavaScriptandDHTMLinWebPages . . . 396
BHTML/CSSReferenceTable . . . 465
WhenILinkMyImages,TheyHaveLittleColoredDashesNexttoThem! . . . 487
ISavedMyImageasaJPEG,buttheBrowserSaysIt’sNotaValidFileFormat! . . . . 487
StrangeCharactersAreattheTopofMyPage! . . . 487
ITriedtoSendMyWebPageinanE-Mail,butthePageLookedTerrible! . . . 489
IUpdatedMyWebPage,butIDon’tSeetheChangesintheBrowser! . . . 489
xix
Acknowledgments
T
hankstoeveryoneatMcGraw-Hillformakingiteasytowriteandupdatethisbook.Thanks tomytechnicaleditorformakingsureeverythingisclear,concise,andaccurate.Thanks tothereadersofthepreviouseditionsforpointingouterrataandsuggestingadditions,soI couldmakethiseditionevenbetterthanthepreviousone.xxi
Introduction
W
henIwasfirstapproachedaboutwritingthisbook,Imustadmitthatmythoughtwas,“AnotherHTMLbook—howmanydoweneed?”IlearnedHTMLbyexperiencewhen therewasonlyoneversionofNetscape,andithadbeenalongtimesinceI’devenlookedat anHTMLbook.ButafterIresearchedtheotherHTMLbooksonthemarket,Ifeltcompelled towriteabookthatgivesreadersarealistic,easy-to-understandapproachtolearningHTML, whileatthesametimeofferingreal-worldpracticeactivitiesandadviceonrelatedissues.
HTML:ABeginner’sGuideisthatbook,offeringyoupracticaltoolsandknowledgethat caneasilybeappliedtoavarietyofdevelopmentsituations,withouttheboringrhetoricor lengthytechnicalfluff.Thisbooktellsyouwhatyouneedtoknow,whenyouneedtoknowit. Inrevisingthisbook,Iagainreviewedcompetingbookstodeterminewhatreaderswantedand neededina“new”HTMLbook.Againandagain,Isawthatyouwantedabookthatcombined HTMLandcascadingstylesheetsinawaythatwaseasytounderstandanduse.Furthermore, readersclamoredforabeginning-levelHTMLbookthatcoveredthestandards-compliantway tocodeusablewebpages.Thisisthatbook.
Who Should Read This Book
Youdon’tneedtoknowanythingaboutcomputerprogrammingorwebdevelopmentin ordertolearnHTML,andyoucertainlydon’tneedtoknoweitherofthosethingstogetalot fromthisbook.
What This Book Covers
Chapter12,“PositioningPageElements,”tackleshowtomovecontentaroundonthepage
How to Read This Book
Theprojectsattheendofeachchapterbuilduponeachother,butyoucouldcertainlyadapt aspecificprojecttoyourownneedsifyoureadthemoutoforder.
Special Features
EachchapterincludesTipsandNotestoprovideadditionalreferenceinformationwherever needed.Detailedcodelistingsareincluded,manytimeswithcertaintagsorfeatureshighlighted withfurtherexplanation.
ManychapterscontainAsktheExpertquestion-and-answersectionstoaddresspotentially confusingissues.EachchaptercontainsTryThisexercisesandstep-by-stepprojectstogive youachancetopracticetheconceptstaughtthusfar.Theseprojectsarebasedonareal-world webdevelopmentprojectIworkedonforanonprofitcalledChopPointinWoolwich,Maine.
SelfTestsareincludedattheendofeachchaptertogiveyouanotherchancetoreviewthe conceptstaughtinthechapter.TheanswerstotheSelfTestsareinAppendixA.
YoucandownloadthecontentfortheChopPointprojectsfrommywebsite (www.wendywillard.com).
Part
I
33
Chapter
1
KeySkills&Concepts
● UnderstandtheInternetasaMediumforDisseminatingInformation
● BeAwareoftheCurrentVersionofHTML
● PlanfortheAudience,Goals,Structure,Content,andNavigationofYourSite
● IdentifytheBestHTMLEditorforYou
● LearnfromtheProsUsingtheViewSourceCommandofPopularWebBrowsers
F
oraslongasI’vebeeninvolvedinmakingwebpages,peoplehaveaskedmetoteachthem theprocess.Atthestart,manyareintimidatedbythethoughtoflearningHTML.Butfear not!Afterall,oneofthereasonsIdecidedtoattendartschoolwastoavoidallthemathand scienceclasses.So,asItellmystudents...ifIcouldlearnHTML,socanyou.HTMLisnotrocketscience.Quitesimply,itisameansoftellingawebbrowserhow todisplayapage.That’swhyit’scalledHTML,whichistheacronymforHypertextMarkup Language.Likeanynewskill,HTMLtakespracticetocomprehendwhatyouaredoing.
Beforewediveintotheactualcreationofwebpages,youmustfirstunderstandafew thingsabouttheInternet.Icouldprobablyfillanentirebookwiththematerialinthisinitial chapter,butthefollowingshouldprovideyouwithafirmfoundation.
Understand the Internet as a Medium
for Disseminating Information
Whenyou’reaskedtowriteatermpaperinschool,youdon’tsitdownandjuststartwriting. First,youhavetodoresearchandlearnhowtoformatthepaper.Theprocessforwritingand designingawebpageissimilar.
The Anatomy of a Web Site
Undoubtedly,you’veseenafewwebsitesbynow.Perhapsyouknowsomeonewho’saweb guru,andyou’vewatchedhimnavigatethroughawebsitebychoppingoffpiecesoftheweb address.Haveyoueverwonderedwhathe’sdoing?It’snottoodifficult.Hejustknowsalittle abouttheanatomyofawebsiteandhowtheunderlyingstructureislaidout.
URLs
one—URLsstartwithhttp://,andtheyusuallyendwith.com,.org,.edu,or.net.(Other possibilitiesinclude.tv,.biz,and.info.Formoreinformation,seewww.networksolutions.com.)
EverywebsitehasaURL—forinstance,Google’siswww.google.com.Thefollowing illustrationshowsanotherexampleofaURLasitappearsinacommonwebbrowser(Firefox) ontheMac.
OnepartofaURListhedomainname,whichhelpsidentifyandlocatecomputersonthe Internet.Toavoidconfusion,eachdomainnameisunique.Youcanthinkofthedomainname asalabelorshortcut.Behindthatshortcutisaseriesofnumbers,calledanIPaddress,which givesthespecificaddressofwherethesiteyou’relookingforislocatedontheInternet.To drawananalogy,ifthedomainnameistheword“Emergency”writtennexttothefirst-aid symbolonyourspeeddial,theIPaddressis9-1-1.
NOTE
Although many URLs begin with “www,” this is not a necessity (depending on how the server is set up). Originally used to denote “World Wide Web” in the URL, using www has caught on as common practice. The characters before the first period in the URL are not part of the registered domain and can be almost anything. In fact, many businesses use this part of the URL to differentiate between various departments within the company. For example, the GO Network includes ABC, ESPN, and Disney, to name a few. Each of these is a department of go.com: abc.go.com, espn.go.com, and disney.go.com. Type www.abc.com in the address bar of your favorite web browser, and you’ll notice the URL changes to abc.go.com. That’s because www.abc.com is an alias—or a shortcut—for abc.go.com.
Businessestypicallyregisterdomainnamesendingina.com(whichsignifiesacommercial venture)thataresimilartotheirbusinessorproductname.Domainregistrationislikerenting officespaceontheInternet.Onceyouregisteradomainname,youhavetherighttopublisha websiteunderthatnameontheInternetforaslongasyoupaytherentalfees.
TIP
Wondering whether yourname.com is already being used? You can check to see which domain names are still available for registration by visiting a registration service like www.godaddy.com or www.networksolutions.com.
Web Servers
NOTE
Some people talk about the computer as the server, as in “We need to buy a new server.” Others call the software the server, saying “We need to install a new web server.” Both uses of the word essentially refer to the same thing—web servers make information available to those requesting it.
WhenyoutypeaURLintoyourwebbrowserorclickalinkinawebpage,yousenda suchaddressesonbillboardsandintelevisionadvertising.Forinstance,www.amazon.comis theURLforAmazon’swebsite,whilewww.cbs.comistheURLforCBS.
Mostcommonly,thesesitesarelocatedindirectoriesorfoldersontheserver,justasyou mighthaveyourC:driveonyourpersonalcomputer.Then,withinthismainsite,theremaybe severalfolders,whichhouseothersectionsofthewebsite.
Q:
I’veheardthephrase“theWorldWideWeb”usedsomanytimes,butI’malittle confusedaboutwhatitactuallymeansandhowitrelatestotheInternet.A:
TheWorldWideWeb(WWWortheWeb)isoftenconfusedwiththeInternet.Whilethe precursortotheInternetwasoriginallycreatedduringtheColdWarasawaytolink beconnectedthroughtheuseoflinksindocuments.Thelanguagecomponentofthese technologiesisHypertextMarkupLanguage(HTML).Ifyouwanttofindoutmore,agood resourceonthehistoryoftheInternetisavailableatwww.isoc.org/internet/history. TheWebwasmostlytext-baseduntilMarcAndreessencreatedthefirstgraphicalwebbrowserin1993,calledMosaic,whichpavedthewayfortheuseofvideo,sound, andphotosontheNet.Asalargegroupofinterconnectedcomputersallovertheworld, theInternetcomprisesnotonlytheWeb,butalsothingslikenewsgroups(onlinebulletin boards)ande-mail.ManypeoplethinkoftheWebasthegraphicalorillustratedpartof theInternet.
Forexample,ChopPointisasummercampandK–12schoolinMaine.Ithasseveralmain sectionsofitswebsite,butafewinclude“camp,”“school,”“aboutus,”and“store.”Ifyou lookattheURLforChopPoint’s“aboutus”section,youcanseethenameofthefolderafter thesitename:
www.choppoint.org/aboutus
Ifyouaccessthemainpagefortheschool,theURLchangesto
www.choppoint.org/school
Pages
Whenyouvisitawebsite,youlookatpagesonthesitethatcontainallitstext,graphics, sound,andvideocontent.Eventhoughawebpageisnotthesamesizeorformatasaprinted page,theword“page”isusedtohelpusdifferentiateamongpages,folders,andsites.The samewaythatmanypagesandchapterscanbecontainedwithinasinglebook,manypages andfolders(orsections)canalsobekeptwithinawebsite.
Mostwebserversaresetuptolookautomaticallyforapagecalled“index”asthemain pageinanyfolder.SoifyouweretotypeintheURLusedinthepreviousexample,theserver wouldlookfortheindexpageinthe“aboutus”folder,whichmightlooklikethefollowing.
www.choppoint.org/aboutus/index.html
Ifyouwanttolookforadifferentpageintheaboutusfolder,youcouldtypethenameof thatpageafterthesiteandfoldernames,keepinginmindthatHTMLpagesusuallyendwith .htmlor.htm,suchasin
www.choppoint.org/aboutus/donate.html
Web Browsers
Awebbrowserisapieceofsoftwarethatrunsonyourpersonalcomputerandenablesyouto viewwebpages.Webbrowsers,oftensimplycalled“browsers,”interprettheHTMLcodeand provideavisuallayoutdisplayedonthescreen.Browserstypicallycanalsobeusedtocheck web-basede-mailandaccessnewsgroups.
ThemostpopularbrowserisMicrosoftInternetExplorer(alsocalledIE).Asofthis writing,someestimatesgiveIEupwardof65percentofthemarketshare.Oneexplanation isthatIEcomespreinstalledwithWindowsandfewpeopleseekoutalternativebrowsers. Apple’spreinstalledbrowserwiththeMacO/SisSafari.
TIP
To keep current on statistics about browser use, visit http://en.wikipedia.org/wiki/ Usage_share_of_web_browsers.
Most browsers can be easily customized, meaning you can change the text sizes, styles, and colors, as well as the first page that appears when you start your browser. This is usually called your “home” page or your “start” page, and it’s the page displayed when you click the “home” button in your browser. For easier access, many people change their home page to a search engine or a news site customized according to their needs. These personalized sites are often called portals and also offer free e-mail to users. A few examples are Yahoo!, Google, and MSN.
Internet Service Providers
YouuseanInternetserviceprovider(ISP)togainaccesstotheInternet.Thisconnectioncan bemadethroughyourphonelinewithacompanylikeVerizon,AT&T,AOL,orEarthlink,or youcanconnectthroughacablelinewithacompanylikeComcastorTimeWarner.
Manycompaniesofferyouachoiceofbrowsers,andmayevenprovideaparticularweb browsercustomizedwithquicklinksforthingslikecheckingyoure-mailandreadinglocalnews. However,somecompaniesmaysupportonlyonebrowser,suchasAmericaOnline(AOL).
Be Aware of the Current Version of HTML
Initsearliestyears,HTMLquicklywentthroughmuchiteration,whichledtoalackof standardizationacrosstheInternet.TheWorldWideWebConsortium(W3C—www.w3.org) steppedinandbeganpublishingalistofrecommendations,calledstandards,forHTMLand otherweblanguages.ThelastofficialstandardforHTMLwasHTML4.01.
2000.Theresultingsetofstandards,calledExtensibleHypertextMarkupLanguage(XHTML), providedawayforHTMLtohandlealternativedevices,suchascellphonesandhandheld computers.
XHTML1.0offeredmanynewfeaturestomakethelivesofwebdeveloperseasier,but itwaspoorlysupportedbywebbrowsersatitslaunchin2001.Intheyearsimmediately following,theW3CupdateditsrecommendationtoXHTML2.0.However,theworlddidn’t adoptXMLasquicklyoraswarmlyastheW3Chadanticipated,andtheorganizationended upswitchinggears.
In2008,theW3Creleasedaworkingdraftofthefutureofhypertextmarkup:HTML5. Thisisverymucha“workinprogress,”whichwilllikelytakeseveralyearstofinalizeand beadopted.Inthemeantime,youcancheckthestatusofHTML5ontheW3C’swebsite: www.w3c.org/TR/html5.
UnlikeXHTML,HTML5isintendedtoallowthebestofHTMLandXMLsimultaneously. ThedevelopmentteamseekstostudythemodernuseofHTMLanditscontent,inaneffortto createcodestandardsthatwillcarryuseasilyintothenextgenerationoftheWeb.
Althoughthestandardisstillindevelopment,certainkeydifferenceshavebeenidentified. Iwillcallattentiontothoseasneededthroughoutthecourseofthisbook.Youcanreadmore aboutthespecificdifferencesatwww.w3.org/TR/2008/WD-html5-diff-20080610.However, youneedn’tactuallycodeforthesedifferencesuntilthemajorityofthebrowsersadopt HTML5.
Plan for the Audience, Goals, Structure,
Content, and Navigation of Your Site
Inadditiontolearningaboutthemedium,youalsoneedtodothefollowing:
● Identifyyourtargetaudience.
● Setgoalsforyoursite.
● Createyourwebsite’sstructure.
● Organizeyourwebsite’scontent.
● Developyourwebsite’snavigation.
Identify the Target Audience
TIP
If your site represents a new company or one that doesn’t already have information about its clients’ demographics, you might check out the competition. Chances are good that if your competition has a successful web site, you can learn from them about your target audience.
Does your site target mostly “navy seal” visitors? These individuals prefer search engines, especially when trying to locate information quickly. Providing a good search engine or site map on your site can greatly increase your repeat visitors.
UserGroup FunctionsPerformed Ages Gender WebExperience
Current customers - bank online
- contact customer service - research additional
services/products
16+ male/female varies
Potential customers - research services/products - contact sales
16+ male/female varies
Potential employees - search job openings - research company - contact HR
18–60 male/female varies
Financial consultants - research services/products - view company financials - contact sales
30–60 male/female 60/40 savvy
Set Goals
SincetheWeb’sinception,millionsofnewwebsiteshavebeencreated.Tocompeteinsuch alargemarket,youneedtosetcleargoalsforthesite.Forinstance,thesitemight
● Sellproducts/services
● Recruitpotentialemployees
● Entertain
● Educate
● Communicatewithcustomers
Alwaysrememberthegoalswhendevelopingthesitetoavoidunnecessarycontent.If apageorsectionofcontentonyoursitedoesn’tmeetoneofthegoals,itmayconfuseorturn awayvisitors.
Create the Structure
Table1-2 Content Organization
CategoryName FolderName
Paper shop/paper/
Pens shop/pens/
Software shop/software/
Furniture shop/furniture/
Furniture, Desks shop/furniture/desks/ Furniture, Chairs shop/furniture/chairs/ Furniture, Bookcases shop/furniture/bookcases/
Figure1-1 A tree diagram showing a portion of the structure for a sample office supply site
index.html
shop/index.html jobs/index.html
products.html
viewcart.html
order.html view.html
apply.html
search.html
Inaddition,considergivingyourvisitorsasmanyvisualcluesaspossibletoaidinthe navigationofyoursite(seeFigure1-2).Thismightbeaccomplishedbyrepeatingthepagenamein
● Thepage’stitle(thetextthatappearsatthetopofthebrowserwindow,aswellasinsearch engines)
● Thepage’sfilename
● Aheadline
● Buttonsandlinkstothepage(highlightedifyouareviewingthatpage)
Figure1-2 Apple’s site gives the user plenty of visual clues to aid in navigation. This page title lists the name
of the site as well as the page and section names.
The URL clues the visitor to the name and location of the section being viewed. This button has a different color
scheme to show the visitor which section is currently being viewed.
The section title is displayed
Identify the Best HTML Editor for You
Tool AveragePrice(US) KeyFeatures
Amaya
www.w3.org/Amaya/ Free -Open-source software project hosted by W3C -Windows/Mac/Linux
-WYSIWYG visual editor (but no browser preview)
-Spell-checking BBEdit
www.barebones.com $125 -Also offers a free, scaled-down version called TextWrangler -Mac only
-Browser preview -FTP upload -Multiuser editing
-Text-based editor capable of handling many popular programming languages, including C, C++, CSS, Java, JavaScript, JSP, Perl, PHP, Ruby, HTML, SQL, and XML
CoffeeCup
www.coffeecup.com $49 --Windows onlyWYSIWYG visual editor -FTP upload
-Spell-checking -Templates Dreamweaver
www.adobe.com/products/dreamweaver $399 --Windows/MacWYSIWYG visual editor with browser preview
-FTP upload -Spell-checking -Templates
-Server-side scripting -Multiuser editing
Tool AveragePrice(US) KeyFeatures Homesite
www.adobe.com/products/homesite
Note:Homesite was acquired by Adobe when it purchased Macromedia in 2005. Although Adobe has not updated Homesite, loyal fans continue to use the last version (5.5), which was released in 2003.
$99 -Windows only
-Text-based HTML/XHTML/CSS editor -FTP upload
-Multiuser editing -Spell-checking
ExpressionWeb
www.microsoft.com/expression Note:Expression Web replaced Microsoft’s Front Page.
$299 -Windows only
-WYSIWYG visual editor with browser preview
-FTP upload -Spell-checking -Templates
-Server-side scripting -Multiuser editing VisualWebDeveloper
www.microsoft.com/express/download Free --Windows onlyWYSIWYG visual editor with browser preview
-FTP upload -Spell-checking -Templates
-Server-side scripting -Multiuser editing NoteTab
www.notetab.com Free/$29.95 --Free and pro versions availableWindows only -Text-based HTML editor
The Pro version is highly customizable and includes features such as a spell-checker and templates
Smultron
http://tuppis.com/smultron/ Free --Open-source, Mac onlyText-based editor capable of handling many popular programming languages, including C, C++, Java, Ruby, HTML, XML, CSS, and D
-Browser preview
TIP
WYSIWYG editors don’t require knowledge of HTML. Instead of looking only at the HTML of your pages, you have the ability to view a “preview” of how the page will look in a browser. This way, you can simply drag and drop pieces of your layout as you see fit.
AfterreviewingTable1-3,youlikelynoticedthatmosttoolsfallintooneoftwo
Which Is Best?
Somewebdevelopersprefertousethetext-basedHTMLeditors,ratherthanhavea WYSIWYGeditordoitforthem,forthefollowingreasons:
● Bettercontrol WYSIWYGeditorsmaywriteHTMLinavarietyofways—althoughnot allofthemwillhavethesameoutcome.Thismeansyourpagescanlookdifferentineach browser.Unfortunately,thishascausedsomeolderWYSIWYGprogramstobelabeled “WYSINWYG”orWhat-You-See-Is-Not-What-You-Get.
● Fasterpages WYSIWYGeditorssometimesovercompensatefortheamountofcode neededtorenderapageproperly,andsotheyenduprepeatingcodemanymoretimesthan necessary.Thisleadstolargefilesizesandlongerdownloads.
● Speedierediting Thelarge-scaleWYSIWYGeditorsoftentakealotofmemoryand systemresources,slowingboththecomputerandthedevelopmentprocess.
● Moreflexibility ManyWYSIWYGeditorsareprogrammedto“fix”codetheythinkis faulty.Thismaymakeyouunabletoinsertcodeoredittheexistingcodeasyouwish.
Thatsaid,modernWYSIWYGeditorshavecomealongwayintermsofcontroland flexibility.Thosedeveloperswhosingtheirpraisestypicallymakethefollowingcomments:
● Preview WYSIWYGeditorsallowyoutopreviewyourpageswithintheHTMLeditor, whichmeansyougetanideaofhowthepageisshapingupevenbeforeswitchingtothe browserview.
● Advancedinlineedition ToolslikeDreamweaverofferthecapabilitytocodecustom CSS,DHTML,andJavaScript,allwithinthesamevisualeditorusedtocodebasicHTML.
● Bestofbothworlds Withtheabilitytodigrightintothecodeandstillseeavisual representationoftheoutput,it’snosurprisethateditorslikeDreamweaverhavebecomeso popular.
Notethat
● DynamicHTML(orDHTML)allowswebpagecontenttobeeasilychangedandcustomized onthefly,withouthavingtosendandreceiveadditionalinformationfromtheserver.Style sheets,usedespeciallyinDHTML,arediscussedthroughoutthebook.
● JavaScriptisascriptinglanguagedesignedtogivewebpagesmoreinteractivitythancan beachievedthroughHTML.Eventhoughthenamemightmakeyouthinkotherwise,
Learn from the Pros Using the View Source
Command of Popular Web Browsers
OneofthebestwaystolearnHTMListosurftheWebandlook attheHTMLforsitesyoulike(aswellasthoseyoudon’tlike). MostwebbrowsersenableyoutoviewtheHTMLsourcecodeof webpages,usingthefollowingcommands:
● Inyourfavoritewebbrowser,bringupthepagewhosesource youwouldliketoview.
TryThis1-1
areferencelibrary.BecausetheWebisopensource,meaningyourcodeisfreeforanyoneto see,copyingotherdevelopers’codeistempting.Butremember,youshouldgivecreditwhere creditisdueandnevercopyanythingprotectedbyacopyright,suchasgraphicsandtext content.NOTE
A few browsers don’t let you use View Source. If you find you cannot view the HTML source of a web page, try saving the page to your local hard drive, and then opening it in a text editor instead.
Develop a Web Site
downloadedfromwww.wendywillard.com.Inaddition,youcanviewmyversionoftheweb siteanytimebyvisitingwww.choppoint.org.
Thisspecificprojecttakesyouthroughtheplanningphaseofthewebdevelopmentproject. Goalsforthisprojectinclude
● Identifyingyourtargetaudience
● Settinggoalsforyoursite
● Creatingyourwebsite’sstructure
● Organizingyourwebsite’scontent
1.Spendsometimeresearchingyourorganization.Trytolearnasmuchaboutitsbusinessas possible.Ifyouknowpeoplewithinthecompany,dosomeinterviewstohelpyouidentify yourtargetaudience,aswellasthesitegoals.Ifyoucan’tspeakwiththem,visitother similarsitestodeterminewhattypeofpeoplethecompetitionistargeting.Somequestions toaskandthingstoconsiderinclude
● Whatbusinessproblem(s)willthewebsiteaddress?Whatdoyouwanttoaccomplish? Whatareyourgoalsforthewebsite?
● Whoarethetargetedusers/visitorsofthesite?Doyouhaveanyexistingresearch regardingyourclientoruserbase,suchasdemographics,statistics,orothermarketing information?
● Todeterminetheappropriatedirectionforthesite,youmustmatchthetargeted usersandthefunctionstheywillperformwhenvisitingthesite.Forexample,will thetargetedusersbe“accidentaltourists”directedtothesitebyanadvertisement, orpotentialinvestorslookingforthefinancials?Howdotheaudiencedemographics affectthis?(Youcanuseatablelikethefollowingtohelpyouplanthetargetedusers andthefunctionstheymightperformatthesite.AnexampleisshownforChopPoint.)
UserGroup FunctionsPerformedatSite Ages WebExperience 1. Potential campers - check session dates
- sign-up
- get more information
10–18 moderate–high
2. 3.
2.Afteryoudecideonthetargetaudienceandgoalsforthesite,it’stimetoevaluateyour content.Thisisbestaccomplishedthroughconversationswiththepeopleyou’redeveloping thesitefor.Ifthisisn’tpossible,becreativeandcomeupwithalistofcontentyouthink couldbeappropriate.
3.Usetheanswerstothefollowingquestionsasaspringboardforbuildingthestructureof yoursite.Thendevelopatreediagram,similartotheoneshowninFigure1-1,toidentify allthepiecesofyoursiteandwheretheyfitwithintheoverallstructure.
● Doesanofficiallogohavetobeusedonthewebsite? ● Isallthecontentwrittenandavailableindigitalformat?
● Whatarethemainsectionsofthesite?Doesallthecontentfitwithinthosesections? ● Listallthecontentforthesite.Assigneachpieceofcontenttoasection(asnecessary)
Summary
BeforeyoubeginwritingtheactualHTMLforyourwebpages,youneedtoknowsomething aboutthesiteyouarecreating.Thequestionsaskedinthisprojectshouldgetyouofftoa goodstartandhelpyoubuildasolidfoundationforyourwebsite.Inthenextchapter,you’ll continueworkingwiththissiteasyouwritethecodeforoneofthepages.
Chapter 1 Self Test
1.Whatisawebbrowser? 2.WhatdoesHTMLstandfor?
3.IdentifythevariouspartsofthefollowingURL:http://www.mcgrawhill.com/books/ webdesign/favorites.html__________://_________________/___________/___________/ __________
4.WhatisWYSIWYG?
5.Fillintheblank:TheversionofHTMLcurrentlyunderdevelopmentis_____________.
6.WhatistheAdobeDreamweaverprogramusedfor?
7.Whatisoneofthetwomostpopularwebbrowsers?
8.Fillintheblank:WhenyoutypeaURLintoyourwebbrowser,yousendarequesttothe ________________thathousesthatinformation.
9.Whatdoestheacronym“URL”standfor?
10.WhatorganizationmaintainsthestandardsforHTML?
11.Howcanyougiveyoursite’svisitorsvisualcluesastowheretheyareinyoursite’s structure?
12.Fillintheblank:Agoodpracticeistoincludeastandard_________________onallpages forconsistencyandeaseofuse.
13.Fillintheblank:Sellingproductsandrecruitingpotentialemployeesareexamplesofweb site_______________.
14.Fillintheblank:Beforeyoucanbegindevelopingyourwebsite,youmustknowalittle aboutthesite’starget_________________.
15.Ifyoursiterepresentsanewcompanyoronethatdoesn’talreadyhaveinformationaboutits clientdemographics,wheremightyoulookforinformation?
21
Chapter
2
KeySkills&Concepts
● CreateanHTMLFile
● PreviewanHTMLFileinaBrowser
● DescribeandApplytheBasicHTMLDocumentFormat ● UseCharacterEntitiestoDisplaySpecialCharacters ● AddCommentstoanHTMLFile
● SetUpStyleSheetsinanHTMLFile
N
owthatyouknowalittleabouttheWebandwhattothinkaboutbeforecreatingaweb page,let’stalkaboutthebasicstructureofanHTMLpage.Create an HTML File
Attheirverycore,HTMLfilesaresimplytextfileswithtwoadditionalfeatures.
1.HTMLfileshavean.htmlor.htmfileextension.Afileextensionisanabbreviationthat associatesthefilewiththeappropriateprogramortoolneededtoaccessit.Inmostcases, thisabbreviationfollowsaperiodandisthreeorfourletterslong.Inthefollowingexample, noticethattheYahoo!homepageendsinan.htmlfileextension.
NOTE
You might also see more advanced types of pages on the Internet, such as Microsoft’s Active Server Pages (.asp) or those written in the Extensible Markup Language (.xml). These are beyond the scope of the traditional HTML page, and therefore not covered in this book.
Naming Conventions
RememberthefollowingfewpointswhennamingyourHTMLfiles.
● Althoughinmostcasesitdoesn’tmatterwhetheryouuse.htmlor.htm,youshouldbe
consistenttoavoidconfusingyourself,thebrowser,andyourusers.
NOTE
● Somewebserversarecase-sensitive,sorememberthiswhennamingandreferencing
filenamesandtrytobeconsistent.IfyounameyourfileMyPage.html,andthenreference itlaterusingmypage.html,youmayendupwithabrokenlink.Onegoodtechniqueisto useonlyuppercaseorlowercasetonameyourfiles.Thisway,ifyouseeafilewithaletter initthatdoesn’tmatch,youknowinstantlythatfileisprobablytheproblem.Eventhepros runintocase-sensitivityproblemsonanalmostdailybasis.
● Usesimplefilenameswithonlylettersandnumbers.Don’tusespaces,punctuation,or
specialcharacters,otherthanhyphens(-)andunderscores(_).Goodexamplesmightbe home.html,my-story.html,andcontactme.html.
TIP
While it’s perfectly acceptable to use an underscore (_) in a file or folder name, I suggest using a hyphen instead. Underscores can easily become confused with an underline, especially when displayed as a link on a web page (because links are usually underlined).
Thesesamerecommendationsholdtrueforanyfoldernamesyouuse.Ifyouwerecreating awebsitethathadyourfavoritelinks,familyphotos,andrésumé,youmightfinditusefulto puteachofthosethingsinaseparatefolder.
TIP
If you decide to use Microsoft Word or WordPad to type your HTML, you need to choose the file type “Text Document” or “Text Only” and give the file an .html extension the first time you save it. This is because both of those programs default to saving “Word for Windows” or “Microsoft Word” documents with a .doc or .docx extension.
Preview an HTML File in a Browser
YoucanviewHTMLfileslocatedonyourpersonalcomputerwithinyourownwebbrowser. Itisn’tnecessaryforyourfilestobestoredonawebserveruntilyouarereadytomakethem visibleontheInternet.
driveuntilyoulocatetheHTMLfileyouwanttoopen.(Note,ifyoudon’tseeanyFilemenus inIE,trypressingtheALTkeytorevealthosemenus.)
Ifyou’regoingtomakefrequentchangestotheHTMLfileinatexteditor,andthenswitch backtoawebbrowsertopreviewthepage,keepingbothprograms(atexteditorandaweb browser)openatthesametimemakessense.Whenusingabasictexteditor,thestepstoedit andpreviewHTMLfilesare
1.Open/returntoyourHTMLfileinatexteditor. 2.EdityourHTMLfileinatexteditor.
3.SaveyourHTMLfileinatexteditor.
4.Open/returntoyourHTMLfileinawebbrowser.
5.ClicktheRefreshorReloadbuttoninyourwebbrowsertoupdatetheHTMLpagetoreflect thechangesyoujustmadetoit.
BykeepingyourHTMLfileopeninbothatexteditorandabrowser,youcaneasilymake andpreviewchanges.
Ifyou’reusingagraphicalorWYSIWYGeditor,thestepsareslightlydifferentbecause thesetypesofprogramsincludeabrowserpreviewoption.Forexample,AdobeDreamweaver offersthreewaystoworkwithanHTMLfile.Oneoptionistoviewonlythecode,asyou wouldinabasictexteditor.Anotheroptionistoworkinthepreviewmode,movingpage elementsaroundonthepagebyclickinganddragging.Finally,youcanuseacombination, wherethecodeisvisibleonpartofthescreenandthebrowserpreviewisvisibleontherest(as showninFigure2-1).
Figure2-1 Accessing both the code and browser preview at once with Adobe
Describe and Apply the Basic
HTML Document Format
AnHTMLentityortagisacommandusedtotellthebrowserhowtodisplaycontentona page.Thiscommandissimilartowhathappensbehindthesceneswhenyouhighlightsome textinawordprocessorandclicktheItalicbuttontomakethetextitalicized.
WithHTML,insteadofclickingabuttontomaketextitalicized,youcantypeatagbefore andafterthetextyouwanttoemphasize,asinthefollowing:
<em>Reminder:</em>Therewillbenobandpracticetoday.
Youcaneasilyrecognizetagsbecausetheyareplacedwithinbrackets(<>),orless-thanand greater-thansymbols.
Didyounoticethatthetagtoemphasizetextandmakeititalicisem?Giventhatpieceof information,canyouguessthetagstoaddaparagraphorcreateitemsinalist?
Purpose Tag
Create paragraphs <p> Create list items <li> Add a line break <br>
NowdoyoubelievemewhenIsayHTMLisnotrocketscience?Don’tworry—mostofthe tagsareprettyintuitiveandeasytoremember.
Types of Tags
InHTML,thereareusuallybothopeningandclosingtags.Forexample,ifyouuse<p>asan openingtagtosignifywheretostartanewparagraph,youhavetouseaclosingtagtosignify wherethatparagraphends(unlessyouwantyourentirepagetobecontainedwithinone paragraph).Todoso,usethesametagwithaforwardslashplacedbeforeit:</p>.Table2-1 showsalistofbasicHTMLpagetags.
Attributes
Manytagshaveadditionalaspectsthatyoucancustomize.Theseoptionsarecalledattributes andareplacedafterthetagbutbeforethefinalbracket.Specificattributesforeachtagare discussedaswemovethroughthebook.Buttogiveyouanideaofhowattributeswork,let’s lookatanexampleusingtheimgtag.
<imgsrc="mypicture.jpg"width="100"height="100"alt="Aphotoofme"/>
There’snoneedtorepeattheimgtag,becausemultipleattributescanbeincludedina singletag.Whenyouaddattributestoatag,youonlyputthemintheopeningtag.Then,you onlyneedtoclosethetag(nottheattributes).Notethatthistagisonethatdoesn’thavea separateclosingtag.(Infact,oldversionsofHTMLdidn’trequiretheimgtagtobeclosedat all.)Toclosetagswithoutseparateclosingversions,simplyplaceaforwardslash(/)beforethe finalbracket,asshownintheprecedingcodeexample.
Required Tags
AllHTMLpagesneedtohavethehtml,head,andbodytags,alongwiththeDOCTYPE identifier.Thismeans,attheveryleast,yourpagesshouldincludethefollowing:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html> <head>
<title>MyFirstHTMLPage</title> </head>
<body>
ThisisaverybasicHTMLpage. </body>
</html>
Hereistheresultofthispagewhendisplayedinabrowser. OpeningTag ClosingTag Description
!DOCTYPE n/a - Tells the browser which set of standards your page adheres to. - Lists the standard (see the section “Doctype” later in this chapter). - Identifies the location of the standard by linking to the URL. <html> </html> - Frames the entire HTML page.
<head> </head> - Frames the identification information for the page, such as the title, that is transferred to the browser and search engines.
<body> </body> - Frames the content of the page to be displayed in the browser window.
<title> </title> - Gives the name of the page that will appear at the top of the browser window and be listed in search engines.
- Is contained within <head> and </head>.
TotestthisbasicHTMLpageforyourself,trythefollowing: 1.Openabasictexteditor,suchasTextEdit(Mac)orNotepad(PC). 2.Copytheprecedingcodeintoanewtextdocument.
3.Saveitasatext-onlyfile(ASCIItext)andnameittest.html.
4.LaunchyourbrowserandchooseFile|OpenFile(FirefoxorSafari)orFile|Open(Internet Explorer).
5.Browseyourharddrivetolocatethetest.htmlfile,andyou’reoffandrunning!
NOTE
If you’re using IE7+ and don’t see the File menus, press ALT to reveal those menus.
Doctype
TheDOCTYPEtagisarequiredtagthatisusedtotellthebrowserwhichversionofHTML isusedinthedocument.WhentheW3CreleasedHTML4andXHTML,itspecifiedthree possibleflavors,orversions,toaccommodatetheanticipatedtransitiontimeduringwhich developersandbrowsersweresupposedtomigratefromHTML4.0toXML:
● XHTMLTransitional Fordocumentsthatcontainacombinationofoldandnew
HTMLcode
● XHTMLStrict Fordocumentsthatdon’tcontainanyoutdatedcodeandarestructurally
“clean”
However,theW3Ceventuallyabandonedtheconceptoftransitionaldocuments,infavor ofHTML5,whichwillsupportbothHTMLandXMLsimultaneously.ButuntilHTML5is finalizedandfullyadoptedbythemajorwebbrowsers,youstillneedtoidentifyyourpage withoneofthesethreeflavorslistedtohelpthebrowservalidateit.Giventhatweknowthese threeflavorswillbephasedoutoverthenextfewyears,Isuggestusingtheeasiestonetowork with(transitional)tovalidateyourcurrentwebpages.Tovalidateyourpagesagainstthisflavor ofXHTML,use
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0
Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">.
NOTE
To give you a glimpse as to what the future holds, after HTML5 is adopted, you’ll simply have to use a doctype that identifies whether your page is HTML or XML. For example, HTML files will use <!doctypehtml>. Simple, huh? In general, HTML5 looks to be a
great next step for this powerful language.
Validating Against These Doctypes
WonderingwhyyouevenneedtovalidateyourHTMLagainstaparticulardoctype?The purposeofvalidationistohelpidentifypotentialproblemsabrowsermightencounter whendisplayingyourpage.BecausebrowsersrenderpagesaccordingtotheofficialHTML specifications(asdictatedbytheW3C),itmakessensetodouble-checkyourpagesagainst thosespecsaspartofyourtesting.
TheofficialW3Cvalidationservicecanbefoundathttp://validator.w3.org.Onceyouget there,you’llnoticeyoucanuseseveraldifferentmethodstotestorvalidateyourpages.
● ValidatebyURI IfyourpageisalreadyliveontheInternet,youcansimplyenterthe
page’sURI(address),andthetoolwillseektovalidateyourpage.
● Validatebyfileupload Ifyou’reworkingonpagescurrentlystoredonyourharddrive
(butnotliveontheInternet),youcanuploadthosepagestotheonlinevalidator.
● Validatebydirectinput Alternatively,youcansimplycopyandpastethecodeintoan
onlineformatthevalidationservice.
Capitalization
OriginalversionsofHTMLwerecase-insensitiveand,infact,veryforgiving.Thismeansall ofthefollowingexampleswouldbeconsideredthesamebythebrowser:
● <html>
● <HTML>
● <HTml>
Thatsaid,HTML4/XHTMLiscase-sensitiveandrequiresalltagstobelowercase.Ofthethree precedingexamples,thebrowsermightproperlyinterpretonlythefirst.
Tomakeitreallyconfusing,HTML5returnstobeingcase-insensitive.Giventhedifferences betweenthevariousversionsofHTMLcurrentlyinuse,Irecommendusingall-lowercasetags.
Quotations
HTML4/XHTMLalsorequiresallvaluestobeplacedwithinstraightquotationmarks,asin thefollowingexample:
<pstyle="font-family:verdana;">
Nesting
Thetermnestingappearsmanytimesthroughoutthecourseofthisbookandreferstothe processofcontainingoneHTMLtaginsideanother.
<strong>Thistextisboldand<em>italic</em></strong>
Q:
ItypedtheprecedingHTMLintoatextfile,butwhenItriedtopreviewthepagein mybrowser,nothinghappened.Why?A:
Thereareseveralpossiblereasonswhyyourpagemightappearblank.First,review thecodeintheprecedingexampleandcompareitlinebylinewiththecodeyoutyped. Forgettingaclosingtagormaybejustaforwardslash(/)iseasy.Sometimesit’shelpful totakeaquickbreakbeforereturningtoscrutinizeyourpage.Ifyoudomakeachange, besuretosavethefileinyourtexteditor,beforeclickingRefreshorReloadinyourweb browser. Ifyou’recertainthecodeinyourpagematchestheexample,tryresavingyourfileunder anewname.Closeyourbrowser,thenrelaunchyourwebbrowserandopenthepageinthe browseragain.
AdditionaltroubleshootingtechniquesarelocatedinAppendixC.
Ask the Expert
The value of the attribute
The em tag is nested
Youhaveaproperwayandanimproperwaytonesttags.Alltagsshouldbeginandend startinginthemiddleandmovingout.Anotherwayofthinkingaboutitinvolvesthe“circle rule.”Youshouldalwaysbeabletodrawsemicirclesthatconnecttheopeningandclosing versionsofeachtag.Ifanyofyoursemicirclesintersect,yourtagsarenotnestedproperly.
Usingthefollowingexample,thefirstoneisproperbecausethestrongtagsarebothon theoutsideandtheemtagsarebothontheinside.
<strong><em>Thesetagsarenestedproperly.</em></strong> <strong><em>Thesetagsarenotnestedproperly.</strong></em>
Eventhoughbothmayworkinsomebrowsers,youneedtonesttagstheproperwaytoensure thatyourpagesdisplaythesameacrossallbrowsers.
Spacing and Breaks
Let’slookcloselyatsomeexampleHTMLtoidentifywhereproperspacingshouldoccur. (Note,theatagandhrefattributeareusedtolinksomething,inthiscasetext.)
<body>
<ahref="http://www.google.com"title="SearchGoogle">SearchGoogle</a>
TwoplacesexistwithinanHTMLfilewhereyoumightliketoaddbreaks:
● Inbetweentags,tohelpyoudifferentiatebetweensectionsofthepage ● Inbetweenlinesoftextwithinthebodyofthepage
Spacing and Breaks Between Tags
Thefirstplaceyoumightliketoaddbreaksisinbetweentags,asinthefollowingexample. <html>
<head>
<title>MyFirstWebPage</title> </head>
Althoughthisisnotrequired,mostpeopleusetheENTERorRETURNkeytoseparate tagswithlinebreaks.Othersalsoindenttagsthatarecontainedwithinothertags,asinthe precedingexample:thetitletagisindentedtoshowitiscontainedornestedwithinthe
headtag.Thismayhelpyoutoidentifythetagsmorequicklywhenviewingthepageina texteditor.
Spacing Between Lines of Text
Thesecondplaceyouaddbreaksisbetweenthelinesoftextinthebodyofthepage.Ifyou usetheRETURNorENTERkeyonyourkeyboardtoaddalinebreakinbetweentwolinesoftext onyourpage,thatlinebreakwillnotappearwhenthebrowserdisplaysthepage.
No space is between the
brackets and the tag. No space should come between a tag and the text it affects.
A single space should come between attributes. A single space should come
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html> <head>
<title>MyfirstWebpage</title> </head>
<body> Welcome.
ThankyouforvisitingmyfirstWebpage.Ihaveseveralotherpages thatyoumightbeinterestedin.
</body> </html>
Inthiscode,IpressedtheRETURNkeytwiceaftertheword“Welcome.”Inthisexample, youcanseethatthebrowserignoredmyreturnsandranbothlinesoftexttogether.
Tomakethoselinebreaksappear,I’dhavetouseatagtotellthebrowsertoinsertaline break.Twotagsareusedforbreaksincontent.
<br/> <p></p>
Thebrtaginsertsasimplelinebreak.Ittellsthebrowsertodropdowntothenextline beforecontinuing.Ifyouinsertmultiplebrtags,thebrowserwilldropdownseverallines beforecontinuing.
acontainertagbecauseitsopeningandclosingtagsshouldbeusedtocontainparagraphsof content.ThebrandptagsarediscussedinmoredetailinChapter4.
NOTE
Because thebr tag doesn’t contain any text, as the p tag does, it doesn’t have opening and closing versions. Instead, you place a slash before the closing bracket to “terminate” the tag, as in: <br/>.
IfIencloseeachoftheseparagraphsinptags,likethefollowing: <p>Welcome.</p>
<p>ThankyouforvisitingmyfirstWebpage.Ihaveseveralother pagesthatyoumightbeinterestedin.</p>
thebrowserwillknowtoseparatethemwithablankline.Thefollowingscreenshowshowthe browserdisplaysthetextnowthatIhavecontainedeachoftheparagraphsinptags.
Inaddition,HTMLneitherrecognizesmorethanasinglespaceatatimenorinterpretsa tabspaceasawaytoindent.Thismeansthatinordertoindentaparagraphorleavemorethan onespacebetweenwords,youmustusestylesheets(seeChapter4)orspecialcharacters.
Eventhoughyoumightbeabletotypeacertaincharacteronyourcomputersystem
A few characters are reserved and given special meaning in HTML. For example, the brackets (< and >) are used to signify HTML tags, while the ampersand (&) is used to begin these entities. If you need to use a bracket within the content of your HTML page, such as when a greater-than symbol is needed, in the case of 3 > 2, you should use the corresponding character entity (>) to do so.
Character NumberedEntity NamedEntity
" " "
& & &
(nonbreaking space)  
© © ©
® ® ®
é é é
< < <
> > >
Havingnowmadethecaseforusingcharacterentities,letmejustsayherethatit’sbeen myexperiencethatcertaincharacterscanactuallybeusedinawebpagewithoutcausingany problems.Theseincludestraight—notcurly—quotationmarks(''),exclamationmarks(!), questionmarks(?),colons(;),andparentheses().WhileIhaven’tnoticedanyofthesetocause problemsinthemajorityofbrowsers,youshouldstilltestyourpagesthoroughlywhenusing anyspecialcharacters.
Add Comments to an HTML File
Sometimesyoumightnotwantyourwebsitevisitorstoseepersonalcommentsornotes you’veaddedtoyourwebpages.Thesenotesmightbedirectionstoanotherpersonor reminderstoyourself.
Aftertheopeningbracket,anexclamationmarkandtwohyphenssignifythebeginningofa comment.Aspaceshouldappearaftertheopeningcommentcode,aswellasbeforetheclosing commentcode.
Commentsarenotrestrictedinsizebutcancovermanylinesatatime.Theendcomment code(-->)doesn’tneedtobeonthesamelineasthebeginningcommentcode.Ifyou forgettocloseyourcommenttag,therestofthepagewillnotappearinyourbrowser.Ifthis happens,don’tbealarmed.Simplygobacktothecodeandclosethatcomment.Therestofthe pagewillbecomevisiblewhenyousavethefileandreloaditinthebrowser.
Set Up Style Sheets in an HTML File
I’vealreadymentionedthephrase“stylesheets”afewtimes,buthaven’treallygiventhema fullexplanationyet.Partofthereasonisthatstylesheetsweren’treallyapartofHTMLuntil itwasrewrittenasXHTML.Thepurposeofcascadingstylesheets(abbreviatedCSS)isto separatethestyleofawebpagefromitscontent.
ThecurrentHTML“rules”dictatethatweonlyuseHTMLtoidentifythecontentofthe page,andthenuseastylesheettospecifythepresentationofthatcontent.Thisnotonlymakes webpagesmoreaccessibleandusabletoallusers(regardlessoftheirbrowsers,platforms, operatingsystems,physicallimitations,andsoforth),butalsotosearchenginesandother typesofsoftware.
TIP
If you’ve ever used the Style drop-down menu in Microsoft Word, you’ve already used a style sheet of sorts. The most basic style sheet might include a style called “Body Text,” that specifies how the body text of the web page should look—which font and color to use, how much space to leave around it, and so on.
Define the Style
Todefineabasicformattingstyle,youfirstmustidentifywhichtagyouwanttoaffect.This tagisthencalledaselectorinCSS.So,ifyouwantedtospecifythestyleofallthelevel-2 headlines(<h2>)onapage,youwoulduseh2asyourselector.
h2
Infact,theselectorisessentiallythetagwithoutthebrackets.Withthatinmind,canyou guesswhattheselectorfor<p>wouldbe?
p