Download - All IT eBooks

Transcript
www.allitebooks.com
AlsobyMarkMyers
www.allitebooks.com
www.allitebooks.com
www.allitebooks.com
ASmarterWay
ToLearnHTML&CSS
Learnitfaster.Rememberitlonger.
www.allitebooks.com
MarkMyers
www.allitebooks.com
Copyright©2015MarkMyers
Allrightsreserved,includingtherighttoreproducethisbook,oranyportionsofit,inany
form.
1.0
http://www.ASmarterWayToLearn.com
www.allitebooks.com
Chapters
Learnitfaster.Rememberitlonger.
Howtousethisbook
1HTML&CSS
2Creatingparagraphs
3Creatingheadings
4Specifyingfonts
5LinkingyourCSStoyourHTML
6Specifyingafont-size
7CSSclasses
8Classesnottiedtoanelement
9Font-weight
10Font-style
11Stylingbitsandpieces
12Colors
13Spacing
14Aligningtext
15First-lineindentandblockquote
16Margins
17Borders
18Padding
19Inheritance
20Grouping
21ID
22Div
23Images
www.allitebooks.com
24Blockvs.inline
25Addingmoreinfototheimagetag
26Positioninganimage
27Centeringanimage
28Floatingimages
29Links
30Linkaddresses
31Linkingtoalocationonapage
32Openinganewwindow
33Stylinglinks
34Clickableimages
35Imagemapspart1
36Imagemapspart2
37Bulletlistsandnumberedlists
38Stylinglists
39Stylingalist’smarkers
40MoreCSSselectors
41Tables:basicstructure
42Tables:headings
43Tables:spanningcolumnsandrows
44Tables:borders
45Tables:spacingpart1
46Tables:spacingpart2
47Tables:aligningtext
48Tables:background-color
49Forms:theformtag
50Forms:textinput
www.allitebooks.com
51Forms:textarea
52Forms:submit
53Forms:radiobuttons
54Forms:checkboxes
55Forms:selectbox
56Forms:label
57Groupingrelatedelements
58Forms:styling
59Comments
60Layout:nestedboxes
61Layout:divs
62Layout:divwidthsandcentering
63Layout:side-by-sidedivs
64Layout:amodernheaderpart1
65Layout:amodernheaderpart2
66Layout:amodernheaderpart3
67Layout:amodernheaderpart4
68Layout:amodernheaderpart5
69Averticalnavigationbarpart1
70Averticalnavigationbarpart2
71Averticalnavigationbarpart3
72Averticalnavigationbarpart4
73Averticalnavigationbarpart5
74Ahorizontalnavigationbarpart1
75Ahorizontalnavigationbarpart2
76Backgroundimagespart1
77Backgroundimagespart2
www.allitebooks.com
78Iframes
79EmbeddingYouTubevideos
80FurthercustomizingYouTubevideos
81EmbeddingVimeovideos
82Audio
83Emsvs.percentagesvs.pixels
84Relativeandstaticpositioning
85Z-index
86Mediaqueries
87Min-andmax-width,min-andmax-height
88Thestuffatthetop
89Themetadescription
90Buildasite
Acknowledgements
Learnitfaster.
Rememberitlonger.
Ifyouembracethismethodoflearning,you’llgetthehangofHTMLandCSSin
lesstimethanyoumightexpect.Andtheknowledgewillstick.
You’llcatchontoconceptsquickly.
You’llbelessbored,andmightevenbeexcited.You’llcertainlybemotivated.
You’llfeelconfidentinsteadoffrustrated.
You’llrememberthelessonslongafteryouclosethebook.
Isallthistoomuchforabooktopromise?Yes,itis.YetIcanmakethesepromises
andkeepthem,becausethisisn’tjustabook.It’sabookplus1,800interactiveonline
exercises.I’vedonemybesttowriteeachchaptersoit’seasyforanyonetounderstand,
butit’stheexercisesthataregoingtoturnyouintoarealHTMLcoder.
Cognitiveresearchshowsthatreadingalonedoesn’tbuyyoumuchlong-term
retention.Evenifyoureadabookasecondorevenathirdtime,thingswon’timprove
much,accordingtoresearch.
Andforgethighlightingorunderlining.Markingupabookgivesustheillusionthat
we’reengagingwiththematerial,butstudiesshowthatit’sanexerciseinself-deception.
Itdoesn’tmatterhowmuchyellowyoupaintonthepages,orhowmanytimesyoureview
thehighlightedmaterial.BythetimeyougettoChapter50,you’llhaveforgottenmostof
whatyouhighlightedinChapter1.
Thisallchangesifyoureadlessanddomore—ifyoureadashortpassageandthen
immediatelyputitintopractice.WashingtonUniversityresearcherssaythatbeingasked
toretrieveinformationincreaseslong-termretentionbyfourhundredpercent.Thatmay
seemimplausible,butbythetimeyoufinishthisbook,Ithinkyou’llbelieveit.
Practicealsomakeslearningmoreinteresting.
Tryingtoabsorblongpassagesoftechnicalmaterialputsyoutosleepandkillsyour
motivation.Tenminutesofreadingfollowedbytwentyminutesofchallengingpractice
keepsyouawakeandspursyouon.
Anditkeepsyouhonest.
Ifyouonlyread,it’seasytokidyourselfthatyou’relearningmorethanyouare.But
whenyou’rechallengedtoproducethegoods,there’samomentoftruth.Youknowthat
youknow—orthatyoudon’t.Whenyoufindoutthatyou’realittleshakyonthispointor
that,youcanreviewthematerial,thenre-dotheexercise.That’sallittakestomasterthis
bookfrombeginningtoend.
I’vetalkedwithmanyreaderswhosaytheythoughttheyhadaproblem
understandingtechnicalconcepts.Butwhatlookedlikeacomprehensionproblemwas
1hasfadedfrommemory,howcanyouunderstandChapter50,whichdependsonyour
knowingChapter1cold?Theread-then-practiceapproachembedstheconceptsofeach
chapterinyourlong-termmemory,soyou’repreparedtotacklematerialinlaterchapters
thatbuildsontopofthoseconcepts.Whenyou’reabletorememberwhatyouread,you’ll
findthatyoulearnHTMLandCSSquitereadily.
Ihopeyouenjoythislearningapproach.AndthenIhopeyougoontosetthe
Internetonfirewithsometerrificwebpages.
Howtousethisbook
Sinceyoumaynothavelearnedthiswaybefore,abriefusermanualmightbe
helpful.
Study,practice,thenrest.Ifyou’reintentonmasteringthefundamentalsofHTML
andCSS,asopposedtojustgettingafeelforit,workwiththisbookandtheonline
exercisesina15-to-30-minutesession,thentakeabreak.Studyachapterfor5to10
minutes.Immediatelygototheonlinelinksgivenattheendofeachchapterandcode
for10to20minutes,practicingthelessonuntilyou’vecodedeverythingcorrectly.
Thentakeawalk.
Don’twearyourselfout.Youlearnbestwhenyou’refresh.Ifyoutrytocovertoo
muchinoneday,yourlearningwillgodownhill.Mostpeoplefindtheycan
comfortablycoveronetothreechaptersaday.Yourexperiencemayvary.
Ifyoufindsomeoftherepetitiontiresome,skipexercises.Iwrotetheexercisesfor
peoplelikeme,whoneedalotofrepetition.Ifyou’reafastlearneroralearnerwith
someHTMLexperience,there’snoreasontoburdenyourself.ClicktheSkip
ExerciseandGetCreditbuttontojumpahead.Skipwholesetsofexercisesifyou
don’tneedthem.Practiceasmuchasyouneedto,butnomore.
Ifyoustrugglewithsomeexercises,youknowyou’rereallylearning.An
interestingfeatureofyourbrainisthattheharderitisforyoutoretrieveapieceof
information,thebetteryourememberitnexttime.Soit’sactuallygoodnewsifyou
havetostruggletorecallsomethingfromthebook.Don’tbeafraidtorepeatasetof
exercises.Andconsiderrepeatingsomeexercisesafterlettingafewweeksgoby.If
youdothis,you’llbeusingspacedrepetition,apower-learningtechniquethat
providesevenmorelong-termretention.
Dothecodingexercisesonaphysicalkeyboard.Amobiledevicecanbeidealfor
reading,butit’snowaytocode.Very,veryfewWebdeveloperswouldattempttodo
theirworkonaphone.Thesamethinggoesforlearningtocode.Theoretically,most
oftheinteractiveexercisescouldbedoneonamobiledevice.Buttheideaseemsso
perversethatI’vedisabledonlinepracticeontablets,readers,andphones.(Italso
simplifiedmyowncodingwork.)
Ifyouhaveanauthorityproblem,trytogetoverit.Whenyoustartdoingthe
exercises,you’llfindthatIcanbeapainaboutinsistingthatyougeteverylittledetail
right.Forexample,ifyouomitasemicolon,theprogrammonitoringyourworkwill
tellyouthecodeisn’tcorrect,eventhoughitmightrun.Learningtowritecodewith
fastidiousprecisionhelpsyoulearntopaycloseattentiontodetails,afundamental
requirementforcodinginanylanguage.
Subscribe,temporarily,tomyformattingbiases.Currentcodeformattingislike
seventeenth-centuryspelling.Everyonedoesithisownway.Therearenouniversally
acceptedstandards.Butthealgorithmsthatcheckyourworkwhenyoudothe
teachercould,because,let’sfaceit,algorithmsaren’tthatbright.SoI’vehadtosettle
oncertainconventions.AlloftheconventionsIteachareembracedbyalarge
segmentofthecodingcommunity,soyou’llbeingoodcompany.Butthatdoesn’t
meanyou’llbemarriedtomyformattingbiasesforever.Whenyoubegincoding
projects,you’llsoondevelopyourownopinionsorjoinanorganizationthathasa
stylebook.Untilthen,I’llaskyoutomakeyourcodelooklikemycode.
1
HTML&CSS
AnHTML(HypertextMarkupLanguage)documentisatextfilethattellsthe
browser(Chrome,Firefox,InternetExplorer,Safari,andothers)howtoassemblea
webpage.Itsaystothebrowser,“Putthisheadinghere.Putthatparagraphthere.Insert
thispicturehere.Putthattablethere.”
Thoughitcancreatewebpageswithformattingthatissometimeselaborateandeven
beautiful,anHTMLdocumentitselfispuretext,withoutanyformattingwhatsoever.This
meansyoucan’tuseawordprocessingprogramlikeMicrosoftWordtowriteHTML,
becauseWordandotherwordprocessorsaddformatting.Instead,you’llchoosefromany
numberofeditingprogramsthatproducepuretext.ThesimplestoftheseisNotepadona
PCandTextEdit,inPlainTextmode,onaMac.Youcanalsousefancierediting
programs.AndtherearewebdevelopmenttoolslikeDreamweaver.Theyallcreatethe
puretextrequiredforHTML.MyfavoritecodeeditoristheopensourceBrackets,freeat
http://brackets.io/.
WhenIaskyoutodosomethinginBrackets,Notepad,orTextEdit,feelfreeto
substituteanyofthealternativeeditors.
EachHTMLdocumentcreatesasinglewebpageinthebrowser.Ifasitehasa
hundredpages,ithasahundredHTMLdocuments.
AnHTMLdocument’snameendswiththe.htmlextension,asinabout.htmlor
products.html.
Whenyou’relookingatawebpage,youcanseethenameofthepage’sHTML
documentinthebrowser’saddressbar.
http://www.ASmarterWayToLearn.com/htmlcss/23.html
Whenthelineofcharactersshownaboveisenteredinthebrowser’saddressbar,the
browserloadstheHTMLdocument23.html,andthatpageisassembledinthebrowser
anddisplayedontheuser’sscreen.Ifauserclicksalinkonthepagefor,say
help.html,thenthefilehelp.htmlloads,andthatpageisdisplayed.
There’soneHTMLnameyouusuallywon’tseeinthebrowser’saddressbar,
index.html.That’sthenameofthepagethatloadsbydefaultwhennoHTML
documentisspecified.It’sthesite’shomepage.Soifyouenterthisinthebrowser’s
addressbar…
http://www.asmarterwaytolearn.com
…thedocumentthatloads(withsomeexceptions)isindex.html.
AlltheHTMLdocumentsforasitearestoredonthewebhosts’sserver,or,inthe
caseofabig,importantsite,oftenonthesiteowner’sownserver.Whenthebrowseris
serveranddisplaysthatpage.
AbrowserwillalsodisplayanHTMLdocumentstoredonyourcomputer’shard
drive.Thatwillpromptyourbrowsertodisplaythepageonyourscreen.
WhereasanHTMLdocumentspecifiesthecontentsofawebpage—theheadings,
paragraphs,images,tables,etc.—ACSS(cascadingstylesheets)filespecifiesthestyling
ofthatpage—fonts,colors,columnwidths,andthelike.
LikeanHTMLdocument,aCSSfileisplaintext.Youcancreateitwiththesame
editoryouusetocreateanHTMLdocument.ACSSfilehastheextension.css.
WhenanHTMLdocumentloads,itcallstheCSSfilethatstylesitscontents.
RatherthancreatingaseparateCSSfile,it’spossibletoincludeallofthestyling
specificationsinanHTMLdocument.Butthepreferredwaytostylewebpagesistoputall
thestylinginformationinaseparateCSSfile,sothat’swhatI’mgoingtoteachyou.
ThesearetherulesI’mgoingtoaskyoutofollowfornamingbothHTMLandCSS
files:
Useonlylower-casecharacters.
Avoidspaces.
Stickto0-9,a-z,and_.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/1.html
www.allitebooks.com
2
Creatingparagraphs
Let’sgetyourfeetwet.
1. Onyourharddrivecreateafoldercalledmy-smarter-site.(Ifyou’reunclearhowto
createafolderinyourparticularoperatingsystem,Googleit.There’splentyofgood
WindowsandMacinstructionforthisonline.)
2. Underthemy-smarter-sitefoldercreateasubfoldercalledcss.(Again,ifthisisn’t
somethingyouknowhowtodo,Googleit.)
3. Online,gotohttp://asmarterwaytolearn.com/htmlcss/practice-2-0.html
4. Copyallthetextonthepage.
5. Openyourplain-texteditor(seethelastchapter)andcreateanewdocument.
6. Pastethecopiedtextintoit.
7. Savethedocumentinyourmy-smarter-sitefolderaspractice.html
8. Ontheemptylinebetween<body>and</body>typeyourname.
9. Savethefile.
10. GotoWindowsExplorer(PC)orFinder(Mac)anddouble-clickthefile.Andvoila!
There’syourname,displayedinthebrowser.You’vejustcreatedanddisplayedyour
firstwebpage.
Ifitdoesn’twork,takealookatthesamplecodeat:
http://asmarterwaytolearn.com/htmlcss/practice-2-1.html
Now,onanewline,addafewmorewordstoyourcode,soitlookslikethis.
<html>
<head>
<title>Practice</title>
</head>
<body>
MarkMyers
That’smyname.
</body>
</html>
Savethefileanddisplaythepage,followingsteps8and9above.
Samplecode,ifyouneedit,isat:
http://asmarterwaytolearn.com/htmlcss/practice-2-2.html.
MarkMyers
That’smyname.
Butthebrowserdisplayeditallononeline.
MarkMyersThat’smyname.
Theproblemisthatthebrowserdoesn’trecognizeacarriagereturn.
Whenyouhitacarriagereturninawordprocessororyourtexteditor,the
applicationbreaksthetextyouwritenextintoanewparagraph,butwhenyouentera
carriagereturninanHTMLdocument,thebrowserignoresit.Ifyouwanttodisplayyour
twosentencesintwoseparateparagraphs,youhavetoexplicitlytellthebrowsertodoit.
Youdothiswithparagraphtags.
<html>
<head>
<title>Practice</title>
</head>
<body>
<p>MarkMyers</p>
<p>That’smyname.</p>
</body>
</html>
Reviseyourpractice.htmltextdocumenttoincludethetagsshownabove.Savethe
file.Displaythepageinyourbrowser.
Ifyoucodedcorrectly,thepagewillnowdisplaythetextintwoseparateparagraphs.
Samplecodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-2-3.html.
TagsarethecommonestfeatureofanHTMLdocument.Youusethemforallkinds
ofthings.Lookatthe9linesofHTMLabove.Therearetagsoneveryline.Usually—but
notalways—HTMLtagscomeinpairs,anopeningtagpairedwithaclosingtag.The
openingtagconsistsofsomecharactersenclosedbyand>.Forexample,<p>.The
closingtagisthesameastheopeningtag,excepta/followstheopening<.Forexample,
</p>.
Theopeningtagtellsthebrowser,“Beginhere.”Theclosingtagtellsthebrowser,
“Endhere.”So,forexample,ifyouwrite…
<p>Thesedirectionsareimportant.Readthemcarefully.</p>
…you’retellingthebrowsertobegintheparagraphat“These”andtoenditat
“carefully.”
Thebrowserdoesn’tcarewhetheryouputseparateparagraphsonseparatelines.AsI
yourcode,likethis.
<p>Hi.</p>
<p>Ho.</p>
Thingstokeepinmind:
It’slegaltowrite<P>insteadof<p>butI’llaskyoutosticktolower-casetags.
Therearenospacesbetweenthetagsandthetextthattheyenclose.
Goodhousekeepingdemandsthatwheneverthebrowserexpectsaclosingtag,you
provideit.Sometimesyoucangetawaywithwriting<p>withoutclosingwith
</p>,butitcanproduceunpredictableresults.
TakegoodcareoftheHTMLandCSSfilesyoucreatedinthischapter.You’llbe
revisingthefilesonaregularbasisasyoumakeyourwaythroughthisbook.Whenyou
completethebookandfinishcodingthefiles,youwillhavetheworst-lookingwebpagein
Internethistory.Butitwillbeadetaileddemonstration—ademonstrationthatyoumade—
ofthemostimportantconceptsinHTMLandCSScoding.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/2.html
3
Creatingheadings
Aheadingonawebpageservesthesamepurposeasaheadinginanewspaperor
magazine.Itshowstheuserwhat’simportantandgivesherasenseofwhattheparagraphs
underneathitareabout.Headingsalsohelpsearchenginesunderstandapage.
HTMLgivesyousixsizesofheadingstochoosefrom,h1throughh6.h1isthe
largest,h6isthesmallest.
Youdon’thavetoincludeallthedifferentsizesofheadingsinyourHTML
document,butyoushouldincludeanh1heading,becausesearchengineslookforit.You
canhaveasmanyh2,h3,h4,h5,andh6headingsinyourdocumentasyouwant,but
youshouldhaveonlyoneh1heading.Otherwise,searchenginesmightgetconfused.
Thisishowyoucodethelargestheading.
<h1>Thisisthelargestheading.</h1>
Noticethatthere’sbothanopeningandaclosingtag.
Here’salongerone,inh3size.
<h3>Thisisalongheadingthatgoesonandonandon,butitstill
</h3>
Let’slookatanotherheading.Ifyouwrite…
<h3>Alltheking’shorsesandalltheking’smencouldn’tputHumpt
</h3>
…thebrowserwillbreakthelinesaccordingtohowmuchwidthisavailable.It
mightbreaktheheadinglikethis:
Alltheking’shorsesandalltheking’s
mencouldn’tputHumptytogetheragain.
Oritmightbreakitlikethis:
Alltheking’shorsesandalltheking’s
mencouldn’tputHumptytogether
again.
topredict,howtheheadingbreaks.Ifyou’reatallfussy,youmightwanttotellthe
browserhowtobreakit.Maybeyouwantitbrokenthisway:
Alltheking’shorses
andalltheking’smen
couldn’tputHumpty
togetheragain.
Soyoutrywriting…
<h3>Alltheking’shorses
andalltheking’smen
couldn’tputHumpty
togetheragain.</h3>
Butthiswayofwritingtheheadinghasnoeffectonthebrowser.Itstillbreaksthe
headingthewayitwantsto.Thebrowserignorescarriagereturns.
Ifyouwantthebrowsertobreaktheheadingacertainway,youhavetotellittodo
soexplicitly,usingthetag<br>.
<h3>Alltheking’shorses<br>andalltheking’smen<br>couldn’tput
</h3>
Notethatthere’snospacebetweenthetextand<br>.Andthere’snoclosingbr
tag.
Bydefault,browsersseparateparagraphsbyaddingspacebetweenthem.For
example,ifyouwrite…
<p>Slowlorisesareagroupofseveralspeciesofprimateswhichma
</p>
<p>Theyhavearoundhead,narrowsnout,largeeyes,anddistinctiv
dependent.</p>
…thetwoparagraphsmightcomeoutlookingsomethinglikethis:
Slowlorisesareagroupofseveralspeciesofstrepsirrhineprimateswhich
makeupthegenusNycticebus.
Theyhavearoundhead,narrowsnout,largeeyes,andavarietyof
distinctivecolorationpatternsthatarespecies-dependent.
nextsentence,you’dconsolidatebothsentencesintoasingleparagraphanduse<br>.
<p>Slowlorisesareagroupofseveralspeciesofprimateswhichma
<br>Theyhavearoundhead,narrowsnout,largeeyes,anddistincti
dependent.</p>
Thenitwoulddisplaylikethis:
Slowlorisesareagroupofseveralspeciesofstrepsirrhineprimateswhich
makeupthegenusNycticebus.
Theyhavearoundhead,narrowsnout,largeeyes,andavarietyof
distinctivecolorationpatternsthatarespecies-dependent.
Thebrowserdisplayseachheadingonitsownline.Thebrowserdoesn’tcare
whetheryouputeachheadingonitsownseparateline,butforhuman-readability,please
do.Forexample:
<h1>OurMission</h1>
<h2>HelpingPeopleHelpPeople</h2>
Inyourpractice.htmldocumentreplacethetwoparagraphsaboutyournamewithan
h1heading,anh2heading,andamulti-lineparagraph.Savethefileanddisplayitinyour
browser.SampleHTMLcode:
http://asmarterwaytolearn.com/htmlcss/practice-3-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/3.html
4
Specifyingfonts
Browsersdisplayheadingsandparagraphsinthefontoftheirownchoosing.Butyou
canspecifythefontyouwant.Let’sspecifyafontforparagraphs.Openyourtexteditor
andcreateanewfile.
1. Inthenewfiletype:
p{
font-family:Georgia,“TimesNewRoman”,Times,serif;
}
2. Savethefileasstyles.cssinthecsssubfolderofyourmy-smarter-site
folder.
Nowyouhavetwofiles,practice.htmlinthemy-smarter-sitefolderand
styles.cssinthecsssubfolderofthemy-smarter-sitefolder.Thingstokeep
inmind:
There’snothingsacredaboutcallingyourHMTLdocumentpractice.htmland
yourCSSfilestyles.css.Youcannamethefilesanythingyouwant,aslongas
theHTMLfilehastheextensionhtmlandtheCSSfilehastheextensioncss.
I’veaskedyoutoputtheCSSfileinasubfolderofyourmainfolder.Thisis
conventional,butnotnecessary.YoucouldputtheCSSfileinthesamefolderasyour
HTMLfileifyouwantedto,butmostdevelopersdo
Let’slookatyourCSScodeindetail.Itbeginswithp.Itmeans,“Thisisastylefor
paragraphs”—thatis,alltextenclosedbythetags<p>and</p>.
p{
font-family:Georgia,“TimesNewRoman”,Times,serif;
}
pisfollowedbyaspaceandanopeningcurlybracket.
p{
font-family:Georgia,“TimesNewRoman”,Times,serif;
}
Next,indented2spaces,isthespecification.
p{
font-family:Georgia,“TimesNewRoman”,Times,serif;
}
Noticethatit’sfont-family,followedbyacolonandaspace.Thelistoffour
www.allitebooks.com
serif,sans-serif,etc.,youneedtogivethebrowseroneormorefallbackfonts.(Ifyou’re
unclearaboutthedifferencebetweenserifandsans-seriffonts,Googleit.)Fallbackfonts
arenecessarybecausethebrowsergrabsthefontsforthewebpagefromtheuser’s
computer.Ifyourfirstfontchoiceisn’tinstalledonthecomputer,thebrowsermovesonto
yoursecond-choicefont,thenyourthird-choicefont,etc.Thestackcanlistasmanyfonts
asyoulike,butthecommonpracticeistolistthreeorfour.Thelastfallback—thelastfont
inthestack—isalwaysthegeneric,forexamplesans-serif,toguaranteethatthebrowser
willbeabletodisplaysomethinginthefamilyifnoneofyourotherchoicesisfound.Ifa
fontnamehasanyspacesinit,encloseitinquotationmarks,asin“TimesNew
Roman”.Thespecificationendswithasemicolon.
p{
font-family:Georgia,“TimesNewRoman”,Times,serif;
}
Finally,onalineofitsown,there’saclosingcurlybracket.
p{
font-family:Georgia,“TimesNewRoman”,Times,serif;
}
Websafefontsarefontsthathaveahighlikelihoodofbeingfoundontheuser’s
computer,whichmakesthemgoodtouseonyourpage.Youcanfindalistofcommon
websafefontstacksathttp://abt.cm/O7bwre.Nowlet’sspecifyadifferentfontforh1
headings.AddthiscodetoyourCSSfile.
h1{
font-family:“TrebuchetMS”,Helvetica,sans-serif;
}
YourCSSfileshouldnowincludetwostyles.
p{
font-family:Georgia,“TimesNewRoman”,Times,serif;
}
h1{
font-family:“TrebuchetMS”,Helvetica,sans-serif;
}
Savethefile.SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-4-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/4.html
5
LinkingyourCSS
toyourHTML
SincetheCSSfileisseparatefromtheHTMLfile,thebrowserhastobetoldwhere
tofindit.Thisishowyoudoit.
<html>
<head>
<title>Practice</title>
<linkrel=“stylesheet”type=“text/css”href=“css/styles.css”>
<body>
<p>MarkMyers</p>
<p>That’smyname.</p>
</body>
</html>
Thisisamouthful,solet’sbreakitdown.
First,noticethatthelinkinformationgoesbetweenthe<head>and</head>tags,
ratherthanbetweenthe<body>and</body>tags,whereyouwroteyourtwo
paragraphs.Thedifferencebetweentheheadandbodysectionsisthattheheadsection
dealswithafewtechnicalmatters—liketellingthebrowserwheretofindtheCSSfile—
whilethebodysectioncontainsthecontentofthepage.
Next,noticethatthelinkinformationitselfisatag.It’splacedinsideanopening<
andaclosing>.Butunlikealltheothertagsyouseeinthecodeabove,itisn’tpairedwith
aclosingtag.Itstandsalone.
Thelinktagconsistsofthree“equations:”Eachequationsaysthatsomethingequals
somethingelse.Thesecondsomethingisinquotationmarks.
1st“equation”:linkrel=“stylesheet”tellsthebrowserthatthelink
relationshipiswithastylesheet.
2nd“equation”:Thisisauseless,vestigialpartofthetag,likeyourappendix.We’ve
alreadytoldthebrowserthelinkistoastylesheet.Allstylesheetsendwiththeextension
“css,”andthey’realltextdocuments,sothisjustrepeatswhatthebrowsershouldalready
know.Butwestillhavetoincludeit(butmaybenotforlong).
3rd“equation”:hrefstandsforhypertextreference.Thispartofthetagtellsthe
browserwheretofindtheCSSfiletolinkto.We’veputitinthecsssubfolderofthe
folderwherethisHTMLdocumentresides,themy-smarter-sitefolder.Thefile
nameis“styles.css.”
Somethingtonoticeaboutformattinghere:Therearenospacesinthetag,except
Enterthelinktaginyourpractice.htmldocument.Saveit,andhaveyour
browserdisplaythewebpageitcreates.Expecttheparagraphstobeinaseriffontandthe
headinginasans-seriffont,asyouspecifiedintheCSSfile.FindsampleHTMLcodeat:
http://asmarterwaytolearn.com/htmlcss/practice-5-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/5.html
6
Specifyingafontsize
Let’schangethefont-sizeofyourparagraphtextandyourh1heading.Openyour
styles.cssfileandaddthetwolineshighlightedbelow.
p{
font-family:Georgia,“TimesNewRoman”,Times,serif;
font-size:1.2em;
}
h1{
font-family:“TrebuchetMS”,Helvetica,sans-serif;
font-size:2em;
}
Whenyouspecify1.2emastheparagraphfontsize,you’resaying(withoutgetting
tootechnical)thatyouwantparagraphtexttobe1.2timesthedefaulttextsize—thesize
thatthebrowserwoulddisplayifyoudidn’tspecifyasize.Ifyouspecified1em,you’dget
thedefaultsize..75emwouldbethree-quartersofdefaultsize.1.5emwouldbe150%of
defaultsize.3.5emwouldbethree-and-a-halftimesdefaultsize.Thismaycomeasa
surprise:Whenyouspecify2emastheh1size,you’renotsayingyouwanttheh1
headingtobe200%ofthedefaulth1size,but200%ofthedefaulttextsize.A2em
headingisthesamesizeas2emparagraphtext.Theheading,though,willbeboldby
defaultandtheparagraphwon’tbe.Thingstonotice:
font-size:1.2em;isindented2spaces.
Thereisnospacebetween1.2andem.
Thelineendswithasemicolon.
CodingAlternativestobeAwareOf
Insteadofspecifyingfont-sizeinems,youcanspecifyitinpercentages,pixels,or
points.Inthisprogramwe’llsticktoemsforfont-size.
SavetheCSSfile.DisplayyourHTMLfile.FindsampleCSScodeat:
http://asmarterwaytolearn.com/htmlcss/practice-6-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/6.html
7
CSSclasses
You’vespecifiedafontfamilyandafontsizeforparagraphsandh1headings.You
canalsocreateclassesofparagraphsandheadingswithformattingthatvariesfrom
generalstylingforparagraphsandheadings.Infact,youcancreateclassesofjustabout
anyelementonthepageforcustomformatting.Openyourstyles.cssfileandadd
thisstyle…
p.important{
font-size:1.5em;
}
SaveyourCSSfile.Nowyou’vecreatedspecialstylingforaclassofparagraphs.
Thisspecialstylenamed“important”willoverridethegeneralstylethatyoucreated
earlier.Whenyousayyouwanttextinparagraphsoftheclass“important”tohaveafontsizeof1.5em,you’resayingyouwantthetexttobeone-and-a-halftimesnormalsize.
Butwhatisnormalsize?Itdependsonwhetheryou’vecreatedageneralstyleinyourCSS
filethatappliestothewholepage(SeeChapter19).Ifyouhaven’tcreatedageneral
paragraphstyle,normalsizeisthebrowserdefaultsize—1em.Sothena1.5emfont-size
fortheparagraphclass“important”wouldbeone-and-a-halftimesthebrowserdefault
size.Therulesfornamingclasseswouldfillabook.Tokeepthingssimple,I’mgoingto
askyoutouselowercasealphabetletters,hyphens,underlines,andnumbers.Butdon’t
startanamewithanumber.Here’sanexampleofaclassforh3headings.
h3.bigger{
font-size:2.5em;
}
Thisclasswillbe250%ofthesizeofnormaltext.Again,“normal”means250%of
thesizeofthebrowserdefaulttextsizeifyouhaven’tspecifiedastyleforthewholepage.
Ifyouhavestyledh3headings,the“bigger”classofheadingswillbe250%ofthatsize.
SaveyourCSSfile.OpenyourHTMLfileandaddthisline…
<pclass=“important”>Warning:Wehavenoslowloriseshere.
</p>
Nowthetext“Warning:Wehavenoslowloriseshere.”willbeone-and-a-halftimes
“normal”textsize.Thingstonotice:
Theclassreferenceispartoftheopeningptag,allenclosedinbrackets.
Theclassnameisenclosedinquotationmarks.
Theclosingparagraphtagdoesn’tchange.It’sstill</p>.
Note:Thesameclasscanbeassignedtoanynumberofelements.Andyoucan
Here’sanexample.
<h3class=”specialconspicuousenhanced“>Heynow!<h3/>
Let’ssayyou’vecreatedaclassnamed“special”thatspecifiesafontsize,asecond
classcalled“conspicuous”thatdisplaysitinred,andathirdclasscalled“enhanced”that
specifiesafont-weightofbold.Intheexampleabove,allthreeclasseswillapplytothe
heading.Itwillbeextra-large,red,andbold.
Saveyourfiles.Displaythepage.
SampleCSScode:
http://asmarterwaytolearn.com/htmlcss/practice-7-1.html.
SampleHTMLcode:
http://asmarterwaytolearn.com/htmlcss/practice-7-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/7.html
www.allitebooks.com
8
Classesnottied
toanelement
Ifyouintendtodefineaparticularclassforonlyonetypeofelement—forexample,
onlyparagraphtextoronlyh3headings—writetheelementnamebeforethedotandclass
name,asin…
p.special{
…or…
h3.special{
Ifyouwantaclasstobeuseableformorethanonetypeofelement—forexample,
bothparagraphtextandheadings—omittheelementname.Justwrite,forexample…
.special{
OpenyourCSSfileandaddthestylebelow.
.typewriter{
font-family:“CourierNew”,Courier,monospace;
}
You’vecreatedanewstylenamed“typewriter”thatwillstyletextinatypewriter
font.Itcouldbeparagraphtext.Itcouldbeheadingtext.Itcouldbeotherkindsoftext
elementsthatI’llintroduceyoutolater.
Noticethatthere’snoelementname,likeporh3,involvedhere.It’sjustadotwith
theclassnamefollowingit.Savethefile.
OpenyourHTMLfileandaddthecodebelow.
<h2class=“typewriter”>Thisheadingisintypewritertext.
</h2>
<pclass=“typewriter”>Thisparagraphisalsointypewritertext.
</p>
You’veassignedtheclass“code”toaheadingandaparagraph.SinceyourCSSfile
doesn’ttietheclasstoanyparticularelement,youcanuseitforanytextelement.
SavetheHTMLfileanddisplayit.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-8-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-8-2.html.
http://www.ASmarterWayToLearn.com/htmlcss/8.html
9
Font-weight
InChapter7youcreatedaparagraphclasscalled“important,”andspecifiedafont
sizeone-and-a-halftimes“normal.”Nowlet’smakeparagraphsclassedas“important”
evenmoreimportant.We’llboldthem.
OpenyourCSSfileandaddthelinehighlightedbelow.
p.important{
font-size:1.5em;
font-weight:900;
Byspecifyingafont-weightof900,you’retellingthebrowsertomakeallthe
paragraphsoftheclassimportantasboldaspossible.Thescaleforfont-weightranges
from100through900—100,200,300andsoon.100isthelightestweight.400isnormal.
900isasheavyasitgets.
Now,whenthebrowserencountersaparagraphoftheimportantclass,itwill
displayitlargerandinboldface.
Anoteaboutfont-weight:Asanalternativetothenumericalscale,youcanuseone
offourfont-weightwords:lighter,normal,bold,andbolder.
SaveyourCSSfile.DisplayyourHTMLfile.“Warning:Wehavenoslowlorises
here.”shouldnowbeinbold.
FindsampleCSScodeat:
http://asmarterwaytolearn.com/htmlcss/practice-9-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/9.html
10
Fontstyle
Youcanspecifyitalicsforanytext.Here’saclassthatappliesitalicstoaparagraph.
p.standout{
font-style:italic;
}
Here’saclassthatappliesitalicstoh4headingsoftheclass“special”.
h4.special{
font-style:italic;
}
Here’saclassthatappliesitalicstoanytext,whetherit’saparagraph,heading,or
someothertextelement.
.emphasized{
font-style:italic;
}
Remember,classnamescanbeanythingyoulike,withintheboundsofthenaming
rulesIcoveredinChapter7.
InsteadofdefiningCSSclassestoitalicizetext,youcanusethe<i>taginyour
HTML.
Inthefollowingparagraph,thewords“DavidCopperfield”areitalicized.
<p>Leadingstylemanualssaybooktitles,like<i>DavidCopperfield
</p>
Analternativetothe<i>tagisthe<em>tag.
<p>Youmustbedressed<em>and</em>readytogo.</p>
Bydefault,the<em>taghasthesamevisualeffectasthe<i>tag.Theyboth
italicizetext.Themaindifferenceisthatwhenascreenreaderseesthe<em>tag,itputs
extravocalemphasisonthetextenclosedinthetag.Itdoesn’tdothatwith<i>text.
InsteadofcreatingaclassforboldtextinCSS,youcanusethe<b>taginHTML.
Inthefollowingparagraphthetext“Pleasenote:”isbolded.
<p><b>Pleasenote:
</b>Theflightscheduleissubjecttochangewithoutnotice.
</p>
Analternativetothe<b>tagisthe<strong>tag.Bydefault,the<strong>tag
hasthesamevisualeffectasthe<b>tag.Theybothboldtextinmostbrowsers.Themain
textinalowertone.Itdoesn’tdothatwith<b>text.
InyourCSSfile,addaclassnottiedtoanelementthatitalicizestext.InyourHTML
filecodeaheadingofthatclass.Thenwriteaone-sentenceparagraph.Intheparagraph,
usethetwoHTMLtagsthatitalicizetextandthetwoHTMLtagsthatboldtext.Savethe
filesanddisplayyourHTMLfile.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-10-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-10-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/10.html
11
Stylingbitsandpieces
Sofaryou’vebeenusingCSStostylewholeblocksoftext—paragraphsand
headings.Butyoucanalsostylebitsandpiecesofthoseblocksusingthe<span>tag.
Let’sgobacktotheemphasizedclassfromthelastchapter.
.emphasized{
font-style:italic;
}
Sincetheclass,asyoudefinedit,isn’ttiedtoanyparticulartextelement—itisn’t
p.emphasizedorh5.emphasizedbutjust.emphasized—itcanbeappliedto
anytextyouchoose,includingpartofaparagraphorheading.Inthefollowingparagraph
thewords“somuch”areitalicized.
<p>Iloveyou<spanclass=“emphasized”>somuch</span>Ihavetouse
</p>
InyourHTMLfileitalicizeaportionoftheparagraphyoucreatedinthelastchapter,
usingaspanclassof“emphasized.”SaveyourHTMLfileanddisplayit.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-11-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/11.html
www.allitebooks.com
12
Colors
Let’ssayyouwanttodisplaycertaintextinred.We’llcalltheclassstandout.
.standout{
color:#cc0000;
}
Youcould,ofcourse,tietheclasstoatextelement.Itcouldbep.standoutor
h2.standout,forinstance.Butwe’llmakeitanall-purposeclasssowecanuseitfor
anytypeoftextelement.Hereitis,appliedtoasinglehyphenatedword.
<p>Thisisgoingtobea<spanclass=“standout”>redletter</span>day!</p>
Hereitis,appliedtoawholeparagraph.
<pclass=“standout”>Pleasereadthischaptercarefully.There<em>w
</p>
Andhereitis,appliedtoaheading.
<h1class=“standout”>RobotsthatCare</h1>
IntheCSSclassasIdefinedit,thecolorisspecifiedbyahexvalue,#cc0000.You
canalsousenamesfromtheCSSlistofcolors,likered,gold,and
mediumslateblue.Gethexvaluesforcolorsathttp://www.colorpicker.com/.Geta
listofCSScolornamesathttp://www.crockford.com/wrrrld/color.html.
InyourCSSfilecreateaclassnottiedtoanelementthatcolorstextred.Inyour
HTMLfileuseaspantocolorsometextred.SavethefilesanddisplayyourHTMLfile.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-12-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-12-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/12.html
13
Spacing
Youcancreatestylesfortextspacing.Let’ssayyourh2headingnormallylookslike
this.Signupforthecoursenow.Ifyoucreatethisstyle…
h2{
letter-spacing:.1em;
}
…theh2headingwouldaddextraspacebetweentheletters.Itwouldlooklike
this…
Signupforthecoursenow.
Notethatwhenyouspecifyanemvalueforletter-spacing,ittellsthebrowserhow
muchmorespaceyouwantbeyondthenormalspacing.Orhowmuchless.Lookatthis
style.
h2{
letter-spacing:-.05em;
}
Thecodeabovetightensthespacebetweenletters,sotheheadinglookslikethis…
Signupforthecoursenow.
Ifyouwantedtousedefaultletter-spacing,you’dwrite…
h2{
letter-spacing:0;
}
Letter-spacingdoesn’tdistinguishbetweencharactersinthemiddleofawordand
charactersthatbeginorendaword.Thismeansthatletterspacingadjuststhespacenot
onlybetweencharactersinawordbutalsobetweenthelastcharacterofawordandthe
firstcharacterofthenextword.Ifyouincreaseletter-spacing,thespacingbetweenwords
increasesautomatically.Ifyoucomparethethreeexamplesabove,you’llseethatspace
hasopenedupbetweenwordsinthefirstandsecondexamples.
Ifyouwanttoadjustspacingonlybetweenwords,useword-spacing.
I’llexaggeratetheword-spacingsoyoucanclearlyseeit.
word-spacing:1em;
}
TheCSSabovestylestheheadingtolooklikethis.
Signupforthecoursenow.
Youprobablywon’tuseword-spacingveryoften.Themostcommonuseforitisto
slightlyopenupthespacebetweenboldedwords,forbetterreadability.
Youcanspecifythespacingbetweentextlines,knownintheanalogworldas
“leading,”byusingline-height.
Here’saparagraphwithnormalline-height.
Slowlorisesareagroupofseveralspeciesofstrepsirrhineprimateswhichmakeupthegenus
Nycticebus.Theyhavearoundhead,narrowsnout,largeeyes,andavarietyofdistinctivecoloration
patternsthatarespecies-dependent.
Supposeyoucreatethisstyle.
p.more-readable{
line-height:2em;
}
AnyparagraphintheHTMLfileassignedtheclass“more-readable”wouldlooklike
this.
Slowlorisesareagroupofseveralspeciesofstrepsirrhineprimateswhichmakeupthegenus
Nycticebus.Theyhavearoundhead,narrowsnout,largeeyes,andavarietyofdistinctivecoloration
patternsthatarespecies-dependent.
Inthecaseofline-height,1.2emmeansnormallinespacing.1.8emwouldbe
roughlyanextrahalf-lineofspacing.1emwouldbeslightlytighterspacingthannormal.
InyourCSSfilecodeaparagraphclassthatincreasesletter-spacing,word-spacing,and
line-height.
InyourHTMLfilecodeaparagraphandassignitthatclass.Savethefilesand
displayyourHTMLfile.SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-13-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-13-2.html.
http://www.ASmarterWayToLearn.com/htmlcss/13.html
14
Aligningtext
Youcancenter,left-align,right-align,andjustifytext.Thiscodecentersh1
headings…
h1{
text-align:center;
}
Anh1headingthatwouldnormallylooklikethis…
HydrogenSkateboards
…nowlookslikethis…
HydrogenSkateboards
Left-alignedisthedefaultstyleforHTMLtext.Butyoucanmakeitexplicit:
p{
text-align:left;
}
Supposeyouwanttoplaceadateallthewayovertotheright.Youcouldwrite…
.date-style{
text-align:right;
}
Textassignedthatclasswouldlookthisthis.(Lookforthedatewayoveronthe
right.)
July1,2018
Here’saparagraphinthedefaultleft-alignedstyle.
Slowlorisesareagroupofseveralspeciesofstrepsirrhineprimateswhichmakeupthegenus
Nycticebus.Theyhavearoundhead,narrowsnout,largeeyes,andavarietyofdistinctivecoloration
patternsthatarespecies-dependent.FoundinSoutheastAsiaandborderingareas,theyrangefrom
ChinainthenorthtotheislandofJavainthesouth.
Noticethattherightsideis“ragged.”
Ifyouwanttoevenitup,youcouldcreateastyle…
p.pretty{
text-align:justify;
}
Aparagraphassignedtheprettyclasswouldhaveanevenrightedge,likethis.
Slow lorises are a group of several species of strepsirrhine primates which make up the genus
Nycticebus. They have a round head, narrow snout, large eyes, and a variety of distinctive coloration
patterns that are species-dependent. Found in Southeast Asia and bordering areas, they range from
BangladeshandNortheastIndiainthewesttothePhillipinesintheeast,andfromYunnanprovincein
ChinainthenorthtotheislandofJavainthesouth.
InyourCSSfilecodeallh3headingssotheycenter.Createaclassofparagraphs
thatjustifiestheparagraph.InyourHTMLfilecodeacenteredheadingandajustified
paragraph.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-14-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-14-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/14.html
15
First-lineindent
andblockquote
Bydefault,browsersdon’tindentthefirstlineofaparagraph.Thefollowing
paragraphshowshowthebrowserdisplaysaparagraphifyoudon’ttellittodisplayit
differently.
Slowlorisesareagroupofseveralspeciesofstrepsirrhineprimateswhichmakeupthegenus
Nycticebus.Theyhavearoundhead,narrowsnout,largeeyes,andavarietyofdistinctivecoloration
patternsthatarespecies-dependent.
Butyoucanspecifyafirst-lineindent.
p{
text-indent:1em;
}
Sonowaparagraphwouldhaveafirst-lineindent,likethis.
Slowlorisesareagroupofseveralspeciesofstrepsirrhineprimateswhichmakeupthegenus
Nycticebus.Theyhavearoundhead,narrowsnout,largeeyes,andavarietyofdistinctivecoloration
patternsthatarespecies-dependent.
Notethatanypositiveemvaluegivesyouanindent.Thelargerthevalue,thedeeper
theindent.
Toexplicitlyspecifythedefault,nofirst-lineindent,youcouldwrite…
p{
text-indent:0;
}
Youuseblockquotetovisuallysetoffaquotationthat’smorethanafewwordslong.
Bydefault,anyparagraphplacedinsideblockquotetagsisindented,likethis.
Weholdthesetruthstobeself-evident,thatallmenarecreatedequal,thattheyareendowedbytheir
CreatorwithcertainunalienableRights,thatamongtheseareLife,Libertyandthepursuitof
Happiness.
ThisistheHTML.
<blockquote><p>Weholdthesetruthstobeselfevident,thatallmenarecreatedequal,thattheyareendowedbyth
www.allitebooks.com
Youcanenclosemorethanoneparagraphinblockquotetags.Youcanenclose
headings,too.Andifyoudon’tlikethedefaultblockquotestyling,youcanchangeitin
yourCSS.Forexample,thiscodeincreasesthesizeofthetextanddisplaysthetextin
gray.
blockquote{
font-size:1.4em;
color:darkslategray;
}
Youcanevenincreaseoreliminatetheamountofblockquoteindent.That’sinthe
nextchapter.
InyourCSSfilecodeaclassofparagraphsthatindentsthefirstline.Thencodea
blockquotethatdecreasesthetextsizeandcolorsthetextgray.InyourHTMLfilecodea
paragraphthatindentsthefirstline.Thencodeaparagraphinsideblockquotetags.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-15-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-15-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/15.html
16
Margins
Youcanputmarginsaroundparagraphs,headings,andmanyotherHTMLelements.
Amargincreatesextrawhitespacearoundthetop,bottom,orsidesofanelement.For
example,ifyouhaveaparagraphthatwouldnormallylooklikethis…
Slowlorisesareagroupofseveralspeciesofstrepsirrhineprimateswhichmakeupthegenus
Nycticebus.Theyhavearoundhead,narrowsnout,largeeyes,andavarietyofdistinctivecoloration
patternsthatarespecies-dependent.
…addingaleftmarginwouldaddwhitespaceontheleft,likethis…
Slowlorisesareagroupofseveralspeciesofstrepsirrhineprimateswhichmakeupthegenus
Nycticebus.Theyhavearoundhead,narrowsnout,largeeyes,andavarietyofdistinctive
colorationpatternsthatarespecies-dependent.
Andaddingarightmargin,inadditiontoaleftmargin,wouldaddwhitespaceonthe
right,likethis…
Slowlorisesareagroupofseveralspeciesofstrepsirrhineprimateswhich
makeupthegenusNycticebus.Theyhavearoundhead,narrowsnout,large
eyes,andavarietyofdistinctivecolorationpatternsthatarespeciesdependent.
Ifyouwanted,youcouldspecifytopand/orbottommarginstoaddwhitespaceabove
and/orbelowtheparagraph.
Here’ssomeCSScodethatcreatesaclassofparagraphsthatI’venamedoffsetthat
addsmarginspaceallaroundthetext.Theamountofwhitespaceistwotimesthesizeof
defaulttext.
p.offset{
margin:2em2em2em2em;
}
Amoreconcisewaytocodeequalmarginsonallfoursides…
p.offset{
margin:2em;
}
Whenyou’respecifyingallfourmarginsinonestatement,youspecifythemin
defaulttext,aleftmargin1.75thesizeofthefont,andnomarginsonthetoporbottom.
You’dwrite…
p.offset{
margin:02em01.75em;
}
Notethatwhenyouwantnomargin,youwrite0,not0em.
Ifyouwanttoaddspacebetweenparagraphs,insteadoforinadditiontoafirst-line
indent,specifyabottommargin.Thiscodeaddsspacebetweenparagraphs.
p{
margin:001em0;
}
Insteadofspecifyingallfourmargins,youcanspecifyindividualmargins.An
alternativetotheexampleaboveis…
p{
margin-bottom:1em;
}
Youcanalsospecifymargin-top,margin-right,andmargin-left.
AddaclassofparagraphstoyourCSSfilethathasextrawhitespaceallaroundit.
ThenaddaparagraphtoyourHTMLdocumentthat’sinthisclass.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-16-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-16-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/16.html
17
Borders
Youcanputaborderaroundaparagraph,aheading,andmanyotherHTML
elementsthatI’llintroduceyoutoinlaterchapters.Thefollowingcodedemonstratesthe
simplestwaytospecifyaborder.(Imadeuptheclassname.Youcouldmakeupa
differentname.)
p.boxed{
border:5pxsolidred;
}
Nowanyparagraphwiththeclassboxedassignedtoitwillhavea5-pixel-wide,
solid,redborderonallfoursides.
Asusual,youdon’thavetotiethestyletoaparticularelement,likeaparagraphor
heading.Youcanwrite,forinstance…
.enclosed{
border:1pxdotted#0000ff;
}
Nowanyelementwiththeclass“enclosed”assignedtoit—paragraph,heading,or
somethingelse—willhavea1-pixel-wide,dotted,blueborderonallfoursides.
Youcanchooseamong8borderstyles:
dotted
dashed
solid
double
groove
ridge
inset
outset
Thingstokeepinmind:
There’snospacebetweenthenumberandpx.It’s2px,not2px.
Youcanusehexvalueslike#ff00fforcolornameslikebluetospecifycolors.
Gethexvaluesforcolorsathttp://www.colorpicker.com/.GetalistofCSScolor
namesathttp://www.crockford.com/wrrrld/color.html.
them,butnocomma.
Youaren’tlimitedjustto4-sidedborders.Youcanspecifywhichsidesyouwant,
andcanevenmixwidths,styles,andcolorsondifferentsidesofthesameborder(though
thiswouldn’tnecessarilybeconsideredgoodgraphicdesign).Herearesomeexamples.
border-top:4pxdoublered;
border-right:2pxsolid#666666;
border-bottom:6pxdasheddarkviolet;
border-left:1pxdotted#00ee44;
InyourCSSfileaddaclassnottiedtoanelementthatspecifiesaborder.Inyour
HTMLfilewriteaheadingofthatclass.Savethefilesanddisplaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-17-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-17-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/17.html
18
Padding
Whenyouputaborderaroundaparagraph,heading,orotherelement,you’lloften
wanttoaddbreathingroom—whitespace—betweentheborderandwhat’sinsideit.To
addafewpixelsofwhitespaceallaround,forexample,youcouldwrite…
p.boxed{
border:5pxsolidred;
padding:.1em;
}
Thehighertheemvalue,thewiderthegapbetweentheborderanditscontent.
Tospecifygapsofdifferentwidthsfordifferentsides:
p.boxed{
border:5pxsolidred;
padding:.1em.2em0.3em;
}
Thecodeabovespecifiesasmallgapatthetop,alargergapontheright,nogapat
thebottom,andthelargestgapontheleft.
Likecodeformargins,thenumbersstartatthetopandgoclockwise.
Youcanalsospecifypaddingforindividualsides.Thefollowingcodeduplicatesthe
effectofthemoreconcisecodeabove.
p.boxed{
border:5pxsolidred;
padding-top:.1em;
padding-right:.2em;
padding-bottom:0;
padding-left:.3em;
}
Ifyou’regoingtospecifypaddingforallfoursides,themoreconcisecodeis
preferable.Butifyouwanttospecifypaddingforjustoneortwosides,youmightprefer
theindividualspecifications.
ReviseyourCSSfiletoincludesomepaddingintheclassthatspecifiesaborder.
Savethefile.DisplayyourHTMLfile.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-18-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/18.html
www.allitebooks.com
19
Inheritance
InheritanceisanefficiencyfeatureofCSS.Itmeansyouhavetowritefarlesscode.
Inordertounderstandinheritance,youneedtounderstandthatanHTMLpageis
organizedintoparentsandchildren.Achildelementofaparentelementisanyelement
that’senclosedbytheparentelement.
Let’sstartwiththeuber-parent.InanHTMLdocument,theparentofallthecontent
thatdisplaysonthepageis<body>.Everythingonthepageisachildof<body>,
becauseeveryelementisenclosedbythe<body>tags.(Both<head>and<body>
haveaparent,<html>,butwe’renotconcernedwiththatnow.)
LookatthesimplifiedwebpagefromChapter2.
<html>
<head>
<title>Practice</title>
</head>
<body>
<p>MarkMyers</p>
<p>That’smyname.</p>
</body>
</html>
Thetwoparagraphs,likeeverythingelsewemightaddtothepage,areenclosedby
theopeningandclosing<body>tags,sotheyareallchildrenof<body>.Asthebody
element’schildren,theyinheritalltheCSSpropertiesofthatelement.So,forexample,if
westylethebodyelementlikethis…
body{
font-family:Georgia,“TimesNewRoman”,Times,serif;
font-size:1.2em;
color:darkslategray;
}
…allthetextonthepagewilldisplayinGeorgiaoroneofthealternatives,at1.2
timesthedefaultsize,andingray.ParagraphswillbeinGeorgiaoroneofitsalternatives.
Sowillheadings.Alltextwillbebasedona“normal”textsizeof1.2timesthebrowser’s
defaulttextsize.Alltext,whetherparagraphsorheadings,willbegray.Unless…
…youoverridetheinheritance.
Forexample,ifyouincludethisstyleinyourCSS…
h2{
font-family:“TrebuchetMS”,Helvetica,sans-serif;
…itoverridestheinheritedfont-family,Georgiaoritsrelatives,andstylesallh2
headingsinTrebuchetoritsrelatives.Sinceyouhaven’tspecifiedanyoverridingstyles
forsizeorcolor,theh2headingswillinheritthesestylesasspecifiedfortheparent,the
bodyelement.h2headingswillbe120%thesizeofthedefaultforh2headings,and
they’llbegray.Ofcourse,youcanoverridetheseinheritedstylesaswell,forexample:
h2{
font-family:“TrebuchetMS”,Helvetica,sans-serif;
font-size:.5em;
color:black;
}
Nowwe’veoverriddenalltheinheritedstyles.
Whenyouoverrideaninheritedsizewithanemvalueasinthecodeabove,thenew
emvalueisrelativetotheinheritedsize.Thestylethattheh2headinginthecodeabove
inheritsfromthebodyelementis1.2em—1.2timesthedefaulttextsize.Sowhenwe
styletheh2headingat.5em,we’resaying,“Makeh2headingshalftheinheritedsize.”
Theinheritedsize,thankstothestyleofthebodyelement,is1.2timesthedefaultsize.
Halfofthatsize,specifiedby.5em,is.6timesthedefaultsize.
That’sprettyconfusing,whichiswhymanydevelopersspecify1emforfont-sizein
thebodystyle.Thatmakesitclearthatallemvaluesspecifiedforotherelementswillbe
relativetothebrowser’sdefaultsize.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/19.html
20
Grouping
Youcangroupelementsthatshareoneormorestylecharacteristics.Forexample,if
h1,h3,andh5headingsarealltobeintheArialfontoroneofitsrelativesandyouwant
themallcentered,youcanwrite…
h1,h3,h5{
font-family:Arial,Helvetica,sans-serif;
text-align:center;
}
Nowallthreetypesofheadingssharethesamefont-familyandtextalignment.
Thisdoesn’tpreventyoufromindividuallystylingtheseelementswithother
characteristics.Forexample,ifyouwanth1andh5headingsinonecolorandh3
headingsinanothercolor,youcouldaddthiscode…
h1,h5{
color:#333333;
}
h3{
color:#999999;
}
Nowallthreeheadingtypessharethesamefont-familyandtextalignment.h1and
h5headingsareonecolor.Andh3headingsareanothercolor.
InyourCSSfilegrouph4headingsandaclassofparagraphsthatcenter.Inyour
HTMLfilecodeanh4headingandaparagraphofthatclass.Savethefilesanddisplay
thepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-20-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-20-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/20.html
21
ID
AtthispointyoushouldbeclearaboutCSSclasses.Theycanbetiedtoanelement,
likethis.
p.extra-special{
font-style:italic;
}
Ortheycanbeforgeneraluse—thatis,nottiedtoanyparticularelement,likethis.
.extra-special{
font-style:italic;
}
InHTMLyouassignaclasstoanelementlikethis.
<pclass=“extra-special”>DailySpecial<p/>
Aclasscanbeassignedtoanynumberofelements.Andanelementcanbeassigned
anynumberofclasses.Ifyouhaveaparagraphclass,itcanbeassignedtoathousand
differentparagraphsifyoulike.Ifyouhaveaclassthatisn’ttiedtoaparticularelement,it
canbeassignedtodifferentkindsofelements.
Anidislikeaclass,butmoreexclusive.ItcanbeassignedonlyonceinanHTML
document.Andanelement,thoughitcanhavemanyclasses,canhaveonlyoneid.
Forexample,supposeyou’restylingaparagraphthatcontainsamissionstatement.
Thisparticularstylingwon’tbeusedforanyotherparagraph.Youcouldstylethisspecial
paragraphwithaclass,butitwouldbeclearer,fromahumanpointofview,tosingleitout
asuniquebyassigningitanid.
Thefollowingcodecreatesanidandstylingforthemissionstatement.
p#mission-statement{
font-family:“TimesNewRoman”,Times,serif;
font-size:1.2em;
color:darkblue;
}
NotethatintheCSSthesyntaxyouusetodefineidsisexactlythesameasfor
classes,exceptthata#replacesthedot.
Thefollowingcodecreatesaheadingid.
Thefollowingcodecreatesanidthatcanbeusedforaparagraph,aheading,orother
elementsthatyou’lllearnaboutlater.Butremember,anyid,includingthisone,shouldbe
usedonlyonceonanyHTMLpage.Forexample,ifyouuseitforaparagraph,don’tuseit
foranotherparagraph,aheading,oranyotherelementonthepage.
font-size:1.5em;
font-style:italic;
}
Here’sanexampleofHTMLthatassignsanidtoanelement.
<pid=“whatever”>Thisparagraphhasauniqueid.</p>
IntheHTMLthesyntaxisexactlythesame,exceptthatyoureplaceclasswith
id.
idsareimportantinHTML,buttheyplayanevenlargerroleinJavaScript,asyou’ll
learninmybookASmarterWaytoLearnJavaScript,availableatAmazon.
InyourCSSfilecodeanh2idthatcolorstheheadingorange.InyourHTMLfile
codeaheadingwiththatid.Savethefiles.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-21-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-21-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/21.html
22
Div
Youcanbreakupawebpageintosections,calleddivs.Eachofthesedivscanhave
itsownstyling,usingeitheraclassoranid.Coderscommonlycreateseparatedivsfor
headers,navigationbars,maincontent,andfooters.Here’ssomecodethatcreatesadiv
forthemaincontentofthepage.Sincetherewouldbeonlyonesuchsection,Iuseanid
ratherthanaclass.
div#main{
font-size:1.1em;
margin:.1em.2em.2em.2em;
}
Here’stheHTMLthatassignstheid.
<divid=“main”>
<h2>Here’sthewholestory.</h2>
<p>It’ssoft.</p>
<p>It’sfluffy.</p>
</div>
Allelementswithinthisdivwillbecontainedinasectionthathasamarginoneach
side.Unlessyou’vewrittenoverridingCSScodethatchangesthefont-sizeofcertaintext
elements,allelementsinthediv,whicharechildrenofthediv,willbe110%of
“normal”size(howeveryou’vedefined“normal”whenyoustyledthebody).Ifthose
individualtextelementsarestyledsmaller(lessthan1em)orlarger(morethan1em)than
normal,they’llbescaledupordowninrelationtothe1.1emspecifiedforthediv,notthe
“normal”specifiedforthebody.Soifyouspecified1em(thebrowser’sdefaultsize)for
thebody,1.1emforthediv,and1.5emforh3headings,theheadingswillbe150%of
110%ofthebrowser’sdefaulttextsize.
Notethatthe<div>tagisclosed,andthattheelementsthatareenclosedbythe
<div>tagsareindented2spaces,sincethey’reallchildrenofthediv.
Whenyou’restylingadivthatappearsonlyonceonthepage,likethenavigation
section,maincontent,orfooter,it’sbesttocreateanidratherthanaclassforit.Ifthere’sa
possibilityadivstylemaybeusedmorethanonce,defineaclass.Forexample:
div.special{
margin:.1em.5em.1em.5em;
}
Anydivassignedthe“special”classwillhaveextramarginsontheleftandright.
Theresultisthatitwillbeinset.
AddadividtoyourCSSfile.Giveit3emleftandrightmargins.Assignitthefont
divcodeaheadingandparagraph.Savethefilesanddisplaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-22-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-22-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/22.html
23
Images
Imagesonawebpagearealmostalwaysoneofthreetypes:jpg,gif,orpng.Ineach
case,thethreeinitialsrefertothefileextensionthatdenotestheimageformat.Thejpg
formatisbestforphotographsandforillustrationswithmanysubtlecolors.Thegifformat
canbeusedforlinedrawings,illustrationswithjustafewcolors,andimagesoftext.Gifs
offertransparency,meaningthatthebackgroundcolorcanshowthroughwhereveryou
wantitto.Gifscanbeanimated.Unlessyouneedanimation,thegifformatisrarelyyour
bestchoice.Thepngformatisbetter.Ithasthesamegeneralfeaturesasgif,buthasno
animation.It’spreferredovergifbecauseitgivesyouhigherqualitythanagifandina
smallerfilesize.Asmallerfilesizemeanspagesloadfaster.
AnHTMLfiletellsthebrowserwhichimagestoplaceonthepageandwhereto
placethem,buttheimagesthemselvesaren’tpartoftheHTMLfile.They’reindividual
jpg,gif,orpngfilesthatcanbestoredanywhereontheInternet.Inpractice,they’re
usuallyplacedinasubfolderunderthesite’smainfolder.Thenamemostoftenusedfor
thesubfolderis“images.”
Let’sassumethatyoursite’simagesareinthe“images”subfolderofyoursite’smain
folder.Thisishowtoplaceanimagecalled“founder.jpg”onyourpage.
imgsrc=“images/founder.jpg”>
imgsrcstandsfor“imagesource.”Ittellsthebrowserwheretofindtheimage.
Anequalsigncomesnext.Thenthere’sthepathandfilename,allinquotes.
Thereisnoclosingtag.
InthenormalflowofHTMLcode,animagewillbeplacedonthepageinthesame
locationasitappearsinthecode.Forexample,inthefollowingcode…
<h3>Ourfounder</h3>
<imgsrc=“images/founder.jpg”>
<p>Ourfounderisnolongerwithus,alas.<p/>
…thephotoappearsundertheheadingandbeforetheparagraph.
Youcan,althoughoftennotlegally,displayanimagefromanotherwebsite.Inthat
case,youhavetoincludethewholeURL.
<imgsrc=“http://www.asmarterwaytolearn.com/surprise.jpg”>
Thefollowingdisplaysanimagestoredinthesubfolder“pics”ofmywebsite.
<imgsrc=“http://www.asmarterwaytolearn.com/pics/loris.jpg”>
UnlessyoutellitotherwiseinyourCSSfile,thebrowserwillplaceanimageallthe
wayoverontheleft.Later,you’lllearnhowtoplaceitwhereyouwantit—forexample,
inthecenterofthepage.
http://www.asmarterwaytolearn.com/loris.jpg.
Savethefileanddisplayit.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-23-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/23.html
24
Blockvs.inline
MostmajorHTMLelements—headings,paragraphs,lists,tables,anddivs—are
blockelements.Whenanelementisablockelement,itmeansthebrowserdoesn’tputany
otherelementbesideit.Ifyouwriteaheading,thenaparagraph,thenalist,theheading
willbeginonanewline.Theparagraphwillbeginonanewline.Thelistwillbeginona
newline.
Blockelementscanbeplacedside-by-side,butonlyifyouspecifyspecialstyling.
Divsareblockelements,butweplacethemside-by-sideallthetimeusingsomething
calledfloat,forexamplewhenweplaceasidebarnexttoacontentsection.You’lllearn
moreaboutthislater.
Allblockelementsinsideadivowntheirownhorizontalspaceonlyinsidethatdiv.
IfyourCSSspecifiesthattwodivsaretobeplacedside-by-side,thenofcourseelements
ofonedivwillsitnexttoelementsoftheotherdiv.It’llbeliketwocolumns,witheach
elementhavingitsownhorizontalspace,butonlywithinitscolumn.
Inadditiontostartingeachblockelementonanewline,thebrowserwilladdextra
spacebetweenthem.Lateryou’lllearntoadjustthisspaceusingCSS.
Inlineelementsdon’tstartonanewline.Forexample,alinkisaninlineelement.If
youwrite…
<p>Tofindthecolorthatcomplementsyourcomplexion,tryour
picker.html”>ColorPicker</a>.</p>
…theahrefelementdoesn’tstartonanewline.That’sgood,becauseyouwantit
tobepartofthesentenceflow,notsetoff.
Youmayfinditsurprisingthatimagesareinlineratherthanblockelements.Ifyou
write…
<imgsrc=“pic-1.jpg”>
<imgsrc=“pic-2.jpg”>
<imgsrc=“pic-3.jpg”>
…thethreeimageswillbearrayedacrossthediv,ifthere’sroomforthemall.
YoucanconvertimagesintoblockelementsusingCSS.
img.owns-its-own-line{
display:block;
}
Nowanyimageassignedtotheclass“owns-its-own-line”won’tsharehorizontal
spacewithotherimages.
assignthatclasstothelorisimagethatyou’vealreadycoded.Thenduplicatethatimage
tag.Nowyouhavetwoimagesoftheloris.Savethefilesanddisplaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-24-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-24-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/24.html
25
Addingmoreinfo
totheimagetag
Inthelastchapteryoulearnedtowritetheminimalamountofcodeforplacingan
imageonthepage.
<imgsrc=“images/founder.jpg”>
Thistaggivesthebrowserthenameoftheimagefileandthepathwhereit’sstored.
Thatwillgetthejobdone.Inpractice,though,you’llwanttowriteamoreelaboratetag.
<imgsrc=“images/founder.jpg”alt=“Ourfounder”width=“55”height=“
Thealtspecificationprovidesawordorafewwordsthatdescribetheimage.It’s
thetextalternativetotheimage,whichthebrowsermaydisplayincasethebrowserfails
todisplaytheimageforsomereasonorapersonisusingascreenreader.Thetextisupto
you,butitshouldbebrief.
Thewidthandheightspecificationstellthebrowserhowbigtheimageistobewhen
it’sdisplayed.Thenumbersarepixels.
Thecommonpracticeistosizeoriginalimagestoexactlythedimensionsthatthey’ll
displayinthebrowser.So,intheexampleabove,theimagefounder.jpgwouldbesavedin
Photoshoporanotherimageeditingprogram55pixelswideand85pixelshigh.Stating
thedimensionsintheimagetaggivesthebrowserahead-startondisplayingtheimage
correctly,whichspeedsuploading.
Thedimensionsyouspecifyintheimagetagdon’thavetobethesameasthe
dimensionsoftheimage.Forexample,ifyouhaveanimagethat’s200pixelswideby300
pixelshigh,youcouldaskthebrowsertoscaleitto50%bywritingwidth=“100”
height=“150”.Youcouldalsoaskthebrowsertoscaleupanimage,butthisisrarely
done,sinceitdegradestheimage.
Askingthebrowsertorescaleanimageslowsdownpageloadingminutely.Ifyou
havemanyimagesonyourpage,theremightbeanoticeabledelay.
Browsersdon’tcareabouttheorderinwhichyouspecifysrc,alt,width,and
height,buttheorderI’vegivenisconventional.I’llaskyoutosticktoitintheexercises.
Areaderandbeta-tester,JohnKoch,rememberstheorderofthefirstthreespecifications
bythinkingofaSAW.
InyourHTMLfileaddanaltspecificationtobothlorisimagetags.Alsoaddwidth
andheightspecifications.Theimagesizeis250x197.Specifythatforthefirstimage.
Specify125x99forthesecondimage.Savethefileanddisplaythepage.
SampleHTMLcodeisat:
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/25.html
26
Positioninganimage
Ifyoudon’ttellthebrowserwhereyouwantanimageplaced,thebrowserwillplace
itallthewayoverontheleft.It’llalsoarrayconsecutiveimagesside-by-sideacrossthe
screenifthere’sroom.
Youcanisolateanimageonitsownlinebylettingthebrowserknowthatyouwant
theimagetreatedasablock,notaninlineelement.Whenit’streatedasablock,itgetsto
monopolizethehorizontalspaceitsitsin.
Asyou’velearned,thisishowyoutellthebrowsertotreatanimageasablock.
img.normal{
display:block;
}
Eventhoughthebrowserpositionsanimageallthewayoverontheleftbydefault,
youcanmoveittotherightasfarasyoulike,usingmargins.Thefollowingcodedefines
animageclassthatmovesanimageslightlytotherightoftheleftedgeofthepageorof
thedivthatcontainsit.
img.inset{
display:block;
margin-left:1em;
}
Ifyouwanteditfarthertotheright,you’dincreasetheemnumber.
Areminder:insetisanameImadeup.Youcannameaclassanythingyoulikeas
longasyoufollowthenamingrules.
InyourCSSfilecreateaclassthatmovesanimageright.InyourHTMLfileadd
thatclasstothesecondlorisimage.Remember,anelementcanhavemorethanoneclass
assignedtoit.Sotheimagewillhaveboththeclass“has-own-line”andtheclass“inset.”
Savethefilesanddisplaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-26-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-26-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/26.html
27
Centeringanimage
Let’screateaclassforcenteringimages.I’mgoingtogiveitaridiculousname,to
remindyouthatclassnamesaremadeup.
img.smack-in-the-middle{
display:block;
margin-left:auto;
margin-right:auto;
}
autotellsthebrowsertosplittheleftandrightmarginsequally.Theresultisa
centeredimage.
Here’stheHTML.
<imgclass=“smack-in-themiddle”src=“images/founder.jpg”alt=“Ourfounder”width=“55”heigh
NotethatintheHTMLaboveclasscomesbeforesrcandalltheother
specifications.Thisisn’tstrictlynecessary,butI’llaskyoutofollowtheconventionwhen
youdotheexercises.
Analternativewaytocodethestyling:
img.smack-in-the-middle{
display:block;
margin:0auto0auto;
}
InyourCSSfilecodeaclassofimagesthatcenters.InyourHTMLfileaddathird
lorisimageandassignitthisclass.Savethefilesanddisplaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-27-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-27-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/27.html
28
Floatingimages
Wouldyouliketowrapsometextaroundanimage?Here’show.
img.wrap-around-the-right-side{
float:left;
}
NowanytextthatcomesaftertheimageinyourHTMLcodewillwraparoundthe
image,ontheright.Ifthetextistoolongtofitcompletelynexttotheimage,it’llcontinue
atfullwidthundertheimage.
Notethatthere’snodisplay:blockhere.Theimagewillshareitshorizontalspaceif
there’sroom.
Ifyouwanttexttowraparoundtheleftsideoftheimage,you’dwrite:
img.r-float{
float:right;
}
Whenyoudothis,you’llnoticethatthebrowserjamsthetextupagainsttheimage,
leavingnobreathingroom.Youcancorrectthisbyaddingsomemargintotheimage.In
thefollowingcode,whitespaceisaddedbetweentheimageandthetextonitsright.
Whitespaceisalsoaddedbelowtheimage,togivebreathingroombetweentheimageand
anytextthatflowsbeneaththeimage.
img.wrap-around-the-right-side{
float:left;
margin:0.75em.5em0;
}
There’soneunintendedconsequenceyouneedtoavoid.Let’ssayyouhaveashort
paragraphwrappingaroundtheleftsideofanimage.Theparagraphissoshortthatit
doesn’tfillallthespacetotheleftoftheimage.Ifyouaddanotherparagraphunderthe
shortparagraph,itwillwrap.Ifyoudon’twantthis,youneedtotellthebrowsertoclear
thefloatafterthefirstparagraph.Todothis,youcreateaclass.
p.no-wrap{
clear:both;
}
Bytellingthebrowsertoclearboth,you’resaying,“Don’twrapanythingfromhere
on.”Here’stheHTML.
<imgclass=“wrap-around-the-rightside”src=“images/founder.jpg”alt=“Ourfounder”width=“55”height=
<p>Thisisourfounder,BradleyB.Bradley,whoenvisionedaBrad’s
wrap”>Whereveryougo,you’llfindaBrad’sBreadsticksnearby,wit
</p>
1. InyourCSSfilecodeaclassofimagesthatfloatsandcreatessomespacebetweenit
andthetextthatwrapsaroundit.
2. Createaclassofparagraphsthatclearsthewrap.
3. InyourHTMLfilecopytheimagetagforthesmallerversionoftheloris.Replace
theclassnamewiththeclassthatfloats.
4. Codeaparagraphthatwillwraparoundtheimage.
5. Codeaparagraphthatclearsthewrap.
6. Savethefilesanddisplaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-28-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-28-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/28.html
29
Links
NowwecometothefeatureforwhichHTMLisnamed,hypertexta.k.a.hyperlinks
a.k.a.links.Youclickonsometextoranimage,andanewpageloads.Orperhaps
somethingelsehappens.
Alinkisdisplayed,bydefault,inblue,withanunderline.Let’ssayIwanttohavea
linkonmysite,ASmarterWaytoLearn,thattakestheusertotheprogrammingsiteStack
Overflow.WhentheuserclicksStackOverflow,heistakentothehomepageofthatsite.
ThisistheHTMLthatcreatesthelink:
<ahref=“http://www.stackoverflow.com”>StackOverflow</a>
Thesearetheparts.
atellsthebrowsertowatchforananchor.Theanchoristhelinktextbetweenthe
opening<a>tagandtheclosing</a>tag.Itisthetextthattheusersees.Inthis
casetheanchor,orlinktext,isStackOverflow.
hrefstandsfor“hypertextreference.”hreftellsthebrowser,“Watchforan
addressimmediatelyfollowingtheequalsign.Thiswillbethepagetoloadwhenthe
userclickstheanchor.”
TheWebaddressisinquotes.Inthiscasetheaddressis
http://www.stackoverflow.com.
Aftertheopeningtagcomestheanchor,thetextthattheuserclickstotellthe
browsertoexecutethelink.Theanchorisnotinquotes.
Theclosingtagendsit.
Ifyou’relinkingtoapageonthesamewebsite,inthesamefolder,allyouneedis
thepagename:
<ahref=“products.html”>Ourproducts</a>
Ifit’sonthesamewebsitebutinasubdirectory,youaddthesubdirectoryname.In
thefollowingcode,thefileisinthecatalogsubdirectory.
<ahref=”catalog/products.html”>Ourproducts</a>
InyourHTMLfilecodealinktoStackOverflowathttp://www.stackoverflow.com”.
Savethefileanddisplaythepage.Clickthelink.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-29-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/29.html
30
Linkaddresses
Whenalinkaddressdoesn’tspecifyapage,likeabout.htmlorfaq.html,the
browserknowstogotothehomepageofthesite,usuallycalledindex.html.
http://www.stackoverflow.com…
…isthesameas…
http://www.stackoverflow.com/index.html
IfIwantedtolinktoapageotherthanindex.html,Iwouldincludethepagenamein
theaddress,like…http://www.stackoverflow.com/web-design.html
Notethatthere’sa/betweenthedomainnameandthepagename.Thereareno
spaces.
IfthepageIwantedtolinktowereinasubfolderunderthemainfolder,I’dinclude
thesubfoldernameaswell:
http://www.stackoverflow.com/questions/web-design.html
Alinkmightdrilldownthroughadditionallevelsofsubdirectories,togettoapage.
Forexample:
http://www.stackoverflow.com/questions/rookie/newest/web-design.html
Youdon’thavetohaveseverallevelsofsubdirectoriesinyoursitestructure,butyou
mightwanttoforpurposesoforganizationifthesitehashundredsofpages.Ontheother
hand,ifit’sasimplesite,youmighthave,forexample,justan“images”subfolderanda
“styles”subfolderunderthemainfolder.AlltheHTMLpageswouldbeinthemain
folder.Oryoumightchoosetohaveaflatstructure,withnosubdirectoriesatall.It’supto
you.
Whenyoulinktoapageonyourownsite,youcanskipthedomainname.For
example,ifIwanttodisplayalinkonthehomepageofmysitethattakestheusertomy
ownsite’sfaqpage,Iwon’thavetowrite…
<ahref=“http://www.asmarterwaytolearn.com/faq.html”>FrequentlyAs
Icanwrite,simply…
<ahref=“faq.html”>FrequentlyAskedQuestions</a>
WhenIomitthedomainname,thebrowserunderstandsthatI’mlinkingtoapageon
thesamesite.
IfthepageI’mlinkingtoisonthesamesitebutinafolderorseverallevelsof
directorieslowerthanthefolderyou’relinkingfrom,youcanstillskipthedomainname,
butyouhavetoincludethename(s)ofthelowerfolderordirectories.
checking.html”>FrequentlyAskedQuestions</a>
Intheexampleabove,you’retellingthebrowserthatthepagecode-checking.html
isonelevelbelowthefolderyou’relinkingfrom,inthesubfolderservices.Notethatthere
isno/beforethesubfoldername.
Butsupposeyouwanttolinkfromapageintheservicessubfoldertoapageinthe
productssubfolderthat’sonthesamelevelastheservicessubfolder.Sonowyouhaveto
tellthebrowsertofirstgobackuponelevel,andthengodownfromtheretotheproducts
subfolder.Thisishowyoudoit.
<ahref=”../products/texteditors.html”>FrequentlyAskedQuestions</a>
Foreachlevelthebrowserneedstogobackupinordertogodownagain,addan
additional../
Forexample,supposeyou’rewritingalinkonapagethat’sinafoldertwolevels
downfromthehomepage.Tolinkbacktothehomepage(index.html),you’dwrite:
<ahref=”../../index.html“>Home</a>
InyourHTMLfilecreateabriefparagraphthatincludesalinkthattakestheuserto
thewhy-exercises.htmlpageatsmarterwaytolearn.com.Savethefileanddisplaythe
page.Clickthelink.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-30-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/30.html
31
Linkingtoalocation
onapage
Whenyoucreateapageofsignificantlength,youmightwanttoprovidelinksto
varioussectionsofthepage,sotheuserdoesn’thavetoscrollthroughthepagelooking
forthesectionshewantstosee.Onalongpage,it’salsonicetoprovidelinkstothetopof
thepage,sowhenshe’sfinishedwithalowersection,shecanjumpbacktothetop.
Youbeginbychoosingaheading,paragraph,orotherelementtoserveasthestarting
pointforthesection.Yougivethiselementanid.
<h2id=“fame-claim”>OURCLAIMTOFAME</h2>
Thenyoucreatealinktoit.
<ahref=”#fame-claim”>Readallaboutourclaimtofame.</a>
It’slikelinksyoulearnedaboutinthelastchapter,exceptthata#precedestheidin
thereference.
Toinsertalinkbacktothetop,you’dcreateanidforanelementatornearthetopof
thepage.Itcouldbethemainheadingforthepage.Oritcouldbethecontentdivthat
encompassesallthecontentonthepage.
<divclass=“content”id=“top”>
Then,whereveryouwanttoplacethelink,youcouldwrite…
<ahref=”#top“>Backtothetop</a>
Whenyouwanttolinktoalocationonanotherpageonthesamesite,youhaveto
includethenameofthepage.
<ahref=”faq.html#whyme“>Getanswerstoyourcosmicquestions</a>
Thecodeabovelinkstoaheading,paragraph,orotherelementwiththeidwhy-me
onthefaq.htmlpage.
Whenyouwanttolinktoasectionofapageonanothersite,youhavetoincludethe
domainname.
<ahref=”http://www.cosmicquestions.com/faq.html#whyme“>Getanswerstoyourcosmicquestions</a>
Inorderforthistowork,thepageontheothersitehastohaveanelementwiththeid
“why-me.”
InyourHTMLfilegivetheheadingatthetopofthepageanid.Atthebottomofthe
andclickit.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-31-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/31.html
32
Openinganewwindow
Nooneeverwantstoloseausertoanothersite,butsometimeswehavetolinkaway
anyway.Thetacticforencouragingtheusernottoleavepermanentlyistoopenthelinked
siteinanewwindow,leavingyoursiteinitsexistingwindow.Thisishowtodoit.
Lookitupat<ahref=“http://www.wikipedia.org”target=“_blank”
WhentheuserclicksthelinktextWikipediaanewwindowopensforWikipedia.
Theoriginalpageremainsopeninitsownwindow.
Haveyouseenlinktextthatsaysthingslike“Explainthis”or“Whatisthis”?When
youclickoneoftheselinks,asmallwindowopensontopofthemainwindowwithabit
ofusefulinformation.Mostofthemainwindowstillshows,sotheuserdoesn’tget
disoriented.Sheseesthelittlewindowasanaddendumtothemainwindow.
Unfortunately,youcan’tcreateoneoftheselittleinformationalwindowsinHTML.You
needJavaScript.MybookASmarterWaytoLearnJavaScriptshowsyouhow,step-bystep.Buthere’ssomecodethatyoucanpasteintoyourpageifyou’dliketocreateasmall
windowwithoutknowingJavaScript.
<pid=“openWindow”>Tellmealittlemoreaboutthis.</p>
<script>
document.getElementById(“openWindow”).onclick=openWindow;
functionopenWindow(){
varw=window.open(“moreinfo.html”,””,“width=200,height=300,left=300,top=400”);
}
</script>
Adaptthescriptabovetoyourneedsbymakingthesechanges:
SubstituteyouranchorforTellmealittlemoreaboutthis.
SubstituteyourHTMLfilenameformore-info.html
Substituteyourpreferredwidthandheightforwidth=200,height=300.Thenumbers
arepixels.
Substituteyourpreferredwindowplacementonthescreenforleft=300,top=400.The
firstnumbertellsthebrowserhowmanypixelstoinsetthewindowfromtheleftedge
ofthescreen.Thesecondnumbertellsthebrowserhowmanypixelstodropthe
windowfromthetopofthescreen.
Don’taddordeleteanyspacesfromthecode.Thespacingmaylookodd,butifyou
trytoimproveitinanyofthewrongplaces,thewindowwon’topen.
InyourHTMLfilecodeaparagraphthatincludesalinktoasmarterwaytolearn.com.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-32-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/32.html
33
Stylinglinks
Bydefaultbrowsersstylelinktextinbluewithanunderline.Butyoucangiveita
differentstyle.Youcanspecifyadifferentfont-family,font-size,font-weight,color,and
otherfontcharacteristics.
Youcanevenlosetheunderlineifyoulike.Butbecareful.Usershavebeen
conditionedtoassociatetheunderlinewithlinks.Ifthere’snounderline,they’llhavea
hardertimeidentifyingtextassomethingtheycanclick.Conversely,it’sabadideato
underlinenon-linkingtextforemphasis.Someuserswilltrytoclickonit.Foremphasis,
it’sbettertoputnon-linkingtextinitalicsorbold.
ThisCSScodecolorsallyourlinksgoldenrod.
a{
color:#b8860b;
}
Youcanmakelinkschangetheirappearancewhentheuserhoversthemouseover
them.Thiscodeboldsthemandremovestheunderlinewhentheuserhovers.(Removing
theunderlineonhoverisn’taproblem,becausetheuserhasalreadyidentifieditasalink.)
a:hover{
font-weight:bold;
text-decoration:none;
}
Inthecodeabove,text-decoration:noneremovestheunderline.
It’snotagoodideatounderlinenonlinkingtextsinceitmayconfusethereaderby
signallingthatthetextisclickable,butyoucanunderlinetextifyouchooseto,by
specifyingtext-decoration:underline.
Youcanchangetheappearanceoflinksatthemomenttheuserclicks.Thiscode
increases
a:active{
font-size:1.25em;
}
Youcanchangetheappearanceoflinksthattheuserhasalreadyclicked.Thiscode
changestheircolor.
a:visited{
color:deeppink;
}
InyourCSSfilecodelinksgreyandlinksthatarehoveredonorange.Savethefile.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-33-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/33.html
34
Clickableimages
Youcansubstituteanimageforalinkanchor(thetextthattheuserclicks).Whenthe
userclicksontheimage,itworksthesameasanchortext:anewpageloadsorsomething
elsehappens.Todoit,youcombinetwotagsyoualreadyknow,theatagandtheimgtag.
LookagainatthelinkcodefromChapter28.
<ahref=“http://www.stackoverflow.com”>StackOverflow</a>
Whentheuserclicksthewords“StackOverflow”she’stakentostackoverflow.com.
Here’ssomecodethatusestheStackOverflowlogoinsteadofananchor.
<ahref=“http://www.stackoverflow.com”>
<imgsrc=“images/stack-overflowlogo.pngalt=“StackOverflowlogo”width=“85”height=“25”>
</a>
Whentheuserclickstheimage,she’stakentostackoverflow.com
Onewaytocreateaclickablebuttonistomakeanimageofabutton,thenmakethe
imageclickable.
<ahref=“faq.html”><imgsrc=“images/buttonfaq.pngalt=“ButtonlinkingtoFAQpage”width=“50”height=“18”>
</a>
Anothergooduseforclickableimagesisaphotogallery.Youarrayoneormore
rowsofthumbnailimagesacrossthepage.Whentheuserclicksoneofthem,alarger
versionoftheimageloadsinanewwindow.Here’scodethatturnsanarrayofthumbnails
intoaclickablecatalog.
<ahref=“full-size-robin.html”><imgclass=“flleft”src=“images/thumbnail1.jpg”alt=“Robin”width=“50”height=“50”></a>
<ahref=“full-size-blue-jay.html”><imgclass=“flleft”src=“images/thumbnail2.jpg”alt=“BlueJay”width=“50”height=“50”></a>
<ahref=“full-size-cardinal.html”><imgclass=“flleft”src=“images/thumbnail3.jpg”alt=“Cardinal”width=“50”height=“50”></a>
<ahref=“full-size-sparrow.html”><imgclass=“flleft”src=“images/thumbnail4.jpg”alt=“Sparrow”width=“50”height=“50”></a>
<ahref=“full-size-pigeon.html”><imgclass=“flleft”src=“images/thumbnail-
Anicewaytodothisistoaddtarget=“_blank”totheatagasIshowedyouin
Chapter32,sothepagewiththebigpictureopensinanewwindow.Evennicer:openitin
awindowthat’ssmallerthanfull-sizesotheusercanseeaportionoftheoriginalpage
underneath,asIshowedyouattheendofChapter32.
InyourHTMLfilecreateanimagetagfor
http://www.asmarterwaytolearn.com/robo_guy.pngandlinkittoasmarterwaytolearn.com.
Savethepageanddisplayit.Clickthepicture.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-34-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/34.html
35
Imagemapspart1
Animagemapisspecialtypeofclickableimage.Yourcodesectionsitintotwoor
moreparts.Iftheuserclicksonesectionoftheimage,anewpageloads.Ifheclicks
anothersection,adifferentpageloads.Forexample,youmighthaveaphotograph
showingsixhistoricalbuildingsinatownsquare.Whenyouclickonaparticularbuilding,
apageloadsthattellsthestoryofthebuilding.
Imagemapsrequirequiteabitofcode,soI’mgoingtodividethesubjectintotwo
chapters.
Let’ssayyourimageis“6-buildings.jpg.”Youbeginwithastandardimgtag.
<imgsrc=“6buildings.jpg”alt=“6historialbuildings”width=“800px”height=“55
Withinthetagyouspecifythenameoftheimagemapthat’sgoingtodivideupthe
photointoclickableregions.
<imgsrc=“6buildings.jgp”alt=“6historialbuildings”width=“800px”height=“55
Givethemapanynameyoulikeaslongasitdoesn’tincludespaces.Precedethe
namewith#.
Nextyoucodetheimagemap.It’sasectionofcodethatbeginswithanopeningmap
tagandendswithaclosing/maptag.
<mapname=“buildings”>
[Hereyoudefineeachofthesectionsandgivetheir
linkaddresses.I’llcoverthisinthenextchapter.]
</map>
Noticethatthemapname,“buildings,”isthesamenameyouspecifiedintheimg
tag,butwithoutthe#.You’venowtoldthebrowsertodisplaythepictureofthesix
buildings,andtoconnectthepicturetoanimagemapnamed“buildings.”Inthenext
chapter,we’llcreatethemapitself.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/35.html
36
Imagemapspart2
You’veplacedanimageonthepage,andyou’veconnectedittoanimagemapby
writing,withintheimgtag,usemap=”#buildings”.Thenyou’vestartedanimage
mapdefinitionwiththeline…
<mapname=“buildings”>
Here’sthewholething.
<mapname=“buildings”>
<areashape=“rect”alt=“TuttleHouse”coords=“76,42,279,510”href=“
house.html”>
<areashape=“rect”alt=“TittleHall”coords=“286,125,346,503”href=
hall.html”>
<areashape=“rect”alt=“ToobleTower”coords=“352,134,445,482”href
tower.html”>
<areashape=“rect”alt=“TibbleManse”coords=“448,119,559,471”href
manse.html”>
<areashape=“rect”alt=“TrebleCottage”coords=“559,211,605,466”hr
cottage.html”>
<areashape=“rect”alt=“TikkelPlace”coords=“606,180,682,460”href
place.html”>
</map>
Thesearethepartsofeachmapsection.
1. Theshapeofthearea.Write“rect”forrectangle,“circle”forcircle,or“polygon”for
polygon.
2. Alternativetextforscreenreaders.YoulearnedaboutthisinChapter2
3. Thescreencoordinatesthatdefinethearea.Seebelowforhowtogetthese
coordinates.Examples:Forarectangle,coordinatesof76,42,279,510meanthe
clickablerectanglebegins76pixelsinfromtheleftedgeoftheimageand42pixels
downfromthetopoftheimage,andextendsrightby279pixelsfromtheleftedgeof
theimageand510pixelsdownfromthetopoftheimage.Foracircle,coordinatesof
100,60,10meantheclickablecirclehasacenterat100pixelsinfromtheleftedgeof
theimageand60pixelsdownfromthetopoftheimage,andhasaradiusof10
pixels.Forapolygon,coordinatesof150,217,190,257,150,297,110,257createa
diamondshape.Thetoppointofthediamondis150pixelsinfromtheleftedgeof
theimageand217pixelsdownfromthetopoftheimage.Therightpointofthe
diamondis190pixelsinfromtheleftedgeoftheimageand257pixelsdownfrom
thetopoftheimage,andsoon.Threesetsofcoordinatescreateatrianglearea,five
setsapentagonalarea,andsoon.
Ratherthantryingtocreateanimagemapbyhand,automatethetaskwithautility
thatdoesmostoftheworkforyou,includingthefussyworkofestablishingcoordinates.
WebdevelopmenttoolslikeDreamweaverincludesuchautility.Youcanalsouseafree
onlineimagemapcreatorliketheoneathttp://www.image-maps.com.Myfavoritetool
forcreatingimagemapsisMapedit,adownloadableprogramfrom
http://www.boutell.com.There’sagenerousfreetrialperiod,afterwhichyoupay$15.
1. InyourHTMLfileinsertabreakaftertherobo_guy.pngimage.
2. Createanimagemapusinghttp://www.asmarterwaytolearn/stooges.jpg
3. I’vemappedtheStooges’facesasthreeclickableareas.They’recircles.The
coordinatesare56,56,47…126,93,31…and208,66,3
4. DoaGooglesearchforeachoftheStooges.CopytheGoogleURLsthatthesearches
generateandusethemasthelinks.Forexample,whentheuserclicksCurly’sface,
she’stakentotheGooglesearchforCurly.
5. Savethefileanddisplaythepage.Clickoneachofthefaces.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-36-1.html
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/36.html
37
Bulletlists
andnumberedlists
TheHTMLtermforabulletlistisunorderedlist.Unorderedmeansnotnumbered.
Anorderedlistisanumberedlist.MakingbulletandnumberedlistsinHTMLis
convenient,becauseHTMLautomaticallyindentslistsandautomaticallynumbersordered
lists.
Inbothtypesoflist,youwriteatagforthelist—<ul>forunorderedlistsand<ol>
fororderedlists.Thenyouwriteatagforeachitem—<li>,whichstandsforlistitem.
<li>isthetagforindividualitemsineithertypeoflist,orderedorunordered.
Thiscodecreatesabullet(unordered)list.
<ul>
<li>Sun</li>
<li>Moon</li>
<li>Planets</li>
<li>Stars</li>
</ul>
Thiscodecreatesanumbered(ordered)list.
<ol>
<li>Wash</li>
<li>Rinse</li>
<li>Repeat</li>
</ol>
Thingstonotice:
Eachlistitemisindentedtwospaces.
Eachopeningtagiscompletedwithaclosingtag.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-37-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/37.html
38
Stlyinglists
Sincelistsaretextelements,youcanstylethemthewayyou’dstyleaparagraphor
heading,withacustomizedfont-family,font-size,font-weight,color,andmargins.
ThisCSScodeinsetsanyunorderedlist,assigningextrawhitespaceonboththeleft
andright.
ul{
margin:01.5em01.5em;
}
Youcould,ofcourse,adjustthetopand/orbottommargins,too.Usethesametype
ofcodefororderedlists.Justsubstituteolforulinthecodeabove.
Thecodeabovestylesalltheunorderedlistsonthepage.Youcouldcreateaclassof
lists,justforsomeofyourlists.
ol.special{
margin:01.5em01.5em;
}
Bydefault,browsersdon’taddanyspacebetweenlistitems.Ithinktheylookbetter
ifthey’reseparatedabit.
li{
margin:.75em;
}
Notethatthere’sonlyonemarginnumberinthecodeabove.Browsersunderstand
thatitspecifiesthespacebetweenlistitems.
Thedefaultisabulletontheoutsidewithalllinesoftextindented.Tomakethe
defaultexplicit,write…
ul{
list-style-position:outside;
}
Toindentonlythefirstlineoftextandmakeallotherlinesflushwiththebullet,
write…
ul{
list-style-position:inside;
}
InyourCSSfileaddspacebetweenlistitems.Savethefile.Displaythepage.
http://asmarterwaytolearn.com/htmlcss/practice-38-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/38.html
39
Stylingalists’smarkers
Markersarethebulletsinanunorderedlistorthenumbersinanorderedlist.
Ifyoudon’tspecifywhatkindofbulletsyouwantinanunorderedlist,thebrowser
displaysadisc:•
ThisistheCSScodethatexplicitlyspecifiesadiscasthemarker.Itwouldnormally
besuperfluous,sincethediscisthedefault.
ul{
list-style-type:disc;
}
Tousea○forthebullet,substitutecirclefordiscinthecodeabove.
Tousea■substitutesquare.
Youcanuseanimageforabullet.Theexamplebelowcreatesaclassofunordered
listthatusesanimage.
ul.custom{
list-style-image:url(“images/heart.png”);
}
Inthecodeabove,“images/heart.png”tellsthebrowserthepathandfile
nameoftheimage.
Animageusedasabulletcreatesheadaches.Tobeginwith,youmustsizetheimage
tofitthelisttext.Then,iftheuserzoomsinoroutonthepage,thebrowserdoesn’tadjust
thebullettofit,asitdoeswiththebuilt-indisc,circle,andsquare.Everythinggetsoutof
whack.It’spossibletobuildadefenseagainstthis,butyou’reprobablybetteroffspending
yourcodingtimeonsomethingthattheusercaresmoreabout.
Thedefaultlist-style-typefororderedlistsisdecimal—1,2,3etc.Youcanchange
ittodecimal-leading-zero—01,02,03etc.;lower-alpha—a,b,cetc.;
upper-alpha—A,B,Cetc.;lower-roman—i.,ii.,iii.etc.;andupper-roman—I,
II,IIIetc.Here’scodethatcreatesaclassforupper-roman.
ol.second-level{
list-style-type:upper-roman;
}
InyourCSSfilestyleunorderedlistmarkersassquares.Savethefile.Displaythe
page.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-39-1.html.
http://www.ASmarterWayToLearn.com/htmlcss/39.html
40
MoreCSSselectors
ACSSselectoriseverythingonthefirstlinethatprecedesthe{.It’sthepartofa
stylerulethattellsthebrowserwhatelements,classes,andidsaruleappliesto.The
selectorsarehighlightedinthefollowingcodefragments.
p{
p.special{
.special{
p#intro{
#intro{
Sofaryou’velearnedtocreate…
1. Anelementselectorlikep,div,orimg.
2. Anelementclassselectorlikep.special,div.important,orimg.gallery.
3. Aclassselectortiedtonoparticulartypeofelementlike.special,.important,
or.gallery.
4. Anelementidselectorlikep#intro,div#sidebar,orimg#logo.
5. Anidselectortiedtonoparticulartypeofelementlike#intro,#sidebar,or
#logo.
Youcancombineselectorstocreatemorecomplicatedselectors.Here’sone.
div.importantp{
Thecodeaboveselectsallparagraphsinadivthat’sbeenassignedtheclass
“important.”
Thefollowingcodeselectsallimages…thatareinlistitems…inanunorderedlist…
withtheid“pix-list.”
ul#pixListliimg{
Here’ssomecodethatselectsthefirstparagraphfollowinganydiv.
div+p{
Thefollowingcodeselectsonlythefirstlevelofdivswithinthedivthathasanid
of“main.”
div#content>div{
Sointhefollowingcode,onlythehighlighteddivsareselected.
<divid=“main”>
<div>
[somecontent]
</div>
[somecontent]
<div>
[somecontent]
</div>
</div>
<div>
[somecontent]
<div>
[somecontent]
</div>
</div>
YoucanlearnalotaboutselectorsbyplayingaroundwiththeinteractiveW3Schools
CSSselectortesterathttp://www.w3schools.com/CSSref/trysel.asp.
InyourHTMLfileyoucodedadivwithanid.InyourCSSfiledoublethesizeof
allparagraphswithinthatdiv.Savethefile.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-40-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/40.html
41
Tables:basicstructure
AlltheHTMLcodeforatableisenclosedinanopeningandclosingtag.
<table>
[Thedetailsofthetablegohere.]
</table>
Withinthosetagsyoucreaterowsandcolumns.Here’satablewithtworowsand
twocolumns.
<table>
<tr>
<td>Row1,column1</td>
<td>Row1,column2</td>
</tr>
<tr>
<td>Row2,column1</td>
<td>Row2,column2</td>
</tr>
</table>
Thisiswhatthetablelookslike(withaborderthatIaddedtomaketherowsand
columnsstandout).
Unlessyoustyleaborderexplicitly,mostbrowsersdisplayitwithoutborders,like
this.
You’lllearnhowtoaddborders,ifyouwantthem,inalaterchapter,andtostyle
tablessothey’remoreattractive.Fornow,let’sgetyoufamiliarwiththisbarebones
structure.
AsyoucanseefromtheHTMLcode,youbuildatablearowatatime.Youcreatea
rowusingthe<tr>(for“tablerow”)tag.Thenyoucreateallthecellswithinthatrow
usingthe<td>(for“tabledata”)tag.
Allthetextcontentofatablecellisenclosedbetweentheopeningtagandthe
closing<td>tag.Theopening<tr>tagandclosing</tr>tagdon’tencloseanytext
content.Theyonlycontainthe<td>tagsandtheirtextcontent.
Allopeningtagsarepairedwithclosingtags.
Eachrowmusthavethesamenumberofcells,createdwiththe<td>and</td>
tags,evenifsomeofthecellsareempty.Tocreatethistable,withnothinginrow2,
column1…
…you’dwrite…
<table>
<tr>
<td>Apples</td>
<td>Oranges</td>
</tr>
<tr>
<td></td>
<td>Pears</td>
</tr>
Noticethatallthe<tr>tagsareindentedtwospacesinsidethe<table>tag,and
the<td>tagsareindentedtwospacesinsidethe<tr>tags.
InyourHTMLfilecodeatablewithtworowsandtwocolumns.Savethefile.
Displaythepage.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-41-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/41.html
42
Tables:headings
Youcantellthebrowsertoaddheadingsfortables.Here’satablewithcolumn
headings.
Thisisthecode.
<table>
<tr>
<thscope=“col”>Dog</th>
<thscope=“col”>Cat</th>
</tr>
<tr>
<td>Canine</td>
<td>Feline</td>
</tr>
<tr>
<td>Bark</td>
<td>Meow</td>
</tr>
<td>Puppy</td>
<td>Kitten</td>
</tr>
</table>
Youbeginbycreatingarowfortheheadings,justasyouwouldforregularcells.
Then,usingtheopening<th>(for“tableheading”)andclosing</th>tags,you
constructcellswithtextinthem,asyouwouldforregulartextcells.Butnote
scope=“col”.Thistellsthebrowserthatyouwantcolumnheadings—headingsontop
—notrowheadings,whichwouldbegineachrowontheleft.Bydefault,mostbrowsers
boldheadingtextandcenterithorizontallywiththecell.Nowlet’screateatablewithrow
headings,likethisone.
Thisisthecode.
<table>
<tr>
<thscope=“row”>Species</th>
<td>Canine</td>
<td>Feline</td>
</tr>
<tr>
<thscope=“row”>Sound</th>
<td>Bark</td>
<td>Meow</td>
</tr>
<tr>
<thscope=“row”>Immature</th>
<td>Puppy</td>
<td>Kitten</td>
</table>
Youcreateaheadingforeachrow.Andyouwritescope=“row”.Here’sthetable
withbothcolumnandrowheadings.
Thisisthecode.
<table>
<tr>
<thscope=“col”></th>
<thscope=“col”>Dog</th>
<thscope=“col”>Cat</th>
</tr>
<tr>
<thscope=“row”>Species</th>
<td>Canine</td>
<td>Feline</td>
</tr>
<tr>
<thscope=“row”>Sound</th>
<td>Bark</td>
<td>Meow</td>
</tr>
<tr>
<td>Puppy</td>
<td>Kitten</td>
</tr>
</table>
Noticethattherearethreecolumnheadings,thefirstoneblank.Thistellsthe
browserthatthereisnocolumnheadingoverthecolumnofrowheadings.
InyourHTMLfilecodeatablewithbothcolumnandrowheadings.Savethefile.
Displaythepage.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-42-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/42.html
43
Tables:
spanningcolumnsandrows
Sometimesyouneedtocombinetwoormorecellsintoasingle,extra-widecell.
Thetableaboveshowstheearly-afternoonscheduleforthreefacilities.I’veadded
borders,andI’vehighlightedthetwospannedrowsthatIwantyoutopayattentionto.
Neitherthebordersnorthehighlightingarepartofthecodebelow.You’lllearnhowto
addbothkindsofstylinginsubsequentchapters.Thisisthecode.
<table>
<tr>
<thscope=“col”></th>
<thscope=“col”>1pm</th>
<thscope=“col”>2pm</th>
<thscope=“col”>3pm</th>
</tr>
<tr>
<thscope=“row”>Gym</th>
<td>Dodgeball</td>
<td>Kickboxing</td>
<td>Sackracing</td>
</tr>
<tr>
<thscope=“row”>Exerciseroom</th>
<td>Spinning</td>
<tr>
<thscope=“row”>Pool</th>
<tdcolspan=“3”>Waterpolo</td>
</tr>
</table>
Thecodeforacolumn-spancelllookslikearegular<td>cell,exceptforthecode
colspan=”[numberofcolumnstospan]”.Theclosingtagisthesameasfor
aregular<td>cell.Noticethata<td>withthecolspanfeaturereplacesthesame
numberofregular<td>sasthenumberofcolumnsthatarespanned.Inthefirstrow,
therearethreeregular<td>s.Inthesecondrow,wheretwocolumnsarespanned,there’s
oneregular<td>plusthespan.Inthethirdrow,wherethreecolumnsarespanned,there’s
noregular<td>.Youcanmaketableheadingsspancolumns,too.Thecodeis…
<thscope=“row”colspan=”[numberofcolumnstospan]”>Whatever</t
Spanningrowsworksthesamewayasspanningcolumns,butusesrowspan.
Here’sthetableabove,reconfiguredsothefacilitiesareatthetopandthetimesareonthe
left.
Thisisthecode.
<table>
<tr>
<thscope=“col”></th>
<thscope=“col”>Gym</th>
<thscope=“col”>ExerciseRoom</th>
<thscope=“col”>Pool</th>
</tr>
<tr>
<thscope=“row”>1pm</th>
<td>Dodgeball</td>
<td>Spinning</td>
</tr>
<tr>
<thscope=“row”>2pm</th>
<td>Spinning</td>
<tdrowspan=“2”>Yogamarathon</td>
<tr>
<thscope=“row”>3pm</th>
<tdrowspan=“3”>Sackracing</td>
</tr>
</table>
Youcanmaketableheadingsspanrows,too.Thecodeis…
<thscope=“column”rowspan=”[numberofrowstospan]”>Whatever</th>
Youcandivideatableintothreesections:aheader,body,andfooter.Thishelps
screenreaders,butdoesn’tdoanythingforsightedusersthatyoucan’tdousingthecode
I’vealreadytaughtyou.I’llshowyouanexample.Youwon’tbetestedonitinthe
exercises.
Thisisthecode.
<table>
<thead>
<tr>
<th></th>
<th>Gym</th>
<th>ExerciseRoom</th>
<th>Pool</th>
</thead>
<tfoot>
<tr>
<th></th>
<th>3activities</th>
<th>2activities</th>
<th>1activity</th>
</tr>
</tfoot>
<tbody>
<tr>
<thscope=“row”>1pm</th>
<td>Dodgeball</td>
<td>Spinning</td>
<tdrowspan=“3”>Waterpolo</td>
</tr>
<tr>
<thscope=“row”>2pm</th>
<td>Spinning</td>
<tdrowspan=“2”>Yogamarathon</td>
<tr>
<thscope=“row”>3pm</th>
<tdrowspan=“3”>Sackracing</td>
</tr>
</tbody>
</table>
Codeasimpletablewithtworowsandtwocolumns.Inthesecondrow,spanthe
columns.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-43-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/43.html
44
Tables:borders
Youcancreateatablewithbordersorwithout.Here’satablewhereallthecellshave
borders.
ThisistheCSScode.
th,td{
border:1pxsolidblack;
}
Byspecifying1pxsolidblackI’maskingforasolidblacklineofminimal—
1-pixel—width.Foraheavierline,increasethepixelnumber.Foranothertypeofline,
specifydottedoroneoftheotherborderstylescoveredinChapter17.
Bydefault,browsersaddalittlespacebetweencells,asinthetableshownabove.
Thiscreatesgapsbetweenthehairlineborders.Ifyoudon’twantthosegaps,adda
specificationforthetable:
table{
border-collapse:collapse;
}
Thisistheresult.
Bydefault,browsersdon’tdrawaborderaroundanything.Ifyoudon’twant
borders,there’snothingtocode.ButwithCSSyoucanaddbordersanywhereyoulike.
Forexample,here’satablewithtopandbottombordersframingthetableheaders.
Here’stheCSScode.
th.top-row{
border-top:1pxsolidblack;
border-bottom:1pxsolidblack;
}
ThefirstsevenlinesofHTMLwouldbe…
<table>
<tr>
<thclass=“top-row”scope=“col”></th>
<thclass=“top-row”scope=“col”>Gym</th>
<thclass=“top-row”scope=“col”>ExerciseRoom</th>
<thclass=“top-row”scope=“col”>Pool</th>
[etc.]
TheonlyreasonIhavetodefineaspecialclassof<th>isthatI’vealsogot<th>s
runningdowntheleftsideofthetable,denotingtimes.SinceIdon’twantborderson
these,Ineedtomakeadistinctionfor<th>sthathavecolumnscope.Otherwise,Icould
justwrite…
th{
border-top:1pxsolidblack;
border-bottom:1pxsolidblack;
}
Tocreateleftandrightbordersuseborder-leftandborder-right.For
example,supposeyouwantheavyorangebordersdefiningtheleftandrightedgesof
certaintables.
Thisisthecode.
table.standout{
border-left:5pxsolidorange;
border-right:5pxsolidorange;
}
ThefirstlineofHTMLwouldbe…
<tableclass=“standout”>
InyourCSSfilespecifybordersforallcells.Eliminatespacebetweenborders.Save
thefile.Displaythepage.SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-44-1.html.Findtheinteractivecoding
exercisesforthischapterat:http://www.ASmarterWayToLearn.com/htmlcss/44.html
45
Tables:
Spacingpart1
Bydefault,browsersdon’taddbreathingroombetweenthetablecellbordersandthe
texttheycontain.They’rejammedupagainsteachother.Itlookscrowded.
Thesolutionistoaddpadding.
th,td{
padding:.25em;
}
TheCSScodeaboveaddsalittlewhitespaceallaroundthetext.
Youincreaseordecreasetheamountofpaddingbychangingtheemnumber.You
canalsospecifydifferentpaddingfordifferentsides.
td{
padding:.25em1.5em01.5em;
}
TheCSScodeaboveaddsextrapaddingatthetop,justalittleonthesides,andnone
specifynone,write0,not0em.
Supposeyouwantcellsspacedapart—say,evenfartherapartthanthebrowser
default.Here’stheCSScode.I’mgoingtospecifylargespaces,sothey’reeasytosee.
table{
border-spacing:1em;
}
Thisistheresult.
Notethatborder-spacingissomethingyouspecifyforthewholetable,notthe<th>
table{
border-spacing:0.25em0.25em;
}
TheaboveCSScodewouldaddextraspaceontheleftandrightandleavetopand
bottomspaceatthedefaultwidth.
Evenifatabledoesn’thaveborders,youcanuseborder-spacingtoaddwhitespace
betweenthecells.Here’sthesametable,withnoborderspecifiedbutwiththeall-around
border-spacingof2.5em.
InyourCSSfileadd.25emofpaddingtoallcells.Savethefile.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-45-1.html.
http://www.ASmarterWayToLearn.com/htmlcss/45.html
46
Tables:
spacingpart2
Bydefault,browsersadjustcellsizetocontents.Ifyouwrite…
<table>
<tr>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
</tr>
<tr>
<td>Rome</td>
<td>AddisAbaba</td>
<td>Cairo</td>
<td>SaintSeaburyontheThames</td>
<td>Dublin</td>
</tr>
</table>
…thebrowserdisplaysthis…(I’vestyleditwithaborderandpaddingandcollapsed
thespacesbetweencells.)
Thebrowserhasusedspaceefficiently,assigningjustenoughwidthtofiteverything
in.Ithinkthislooksbetter:
they’dallbe20%ofthewidthofthefulltable.Inotherwords,they’dallbethesame
width.
th,td{
border:1pxsolidblack;
padding:5px;
width:20%;
}
WhenIspecifycellwidthinsteadoflettingthebrowserallocatespacebasedon
content,Iforcethebrowsertoautomaticallywraplongertextlinessotheyfitintomy
chosenwidth.
Icould,ifIwantedto,definesomeCSSclassesoridstomakedifferentcells
differentwidths.
Nextpoint:I’mnotsureIwantthetabletobesobig.SoI’llforcethebrowserto
givemeanarrowertablebyspecifyingitswidthaslessthan100%.I’lltellittomakeit
three-quartersthewidthofthewindowordivthatitsitsin.
table{
width:75%;
}
Thisistheresult.
Noticethatthebrowserautomaticallywrapslongerlinesintomultiplelinestofit
themintothewidth.
1. InyourHTMLfilecodeasimpletablewithtworowsandtwocolumns.Giveitanid.
2. InyourCSSfilereducethetable’swidthtoafractionofthewindow’swidth.
3. Makethetworowsequal.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-46-1.html.
http://asmarterwaytolearn.com/htmlcss/practice-46-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/46.html
47
Tables:aligningtext
InChapter14youlearnedtoaligntextonthepageusing…
text-align:left;
text-align:right;
text-align:center;
text-align:justify;
Youcanusethissamecodetoaligntextintablecells.Forexample,youcanwrite…
table{
text-align:left
}
Thetextinallcells,including<th>cells,willbepositionedontheleftofthecell.
(Thetextin<td>cellswouldhavebeenpositionedontheleftanyway,bydefault.)You
canbemoresurgicalbystyling,say,just<th>or<td>cells.Forexample,youknow
thatbydefault,browserssettextin<td>cellsontheleft.Ifyou’dprefertocenterthe
text,youcouldwrite…
td{
text-align:center;
}
Ifyouhaveacolumnofnumbers,youmightwanttosetthemtotheright.You’d
createaclassof<td>todothat.
td.num{
text-align:right;
}
Youcanalsocontroltheverticalalignmentwithincells,using…
vertical-align:bottom;
vertical-align:center;
Youcan’tspecifyverticalalignmentforthewholetable,onlyfor<th>and<td>
elements.Youcan,ofcourse,createclassesof<th>and<td>elementsthathavetheir
ownalignment.Bydefault,textisverticallycenteredinboth<th>and<td>cells.Ifyou
wanted<th>textmovedtothebottomofthecell,youcouldwrite.
th{
vertical-align:bottom;
}
Thiscodewouldmovethetexttothetop…
th{
vertical-align:top;
}
InyourCSSfilecentertextinthecellsofthemostrecenttable,theonewiththeid.
Savethefile.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-47-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/47.html
48
Tables:backgroundcolor
Youcanusecodeyoulearnedinearlierchapterstostylethetextforanentiretable,
for<th>and<td>elements,andforclassesandidsofanyoftheseelements.For
example:
th,td{
font-family:Georgia,“TimesNewRoman”,Times,serif;
font-size:1.5em;
font-weight:900;
color:gray;
letter-spacing:.1em;
}
Thiswhatthetablewouldlooklike.
Acharacteristicthatcanbeespeciallyusefulintablesisbackground-color.For
exampleyoucanuseittoshadealternativerowstomakereadingaroweasier.
Startbydefiningaclassof<tr>andspecifying,let’ssay,lightgrayasthe
background-color.
tr.even-row{
background-color:lightgray;
}
You’dwritetheHTMLlikethis.
<table>
<tr>
<thscope=“col”>Price</th>
<thscope=“col”>Shipping</th>
<thscope=“col”>Tax</th>
<thscope=“col”>Total</th>
</tr>
<tr>
<td>Swisher</td>
<td>76.75</td>
<td>6.50</td>
<td>.83</td>
<td>83.93</td>
</tr>
<trclass=“even-row”>
<td>Stirrer</td>
<td>106.60</td>
<td>8.00</td>
<td>1.33</td>
<td>115.93</td>
</tr>
<tr>
<td>Shaker</td>
<td>31.50</td>
<td>2.90</td>
<td>.33</td>
<td>34.37</td>
</tr>
<trclass=“even-row”>
<td>Swirler</td>
<td>220.00</td>
<td>14.00</td>
<td>2.60</td>
<td>236.60</td>
</tr>
<tr>
<td>Splasher</td>
<td>89.00</td>
<td>6.50</td>
<td>.91</td>
<td>96.41</td>
</tr>
</table>
WithsomeadditionalstylingI’mnotshowingyouhere,thetablewouldlooklike
this.
1. InyourHTMLfilerevisethemostrecenttable,theonewithanid.Assignaclassto
thesecondrow.Savethefile.
2. InyourCSSfilecodealightbackgroundcolorforthatclass.Savethefile.
3. Displaythepage.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-48-1.html.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-48-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/48.html
49
Forms:theformtag
It’sararewebsitethatdoesn’tusesomeforms.Ataminimum,you’reprobably
goingtowanttoincludeanemailformonyoursitetomakeiteasyforuserstocontact
you.Everyformbeginsandendswithanopening<form>andclosing</form>tag.
<formaction=“send-email.php”method=“post”>
[Here’swherethecontentsoftheform,likeinput
fieldsandasubmitbutton,arecoded.We’llstart
workingontheseinthenextchapter.]
</form>
Inmostcases,whenausercompletesaform,aprogramseparatefromtheHTML
fileruns.Intheexampleabove,action=“send-email.php”tellsthebrowserthat
whentheusersubmitstheform,theinformationtheuserhasenteredintheformistobe
senttoaPHPprogramonthewebsiteforprocessing.Theprogram’sURLis“sendemail.php.”It’saprogramthatrunsonthehost’sserver.ThisisdifferentfromanHTML
file.AnHTMLfileisstoredonthehost’sserverbutrunsintheuser’sbrowser.
Inthecaseoftheexample,send-email.phpmightsendanemailtothesite
ownerthatincludesthedatatheuserhasentered.Oraprogrammightwritethedata
enteredbytheusertoadatabaseontheserver.Oraprogrammightprocesscreditcard
informationenteredinaform.
Thereareallkindsofprograms,writteninvariouslanguages,thatcanprocessdata
fromaform.ThelanguagesincludePHP,Ruby,Python,Perl,Java,andC#.The
processingprogramswrittenintheselanguagesareoutsidethescopeofthisbook,soyou
won’tlearnanythingaboutprocessingformshere,otherthanlearninghowtospecifythe
formactioninHTMLtags.
Butdon’tbediscouragedifyoudon’tknowanyoftheselanguages.Atsiteslike
http://www.hotscripts.com/you’llfindthousandsofprograms,bothfreeandforsale,that
processformsforeverypurpose.Youdon’tneedtoknowacomputerlanguagetouse
thesescripts.Thepeoplewhowritethemtellyouhowtochangeafewlinesofthecodeto
adaptthemsothey’llworkonyoursite.Makeafewsimplechanges,thenuploadthecode
toyoursite,andyou’reinbusiness.
Theexampleabovespecifiesmethod=“post”.Thismethodistheoneyouuseto
processmorethanalittlebitofinformation,andwhenyouwanttokeeptheinformation
secure.Thesecondmethod,get,isusedmostlyforsearchforms.Youknowaformis
usingthegetmethodwhentheinformationenteredintheform(connectedbyplussigns)
appearsintheURLafteryouclickSubmit.Here’stheURLthatdisplayedwhenIsearched
http://www.newyorker.com/search?
qt=dismax&sort=score+desc&query=alice+munro&submit=
Ifyoudon’tspecifyamethod,thegetmethodisused.Sincethisunsecuremethod
isn’tappropriateformostpurposes,you’llusuallywanttospecifythepostmethod.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/49.html
50
Forms:textinput
Here’saformthat’slimitedtoonesingle-linetextfield.It’suseless,becauseit
doesn’tincludeaSubmitbutton.We’lladdthatlater.
ThisistheHTML.
<formaction=“send-email.php”method=“post”>
Lastname:
<inputtype=“text”name=“surname”size=“25”maxlength=“40
</form>
Itbeginswithsomeplaintext,Lastname:Itdoesn’thavetobeplacedtotheleft
ofthefield.Itcouldbeabove,totheright,orevenbelowthefield.
Theinputtaghasfourparts:
1. type=“text”.Thistellsthebrowsertodisplayasingle-lineboxinwhichtheuser
canentertext.
2. name=“surname”.Thenamecanbealmostanythingyoulike,butdon’tuse
spacesinit.Thenametellstheprogramthat’sprocessingthedatawhattocallthe
informationthattheuserentersinthatfield.
3. size=“25”.Thistellsthebrowserhowwidetomakethebox.Whenyouwrite
size=“25”you’retellingthebrowsertomaketheboxroughly25characterswide.
Iftheusertypesmorethan25characters,thelinewillscrollhorizontally.Specifying
thesizeisoptional.Ifyoudon’tspecifyit,thebrowserwillmakeatextbox20
characterswidebydefault.
4. maxlength=“40”.Thistellsthebrowsertoputalimitonthenumberofcharacters
thatcanbetypedintothisfield.Ifthere’sscrolling,thescrollingwillstopatthis
limit.Specifyingthemaximumlengthisoptional.Ifyoudon’tspecifyit,theboxwill
acceptanynumberofcharactersandwillscrollasfarasitneedstoinorderto
accommodateallthecharacters.
Apasswordfieldislikeatextinputfield,exceptthatthecharactersthattheuser
entersaredisguisedasasterisksorcirclesinthefield.Youcodeapasswordfieldthesame
wayyoucodeatextinputfield,exceptthatyoureplacetheworld“text”withtheword
“password”.
Alloftheindividualpartsofaform—theone-linetextboxthatyoujustlearnedto
createandalltherestthatyou’reabouttolearn—arecalledcontrols.
Codeaformwithasingletextinput.Don’tbotherwiththeactionormethod.Specify
name,size,andmaxlength.Savethefile.Displaythepage.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-50-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/50.html
51
Forms:textarea
Inthelastchapteryoulearnedhowtocodeaone-linetextboxusinginput
type=“text”.Here’sasecondtypeofcontrol,amulti-linetextbox.(Inthisexample
formIhaven’tincludedafirst-namefield.Thisexampleformisonlyforlearning,sowe’ll
limitittojustonecontrolofeachtype.)
ThisistheHTML.
<formaction=“send-email.php”method=“post”>
Lastname:
<br>
<inputtype=“text”name=“surname”size=“25”maxlength=“40”>
<br><br>
Message:
<br>
<textareaname=“message”rows=“4”cols=“30”></textarea>
</form>
Notice,first,thatthistagisclosed,with</textarea>.
rows=“8”cols=“30”specifiesthenumberofvisiblerowsandcolumns.By
default,thefieldcanberesizedbytheuserwhenshedragsthelower-rightcornerwiththe
mouse.
InyourHTMLfileaddatextareatotheformyou’vealreadycoded.Specifyrows
andcolumns.Savethefile.Displaythepage.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-51-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/51.html
52
Forms:submit
Let’saddasubmitbuttontotheform.Whentheuserclicksit,theformissubmitted.
Thatis,allthedataissenttotheprogram(PHPoranotherlanguage)thatprocessesit.
Thisisthecode.
<formaction=“send-email.php”method=“post”>
Lastname:
<br>
<inputtype=“text”name=“surname”size=“25”maxlength=“40”>
<br><br>
Message:
<br>
<textareaname=“message”rows=“4”cols=“30”></textarea>
<inputtype=“submit”value=“Sendemailmessage”>
</form>
Thisisasimpleinputtag,withonlytwoparts.Thefirstpartcreatesthebuttonthat,
whenclicked,submitstheform:
inputtype=“submit”
Thesecondpartspecifiesthebuttontext.Insteadof“Sendemailmessage,”itcould
be“Submit,”“Send,”“Subscribe,”“Purchase,”oranyothertextyouwant…
value=“Sendemailmessage”
Thesubmittagcreatesastandardbutton.Ifyouwantacustombutton,createyour
ownbuttonimageandwriteataglikethis.
<inputtype=“image”src=“images/subscribebutton.png”alt=“Signup”width=“72”height=“18”>
ThebrowserknowsthisisaSubmitbuttoneventhoughyousaytheinputtypeis
“image”.Everythingyouwriteafter<inputtype=“image”isexactlythesameas
theimgtagyoulearnedtowriteinChapter24.
InyourHTMLfileaddaSubmitbuttontotheformyou’vealreadycreated.Save
thefile.Displaythepage.SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-52-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/52.html
53
Forms:radiobuttons
Nowwe’lladdradiobuttonstotheform.Radiobuttonsallowtheusertomakeone
andonlyoneselection.We’llasktheusertotellushowshefoundoursite.
<formaction=“send-email.php”method=“post”>
Lastname:
<br>
<inputtype=“text”name=“surname”size=“25”maxlength=“40”>
<br><br>
Howdidyoufindus?<br>
<inputtype=“radio”name=“foundthru”value=“Google”checked=“checked”>Google
<inputtype=“radio”name=“foundthru”value=“Review”>Review
<inputtype=“radio”name=“foundthru”value=“Friend”>Friend
<br><br>
Message:
<br>
<textareaname=“message”rows=“4”cols=“30”></textarea>
<br><br>
<inputtype=“submit”value=“Sendemailmessage”>
</form>
Noticethateachradiobuttonhasitsownseparateinputtag.Whatbindsallthe
radiobuttonsinagrouptogetheristhatthey’reallgiventhesamename.Intheexample,
I’vegivenitthename“found-thru.”
Itbeginsasotherinputtagsdo,butspecifies“radio”insteadof“text,”“submit,”
oranotherinputtype…
inputtype=“radio”
Thename,sharedbyalltheradiobuttonsinaparticularradiobuttongroup,bindsall
thebuttonswithinthegrouptogether.Youmakeupthename…
name=“found-thru”
Thevalueisthewordorwordssenttotheprocessingprogramtellingtheprogram
whichbuttonhasbeenchecked.
value=“Google”
Thenextpartisoptional.Whenyouincludeitinatag,itmeansthebuttonis
checkedbydefault.Sinceonlyonebuttoninagroupcanbechecked,youwouldinclude
thisinonlyonebuttontagwithinagroup.Ifyouomitit,nobuttonischeckedbydefault.
checked=“checked”
Finally,there’sthetextthattheusersees.Itwouldnormallybethesamewordor
wordsthatyouspecifyforvalue.
Google
InyourHTMLfileaddtworadiobuttonstotheformyou’vealreadycoded.Savethe
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-53-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/53.html
54
Forms:checkboxes
Checkboxesworklikeradiobuttons,exceptthattheusercancheckmorethanone.
Let’saddcheckboxesthatallowtheusertogiveussomefeedback.
Thisisthecode.
<formaction=“send-email.php”method=“post”>
Lastname:
<br>
<inputtype=“text”name=“surname”size=“25”maxlength=“40”>
<br><br>
Howdidyoufindus?<br>
<inputtype=“radio”name=“foundthru”value=“Google”checked=“checked”>Google
<inputtype=“radio”name=“foundthru”value=“Review”>Review
<inputtype=“radio”name=“foundthru”value=“Friend”>Friend
<br><br>
Howwouldyoudescribeoursite?<br>
<inputtype=“checkbox”name=“feedback”value=“Wonderful”checked=
<inputtype=“checkbox”name=“feedback”value=“Fabulous”>Fabulous
<inputtype=“checkbox”name=“feedback”value=“Brilliant”>Brillia
<br><br>
Message:
<br>
<textareaname=“message”rows=“4”cols=“30”></textarea>
<br><br>
<inputtype=“submit”value=“Sendemailmessage”>
</form>
Again,aswithradiobuttons,eachcheckboxhasitsownseparateinputtag.And
again,whatbindsallthecheckboxesinagrouptogetheristhatthey’reallgiventhesame
name.Intheexample,thenameis“feedback.”
You’refamiliarwiththebeginningpartbynow.
inputtype=“checkbox”
Thename,sharedbyallthecheckboxesinaparticularcheckboxgroup,bindsallthe
checkboxeswithinthegrouptogether.Youmakeupthename.
name=“feedback”
Thevalueisthewordorwordssenttotheprocessingprogramtellingtheprogram
thatthisboxhasbeenchecked.
value=“Wonderful”
Thenextpartisoptional.Whenyouincludeitinatag,itmeanstheboxischecked
bydefault.Youcanusethisspecificationtopre-checkasmanyboxesasyoulike.Ifyou
omititfromallcheckboxtags,noboxispre-checked.
checked=“checked”
Finally,there’sthetextthattheusersees.Itwouldnormallybethesamewordor
Wonderful
InyourHTMLfileaddtwocheckboxestotheformyou’vealreadycoded.Savethe
file.Displaythepage.SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-54-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/54.html
55
Forms:selectbox
Thestandardwaytoasktheusertotellyouthestatehelivesinistheselectbox.A
selectboxworkswellwhenyouwanttheusertoselectfromalistthat’stoolongtobe
handledgracefullybyradiobuttons.Likeradiobuttons,onlyoneselectioncanbemadein
aselectbox.Let’saddoneforastateselection.I’lljustdothreestatestoshowyouhowit
works.
Thisisthecode.
<formaction=“send-email.php”method=“post”>
Lastname:
<br>
<inputtype=“text”name=“surname”size=“25”maxlength=“40”>
<br><br>
Howdidyoufindus?<br>
<inputtype=“radio”name=“foundthru”value=“Google”checked=“checked”>Google
<inputtype=“radio”name=“foundthru”value=“Review”>Review
<inputtype=“radio”name=“foundthru”value=“Friend”>Friend
<br><br>
Howwouldyoudescribeoursite?<br>
<inputtype=“checkbox”name=“feedback”value=“Wonderful”checked=
<inputtype=“checkbox”name=“feedback”value=“Fabulous”>Fabulous
<inputtype=“checkbox”name=“feedback”value=“Brilliant”>Brillia
<br><br>
Yourstate:<br>
<selectname=“current-state”>
<optionvalue=“AL”>Alabama</option>
<optionvalue=“AK”>Alaska</option>
<optionvalue=“AZ”>Arizona</option>
</select>
<br><br>
Message:
<br>
<textareaname=“message”rows=“4”cols=“30”></textarea>
<br><br>
<inputtype=“submit”value=“Sendemailmessage”>
</form>
Thesyntaxforaselectboxisdifferentthanthesyntaxyou’velearnedforotherinput
types.
Startswith<select,not<inputtype=
Unlikeradiobuttonsandcheckboxes,whicharefreestandingandboundtogetherbya
commonname,allthechoicesareenclosedbyopeningandclosingselecttags.
Unlikemostotherinputtypes,optiontagsareclosed.
Thenameisspecifiedonlyonce,intheselecttag.
Bydefault,thefirstoptionispre-selected.Intheexample,it’sAlabama.Youcan
pre-selectanotheroptionbyincludinginoneoftheoptiontagsthewords
Aproblemwiththeexampleisthatiftheuserdoesn’tbothertomakeaselection,his
statewillbeinputasAlabamaevenifhelivesinAlaska,sinceAlabamadefaultsasthe
choiceiftheuserdoesn’tmakeone.Thesolutionistomakethefirstoptionsomethinglike
“Selectastate.”Whentheuserclickstheinputbutton,alittleJavaScriptroutinecancheck
toseewhether“Selectastate”istheselectedoption,whichmeansthattheuserhasn’t
madeaselection.Ifso,theusercanbepromptedtoselectastate.MybookASmarter
WaytoLearnJavaScript,availableatAmazon,showsyouhowtowritethisroutine.
InyourHTMLfileaddaselectboxwithtwoselectionstotheformyou’vealready
coded.Savethefile.Displaythepage.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-55-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/55.html
56
Forms:label
It’sagoodideatogiveeachcontrolalabeltag.Theformtagitselfdoesn’ttake
one,butit’sagoodideatoaddonetoeachtextfield,textarea,radiobutton,checkbox,
andselectionoption.Butitisn’trequired.
Labelsallowscreenreaderstocalloutthetextthatgoeswitheachcontrol.
Forexample,iftheuserisworkingwithascreenreaderandyou’regotaone-line
textboxfortheuser’slastname,thelabeltagmakesthescreenreadersay,“Lastname”
whentheusertabstothefield.
Inadditiontomakingthetextreadablebyascreenreader,alabelmakesthetext
clickablelikethecontrolitself,givingtheuserabiggertarget.Thisisespeciallyhelpful
forradiobuttonsandboxes,whichcanbehardtohitwiththecursor.Forexample,ifyou
write…
<label><inputtype=“radio”name=“foundthru”value=“Google”>Google</label>
…theuserdoesn’thavetohitthebutton.Hecanclick“Google”andthebuttonwill
bechecked.
Noticehowthelabeltagenclosesboththetextandthecontrol.Thisistheeasyway
toaddalabeltag.Thehardway,preferredbyexpertsforesotericreasons,requiresthat
yougivethecontrolanid.Inthismethod,theopeningandclosinglabeltagsencloseonly
thetext.
<inputtype=“radio”name=“foundthru”id=“goo”value=“Google”>
<labelfor=“goo”>Google</label>
InyourHTMLfileusetheeasywaytoaddlabelstotheradiobuttons.Usethehard
waytoaddlabelstothecheckboxbuttons.Savethefile.Displaythepage.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-56-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/56.html
57
Groupingrelatedelements
Ifyourformhasalotofparts,youcanimprovetheuser’sexperiencebygrouping
relatedpartstogethervisually.Takethisform…
It’llbeeasierfortheusertounderstandifyouencloseeachgroupinabox…
Thisisthecode.(I’veaddedalittleCSSstyling.Wewon’tgointothatnow.)
<formaction=“questionnaire.php”method=“post”>
<fieldset>
<label>Firstname:<inputtype=“text”name=“firstname”size=“15”maxlength=“30”></label>
<label>Lastname:<inputtype=“text”name=“lastname”size=“15”maxlength=“30”></label><br><br>
<label>Email:<inputtype=“text”name=“email”size=“25”maxleng
</label>
</fieldset>
<br>
<fieldset>
<textareaname=“meaning”rows=“4”cols=“40”>
</textarea></label><br><br>
Whatdoyouwantonyourpizza?<br>
<label>
<inputtype=“checkbox”name=“topping”>Pepperoni</label>
<label>
<inputtype=“checkbox”name=“topping”>Sausage</label>
<label>
<inputtype=“checkbox”name=“topping”>Mushrooms</label>
<label>
<inputtype=“checkbox”name=“topping”>Olives</label>
</fieldset>
</form>
Byenclosingthetwogroupsofcontrolsinopeningandclosingfieldsettags,we
tellthebrowsertoenclosethegroupsinseparateboxes.
Notethateverythingwithinthefieldsettagsisindented2spaces.
Wecanimprovethereadabilityoftheformevenfurtherbyaddinglegends—
descriptivetextthat’satthetopofthebox.
Nowthefirstgrouphasthelegend“Contactinfo”andthesecondgrouphasthe
legend“Questions.”Thisisthecode.
<formaction=“questionnaire.php”method=“post”>
<fieldset>
<legend>Contactinfo</legend>
<label>Firstname:<inputtype=“text”name=“firstname”size=“15”maxlength=“30”></label>
<label>Lastname:<inputtype=“text”name=“lastname”size=“15”maxlength=“30”></label><br><br>
<label>Email:<inputtype=“text”name=“email”size=“25”maxleng
</label>
<br>
<fieldset>
<legend>Questions</legend>
<label>Whatisthemeaningoflife?<br>
<textareaname=“meaning”rows=“4”cols=“40”></textarea>
</label><br><br>
Whatdoyouwantonyourpizza?<br>
<label>Pepperoni<inputtype=“checkbox”name=“topping”>
</label>
<label>Sausage<inputtype=“checkbox”name=“topping”>
</label>
<label>Mushrooms<inputtype=“checkbox”name=“topping”>
</label>
<label>Olives<inputtype=“checkbox”name=“topping”>
</label>
</fieldset>
</form>
Thelegendtagsgoonthelinefollowingtheopeningfieldsettagand,like
everythingenclosedbythefieldsettags,areindented2spaces.
InyourHTMLgroupthetwotextfieldswithonesetoffieldsettagsandthe
radio,checkbox,andselectioncontrolswithasecondsetoffieldsettags.Makeup
legendsforbothgroups.Savethefile.Displaythepage.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-57-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/57.html
58
Forms:styling
Here’safilled-outformwithoutanyCSSstyling.
NowI’llgiveitsomestyling.Itisn’tmuseum-quality,butIlikeitbetter.
TherearemorewaystocustomizeHTMLformsthantherearestarsinthegalaxy.
LetmeshowyoutheminimalstylingIusedfortheformshownabove.
Tobeginwith,Istyledthelabelsandlegendsbyspecifyingasans-seriffont-family
andlargerfont-sizefortheform.
form{
width:50%;
margin:0auto0auto;
font-family:Verdana,Geneva,sans-serif;
font-size:1em;
}
Thestylingshownabovecontrolsthewidthoftheformandalsocentersit.Fontstylingfortheformaffectsonlythelabelsandlegends.Iwantedalargerfont-sizeforthe
userinputsaswell,soIhadtocreateseparatestylingforthem.
input[type=“text”],input[type=“email”],textarea{
margin-bottom:.25em;
padding:.25em;
font-size:1em;
}
Asyoucansee,thesyntaxvaries,dependingonthetypeofinputsyou’restyling.
Forsingle-linetextandemailinputs,theselectorsareinput[type=“text”]and
input[type=“email”].
Foratextarea,it’sjusttextarea.
IwantedaheftySubmitbutton,soIcodedthisstyling.
input[type=“submit”]{
font-size:1.25em;
}
Thebuttonwillexpandtoaccommodatetheenlargedtext.
Iboldedthelegends.
legend{
font-weight:700;
}
InyourCSSfiledoublethefont-sizeoftextinputandtextareacontrols,andgive
themsomepaddingallaround.Savethefile.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-58-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/58.html
59
Comments
Commentingisawaytotellthebrowsertoignorecertainportionsoftextthatyou
includewithinthebodyofcode.Commentsareforthehuman,notthemachine.Theyhelp
youandothersunderstandyourcodewhenitcomestimetorevise.Youcanalsouse
commentingtocommentoutportionsofyourcodefortestinganddebugging.
InHTMLanytextenclosedbyanopening<!—tagandaclosing-->tagis
invisibletothebrowser.Inthefollowingcode“Beginningofquestionnaireform”isa
commentthatthebrowserignores.
<!—Beginningofquestionnaireform-->
<formaction=“questionnaire.php”method=“post”>
<fieldset>
<legend>Contactinfo</legend>
<label>Firstname:<inputtype=“text”name=“firstname”size=“15”maxlength=“30”></label>
[etc.]
Here’samulti-linecomment.Whenyouwriteamulti-linecomment,putthetagson
theirownseparatelinesforreadability.
<!—
Notetomyself.Thinkaboutcombiningthe
questionnaireformwiththefeedbackform.
-->
YoucanalsocommentCSScode,butthetagsaredifferent.It’s/*toopen,*/to
close.
/*Stylesforheadings*/
h1{
font-size:3em;
}
h2{
[etc.]
Youcanhavemutli-lineCSScomments.Again,puttagsontheirownseparatelines
forreadability.
/*
ThisCSSfilewascreatedonMay28,2018.
Thestylesareoptimizedforalearningsite.
*/
InyourHTMLfileaddamulti-linecomment.InyourCSSfileaddamulti-line
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-59-1.html.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-59-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/59.html
60
Layout:nestedboxes
ThefirstthingtoknowaboutHTMLpagelayoutisthatit’salwaysacollectionof
invisiblenestedboxes.Everything,fromtheheadertotheshortestparagraphortiniest
icon,isinsidesomethingelse.
Inanearlierchapteryoulearnedthatallofthecontentofawebpageisenclosedby
anopening<body>tagandclosing</body>tag.Thismeansthatthebodyisthe
biggestbox,theboxthatcontainseverythingelse.(Well,it’sthebiggestboxyourCSS
codecanaffect.Thebodyisactuallyinsidetheboxcreatedbytheopening<html>and
closing</html>tags.)ThinkofthebodyasthebrownboxwiththeAmazonlogoonit
thatthepostalcarrierdelivers.Alltheotherboxesareinsideit.Totakethemetaphoreven
further,theoutermostbox,definedbytheopeningandclosing<html>tags,whichyou
neverdealwithexcepttowritethetags,isthemailtruck.
Howmanyboxesarecontainedinsidethebigouterbox(thebody),andhowmany
levelsofnestingwindupinsideit,aredecisionsyoumake,dependingonwhatyouwant
yourpagetolooklike.Ataminimum,mostprofessionalwebsitesincludeacollectionof
boxesthatlookssomethinglikethis.
Oftheboxesshowninthediagram,theonlybigboxthatyouabsolutelymusthave
inyourcodeistheouterboxcreatedbytherequiredopening<body>andclosing
</body>tags.Youcan,ifyouchoose,putallofyourheadings,paragraphs,images,and
linksinsidethatonebig,undifferentiatedbox,andsomepeopledo.You’veseensuch
pages.Thetextstretchesallthewayacrossthebrowserwindow.There’snolayout,really.
Youexitthesiteasfastasyoucan.
Thediagramaboveshowstheboxesthatrepresentmajorsectionsofthepage.IfI
hadwantedtoshowallthesmallerboxesthatarecontainedwithinthoseboxes,Iwould
haveincludedtheboxescontainingtext.Theseboxesarecreatedbyopening<p>and
closing</p>tags,openingandclosingheadingtags,opening<ul>andclosing</ul>
tags,andopening<li>andclosing</li>tags.OnanHTMLpage,everythingisinside
somethingelse.WheneveryouwriteanHTMLtag,youcreateabox.Theopening<p>
andclosing</p>tagsinthefollowingexamplecreateaboxcontainingthetext“Hey
now!”
<p>Heynow!</p>
Inthefollowingexampletheopening<a>andclosing</a>tagscreateabox
containingthetext“StackOverflow.”
ahref=“http://www.stackoverflow.com”>StackOverflow</a>
Foranyboxofanysize,itscontentsareaffectedbyanystylesyouspecifyforthat
box.Soifyouwrite…
p{
color:purple;
}
…allthetextenclosedbyanopening<p>tagoraclosing</p>tagwillbe,God
helpyou,purple.
…unlessyoumakeanexception.Forexample,youcanwrite…
.sane-color{
color:black;
}
Then,althoughthegeneralstyleforparagraphsisstillpurple,anytextenclosedbya
tagthatbegins<pclass=“sane-color…”willbeblack.
Oryoucouldwrite…
<p>Thisis<spanclass=“sane-color”>not</span>apretty
sentence.</p>
…andyou’vecreatedaspanboxwithintheparagraphboxthatcolorstheword
“not”black,whiletherestofthesentenceispurple.
Here’ssomestylingforthebiggestbox,theboxthatcontainsever
body{
width:100%;
font-size:1em;
background-color:white;
color:black;
}
Sincethebodyisthebiggestbox,thisbitofCSSmeansthatallthetextonthepage,
includingallparagraphs,headings,tabletext,andlistitems,willbeblackonawhite
background,willbeintheGeorgiafontoravariant,andwillbebasedonthebrowser’s
defaulttextsize.
…unlessyoumakeanexception.Andofcourse,youmightmakeallkindsof
exceptions,onjustabouteverylevel.Forexample,youcancreateageneralstylefor
paragraphsthatdiffersfromthedefaultforalltextestablishedinthebodystyle.Another
example:whenyouexplicitlycallforpurpletextasapstyle,alltextenclosedin<p>tags
ispurpleratherthanthebody’sdefaultblack.Asyoulearnedinanearlierchapter,youcan
alsomakeexceptionstothatrulebycreatingclassesandIDsforparagraphsthatspecify
differentcharacteristics.
LaterI’lldiscussthewidth:100%andfont-size:1emspecificationsinthe
bodystyleshownabove.Butfirstweneedtotalkabouthowtocreatethebigsections,
liketheheaderandmainsections,showninthediagramabove.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/60.html
61
Layout:divs
AlltheboxesthatconstituteanHTMLlayoutarecontainedinthebigboxcreatedby
theopening<body>andclosing</body>tags—thetagsthatbeginandendthemain
sectionofeveryHTMLdocument.Inthediagraminthelastchapter,yousawsome
relativelylargeboxesnestedinsidethebigoutermostBodybox.Whatthediagramdoesn’t
showisallthesmallerboxesnestedinsidetheserelativelylargeboxes.Thesmallerboxes
arecreatedbytheopeningandclosingtagsforheadings,paragraphs,listitems,andsoon.
Sohowdoyoucreatetherelativelylargeboxes,fortheheader,navigationsection,
mainsection,andsoon—theboxesshowninsidethebigBodyboxinthediagram?
Youcreatetheseboxesbyusingdivtags.Forexample:
<divid=“content”>
<h3>Theslowloris.</h3>
<imgsrc=“slowloris.jpg”alt=“Slowloris”width=“55”height=“85”>
<p>Slowlorisesareagroupofseveralspeciesofprimateswhich
</p></div>
Intheexample,therearethreeelementsgroupedtogetherinsidethediv—a
heading,animage,andaparagraph.Justasanystylingthatyouspecifyforthebodywill
beappliedtoallelementscontainedinthebodyunlessyoumakeexplicitexceptions,any
stylingthatyouspecifyforthedivwillbeappliedtoallelementsinsidethedivunless
youmakeexplicitexceptions.IntheHTMLcodeabove,I’vecreatedadivwithanidof
“content.”I’llstylethedivwithacolor.
div#content{
color:red;
}
Withthisstyle,theheadingandparagraphtextinthedivwillbered—unlessyou
createexceptions.Anexceptionwouldbeifyou’veexplicitlyspecifiedaparticularcolor
forh3headingsoraparticularcolorforparagraphs.Thenthosespecificationswill
overridethedefaultcolorthatyou’respecifyingforthediv.
Stylingprecedenceworkslikethis:
Stylingforaninnerboxoverridesstylingforanouterbox.Forexample,inthelast
chapterwespecifiedblackasthecolorforallthetextinthebody.Blackisthecolor
unlessotherwisespecified.Thisdefaultisoverriddenbythedivwecreatedabove,
whichcallsforredtext.Sonowthedefaultcolorforallthetextinthedivisred.
Stylingforanelement,likeaparagraph,overridesstylingforadiv.Thisisreally
thesameruleasthefirstruleabove,sincetheboxcreatedbytagsisinsidethebox
stylingforanouterbox.Stylingforthedivsaysblack,butwecreateastyleforallp
elementsthatsayspurple,thepurpleparagraphstylewilloverridethedivblack
style.
Classandidstylingoverridegeneralstyling.Ifwecreatea“sane-color”classof
paragraphs,thegeneralpurplespecificationforparagraphsisoverriddenforany
paragraphswhosetagbegins<pclass=“sane-color…”
WhydidIcreateanidforthedivratherthanaclass?Becausethisparticulardiv—
theonethatcontainsallthecontentonthepage—occursjustonceinthedocument.A
classcanbeusedmorethanonce,anidonlyonce.Ifwewerestylingadivthatmight
occurmorethanonceintheHTML,we’dcreateaclassratherthananid.
Asyou’veseeninthischapter,adivishandyforsettingdefaultstylingwithina
section,butthemostimportantfunctionofdivsislayoutpositioning.That’snext.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/61.html
62
Layout:
divwidthsandcentering
Let’stalkaboutthedivthatcontainsmostofthecontentofthepage,theonethat,in
ourexample,createstheMainbox.It’sthethirdboxdowninthediagramshowninthe
lastchapter.StickingwiththenameIusedinthediagram,we’llgivethedivanidof
“main.”
Usually,youdon’twantthecontentsofasectiontobumpupagainsttheleftand
rightedgesofthewindow.Asinabook,youcreatesomewhitespaceontheleftandright.
Agoodwaytodoitistospecifyawidthforthesection,likethis.
div#main{
width:90%;
}
Thisstyleaddsaminimumamountofwhitespaceontheside.
But90%ofwhat?Well,whenyouspecifyemsorpercentages,thesevaluesare
alwaysrelativetowhat’s“normal”—eitherthebrowser’sdefaultorastyleyou’ve
overriddenwithCSSstyling.Inourexample,wecreatedadefaultwidthinthebody
styling,width:100%.Thisstyletellsthebrowsertomakethebodywidththefull
widthofthebrowserwindow.That’sthebrowser’sdefault,sowe’rejusttellingittodo
whatitwoulddoanyway.Butbymakingitexplicit,wetellanyhumanreaderstryingto
understandourCSSthatwe’reacceptingthebrowser’sdefault.
Sowhenyouspecifywidth:90%forthemainsection,you’retellingthebrowser
tomakethesectiononly90%aswideasthebrowserwindow.Ifwehadspecified
width:60%forthebody,specifyingwidth:90%forthemainsectionwouldmake
thesection60%times90%,or54%ofthefullwindowwidth.
Butthere’saproblem.Bydefault,browsersplacethingsontheleft.Thismeansthat
ifwemakethemainsectionnarrowerthanthebody,themainsectionwillbumpup
againsttheleftedgeofthebrowserwindow,andallthewhitespacewillwinduponthe
right.That’snotwhatwewant.Wewantthesectioncentered.Soweaddaline.
div#main{
width:90%;
margin:0auto0auto;
}
Oncewe’vetoldthebrowserhowwidetomakethediv,specifyingautoforleft
andrightmarginstellsthebrowserthatifthere’sanywidthleftover—inthiscase10%—
tosplitthedifference.Nowthere’llbeamarginontheleftthat’sequalto5%ofthe
willbecentered.
Youcanmakethesectionnarrower,withwidermargins,byreducingthepercentage
youspecifyforthewidth.
Youcanaddwhitespaceaboveand/orbelowthesectionbyreplacingthezeroswith
emvalues.
div#main{
width:90%;
margin:1.5emauto1%auto;
}
You’llhavetoplayaroundwiththeemvaluestogetthemarginstosuityou.
Nowsupposeyouhaveseveraldifferentdivswithinthemaindiv,andyouwant
togivetheseproportionallythesamemarginsthatyou’veassignedtothemaindiv(not
thatthemarginshavetobeproportional).Youcoulddothisbyusingexactlythesame
specificationsyouusedforthemaindiv.
div.inset{
width:90%;
margin0auto0auto;
}
Sinceallvaluesoftheinnerdivarerelativetothevaluesoftheouterdiv,the
divsoftheclass“inset”willhave90%ofthewidthoftheouterdiv.Thisistheresult.
Ofcourse,theinnerdiv’swidthvaluedoesn’thavetobethesameasthewidth
valueoftheouterdiv.Ijustdiditthiswaysoyoucanseethatthewidthoftheinner
div,thoughitsharesthesamevalue,isnarrowerthantheouterdiv,sinceit’s90%of
90%ofthebodywidth,whereastheouterdivis90%ofthefullbodywidth.
InChapter60Ipromisedtodiscusstwospecificationsinthebodystyling:
body{
width:100%;
font-family:Georgia,“TimesNewRoman”,Times,serif;
font-size:1em;
background-color:white;
color:black;
}
Amomentago,Idiscussedthewidth:100%specificationforthebodystyle,
sayingthatit’sredundantinthesensethatyou’retellingthebrowsertodowhatitwould
doanyway.Thepurposeistohelpothercoders,byexplicitlysayingthatyou’reaccepting
thedefaultwidth—thefullwidthofthebrowserwindow—asthebodywidththatthe
lettingothercodersknowthatyou’reacceptingthebrowser’sdefaultsizeasthevaluethat
allotherstyleswillbebasedon.
InyourCSSfilecodeadividthat’s20%wideandcentered.InyourHTMLfile
codethedivandputaparagraphinit.Savethefiles.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-62-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-62-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/62.html
63
Side-by-sidedivs
Lookattheboxdiagramagain.I’vemadeasmallchangetoit.I’venudgedthe
Contentsectionleft,soit’supagainsttheleftsideoftheMainbox,andtheSidebar
sectionright,soit’supagainsttherightsideoftheMainbox.Intheoriginaldiagram,I
leftsomespacebetweenthesetwosectionsandtheMainsectionsoyoucouldseeallthe
boxesclearly,butIdon’treallywantanyextrawhitespaceontheleftandrightbetween
theouterboxandthetwoinnerboxes.
Iwantthetwosectionstositside-by-side.Iwantnoextrawhitespaceontheleftor
right,separatingthemfromtheouterMainbox.Thisishowwedoit.
First,wespecifyawidthforeachofthetwoinnerboxessowhentheirwidthsare
addedtogethertheydon’tadduptomorethan100%ofthewidthofthedivthatcontains
them,theMainbox.ButsinceIdon’twantthembumpingupagainsteachotherinthe
middle,I’mgoingtogivethemwidthsthatadduptojust97%.Thisleavestheremaining
3%foracentergutterbetweenthem.Here’sthecode.
div#content{
width:68%;
}
div#sidebar{
width:29%;
}
Sofar,thisstylingdoesn’tpreventthebrowserfromplacingoneelementunderneath
theother.Ifwedon’tdosomethingaboutit,theseconddivwillgorightunderneaththe
firstdiv,sinceadivisablockelement.Bothofthemwillbeflushwiththeleftedgeof
theMainbox.Soweneedtodoonemorething.Rememberhowyoulearnedtowrite
float:leftandfloat:righttostyleanimagesotextwrapsaroundit?Weuse
thesamelanguagetoplacethetwodivsside-by-side.
div#content{
width:68%;
float:left;
}
div#sidebar{
width:29%;
float:right;
}
Nowthey’reside-by-side,andthere’sagutterbetweenthemthat’s3%ofthewidth
oftheircontainingelement,theMainbox.
Letmegiveyouanotherexample.Supposeyouwantthreedivsofequalwidth
placedside-by-side.
div#d1{
width:31%;
float:left;
}
div#d2{
width:31%;
float:left;
margin:0003.5%;
}
div#d3{
width:31%;
}
Thefirsttwodivsarefloatedleft.Thethirddivisfloatedright.Eachdivis31%
wide,addinguptoatotalof93%ofthewidthofthecontainingMainbox.Thatleaves7%
forthetwogutters.Ispecifyaleftmarginof3.5%fortheseconddiv,forcingittothe
right.Thisleaves3.5%forthesecondgutter.Nowthethreesectionsarespacedevenly.
RememberlearninginChapter27thatyouneedtoclearimagefloatstoavoidunintended
wraps?Youdothesamethingwithdivfloats.
.no-wrap{
clear:both;
}
Aftercodingside-by-sidedivsinHTML,you’dcodeanemptydivwhoseonly
purposeistoclearthefloataboveit.
<divclass=“no-wrap”></div>
Oryoucoulddoitwithaparagraphthatclearsthefloat.
InyourCSSfilecreatetwodividsthatwillplacethedivsside-by-side,witha
gutterofwhitespacebetweenthem.InyourHTMLfilecodethetwodivsandputa
paragraphineachone.Savethefiles.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-63-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-63-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/63.html
64
Layout:
amodernheaderpart1
Theboxdiagramwe’vebeenworkingwithshowstheheadersectionscaledalittle
narrowerthanthebodysection,withsomewhitespaceatthetop.
Whenthepagedisplays,there’sasmallamountofwhitespacebetweenthetopedge
ofthewindowandthetopoftheheader.Andthere’sasmallamountofwhitespacealsoon
bothsidesoftheheader.Thishappensautomaticallyifyoudon’toverrideit.
Aheaderwithwhitespaceallarounditisacceptable,butamoremoderndesign
wouldhavetheheaderonacolorblockthatisflushwiththetopofthewindowand
stretchesallthewayacrossthewindowfromedgetoedge.Theboxdiagramwouldlook
likethis.
Let’smakeoneofthesemodernheaders.
Westartbymakingtheheaderstretchfromedgetoedge.Andwecreatethecolor
blockbygivingitabackground-colorofdarkcrimson.
div#header{
background-color:#990000;
}
ThisistheHTMLthatcreatesthediv.
<divid=“header”>
[Thecontentsofthedivwillgohere.]
</div>
Byspecifyingawidthof100%,we’veaskedthebrowsertostretchthedivfrom
edge-to-edge,butthebrowserisn’tcooperatingfully.It’sstillleavingalittlewhitespace
ontheleftandrightedges.
Soweneedtoforcetheissue:
div#header{
width:100%
position:absolute;
left:0;
background-color:#990000;
}
Byspecifyingposition:absolute,weoverridewhateverthebrowserthinks
wemeanbywidth:100%andexplicitlytellitwherewewanttheleftedgetostart.By
specifyingleft:0,wesay,“Startit0pixelsinfromtheleftedgeofthewindow.”In
otherwords,eliminateallwhitespace.Happily,withoutanyadditionalinstructions,the
browsereliminatesallwhitespaceontherightedgeaswell.
But,thankstothebrowser’stendencytosurroundadivwithwhitespace,westill
haveagapabovetheheader.Howdowesolvethis?Youcanprobablyguess.
div#header{
width:100%
position:absolute;
top:0;
left:0;
background-color:#990000;
}
Nowwe’vetoldthebrowsertostartthediv0pixelsfromthetopofthewindow.
Thegapdisappears.
Sodoweseeacolorblockatthetopofthebrowser?No.Ifyouopenthepageina
browser,thecolorblockisn’tanywheretobefound.
InthenextchapterI’lldealwiththis.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/64.html
65
Layout:
amodernheaderpart2
Inthelastchapterwetookthefirststepstocreateaheaderthat’sflushwiththetop
ofthebrowserwindowandstretchesfromedgetoedgeofthewindow.Wespecifieda
widthof100%forthediv.Weinstructedthebrowsertoeliminatethewhitespaceitwould
normallyaddtothetopandsides.Andweaddedabackgroundcolor.
Butnoheadercolorblockshowedup.Why?Becausewithoutaheightspecification
oranycontentthatwouldforcethebrowsertostretchthedivupanddownto
accommodatethecontent,thebrowserassignsthedivaheightof0.Thecrimsoncolor
blockhasawidthbutnoheight.It’sone-dimensional,aninvisiblephantom.
Wecouldassignitaheight,specifyinganumberofpixels,butwe’reavoidingpixels
becausetheypreventthepagefromadaptingtodifferent-sizewindows.Wecouldassignit
aheightasapercentagetoavoidthepixelproblem,butwedon’tneedto.Whenweput
somecontentinsidethediv,thedivwillexpandtoaccommodateit.Forcontent,I’ll
startwithaheading.
Westartbycreatingastylefortheheading.
div#headerh2{
font-family:Verdana,Geneva,sans-serif;
font-weight:900;
color:white;
}
Thehighlightedfirstlinesays,“Applythisstyletoanh2headingwithinthediv
whoseidis“header.”Nowwecanwrite…
<divid=“header”>
<h2>ASmarterWaytoLearn</h2>
</div>
…andaheaderappearsinthebrowser.
I’dliketomaketheheadingalittlebeefier,soIaddthis:
div#headerh2{
font-family:Verdana,Geneva,sans-serif;
font-weight:900;
color:white;
font-size:2em;
}
Thisistheresult:
div#headerh2{
font-family:Verdana,Geneva,sans-serif;
font-weight:900;
color:white;
font-size:2em;
margin-left:2%;
padding:0;
}
Andherewego:
InyourCSSfilecodea100%-widedivwithabsolutepositioningatthetopleft.
Assignitalightcolor.InyourHTMLfilecodethedivandputaheadinginit.Savethe
files.Displaythepage.(Thedivwillbeatthetopofthepageifyoucodedcorrectly.)
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-65-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-65-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/65.html
66
Layout:
amodernheaderpart3
Let’saddalogototheheader.We’llplaceittotheleftoftheheadertext.
Here’sastart:
<divid=“header”>
<imgsrc=“images/logo_led_bulb.png”alt=“logo”width=“40”height=
<h2>ASmarterWaytoLearn</h2>
</div>
Thatgivesusthis:
That’snotwhatwewant.We’llhavetofloattheimage.
div#headerimg{
float:left;
Here’swhatthefloataccomplishes:
We’regettingclose.Wejustneedtoaddsomespacearoundthelogo.
div#headerimg{
float:left;
margin:.9em.6em0.75em;
}
Andthereyouhaveit.
Noticethatthecolorblock—thediv—hasexpandedverticallytoaccommodatethe
topandbottommargins.
1. InyourCSSfilestyletheimageinsidethedivsoitfloatsleftandhas1emof
margin.
2. Givetheheadinginsidethedivsometop-paddingsoitmovesdowntocenter
vertically.
3. InyourHTMLfileaddanimageinsidethediv:
http://www.asmarterwaytolearn.com/loris_50.jpg
4. Savethefileanddisplaythepage.(Don’tbesurprisedtoseetheheadercoverup
somecontent.We’lldealwiththisinChapter6)
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-66-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-66-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/66.html
67
Layout:
amodernheaderpart4
Inthelastchapteryoulearnedhowtoforcethebrowsertopositionadivprecisely
whereyouwantit.Theheaderthatwecreatedusingthisapproachappearsinthatposition
whenthepagefirstdisplays.Theniftheuserscrollsthepage,theheaderscrollswithall
theothercontent.Butyoucantellabrowsertoleaveadivwhereyouputit,tonotscroll
itwhenthepagescrolls.Forexample,youmightwanttheheadertostayvisibleatthetop
ofthebrowserwindowaseverythingbelowitscrolls.Here’sthecode.(I’momittingall
theheaderstylingthatIcoveredinthelastchapter.)
div#header{
position:fixed;
top:0;
left:0;
}
position:fixedtellsthebrowsertokeepthedivimmobilizedaseverything
elseonthepagescrolls.Thismakesthediv’spositionwithinthewindowpermanent.As
youlearnedinthelastchapter,top:0andleft:0tellthebrowsertoplacethe
headerflushagainstthetopofthewindowandflushagainsttheleftsideofthewindow.
Ifyouweretowritethis…
div#ad-box{
postion:fixed;
top:150px;
left:50px;
}
…thedivwiththeid“ad-box”wouldbepermanentlypositioned150pixelsfrom
thetopofthewindowand50pixelsinfromtheleftsideofthewindow.
Youcanalsospecifyapositionsomedistance(ornodistance)infromtherightside
ofthewindow.Thefollowingcodepositionstheadboxflushagainstthetopofthe
windowand10pixelsinfromtheright.
div#ad-box{
postion:fixed;
top:0;
right:10px;
}
Alternatively,youcanspecifyapositionsomedistance(ornodistance)upfromthe
div#footer{
position:fixed;
bottom:0;
left:0;
}
I’vecodedthepositionsinpixels,becausethat’seasierforyoutounderstand.But,as
youknow,percentagesarepreferable,so…
div#ad-box{
postion:fixed;
top:0;
right:2%;
}
InyourCSSfilechangetheabsolutely-positioneddivtofixedposition.Savethe
fileanddisplaythepage.Tryscrollingdownfromthetop.(Don’tbesurprisedtoseethe
headercoverupsomecontent.We’lldealwiththisinthenextchapter.)
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-67-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/67.html
68
Layout:
amodernheaderpart5
Inthelasttwochapterswecreatedheaderswithafixedpositionatthetopofthe
browserwindow.InChapter66,youlearnedtocreateaheaderwithabsolutepositioning
thatscrolls.InChapter67,youlearnedtocreateaheaderwithfixedpositioningthat
doesn’tscroll.We’llsoonbeaddingmoretotheHTMLdocument,withtheintentionof
buildingapagewhosecontentlookslikethis.(I’mshowingonlyatopportionofthe
page.)
Thepictureaboveshowswhatwewant,butthat’snotwhatwe’regoingtoget.When
youspecifyposition:absoluteorposition:fixed,youremovethediv
thenaturalflowoftheotherHTMLelements.Theyreturnthefavorbytotallyignoringthe
divelement.Theybehaveasifitweren’tthere.Whatthismeansisthatwhenyouforcea
headertotakeaparticularposition,theotherstuffonthepagewon’trespectfullymake
roomforit.Sincetheotherelementsdon’tknowit’sthere,they’llpositionthemselvesas
ifitisn’tthere,rightwherethedivis,violatingthenaturallawthatsaystwothingscan’t
occupythesamespace.Unawareofthediv,they’llflownormallyandwillwindup
underthediv.They’llbeinvisible.
Youcouldstylethesidebarandmainsectionwithbigtopmarginstomovethem
downbelowtheheadersothey’reintheclear.ButIpreferamoreelegantsolution.
Createaduplicateoftheheader—acopyofitthatisn’tfixed,aheaderthatispartof
themainflow.Youmakethisheadervisibletothebrowserbutinvisibletotheuser.In
effect,it’saspacer.
div#invisible-header{
width:100%;
visibility:hidden;
}
Addanewselectortotheheader’sh2stylingsotheinvisibleheadingisstyledlike
thevisibleheading:
div#headerh2,div#invisible-headerh2{
font-family:Verdana,Geneva,sans-serif;
font-weight:900;
color:white;
font-size:2em;
margin-left:2%;
padding:0;
}
Dothesamethingfortheimage.
div#headerimg,div#invisible-headerimg{
float:left;
margin:.9em.6em0.75em;
}
visibility:hidden,specifiedfortheheaderdivandeverythingitencloses,
tellsthebrowsertokeepitscontentsinvisible(thoughthebrowserknowsit’sthere).
Sincewefloatedtheimage,weneedaparagraphthatclearsthefloat.We’llstyleit
thisway:
p.clearFloat{
clear:both;
}
TheHMTLcodefortheinvisibleheaderanditscontentsisinsertedatthetopofthe
page.
<divid=“invisible-header”>
<imgsrc=“robot-logo-bust.png”alt=“logo”>
<h2>ASmarterWaytoLearn</h2>
</div>
Forprecisionplacementoftheelementsimmediatelybelowtheheader,youmay
needtoadjustthemarginofthespacerdiv.Sincethebrowserwilladdalittlewhitespace
abovethespacerdiv,it’sgoingtodropalittlebelowthevisibleheader.Tomoveitupso
itmimicsthevisibleheader,giveitsomenegativetop-margin.
Whyisthevisiblefixedheadercoveringuptheotherelementsinsteadoftheother
wayaround?Becausebydefaultafixed-positionelementgoesontop.Butyoucan
interferewiththisstackorder,usingz-index.Thelowerthez-indexnumber,the
loweritsplaceinthestackorder.AllelementsthatareinthenormalHTMLflowhavean
implicitz-indexof0.
InyourCSSfile,codeinvisibleversionsofthefixed-positiondiv,itsheading,and
itsimage.InyourHTMLfileinsertthedivanditscontentsatthetopofthepage
contents,under<body>.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-68-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-68-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/68.html
69
Averticalnavigationbar
part1
Sinceanavigationbarpresentstheuserwithalistofchoices,theusualwaytomake
oneistocodeanunorderedlist.Here’ssomecode.
<divid=“navbar”>
<ul>
<li>WhyChooseUs</li>
<li>RecentProjects</li>
<li>OurTeam</li>
<li>GetaQuote</li>
<li>ContactUs</li>
</ul>
</div>
Thisiswhatitlookslikesofar.
Itisn’tanavigationbarifitisn’tclickable.Solet’saddsomelinks.
<divid=“navbar”>
<ul>
<li><ahref=“why-choose-us.html”>WhyChooseUs</a></li>
<li><ahref=“recent-projects.html”>RecentProjects</a>
<li><ahref=“our-team.html”>OurTeam</a></li>
<li><ahref=“get-a-quote.html”>GetaQuote</a></li>
<li><ahref=“contact-us.html”>ContactUs</a></li>
</ul>
</div>
Nowthelistitemsareblueandareunderlined,indicatinglinks.
Sinceit’sgoingtobeanavigationbar,wedon’tneedthebullets.Thisisthecode
thatremovesthem.
div#navbarul{
list-style-type:none;
}
Nowthebulletsaregone.
We’llcontinuewiththenavigationbarinthenextchapter.
1. InyourCSSfile,codeadividforanavigationbar.Includeanid.Giveitaclear:
bothspecificationtopreventwrapfromthedivaboveit.
2. Styleanunorderedlistwithinthedivsoithasnobullets.
3. InyourHTMLfile,codethediv.
4. Withinthediv,codeanunorderedlistwithlinks.Makeupthelinks.Theydon’t
havetowork.
5. Savethefiles.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-69-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-69-2.html.
70
Averticalnavigationbar
part2
Inthelastchapter,westartedconstructinganavigationbar.Wecreatedanunordered
list,madethelistitemsclickable,andremovedthebullets.Nowlet’sstyletheanchors.
Thestylewillapplytoallanchorsthatarelistitemsinanunorderedlistinthedivwith
anidof“navbar.”
div#navbarullia{
font-family:Arial,Helvetica,sans-serif;
font-size:1.1em;
font-weight:900;
}
Nowwehavethis.
Sinceit’sanavigationbar,wecanassumethattheuserknowsit’sclickable.We
don’tneedtheunderlinetocommunicatethatthetextitemsarelinks.So…
div#navbarullia{
font-family:Arial,Helvetica,sans-serif;
font-size:1.1em;
font-weight:900;
text-decoration:none;
}
Thisistheresult.
We’llcontinueconstructingthenavigationbarinthenextchapter.
InyourCSSfile,maketheanchorsbigger,bolder,andsans-serif.Takeawaythe
underlines.Savethefile.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-70-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/70.html
71
Averticalnavigationbar
part3
Inthelastchapterwestyledtheanchors.Nowlet’sgivethedivabluebackground.
div#navbar{
background-color:blue;
}
We’llmaketheanchorswhitesotheyshowuponthebluebackground.
div#navbarullia{
font-family:Arial,Helvetica,sans-serif;
font-size:1.1em;
font-weight:900;
text-decoration:none;
color:white;
}
Andwe’llstylethedivsoit’sjustwideenoughtoaccommodatethelistitems,but
nowider.
div#navbar{
clear:both;
background-color:blue;
display:inline-block;
}
inline-blocktellsthebrowsertoshrinktofit.
Nowwehave…
Thebrowserhasn’tforgottenthatthisisalist,soithasaddedpaddingontheleft
sidetoindentit.Wedon’twantitindented.Sowespecifyzeroleft-sidepaddingforthe
ul.
div#navbarul{
list-style-type:none;
padding-left:0;
}
Thatmovesitflush-left.
Becauseanunorderedlistisablockelement,thebrowserhasaddedtopandbottom
margins.We’llkeepthem.InyourCSSfile…
1. Makethenavigationbardivadarkcolor.
2. Maketheanchorsalightcolor.
3. Shrinkthenavigationbartofit.
4. Removepaddingfromtheleftsideofthelist.
5. Savethefile.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-71-1.html.
http://www.ASmarterWayToLearn.com/htmlcss/71.html
72
Averticalnavigationbar
part4
We’restillworkingontheverticalnavigationbar.
Iwantthecolorblocktoexpandhorizontally.Wecoulddothisbyaddingleftand
rightpaddingtotheul,butbecauseofsomethingwe’regoingtodointhenextchapter,
I’lladdthepaddingtothelielementsinstead.
div#navbarulli{
padding:01em01em;
}
Nowwe’lladdalittlepaddingbeloweachlistitemtoseparatethem.
div#navbarulli{
padding:01em.3em1em;
}
Theresult:
InyourCSSfile,addsomepaddingontheleftandrightoflistitems.Addalittle
paddingtothebottomofeachlistitemtoseparatethem.Savethefile.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-72-1.html.Findtheinteractivecoding
exercisesforthischapterat:http://www.ASmarterWayToLearn.com/htmlcss/72.html
73
Averticalnavigationbar
part5
Theverticalnavigationbarwecreatedinthelastchapterisfunctional,butdoesn’t
lookthatgreat.Let’sdressitupalittle.
Insteadofalistoflinksagainstabluebackground,we’regoingtohavefiveseparate
blueblocks.Eachblockisanavigationchoice.
Weremovethebluebackgroundfromthediv,sincewe’regoingtocolortheli
elementsindividually.
div#navbar{
background-color:blue;
display:inline-block;
clear:both;
}
Thestylingfortheunorderedlistisunchanged…
div#navbarul{
list-style-type:none;
padding-left:0;
}
We’regoingtocoloreachlielementseparately,sowewrite…
div#navbarulli{
background-color:blue;
padding:01em.3em1em;
}
We’regoingtostretchoutthebluelielementsbypaddingtheaelementsinside
them,sowenolongerneedpaddingonthelielements.
div#navbarulli{
background-color:blue;
padding:01em.3em1em;
}
Toenlargethebluebackgroundofthelielements,wedeclareeachaelementa
blockandpaditout.
div#navbarullia{
font-family:Arial,Helvetica,sans-serif;
font-size:3em;
font-weight:900;
text-decoration:none;
color:white;
display:block;
}
Allthesechangesproducethis.
Separatethelistitemswithalittlebitofbottommargin…
div#navbarulli{
background-color:blue;
margin:00.25em0;
}
Andthereyouhaveit:
ReviseyourCSSfiletostylethenavbarliketheoneshownabove.Savethefile.
Displaythepage.(Codethelibottommarginasabove,specifying0fortheotherthree
sides,tooverrideageneralmarginspecificationforlielementsthatyoucodedearlier.)
SampleCSScodeisat:
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/73.html
74
Ahorizontalnavigationbar
part1
Youdon’tneedtoknowmuchmorethanyoualreadyknowinordertocreatea
horizontalnavigationbar.Likeaverticalnavigationbar,it’sjustalistoflinkswithsome
styling.
We’llstartbyreplacingtheshrink-to-fitinline-blockspecificationwithawidth.
div#navbar{
display:inline-block;
width:100%;
}
Theulstylingisthesameasbefore.
div#navbarul{
list-style-type:none;
}
Theaelementstylinghasonlyonechange.
div#navbarullia{
font-family:Arial,Helvetica,sans-serif;
font-size:1.1em;
font-weight:900;
text-decoration:none;
color:white;
display:block;
padding:.75em;
}
Thebigchangesareinthelistyling.
div#navbarulli{
background-color:blue;
text-align:center;
display:inline;
width:19%;
float:left;
margin-right:.5em;
}
display:inlinetellsthebrowsernottoarrangethelistitemsvertically,the
default,buttoputthemside-by-side.
Wewanteachofthefiveblockstobethesamewidth.Byspecifyingthateachblock
occupy19%ofthewidthofthediv,weleaveroomforthemarginthatcreatesalittle
whitespacebetweeneachblock.
acrossthewindow.
The.5emrightmarginseparatestheblockswithalittlewhitespace.Wewouldn’t
havetodothis,ofcourse.Wecouldskipthemarginandhavethenavigationbarbeasolid
blueblockacrossthewindow.
Thisistheresult.(I’mshowingyoujustthelefthalfofthemenu.)
ChangeyourCSSfiletoconverttheverticalmenutoahorizontalmenu.Savethe
file.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-74-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/74.html
75
Ahorizontalnavigationbarpart2
Let’saddtwomorefeaturestothenavigationbar.Whentheuserhoversovera
selection,thebluecolorblockturnslightblue.
Inordertodothis,weneedtocreatespecialclassforthelielements.Westartby
removingalinewe’vealreadycoded.
div#navbarulli{
background-color:blue;
text-align:center;
display:inline;
width:19%;
float:left;
margin-right:.5em;
}
Thenwecreatethespecialliclass.
li.changeBackground{
Westartbycodinganormalcolorfortheclass.
li.changeBackground{
background-color:blue;
}
Thenwecodethehoverstate.
li.changeBackground:hover{
background-color:lightBlue;
}
Wecanalsocodeacolorfortheactivestate.
li.changeBackground:active{
background-color:darkBlue;
}
Whentheuserclicksaselection,thecolorblockturnsdarkblue.
ThisistheHTML.
<divid=“navbar”>
<ul>
<liclass=“changeBackground”><ahref=“why-chooseus.html”>WhyChooseUs</a></li>
<liclass=“changeBackground”><ahref=“recentprojects.html”>RecentProjects</a></li>
<liclass=“changeBackground”>ahref=“ourteam.html”>OurTeam</a></li>
<liclass=“changeBackground”><ahref=“get-aquote.html”>GetaQuote</a></li>
<liclass=“changeBackground”><ahref=“contactus.html”>ContactUs</a></li>
</ul>
</div>
ChangeyourCSSandHTMLfilestocreateaclassoflistitemthatisonecolorto
startwith,asecondcolorwhenit’smousedover,andathirdcolorwhenit’sactive.Save
thefiles.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-75-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-75-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/75.html
76
Backgroundimagespart1
Inpreviouschaptersyoulearnedhowtounderlayanelementwithasolidcolorusing
background-color.Youcanalsounderlayanelementwithanimage.Thisisan
example.
div#main{
background-image:url(“images/field-of-poppies.jgp”);
}
Thedivwithanidof“main”willbeunderlaidwiththeimagewhoseURLisshown
insidetheparenthesesandquotationmarks.
Youcanputabackgroundimagebehindanyelement.It’scommontounderlaythe
wholepagewithanimage.
body{
background-image:url(“images/gray-gradient.png”);}
TheentirepagewillbeunderlaidwiththeimagewhoseURLis“images/graygradient.png”.Intheexampleabove,theimage,whichmustbesizedtofitthewholepage,
willbealargeone,andsowilltakesometimetoload.Ifyourbackgroundimageis
nothingbutarepeatingpattern,youcanmakeitloadfasterbyspecifyingasmallslicefor
theimageandaskingthebrowsertorepeatit.
Youcancutthisimagedowntoa1-pixel-wideslicethathasthesameheight,and
writethisCSS:
body{
background-image:url(“images/gray-gradient-slice.png”);
background-repeat:repeat-x;
}
Theslicewillbetiledallacrossthewidthofthepage(thex-axis),creatingthesame
effectasthebigimage,butusingafast-loadingsmallimage.
Supposeyouhaveagradientfadingfromleft-to-rightratherthantop-to-bottom.
Thenyouwouldtakea1-pixel-highhorizontalsliceandtileitfromtoptobottom(theyaxis).
body{
background-image:url(“images/gray-gradient-slice.png”);
background-repeat:repeat-y;
}
Ifyouhaveabackgroundimagethatyouwanttorepeatbothhorizonallyand
vertically,omitthebackground-repeat:specification.
background-image:url(“images/gray-gradient-slice.png”);
background-repeat:repeat-x;
}
Thebrowserwillautomaticallytiletheimageinbothdirectionstofillthepage.
InyourCSSfile,findthedivthat’s20%wide.Tilethefollowingimageacrossthe
widthofthediv:http://www.asmarterwaytolearn.com/gray-gradient-slice.png.Savethe
file.Displaythepage.Checkoutthediv.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-76-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/76.html
77
Backgroundimagespart2
Supposeyouhaveanimagethat’ssmallerthanthepageandyouwanttokeepitthat
way.Youdon’twantittorepeat.Butifyouwrite…
body{
background-image:url(“images/faded-logo.png”);
}
…thebrowserwillautomaticallyrepeatit,tofillthepage.Soyouwrite…
body{
background-image:url(“images/faded-logo.png”);
background-repeat:no-repeat;
}
Asmallimagethatdoesn’trepeatisplaced,bydefault,attheleft-uppercorner.But
youcanspecifyaposition.
body{
background-image:url(“images/faded-logo.png”);
background-repeat:no-repeat;
background-position:righttop;
}
Nowtheimagewillbepositionedattheright-topcorner.
Thehorizontalspecificationsareleft,center,andright.Thevertical
specificationsaretop,center,andbottom.Youalwayswritethehorizontal
specificationfirst.It’sleftbottom,neverbottomleft.Ifyouwanttocenteran
imagebothhorizontallyandvertically,youwrite:
background-position:center;
Doyouwanttheimagetoscrollwitheverythingelse?Ifso,youwrite…
body{
background-image:url(“images/faded-logo.png”);
background-repeat:no-repeat;
background-position:righttop;
background-attachment:scroll;
}
Ifyouwanttheimagetostayput,youwrite…
body{
background-image:url(“images/faded-logo.png”);
background-repeat:no-repeat;
background-attachment:fixed;
}
InyourCSSfile,addabackgroundimagetotherighttopofthewindow.Don’tletit
repeat.Fixitinplace.Theimageishttp://www.asmarterwaytolearn.com/monarch.jpg.In
yourHTMLfile,use<!—and-->tohidethefixed-positionheaderfromthebrowserso
itdoesn’tdisplay.Savethefile.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-77-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-77-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/77.html
78
iframes
AniframeislikeyourTV’spicture-in-picture.It’sanHTMLpagewithinanHTML
page.Forexample,supposeIwanttoruntheMetropolitanOpera’spageinsidemypage.
ThisistheHTML.
<iframesrc=“http://metopera.org/”width=”700”height=“450”>
</iframe>
<p>TheMetropolitanOpera,commonlyreferredtoasthe“Met”,isa
profitMetropolitanOperaAssociation,withPeterGelbasetc.
Thingstonotice:
There’sanopening<iframe>tagandaclosing</iframe>tag.
src=”[URL]”specifiesthelocationoftheHTMLfilethat’stobeimbedded,the
samewaysrc=”[URL]”specifiesthelocationofanimagefile.I’veshortenedthe
URLsoyoucanfocusonthesyntax.
Youspecifywidthandheightinpixels.Scrollbarsallowtheusertoexplorethewhole
embeddedpage.
Youcanwraptextaroundaniframe.ThisistheCSS.
iframe{
float:left;
margin:02em00;
}
InyourHTML,createaniframethatembedsanonlinewebpageofyourchoice.
Savethefile.Displaythepage.Adjustthedimensionsoftheiframeuntilyou’rehappy
withtheresult.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-78-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/78.html
79
EmbeddingYouTubevideos
Thereareseveralwaysyoucanaddvideotoyourwebsite.Theeasiestistoembeda
YouTubeorVimeovideo.Plus,whenyouletYouTubeorVimeohostthevideofree
insteadofstoringitonyourwebhost’sserver,youavoidpossibleextrachargesyour
webhostmighthityouwithforusingextrabandwidth(videoisabandwidthhog).
Forcompletecontrol,youcanhostvideosyourself.Thevastmajorityofsiteowners
don’tdoit,though,becauseit’saheadache—andnotjustaregularheadachebuta
migraine.Becausemakersofdevices,operatingsystems,andbrowserscan’tagreeonone
videostandard,youhavetocreateavarietyofdifferentvideofilesifyouwantyourvideo
tobeseenbyeverybody.You’reashoemanufacturerwhohastomakesixteendifferent
sizes.
Sinceit’ssomucheasiertoletYouTubeorVimeohandlethecompatibilityissues,
that’swhatI’mgoingtofocuson.
InthelastchapteryoulearnedhowtoplaceanexteriorpageinsideanHTMLpage
bycodinganiframe.That’sthemethodyouusetoembedaYouTubeorVimeovideo.
Let’sstartwithYouTube.
YoucanfindouthowtopostaYouTubevideoatYouTubeorelsewhereonline.I’m
goingtoassumeyou’veproducedyourvideoandpostedittoYouTube.Here’showtoput
itonyourwebpage.
1. FindyourvideoonYouTube.Locate“Share”underthevideowindowandclickit.
2. Click“Embed.”
3. Click“SHOWMORE.”
4. Scrolldowntoseesomechoicesyoucanmake.
5. ClicktheVideosizedropdown,andyoucanchoosefromfourstandardvideosizes.
Youcanalsochoose“Custom.”
Ifyouchooseacustomsize,besuretokeeptheratioofwidthtoheightat16to
Otherwise,thepicturewilldistort.Toremembertheratio,pictureayoungpersonin
theU.S.gettingherdriver’slicense(16yearsold),anddrivingthenumber9around.
Youcanalsousearatioof4to3.Ifyoudo,you’llneedtochangetheAspectRatio
onyourvideo’sPlayercontrolspanel.Seethenextchapterformoreonthis.
6. Next,lookattheotherchoicesyouhave,belowtheVideosizedropdown.
You’llwanttouncheck“Showsuggestedvideoswhenthevideofinishes,”unlessyou
finishes.
“Enableprivacy-enhancedmode”meansthatYouTubewon’tstoreinformationabout
visitorstoyoursiteunlesstheyplaythevideo.Inmostcases,youwon’tcareabout
this.
7. Whenyou’vefinishedmakingyourselections,copyandpastetheYouTubegeneratediframecodeintoyourHTMLdocument.
8. Ifyou’dliketoaddaframeborder,changethe“0”toa“1”.
<iframewidth=“640”height=“360”src=”//www.youtube.com/embed/_t
rel=0”frameborder=“1”allowfullscreen></iframe>
9. Ifyoudon’twanttheusertobeabletoenlargetheframetofullscreensize,delete
allowfullscreen.
<iframewidth=“640”height=“360”src=”//www.youtube.com/embed/_t
rel=0”frameborder=“1”allowfullscreen></iframe>
InyourHTMLfile,replacetheiframeyoucodedforthelastchapterwithan
embeddedYouTubevideo.Itdoesn’thavetobeyourownvideo.Usemineifyoulike:
https://www.youtube.com/watch?v=_tky2rAxBIUSavethefile.Displaythepageandplay
thevideo.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-79-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/79.html
80
Furthercustomizing
YouTubevideos
Whenyou’reembeddingavideoonyoursite,youmaynotwantaYouTubevideoto
looklikeaYouTubevideo.YoumaywantittodisplaywithouttheYouTubebrandingand
controls.
WhenyoubanishtheYouTubebrandingandcontrols,aYouTubelogowillappearin
thelowerrightcornerbeforeplaybackandwhentheusermousesoverthevideo,but
otherwise,you’vegotavideothatlooksproprietary.
Youcanchoosefromanumberofoptionstomakethevideolookandperformthe
wayyouwantitto.ButyouhavetogotoGoogle,theownerofYouTube,todoit.
Beginbycopyingyourvideo’sYouTubeIDfromtheYouTubeURLforyourvideo.
It’sthecodethatfollowstheequalsign.
Alternatively,youcancopytheIDfromtheiframecodethatYouTubeoriginally
generatedforyou.
<iframewidth=“640”height=“360”src=”//www.youtube.com/embed/
rel=0”frameborder=“1”allowfullscreen></iframe>
NotethattheIDendsatthelastcharacterbeforethequestionmark.Goto:
https://developers.google.com/youtube/youtube_player_demo.
Pasteyourvideo’sIDintothevideoIDfield.
Click“Updateplayerwithselectedoptions.
Googlereplacesthedemovideoswithyourvideowhenyouclick“Updateplayer
withselectedoptions.”
IfyourIDiscorrect,thefourvideothumbnailsarereplacedbyyourvideo.Itplays.
Youcanpauseitwhileyouchoosecustomoptions.
Next,clicktheShowplayerparametersbuttonatthetopofthepanel.
Anotherpanelwithanarrayofcustomizingchoicesdisplays.
ClickmodestbrandingtobanishtheYouTubelogo.
Whenyou’vefinishedmakingselections,onceagainclick“UpdatePlayerwith
SelectedOptions”atthetopofthepanel.
Theiframeembedcodechangestoreflectyourselections.Copyandpasteitinto
yourHTMLdocument.
InyourHTMLfile,changeyourembeddedvideosoithasmodestbranding.Save
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-80-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/80.html
81
EmbeddingVimeovideos
IfYouTubeisthenetworkTVofonlinevideo,Vimeoiscable.It’salittleclassier,
looksalittlebetter,andispreferredbymanycreativepeople.It’sfreeforthebasicservice.
YoucanremoveallVimeobrandingifyou’rewillingtopay$199ayear.
TheprocessofembeddingaVimeovideoissimilartoYouTube’s.
I’massumingyou’veproducedyourvideoandpostedittoVimeo.Here’showtoput
itonyourwebpage.
1. OnyourVideospageatVimeolocatethevideoyouwanttoembed.Clickthepaperairplaneiconattheupperright.
2. Anewwindowopens.Ifyoudon’tchoosetocustomize,copytheiframecodeand
pasteitintoyourHTMLdocument,andyou’redone.
3. Tocustomize,click+ShowOptions.
4. Selecttheoptionstochangefromthedropdown.
5. Intheoptionspanelyoucanspecifythedimensionsofthevideoplayer.Changethe
widthortheheight.Vimeowillautomaticallychangetheotherdimensiontopreserve
theratioof16to
6. Byclickingonacolorblockorspecifyingacolorbyhexcodeyoucanchangethe
colorthevideotitle.Thecoloroftheprogressbarwillchangetomatch.
7. Foracleanlook,you’llprobablywanttouncheckPortrait,Title,Byline,andShow
textlinkunderneaththisvideo.
8. Tomakethevideoplayautomatically,checkAutoplaythisvideo.Tomakeitloop
checkLoopthisvideo.Chancesare,youdon’twantavideodescription.Ifyou
don’t,leavethelastitemunchecked.
9. CopytheembedcodeandpasteitintoyourHTMLdocument.
For$59.95ayearVimeogivesyouadditionalcustomizationoptionsandother
privilegesincludingfasterconversion.For$199ayear,theVimeologogoesaway;you
can,ifyouwish,insertyourownlogo.
InyourHTMLfile,replacetheembeddedYouTubevideowithanembeddedVimeo
video.Usemineifyoulike:https://vimeo.com/97326700Sinceyou’rerunningtheHTML
locallyratherthanontheWeb,youneedtoinserthttp:atthebeginningofthevideo
URLsoyourpagecanconnecttothevideoonline.Savethefile.Displaythepage.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-81-1.html.
http://www.ASmarterWayToLearn.com/htmlcss/81.html
82
Audio
It’sfareasiertohostyourownaudiofilesthanyourownvideofiles,becausethe
compatibilityissuesaretamer.IfyouuseAudacityoranotheraudioeditortosaveyour
fileinjusttwoformats,mp3andOggVorbis,youraudiowillplayinanymodernbrowser,
usingHTML5.Thisisthecode.
<audiocontrols>
<sourcesrc=“whatever.ogg”>
<sourcesrc=“whatever.mp3”>
</audio>
Ifaparticularbrowsercan’thandletheOggVorbisfile,it’llplaythemp3file.
Theaudiotagshownaboveincludestheoptionalcontrols.Thistellsthebrowser
tomaketheplayervisibleandallowtheusertocontrolit.
<audiocontrols>
<sourcesrc=“whatever.ogg”>
<sourcesrc=“whatever.mp3”>
</audio>
Analternativeistohavetheaudioautoplay,withorwithoutcontrols.Thefollowing
codestartstheaudioautomatically,withoutavisibleplayer.
<audioautoplay>
<sourcesrc=“whatever.ogg”>
<sourcesrc=“whatever.mp3”>
</audio>
Thefollowingcodestartstheaudioautomaticallyanddisplayscontrols.
<audiocontrolsautoplay>
<sourcesrc=“whatever.ogg”>
<sourcesrc=“whatever.mp3”>
</audio>
Becarefulwithautoplay.Inmostsituations,usersfinditannoying.
Youcanaddaparagraphinsidetheaudiotagsthatdisplaysiftheuserhasanantique
browserthatdoesn’thandleHTML5.
<audiocontrols>
<sourcesrc=“whatever.ogg”>
<sourcesrc=“whatever.mp3”>
</audio>
InyourHTMLfile,inserta<br>atthebottom,thenembedtheaudiofiles
http://www.asmarterwaytolearn.com/boing.oggand
http://www.asmarterwaytolearn.com/boing.mp3.Savethefile.Displaythepage.Playthe
audio.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-82-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/82.html
83
Emsvs.percentagesvs.pixels
Ems,percentages,andpixelsarethreedifferentunitsofmeasurementthatyouuseto
styletheelementsofawebpage.They’resomewhatinterchangeable.Thatis,although
I’vetaughtyou,forexample,toexpressfont-sizeinems,youcan,ifyoulike,express
itinpixelsorasapercentage.
Pixelsareeasytoworkwith,becausethey’resimpleandabsolute.Withpixels,you
don’thavetodealwiththesometimesconfusingrelativismofemsandpercentages.But
theproblemwithpixelsisthattheyareabsolute.ACSSfilefullofpixelspecifications
doesn’tadapttodifferent-sizescreens,becauseitisn’trelative.Theneedforresponsive
designforcesustolimitouruseofpixelsandstickmostlytoemsandpercentages.Here
aretherulesofthumbthatmanydevelopersfollow,andthatIusuallyfollowinthisbook.
Ems—Usethemfortypography,margins,andpadding.
Percentages—Usethemfordivs,tables,iframes,andsometimesmarginsand
padding.
Pixels—Usethemforimages,borders,windows,iframes,andfixed,absolute,and
relativepositioning(seenextchapter).
InyourCSSfile,styleanewdivclass.Makeitlessthanthefullwidthofthe
window.Thenstyleanewparagraphclass.Makeitlessthanthefullwidthofthedivand
centerit.InyourHTMLfile,codeadivofthatclassand,withinit,aparagraphofthat
class.Savethefiles.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-83-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-83-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/83.html
84
Relativeandstaticpositioning
Asyouknow,thebrowserdisplaystheelementsofyourpageinthesameorderin
whichyouwritetheminyourHTMLdocument.Ifyouwriteaheading,followitwitha
paragraph,followthatwithatable,andfollowthetablewithasecondparagraph,the
browserwilldisplayeverythinginthatorder:
Heading
Paragraph1
Table
Paragraph2
ButasyousawinChapters64and67,youcaninterferewiththisnaturalorder.In
thosechapters,youlearnedhowtopositionaheaderexactlywhereyouwantitregardless
ofitsorderintheHTMLdocumentusingabsoluteandfixedpositioning.So,withabsolute
andfixedpositioning,whereyouplacethecodeinthedocumentdoesn’taffectitsposition
onthepage.Youcouldaddthecodetotheveryendofthebodysection,putitsomewhere
inthemiddle,orstartitoffatthebeginning.Itslocationonthepageisdeterminedbythe
positionyouspecifyinyourCSS,notitspositionintheHTMLdocument.
Andremember,withthesetypesofpositioning,alltheotherelementsbehaveasif
theydon’tknowtheelementisthere.Theydon’tmakeroomforit,astheydofornormally
positionedelements.Thiscreatesoverlapunlessyoupullatrickliketheoneyoulearned
inChapter68,creatinganinvisiblecopyoftheheaderthat’spositionednormallyandso
actsasaspacer,tokeeptheothernormally-positionedelementsfromdisappearing
underneaththefixed-positionheader.
Bothabsoluteandfixedpositioningspecifyspacingintermsofhowfartheyare
fromtheedgesofthebrowserwindow.
Athirdwaytointerferewiththebrowser’sdefaultlayoutistospecifyrelative
positioning.Relativepositioningtellsthebrowsertopositionanelementacertaindistance
fromitsnormalposition.
Forexample,ifyouwantedtopositionsomeparagraphs50pixelsbelowtheir
normalposition,youcouldwrite,forexample…
p.spaced-out{
position:relative;
top:50px;
}
Ifyouwantedatablepushedupandnudgedleft,youcouldwrite,forexample…
position:relative;
bottom:25%;
right:35%;
}
Inrelativepositioningtheotherelementsdon’tadjusttotherelativelypositioned
element’salteredposition.Theybehaveasiftheelementwereinitsnormalposition.So,
aswithabsoluteandfixedpositioning,it’spossibletohaveoverlap.Ifnecessary,youcan
solvethiswithaspacingtacticsimilartotheoneyoulearnedinChapter68.
Inmostcircumstances,youdon’thavetotellthebrowsertopositionanelement
normally,sincethat’sthedefault.Butjustsoyouknow,anormallypositionedelementhas
staticpositioning.
div.normal{
position:static;
}
InyourCSSfile,userelativepositioningtomovethedivthatyoucreatedforthelast
chaptertotheright.Savethefile.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-84-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/84.html
85
z-index
Inthelastchapteryoulearnedthatwhenyouoverridethenormalflowofawebpage
byusingfixed,absolute,orrelativepositioning,elementsmayoverlapeachother.
Occasionally,youmaywantthistohappen.Forexample,youmightwanttooverlaya
headingontopofanimage.
Youwanttheheadingtobeontopoftheimage,nottheotherwayaround.Howdo
youtellthebrowsertoputtheheadingontop?Byspecifyingaz-indexfortheheading.
Thehigherthez-index,thehigheritgoesinthestack.Anelementwithazindexof10willsitontopofanelementwithaz-indexof9.
Thedefaultz-indexofelementsis0.Soifyougiveyourheadingaz-indexof
1,it’llbeplacedontopoftheimage,which,assumingyouhaven’tassigneditazindex,hasaz-indexof0.
h2#header{
z-index:1;
}
Ifyougiveitaz-indexof-1,it’llbeonelayerbelowthedefault.
1. InyourCSSfile,codeadivid.
2. Fixitspositionatthebottom-left.
3. Giveitaz-indexof-1.
4. InyourHTMLfile,codetheid.Placeanimageinsideit:
http://www.asmarterwaytolearn.com/monarch.jpg.
5. Savethefiles.Displaythepage.Scrollandseewhathappens.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-85-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-85-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/85.html
86
Mediaqueries
Thesedays,youalmosthavetomakeyoursiteresponsive.Thatmeanscreating
customstylingforscreensofdifferentsizes,fromthesmallestphonetothelargest
desktop.
Forexample,fivemedium-sizeimagesarrayedacrossthescreenarefineifthe
screenis1280pixelswide.Butnotifit’sa480-pixeliPhonescreen.Onaphone,you’ll
wanttoforcethemtostackvertically.
Tocreatedifferentstylerulesfordifferentscreens,youwritemediaqueries.For
example,amediaqueryasks,“Isthescreennowiderthanxpixelsandnonarrowerthany
pixels?Ifso,followthesestylerules.”
Responsivedesigncanbeamaddeninglycomplicatedbusinessanddeservesabook
ofitsown,butIwanttogiveyouasenseofhowitworks,soI’llshowyouoneexample.
Therearevariouswaystoincorporatemediaqueriesinyourcode.I’llshowyouhow
toaddthemtoastylesheet.
Therearethirteendifferentmediacharacteristicsyoucantestforinamediaquery,
includingcolorandwhethertheuserislookingatamobiledeviceinportraitorlandscape
orientation.I’llfocusonthemostcommontests,forascreenofanykind(thatis,nota
printer)andforminimumdevicewidthandmaximumdevicewidth.
Here’ssomecode.
@mediaonlyscreenand(min-device-width:320px)and(maxdevice-width:480px){
img.gallery{
display:block;
}
}
Thecodeabovespecifiesblock—thatis,oneoneachline—forthe“gallery”class
ofimageswhendisplayedonaphone,adevicewedefineashavingaminimumwidthof
320pixelsandamaximumwidthof480pixels.
Let’slookateachpieceofthecode.
@mediaishowallmediaqueriesbegin.
@mediaonlyscreenand(min-device-width:320px)and(maxdevice-width:480px){
img.gallery{
display:block;
}
onlyscreenmeansthestyleruleappliesonlytodeviceswithscreens.Thismeansit
doesn’tapplytoprinters.
@mediaonlyscreenand(min-device-width:320px)and(maxdevice-width:480px){
img.gallery{
display:block;
}
}
Whenyouwriteandinamediaquery,you’resaying,“Thefollowingmustalsobe
trueinorderforthestyleruletoapply.”Soit’snotenoughforthedevicetobeascreen.It
mustbeascreenandtheminimumdevicewidthmustbe320pixels(portraitmode)and
themaximumdevicewidthmustbe480pixels(landscapemode).
@mediaonlyscreenand(min-device-width:320px)and(maxdevice-width:480px){
img.gallery{
display:block;
}
}
Thedevice-widthspecificationsmustbeenclosedinparentheses.
@mediaonlyscreenand(min-device-width:320px)and(maxdevice-width:480px){
img.gallery{
display:block;
}
}
Bywritingdisplay:block,youtellthebrowsernottofloattheimages.
@mediaonlyscreenand(min-device-width:320px)and(maxdevice-width:480px){
img.gallery{
display:block;
}
}
Thefollowingmediaquerytellsthebrowsertofloattheimageswhenthey’re
displayedonadesktoporlaptop,definedashavingaminimumwidthof1224pixels.Note
thatthere’snomaximumwidth,sincewe’retestingforjustoneorientation.
@mediaonlyscreenand(min-device-width:1224px){
img.gallery{
float:left;
}
}
family“ComicSansMS”,cursive,sans-serif—ifthescreenisat:
least800pixelswide.
2. InyourHTMLfile,codeaparagraphofthatclass.
3. Savethefiles.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-86-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-86-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/86.html
87
Min-andmax-width
Min-andmax-height
Supposeyou’vestyledadivtooccupy20%ofthewidthofthescreen.Thisworks
fineaslongasthescreenislarge,butwhathappensonaphonewitha320-pixelscreen?
Thedivwidthshrinksto64pixels—anarrowstripedownthepagewithroomforoneor
twowordsperline.Topreventthis,youspecifyamin-width.
div#additional-info{
width:20%;
min-width:200px;
}
Nowthedivwillrun20%ofthewidthofthescreen—butonlyaslongasthewidth
doesn’tgobelow200pixels.Whenthatpointisreached,yourCSStellsthebrowserto
makethewidth200pixels.
Thenthere’stheoppositeproblem.You’vecreatedadivthatruns40%ofthewidth
ofthescreen.Ablockoftextinsidethisdivmightmeasureauser-friendly12to14
wordswide.Butwhenthesamepageisdisplayedonanoversizescreen,itcouldstretchto
20wordswide.That’stoowideforeasyreading.Soyouspecifyamax-width.
div#main{
width:40%;
max-width:500px;
}
Now,onawidescreen,thewidthwillshrinkto500pixelswhen40%translatesinto
morethan500pixels.
Youcanalsoestablishlimitsonheight,usingmax-heightandmin-height.
p.article{
min-height:150px;
max-height:600px;
}
Aproblemoccurswhenthecontentofanelementexceedsthemax-heightthat
you’vespecifiedfortheelement.Intheexampleabove,youtellthebrowsertolimitthe
paragraphtoaheightof600pixels.Ifthetextintheparagraphruns,say750pixelshigh,
thetextoverflows,potentiallycreatingamess.Yousolvethiswithoverflow:
hiddenoroverflow:scroll.
Inthefollowingexample,youtellthebrowsertomakeanyoverflowingcontent
invisible.
min-height:150px;
max-height:600px;
overflow:hidden;
}
Inthefollowingexample,youtellthebrowsertodisplayascrollbarthatallowsthe
usertoscrolldowntoanyoverflow.
p.article{
min-height:150px;
max-height:600px;
overflow:scroll;
}
1. InyourCSSfile,codeaclassofparagraphwithamax-widthof100pixelsanda
max-heightof100pixels.Maketheoverflowscroll.
2. InyourHTMLfile,codeaparagraphofthatclass,includingatleastadozenwords.
3. Savethefiles.Displaythepage.
SampleCSScodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-87-1.html.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-87-2.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/87.html
88
Thestuffatthetop
ThestandardcodeyoufindatthetopofanHTMLdocumentisgobbledygook,but
asaconscientiouscoder,you’realwaysgoingtoincludeit,soyoumayaswellknowwhat
itmeans.
Thefirstlineinthedocumentisthedoctypedeclaration.
<!DOCTYPEHTML>
ThistellsthebrowserthedocumentiswritteninHTML5.Thisiswhatyou’llalways
writewhenyou’recreatinganewdocument,whetherthedocumenthasanyHTML5
featuresinitornot.Thingstonotice:
1. Theexclamationpoint.
2. It’sinall-capitalletters,aconventionnotarequirement.
3. There’snoclosingtag.
Nextcomesthe<html>tag.Tokeepthingssimple,I’vecodeditminimallyin
previouschapters,buttherecommendedwaytowriteitislikethis.
<!DOCTYPEHTML>
<htmllang=“en”>
Thatlittlebitofextrainformationtellsthebrowser,thesearchengines,andscreen
readersthatthetextcontentofthepage—theheadings,paragraphs,andtables—arein
English.IfyourpageisinItalian,you’dwritelang=“it”;inHindi,lang=“hi”;etc.
Asyouknow,the<html>tagisclosedwith</html>attheendofthedocument.
The<head>tag,whichyou’refamiliarwith,goesonthethirdline.
<!DOCTYPEHTML>
<htmllang=“en”>
<head>
Itisclosedwiththe</head>tagattheendoftheheadsection.Ataminimum,the
headsectioncontains…
<metacharset=“utf-8”>
Thistagtellsthebrowsertouseaparticularflavoroftextencodingthatpermitsthe
greatestvarietyofcharacters,thusaccommodatingthegreatestnumberoflanguages.The
tagisn’tclosed.
Next,you’llwriteopeningandclosingtitletags.Insidethemyou’llwritethetext
thatwillappearinthebrowsertoolbar,inabookmarklist,andinsearchengineresults.
Giveeachpageauniquetitlethatdescribesitsparticularcontents.
<htmllang=“en”>
<head>
<metacharset=“utf-8”>
<title>CharacteristicsoftheSlowLoris</title>
InyourHTMLfile,codethefirsttwotagsatthetopofadocument.Codethemeta
charsettagbeneaththeheadtag.Savethefile.Displaythepagetobesureyour
changeshaven’tbrokenanything.
SampleHTMLcodeisat:
http://asmarterwaytolearn.com/htmlcss/practice-88-1.html.
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/88.html
89
Themetadescription
Ifyou’rehopingpeoplewillfindyourpagethroughasearchengineandthenclick
onthelink,youneedametadescription.Agoodmetadescriptiondoesn’timproveyour
searchranking,butitdoesincreaseclicks,becausesearchenginesdisplaythedescription
inthesearchresult.WhenIgoogled“Carlypso,”Googledisplayedthisresult…
www.carlypso.com
SellyourcarwithCarlypso.Getupto40%morethantrade-inwiththesame
convenience.
Thetwosentencesfollowingthelinkarethemetadescriptioncodedintothe
Carlypsohomepage.CanyouseewhyhavingGoogledisplaythesesentenceswould
increasethenumberofclicks?
Youwritethemetadescriptionintheheadsectionofyourpage.
<head>
<metacharset=“utf-8”>
<title>SellYourCarHassle-Free</title>
<metaname=“description”content=“SellyourcarwithCarlypso.Ge
inwiththesameconvenience.”>
Thingstonotice:
Itbeginswith<metaname=“description”
That’sfollowedbycontent=
Thencomesthedescriptionitself,inquotes.
There’snoclosingtag.
Someadvice:
Makeyourdescriptionasappealingaspossible,butdon’tpromisemorethanyoucan
deliver.
Searchenginescutoffadescriptionafterabout160characters.That’safewmore
charactersthanaTwitterTweet.Limityourdescriptiontothatlength.
Don’trepeatyourtitleasadescription.
Giveeachpageonyoursiteauniquemetadescription.
AddametadescriptiontoyourHTMLfile.Savethefile.Displaythepagetomake
sureyourchangehasn’tbrokenanything.SampleHTMLcodeisat:
Findtheinteractivecodingexercisesforthischapterat:
http://www.ASmarterWayToLearn.com/htmlcss/89.html
90
Buildasite.
Lookhowfaryou’vecome,andhowmuchHTMLandCSSyou’velearnedina
rathershorttime.Congratulations.
Sonowyou’rereadytobuildasite.(Andifyou’renottotallyready,youknow
wheretofindtheinformationyouneedifyouforgethowtodosomething:rightherein
thisbook.)
Asafinalproject,I’mgoingtoaskyoutobuildathree-pagesiteforyourcity,
region,orcountry.It’lldemonstratethemostimportantthingsyou’velearnedinthisbook.
Youdon’thavetodoanyoriginalwriting.Allthecontentyouneedisat:
Wikipedia,yourchamberofcommerce,oranynumberofinformationalwebsitesthat
coveryourarea.
Youcancreatethesiteonyourharddriveandrunitoffthedrive,asyou’vebeen
doingwiththepracticepage.Or,ifyouhaveawebsite,youcanuploadittoyoursite.If
youdopublishthesite,takecarethatyoudon’tviolateanycopyrightswhenyoucopy
contentfromothersitesandpasteitintoyourHTMLfiles.(Wikipediaissafe.)
I’vebuiltanexamplesitethatyoucanuseasamodel.It’sat
http://www.asmarterwaytolearn.com/htmlcss/taos.html.
FindtheCSSandHTMLfilesforthesiteat:
http://www.asmarterwaytolearn.com/htmlcss/taos_css_code.html
http://www.asmarterwaytolearn.com/htmlcss/taos_code.html
http://www.asmarterwaytolearn.com/htmlcss/hiking_code.html
http://www.asmarterwaytolearn.com/htmlcss/skiing_code.html
I’veheavilycommentedthefirsttwofiles,tohelpguideyouinbuildingyourown
site.
ForcapturingimagesfromtheWeb,Ilikethefreeutilityfromhttp://prntscr.com.
(Again:don’tviolateanyone’scopyrightifyou’regoingtopublish.)
Tocropandresizeimagesonline,thefreehttp://picresize.comisexcellent.
http://www.awardspace.comoffersfreehostingforasmallwebsite.
https://filezilla-project.orgoffersafreeFTPclientthatmakesiteasytouploadyour
filestoyourwebhost.
Happywebsitebuilding.
Acknowledgements
Ifyoulikethebookandtheonlineexercises,giveatipofthehattothesereaders,
whotookthetimetomakecorrectionsinthebookandexercises.Thisprogramisnowso
muchbetterbecauseoftheirgenerosity.
JamesFoxworthy
JohnKoch
JackMcKinnon
TimMiller
JimRohrer
ChristopherUrrutia