HTMLTutor
SimpleHTMLEditor
HTMLmeansHypertextMarkupLanguage.Itsbasicallyjustatextfilewithcodesthattellthebrowserhowtodisplaytheinformation.Forexample,youcanletthebrowserknowthatacertainstringoftextshouldbedisplayedasaheaderwithboldfont,orthatthetextshouldbecenteredonthepage.ToletthebrowserknowthetextfilecontainsHTML,weusethefileextension.htmlratherthan.docor.txtor.rtf.
SinceaHTMLdocumentisnothingbutatextfile,youcanuseanytexteditortomakeone.YoucanuseMicrosoftWord,Pages,oryourbuiltintexteditorsprovidedbytheoperatingsystem.HoweverifyouareaMacuserI’mgoingtorecommendaspecialHTMLeditorwhichisfreecalledKompozer.ThenicethingaboutKompozeristhatitallowsyoutopreviewyourfileinrealtimeinsidetheapplicationwithouthavingtosaveyourhtmlfileandloadingitinabrowser.AlthoughinthisbookwewillbefocusingonteachingHTMLandCSS,KompozerallowsWYSWYGeditingofwebpages.Youcandownloaditfreehere:
http://www.kompozer.net/
AwebsiteismadeupofmultipleHTMLpages.SoeachHTMLfileisasinglewebpage.Whenyoutypeinawebsiteshomeaddress,suchashttp://cnn.comorhttp://nytimes.com,whathappensisthebrowseropensaspecialfilenamedindex.html.Inanutshellthisisanhtmlfilenodifferentthananyother,butithasthenameindexthattellsthebroswertoloadthisfilewhensomeonevisitsthewebsite.Onyourserveryouwillplacetheindex.htmlfileinthehomedirectory.Therearesomeexceptionstothisbutfornowthatishowyoucanviewthehomepageofawebsite.
Theotherwebpagesonthesitewillhavedifferentnamespageone.html,pagetwo.htmletc.Theseotherpagescanbeinthehomedirectoryoryoucanmakeafolderonyourserverandplacethepagesinthere.Soforexample,supposeyouhaveawebsitehttp://acmeincorporated.com.Inthepublic_htmlfolderontheserver,youwouldplacethehomepagehere.Thiswouldbethefileindex.html.Youcouldplaceanabout.htmlpageinthisfolderaswell.Thenitwouldbereferencedinthebrowseras:
http://acmeincorporated.com/about.html
Alternatively,youcouldcreateafolderinyourhomedirectoryandplacetheabout.htmlfileinthere.Letssaythatwecalledthatfolderinfo.Inthatcase,thewebaddresswouldbe:
http://acmeincorporated.com/info/about.html
Likeawordprocessingdocument,anHTMLfilecanincludedifferentfonts,colors,images,andlinkstootherhtmlpages.AnHTMLpagecanalsohaveastyleformatwhichisdoneusingCSS.Wewillseehowtoentertheappropriatecodestodothesetasksinfuturechapters.
YourFirstWebpage
NowthatwehaveanideaofwhatawebpageandHTMLfileisandhowtocreateone,let’sgetourfeetwetandstartcreatingsimplewebpages.Thefirstthingyouneedtoknowishowtogiveinstructionstothebrowser.Thisisdonebyusingtags.Theformatusedtoenteratagistoencloseitin<>.Youwillneedanopeningtagandaclosingtag.Insidethe<>characters,yougivethebrowserandinstruction.Soforillustration,totellthebrowserthatablockoftextistag_one,theopeningtagwouldbe:
<tag_one>
Aclosingtagisindicatedwithaforwardslash/.Sototellthebrowserthatwearefinishedwithtag_one,wewouldwrite:
</tag_one>
Nowlet’sgetintothestructureofanactualHTMLdocumentandrealtagsthatareused.Thefirstlineinyourfileisthisone:
<!DOCTYPEhtml>
Asthenameimplies,thisiscalledtheDocumentTypeDeclaration.ItletsthebrowserknowwhattypeofHTMLyouareusing.Aswrittenabove,thistellsthebrowserweareusingthemostrecentversionofHTMLwhichisHTML5.
NowweneedtotellthebrowserwhereourHTMLactuallyis.ThatmightseemstrangesincewejustletitknowthatthedocumentwasanHTML5document.Howeveryouhavetospecifywhateveryblockoftextis.Totellthebrowserthatthefollowingtextishtml,weusethehtmltagas
.Wealsoneedtheclosingtag,soourfileshouldlooklikethis:
<!DOCTYPEhtml>
<html>
</html>
Henceanythingthatfallsbetween<html>and</html>isinterpretedbythebrowserasbeinghtml.Unfortunatelywearen’tdone.Weneedasecondtagcalledthebodytagthatindicateswherethecontentofthewebpageisplaced.Soweupdateourfileasfollows:
<!DOCTYPEhtml>
<html>
<body>
</body>
</html>
Nowwecanputtheactualcontentofourwebpageinbetween
and.Toputtext,yousimplytypeitasifyouwereusingawebprocessor.Followingtheusualpracticeinteachingcomputertopics,we’lladd“HelloWorld”toourwebpage.
<!DOCTYPEhtml>
<html>
<body>
HelloWorld!
</body>
</html>
HereisourwebpagepreviewinKompozer.Notveryimpressivebutitsastart!
Nowthatwe’velearnedtoaddtexttoawebpage,letslearnhowtouseHTMLtoaddlinebreaksandcentertext.
LinebreaksandCenterTags
InourfirsttutorialwecreatedaHelloWorldwebpage.Itwasn’ttooexcitingitjustprintedourHelloWorldmessagetothescreen:
HelloWorld!
Nowlet’smoveforwardbyaddingsometextformatting.Firstlet’saddacouplemorelinesoftext.Maybewewanttoprintthefollowing:
HelloWorld!
MynameisJoe.
MyfriendisSally.
OurHTMLlookslikethis:
<!DOCTYPEhtml>
<html>
<body>
HelloWorld!
MynameisJoe.
MyfriendisSally.
</body>
</html>
Whenyoudothisandsaveyourhtmlfile,andthenopenitinabrowser,whatyouseeisthis:
HelloWorld!MynameisJoe.MyfriendisSally.
Soeventhoughweputlinebreaksandsomespacing,thebrowserignoresit.Thebrowserseesonelongstringoftextunlessyouaddtagstotellithowtodisplaythattext.
CenteringText
Tocentertext,whatyoudoisaddacentertag.Theopentagtouseis<center>andtheclosingtagis</center>.SowecancentertheHelloWorld!stringinthefollowingway:
<!DOCTYPEhtml>
<html>
<body>
<center>HelloWorld!</center>
MynameisJoe.
MyfriendisSally.
</body>
</html>
Thisproducesawebpagethatlookslikethis:
HelloWorld!
MynameisJoe.MyfriendisSally.
Noticethatclosingthecentertagaddedalinebreak.Tocenterallthetext,wewouldwrite:
<!DOCTYPEhtml>
<html>
<body>
<center>
HelloWorld!
MynameisJoe.
MyfriendisSally.
</center>
</body>
</html>
Nowweobtain:
HelloWorld!MynameisJoe.MyfriendisSally.
LineBreaks
Wecanchangetheappearanceofthepageagainandmakeitmorereadablebyaddingsomelinebreaks.Thisisdonewiththetag<br>.Unlikeothertags,aclosingtagisn’tnecessary.Youjustaddoneforeachlinebreakyouwant.Fornowletsremovethecentertagandjustaddlinebreaks.SoletsaddalinebreakaftertheHelloWorld!string:
<!DOCTYPEhtml>
<html>
<body>
HelloWorld!<br>
MynameisJoe.
MyfriendisSally.
</body>
</html>
Thisproduces:
HelloWorld!
MynameisJoe.MyfriendisSally.
Wecanaddmorelinebreakstoputeachsentenceonitsownline:
<!DOCTYPEhtml>
<html>
<body>
HelloWorld!<br>
MynameisJoe.<br>
MyfriendisSally.<br>
</body>
</html>
Andwegetthis:
HelloWorld!
MynameisJoe.
MyfriendisSally.
Tomakeitdoublespaced,wecanaddextra<br>
tags.
<!DOCTYPEhtml>
<html>
<body>
HelloWorld!<br><br>
MynameisJoe.<br><br>
MyfriendisSally.
</body>
</html>
Andnowwesee:
HelloWorld!
MynameisJoe.
MyfriendisSally.
Rememberforlinebreaksyoudon’tneedaclosingtag.Toaddmorelinebreaks,justaddmore
tags.Supposewewant:
HelloWorld!
MynameisJoe.
MyfriendisSally.
TogetthisresultourHTMLlookslikethis:
<!DOCTYPEhtml>
<html>
<body>
HelloWorld!<br><br><br><br><br>
MynameisJoe.<br><br>
MyfriendisSally.
</body>
</html>
Inthenextlesson,we’lllearnhowtoaddaheadlinetoourwebpage.
HeaderTags
Headertagsenableustoeasilycreateniceboldtexttospruceuptheappearanceofourwebpages.Headertagsusetheformat<hx>wherexisaninteger1,2,3,4….Thesmallerthenumber,thelargertheheader.Thetruthisyoualreadyknowaboutthissinceyou’veprobablyuseddifferentlevelsofheadersinyourwordprocessingprogram.
Headertagshaveanopeningandclosingtag.Thegeneralsyntaxis:
<hx>Yourtexthere</hx>
Workingonourpreviousexample,wecanmakethephrase“HelloWorld!”aheaderbyusingthe<h1>tag:
<h1>HelloWorld!</h1>
Ifourentirehtmllookslikethis:
<!DOCTYPEhtml>
<html>
<body>
<h1>HelloWorld!</h1><br>
MynameisJoe.<br>
MyfriendisSally.
</body>
</html>
Theresultweseeis:
HelloWorld!
MynameisJoe.
MyfriendisSally.
Whenyouaddaheadertag,thetextbetweentheheadertagsisnotautomaticallycentered.Wehavetotothatmanually.Let’schangeourhtmlto:
<!DOCTYPEhtml>
<html>
<body>
<center><h1>HelloWorld!</h1></center><br>
MynameisJoe.<br>
MyfriendisSally.
</body>
</html>
Nowthepageappearsas:
HelloWorld!
MynameisJoe.
MyfriendisSally.
Wecanalsoenhancetheappearanceofthepagebyaddingsubheadings.Thisisdonebyspecifyingtheheaderlevelwithanintegerlargerthan1.Forexample<h1>,<h2>,<h3>etc.where<h1>isthehighestheaderlevel,sowillhavethelargesttext.
Let’saddaheaderandputasubjectheadingasfollows:
<!DOCTYPEhtml>
<html>
<body>
<center><h1>HelloWorld!</h1></center><br>
<h2>Friends</h2>
MynameisJoe.<br>
MyfriendisSally.
</body>
</html>
Nowthewebpagelookslikethis:
HelloWorld!
Friends
MynameisJoe.
MyfriendisSally.
Noticethatsomespacingisautomaticallyplacedinbetweentheheaderandthetextthatfollows.Basicallythisisworkinglikeyouwerejusttypingawayinawordprocessor,exceptweareputtingintheformattingcommandsbehindthescenes.
Inthenextchapter,we’llseehowtoformattextcolors.
FontColor
Aplainblackandwhitewebpagemightbefunctional,butitsnotveryinteresting.Let’sseehowwecanimprovetheappearanceofourwebpagesusingthefonttagandcolorattribute.It’sveryeasy.Let’sreturntothehtmlwehadinthelastlesson:
<!DOCTYPEhtml>
<html>
<body>
<center><h1>HelloWorld!</h1></center><br>
<h2>Friends</h2>
MynameisJoe.<br>
MyfriendisSally.
</body>
</html>
Tohaveatextstringappearinaparticularcolor,weusethesyntax:
<fontcolor=“color”>TextString</font>
Hence,wecanhavetextappearredusing:
<fontcolor=“red”>Sometext</font>
Changingourhtmlfilewiththisinmindwecanmakethemainheaderred:
<!DOCTYPEhtml>
<html>
<body>
<center><h1><fontcolor=“red”>HelloWorld!</font></h1></center><br>
<h2>Friends</h2>
MynameisJoe.<br>
MyfriendisSally.
</body>
</html>
Thewebpagenowappearsas:
HelloWorld!
Friends
MynameisJoe.
MyfriendisSally.
Let’ssaywewantedthe“Friends”sub-headertoappearasbluetext.Allwehavetodoisaddanotherfonttagwiththecolorattribute,forthe“Friends”textstring:
<!DOCTYPEhtml>
<html>
<body>
<center><h1><fontcolor=“red”>HelloWorld!</font></h1></center><br>
<h2><fontcolor=“blue”>Friends</font></h2>
MynameisJoe.<br>
MyfriendisSally.
</body>
</html>
Notethatweneedaclosingtagwhenusingdifferentfontattributes.
Nowourwebpagelookslikethis:
HelloWorld!
Friends
MynameisJoe.
MyfriendisSally.
Besideschangingcolor,youmightwanttomakeotherchangestofontssuchassettingthetypeface.Wewillexplorethisinthenextlesson.
FontSizeandTypeFace
Inthislessonwe’lllearnhowtochangefontsizeandtypeface.Thisisalsodoneusingthefonttag.Tospecifyafontsize,wesimplywrite:
<fontsize=“x”>Thisissometext.</font>
wherexisaninteger.Forexamplewecanwrite:
<fontsize=“3”>MynameisJoe.</font>
Youcansetdifferentattributesusingthesamefonttag.Let’ssupposethatwewantedthetexttoappearredandsetthefontsizeto5.Thiscouldbedonebywriting:
<fontsize=“5”color=“red”>MynameisJoe.</font>
Thisproduces:
MynameisJoe.
Tochangethetypeface,wecansetthefaceattributeinafonttag.Forexample,tosetthefontofatextstringtoverdana,wewrite:
<fontface=“verdana”>MyotherfriendisBob.</font>
Andweobtain:
MyotherfriendisBob.
Asbeforewecancombinemultipleattributesincludingthetypeface.Soletssetthetexttogreen,thefacetoverdana,andalsosetthesizeattributeofthetext.
<fontcolor=“green”face=“verdana”size=“4”>MyotherfriendisBob.</font>
Thisgivesus:
MyOtherfriendisBob.
Beingabletochangethesefontattributesgivesusthepowertoimprovetheappearanceofourwebpages.Referringtothehtmlofthelastchapter,supposethatwechangeditto:
<body>
<center>
<h1><fontcolor=“red”>HelloWorld!</font></h1>
</center>
<h3><fontcolor=“blue”>Friends</font></h3>
<fontcolor=“red”size=“5”>MynameisJoe.</font>
<br>
<br>
<fontcolor=“blue”size=“4”>MybestfriendisSally.</font>
<br>
<br>
<fontcolor=“green”face=“verdana”size=“4”>MyotherfriendisBob.</font>
<br>
<br>
</body>
</html>
Nowwesee:
HelloWorld!
Friends
MynameisJoe.
MybestfriendisSally.
MyotherfriendisBob.
ParagraphandDivTags
Nextweexploretwomoreformattingtagsthatcanbeusedtoimprovetheappearanceofyourwebpagesandpresentcontentinameaningfulway.Thefirstistheparagraphtag.Itdoesexactlywhatitsays,itcreatesaformattedparagraphforanytextenclosedwithinthetags(byaddingmarginsandspacing).Theparagraphtagisdefinedby<p>andyoumustaddaclosingtag</p>whereyouwanttheparagraphtoend.
Forexamplewecanwrite:
<body>
<p>Helloworldthisissometext.Hereisasecondline.</p>
<h2>Thisismyheading</h2>
Anotherlineoftext.<br>
Linetwoofnewsection.<br>
Somemoretext.<br>
<h2>ADifferentSection</h2>
Textforthesecondsection.
<br>
<br>
</body>
</html>
Thiswillput“Helloworldthisissometext.Hereisasecondline.”intoaparagraphandautomaticallyputspacingbetweenitandtheheadingonthenextline.
Thedivtagisusedtogrouptogetherelementsintoasectionandapplyformattingtothem.Soinshortitdefinesasectioninyourhtmldocument.Forasimpleexample,wewilltakesomeofthetextaboveanddefineasectionoutofitusingthedivtag,andcolorthefontblue.Thedivtagiswrittenas<divstyle=…>andyouuseaclosingtagtoendthesectionas</div>.
Youcanseehowtousethedivtaghere,wherewecolorasectionblue:
<body>
<p>Helloworldthisissometext.Hereisasecondline.</p>
<divstyle=“color:rgb(0,0,255);”>
<h2>Thisismyheading</h2>
Anotherlineoftext.<br>
Linetwoofnewsection.<br>
Somemoretext.<br>
</div>
<h2>ADifferentSection</h2>
Textforthesecondsection.
<br>
<br>
</body>
</html>
Weobtainthisresult:
Helloworldthisissometext.Hereisasecondline.
ThisismyheadingAnotherlineoftext.
Linetwoofnewsection.
Somemoretext.
ADifferentSectionTextforthesecondsection.
Hyperlinks
Theinternetwouldn’thavemuchfunctionalityifyoucouldonlylookatonewebpageatatime.Toeasetheabilityofuserstomoveaboutyourwebsiteandtovisitrelatedpagesofinterestweneedtoaddhyperlinkstoourhtmldocuments.Thisisdonewiththehyperlinktag.
Oddlythehyperlinktagisdenotedwiththelettera.Theletteraisusedbecauseitmeansanchortext.Hencethe<a>tagdefinesahyperlinkwhichwillopenanewwebpagewhentheuserclicksonit.Asyouprobablyknowhyperlinksaredisplayedtotheuserasunderlinedtext,withbluecolorforapagetheyhavenotopenedbeforeandpurpleforwebpagesthey’vealreadyvisited.
Severalattributescanbespecifiedwiththehyperlinktag.Themostimportantisthehrefattributewhichtellsthebrowserwhichlinktoopenwhentheuserclicksonthetext.Sohrefisjusttheurlofthetargetwebpage.
HTML5introducessomenewattributes.Forexample,youcanusedownloadtotellthebrowsertobegindownloadingafilewhentheuserclicksonthelink.
Thetargetspecifiedinthehrefattributecanbealocalfile(relativetothewebpage)oranyURL.Thesyntaxyouwilluseis:
<ahref=“urltoopen”>Textdisplayedtouser</a>
Thetextdisplayedtotheusercanbeanything,mostwebpagedevelopersputdescriptivetextthatmakesitmorereadableandmoreamenabletosearchengines.ButyoucanjustputtheURLthereifdesired.Thesedayspeopleautomaticallyknowthatunderlinedbluetextisahyperlinksoputtingdescriptivetextispreferred.
HereisanexamplethatwilldisplayalinktotheNewYorkTimeswebsite:
<body>
HelloWorld!
<br>
<ahref=“http://nytimes.com”>NewYorkTimes</a>
<br>
Thislookslikeso:
HelloWorld!
NewYorkTimes
Ifwewantedtojustdisplaytheactuallinktotheuser,wecouldwrite:
<body>
HelloWorld!
<br>
<ahref=“http://nytimes.com”>http://nytimes.com</a>
<br>
Thenwewouldget:
HelloWorld!
http://nytimes.com
Nowsupposeyouwanttoopenafileonyourownserver.Considerthecaseofawebpagenamedabout.htmlinyoursamedirectory.Thenyouwouldwrite:
<body>
HelloWorld!
<br>
<ahref=“about.html”>AboutUs</a>
<br>
Ifthefilewasinafoldercalled“Info”you’dwrite:
<body>
HelloWorld!
<br>
<ahref=“about.html”>/Info/AboutUs</a>
<br>
Oftenlinksareplacedinthemiddleofatextstring,forexample:
Hereissomemoretextlinkingto<ahref=“http://cnn.com”>cablenews
network</a>findoutwhatthelatestnewsis.
Thisdisplaysas:
Hereissomemoretextlinkingtocablenewsnetworkfindoutwhatthe
latestnewsis.
DisplayingImages
Imagesaredisplayedinawebpageusingtheimgtag.Thesyntaxis:
<imgsrc=“linktoimage”alt=“texttodisplayifimagenotrendered”style=“width:Xpx;height:Ypx;>
YoucanlinktoimagesonyourownserverortoanyimageonthewebifyouknowtheURL.TogiveaspecificexampleIhaveobtainedalinktoapictureoftheactressSelmaHayek.Wecandisplaytheimageinourwebpageasfollows:
<body>
<h1>SelmaHayek!</h1>
<br>
<br>
<imgsrc=“http://bit.ly/1HDOqOk”alt=“SelmaHayekNotHere”
style=“width:200px;height:250px;”>
<br>
<br>
</body>
Iftheimagedoesn’trender,thetext“SelmaHayekNotHere”willbedisplayedinitsplace.Hereishowthewebpagelooks:
SelmaHayek!
Toseehowthealtattributeworks,youcancopyandpastefromthepreviewinKompozertoatextdocument,andyouwillsee:
SelmaHayek!
SelmaHayekNotHere
Youcanputothertagsaroundtheimagetoimprovetheappearanceofyourwebpage.Forexample,ifwewantedtocentertheimage,wewouldwrite:
<body>
<h1>SelmaHayek!</h1>
<br>
<br>
<center>
<imgsrc=“http://bit.ly/1HDOqOk”alt=“SelmaHayek”
style=“width:200px;height:250px;”>
</center>
<br>
<br>
</body>
</html>
VideoPlayersonWebPages
Ournexttopicisthevideotag.Using<videoyoucanputalinktoavideoyouwanttouseanddisplayitusingHTML5inafullfeaturedvideoplayer.Thebestwaytoteachthisistosimplyshowanexample.
<body>
<videowidth=“400”controls=””>
<sourcesrc=“savagearchives.info/video/20-Timer-sm.mp4”type=“video/mp4”>
YourbrowserdoesnotsupportHTML5video.
</source>
</video>
<p>Videocourtesyof<ahref=“http://www.xcode-training-and-tips.com/”
target=“_blank”>XcodeTraining</a>.
</p>
</body>
Sowestartwiththe<video>tag,thenfollowitwiththe<source>tagwhichtellsthebrowsertheURLwherethevideoislocated.AsusualtheURLcanbealocalfileoranyURLontheinternet.
ThecodehasabitoftextthatisdisplayedifthebrowserdoesnotsupportHTML5.KompozerhasnotbeenupdatedinawhilesowhenIpreviewthiscodeinKompozerIseethis:
YourbrowserdoesnotsupportHTML5video.
VideocourtesyofXcodeTraining.
Ontheotherhand,openingitinthebrowserwesee:
OrderedandUnorderedLists
InthislessonwearegoingtolearnhowtodisplaybulletedandnumberedlistsusingHTML.Thisisdoneusingtheunorderedlistororderedlisttag.Anunorderedlistisjustabulletedlistofitems.Tocreateanunorderedlist,youwillencloseyourlistitemswithinanopening<ul>tagandaclosing</ul>tag.Eachlistitemisdenotedwithalistitemor<li>tag.Youneedaclosing</li>tagattheendofeachlistitem.
Asanexample,let’screatealistoffriendsnames.Inmostcasesyouwillhaveaheaderofsomekindtodenotethelist.Thiscanbedonebyputtingthetextintroducingyourlistinbetweenparagraphtags.Solet’sstartbyputtingatitleforourlistasfollows:
<p>MyBestFriends:</p>
Nowwewillneedtoenclosethelistwith<ul>and</ul>:
<p>MyBestFriends:</p>
<ul>
</ul>
Eachbulletedlistitemwillappearas<li>itemtext</li>.Let’smakeourlistofnames:
<p>MyBestFriends:</p>
<ul>
<li>Sally</li>
<li>Jose</li>
<li>Paul</li>
</ul>
Whatthisproducesisthefollowing:
MyBestFriends:
•Sally
•Jose
•Paul
Using<ol>inplaceof<ul>producesanumberedlist.Thetag<ol>meansorderedlisting.Forexample:
<p>Countries:</p>
<ol>
<li>China</li>
<li>UnitedStates</li>
<li>UnitedKingdom</li>
<li>France</li>
</ol>
Givesus:
Countries:
1.China
2.UnitedStates
3.UnitedKingdom
4.France
BigandSmalltags
TheBigandSmalltagsprovideyouwithameanstocarefullycontroltextsize.Youcannestbigandsmalltagstogetastringoftexttobethesizeyouwant.
TouseaBigtagsimplyplaceanopening<big>atthestartofthetextyouwanttobelargerfont.Tomakeitlargeraddasmany<big>tagsasnecessary.Attheendofthetextyouwanttohavelargerfont,placeacorrespondingclosingtag</big>.
Thesmalltagworksinananalogousmanner.Forexample:
<h1>MyWebPage</h1>
<p>Video<big><big><big>is</big></big></big><small><small><small>courtesy</small></small></small>
ofXcodetraining</a></p>
Produces:
VideoiscourtesyofXcodetraining
BasicTextFormattingTags
Inthislessonwewillintroducetagsusedtomaketext:
•Bold
•Italic
•Underlined
Tomakeastringoftextbold,encloseitin<b>and</b>tags.Forexample:
<b>BarakObama</b>isPresidentoftheUnitedStates
produces:
BarakObamaisPresidentoftheUnitedStates
Toputastringinitalicsencloseitin<i>and</i>tags:
BarakObamais<i>President</i>oftheUnitedStates
givesus:
BarakObamaisPresidentoftheUnitedStates
Tounderlineastringoftext,encloseitin<u>and</u>tags:
BarakObamaisPresidentofthe<u>UnitedStates</u>
Thisgivesus:
BarakObamaisPresidentoftheUnitedStates
Youcanofcourse,nesttagstoapplymorethanonetypeofformatting.Wecanmake“UnitedStates”boldandunderlined:
BarakObamaisPresidentofthe<b><u>UnitedStates</u></b>
Giving:
BarakObamaisPresidentoftheUnitedStates
Toalsomakeititalic,justadd<i>and</i>tags:
BarakObamaisPresidentofthe<i><b><u>UnitedStates</u></b></i>
Thisgives:
BarakObamaisPresidentoftheUnitedStates
SuperscriptandSubscriptTags
Textoftenrequiressuperscriptsandsubscripts.Youcantothisinhtmlusingthesupandsubtags.Eachalsorequiresaclosingtagotherwiseanytextthatfollowswillalsobealteredbythetag
Oftensuperscriptsareusedtoindicatereferences.Tocreateasuperscriptenclosethedesiredsuperscripttextinthetags<sup>and</sup>.Forexampleifwewantedthetext:
BarakObamawonthe2012PresidentialElectionintheUnitedStates.19
Wewouldusethefollowinghtml:
<b><i>BarakObama</i></b>wonthe2012<i>PresidentialElection</i>inthe<b><u>United
States</u></b>.<sup>19</sup>
Tocreateasubscript,simplyenclosethetextin<sub>and</sub>tags.Toobtain:
Xi
Wewoulduse:
X<sub>i</sub>
QuotingPassagesofText
Therearetwotagsthatareusefulfordisplayingquotesonyourwebpages.Thefirstisthe<q>tagwhichsimplyenclosestextinquotes.Supposethatwehadthisphraseofplaintextinourhtmlfile:
Notonlyourfutureeconomicsoundnessbuttheverysoundnessofourdemocraticinstitutionsdependsonthedeterminationofourgovernmenttogiveemploymenttoidlemen.
Ifweencloseitin<q>and</q>tags,onthewebpageitwillbedisplayedlikethis:
“Notonlyourfutureeconomicsoundnessbuttheverysoundnessofourdemocraticinstitutionsdependsonthedeterminationofourgovernmenttogiveemploymenttoidlemen.”
Wecanalsoenhancethedisplayofthequoteusingthe<blockquote>tag.Whatthisdoesissetoffandindentthequote.Soifwehad:
Hereisaline.
Notonlyourfutureeconomicsoundnessbuttheverysoundnessofourdemocraticinstitutionsdependsonthedeterminationofourgovernmenttogiveemploymenttoidlemen.
Hereisanotherline.
ChangingourHTMLto:
Hereisaline.<br>
<blockquote><q>Notonlyourfutureeconomicsoundnessbuttheverysoundnessofourdemocraticinstitutionsdependsonthedeterminationofourgovernmenttogiveemploymenttoidlemen.</q></blockquote>
Hereisanotherline.
Willgiveus:
Hereisaline.
“Notonlyourfutureeconomicsoundnessbuttheverysoundnessofour
democraticinstitutionsdependsonthedeterminationofourgovernmenttogiveemploymenttoidlemen.”
Hereisanotherline.
CreatingTables
Tablesallowyoutodisplaydatainarowandcolumnformat.Therearethreetagsyouwillneedtocreateasimpletable:
•<Table>
•<TR>-tablerow
•<TD>-tabledatacell
<TR>isatagthattellsthebrowsertobeginanewrowinthetable.Anythinginbetweentheopeningtag<TR>andtheclosingtag</TR>constitutesasinglerow.Individualcellsintherowaredenotedby<TD>withtheclosingtag</TD>.
Toseehowtosetupanexample,let’ssupposethatwearedisplayingsportsscores.Wecanaddacenteredheadline:
<center>
<h1>BasketballScoresfromFinalFour</h1>
</center>
Nowletsaddourtable.Webeginbyaddingthetabletag,specifyingborderwidth:
<center>
<tablesummary=“Example”border=“1”>
</table>
Thesummaryisnotdisplayedonthepage.Nowletsaddourrows:
<center>
<tablesummary=“Example”border=“1”>
<tr>
<td>GameOne</td>
<td>Michigan75</td>
<td>Kentucky73</td>
</tr>
<tr>
<td>GameTwo</td>
<td>Arizona68</td>
<td>Duke61</td>
</tr>
</table>
</center>
DrawingLinesonWebPages
Inthislessonwearegoingtolearnhowtodrawhorizontalandverticallines.Drawinghorizontallineswithhtmlisveryeasyusingthe<hr>tag.Allyouneedtodoisplacean<hr>tagwhereyouwantthelinetoappear.Forexample,ourhtmllookslikethis:
<body>
<center>
<h1>BasketballScoresfromFinalFour</h1>
</center>
<hr>
<br>
<br>
<center>
<tablesummary=“Example”border=“1”cellpadding=“16”width=“100%”>
<tbody>
<tr>
<thbgcolor=”#ccffff”width=“50%”>GameOne</th>
<tdbgcolor=”#ffffcc”width=“25%”>Michigan75</td>
<tdwidth=“25%”>Kentucky73</td>
</tr>
<tr>
<th>GameTwo</th>
<td>Arizona68</td>
<td>Duke61</td>
</tr>
</tbody>
</table>
</center>
</body>
Wesee:
Youcanalsodrawverticallinesusingthe<hr>tag,butittakesabitofatrick.The
followingcodeusing2<hr>tagsinarowwilldrawaverticallinedownthecenterofthewebpage:
<hr
style=“padding:0px;height:400px;width:2px;margin-bottom:-8px;”>
<hrstyle=“padding:0px;height:100px;width:2px;margin-top:-8px;”><br>
DropDownLists
OnmanyoccasionsyouwillwanttogivewebsitevisitorstheabilitytoselectanoptionfromadropdownlistLetsseehowtosetalistlikethisoneupforyourwebpage:
Thisisdoneusingthe<select>tag.Youenclosethechoicesyouwanttopresenttotheuserinbetweenandopeningandclosingselecttag,usingthe<option>tagforeachitem.Theformatusedfortheoptiontagistopresentthevalueandtextdisplayedtotheuser.Forexample:
<optionvalue=“Alaska”>Alaska</option>
Theentirecodeforthepageshownabove,includingheader,horizontallineanddropdownlistwiththecoderelevantforthedropdownlisthighlightedinredisasfollows:
<body>
<h1>MyGreatHeader</h1>
<p>Sometextformygreatwebpage.</p>
<hr>
<br>
<br>
<select>
<optionvalue=“Alaska”>Alaska</option>
<optionvalue=“California”>California</option>
<optionvalue=“Delaware”>Delaware</option>
<optionvalue=“Florida”>Florida</option>
<optionvalue=“Texas”>Texas</option>
</select>
</body>
PlayingAudioFiles
Inthislessonwe’regoingtolearnhowtosetupanaudioplayeronyourwebpage.Itwillbecompletewithplay/pausebuttons,volumecontrol,andtimeplayeddisplayed.Thesecontrolsaredisplayedbydefault.
Toplayaudioyouneed2tags:
•<audio>tag
•<source>tagwithapathtoyourfileandtellingthebrowserwhattypeofaudiofileyouhave
Setupiseasy.Beginwiththeaudiotag:
<audiocontrols=“”>
Next,wetellitwhereoursourcefileisandwhattypeoffilewehave.Youcanincludemultiplelinestoincludedifferentfileformatsifyouneedtoprovidethosefordifferentbrowsers.
<sourcesrc=“Genesis.mp3”type=“audio/mpeg”>
Inmyexample,thefileisinthesamefolder/directoryasthewebpage.Ifyoursisnotbesuretoprovidethecorrectpathtothefileforthesrcattribute.
Nextyouneedtoprovideatextstringthatwilldisplayiftheusersbrowsercannotdisplaytheaudiocontrols.
Ourentirecodelookslike:
<audiocontrols=””>
<sourcesrc=“Genesis.mp3”type=“audio/mpeg”>
Yourbrowserdoesnotsupportaudiocontrols
</source>
</audio>
Ifweincludethisinthecodeforthepreviouswebpagewewereworkingon:
<body>
<h1>MyGreatHeader</h1>
<p>Sometextformygreatwebpage.</p>
<hr>
<br>
<br>
<audiocontrols=””><sourcesrc=“Genesis.mp3”type=“audio/mpeg”>Your
browserdoesnotsupportaudiocontrols
</source></audio>
</body>
Thenourpagelookslikethis:
iFrameUsingtheiframetagallowsyoutoembedanotherwebpageorURLinsideyourwebpage.Inthesimplestcase,wecanjustpasstheURLasfollows:
<iframesrc=“http://nytimes.com></iframe>
Howevertherearemanypropertieswecanspecify.Forexample,wecansetthewidthandheightoftheframe:
<iframesrc=“http://nytimes.com”width=“700”height=“400”><iframe>
Youcanalsousethestyleattributetosetaborder.Wecouldforexamplesetourembeddedwebpageinsideadottedredboxwiththebordergivena5pixelwidth:
<iframesrc=“http://nytimes.com”style=“border:5pxdottedred”></iframe>
Here,we’vesetthewidthandheightandaddedasolidblueborder:
<iframesrc=“http://nytimes.com”style=“border:5pxsolidblue;”
height=“500”width=“700”></iframe>
Addingthistothehtmlwe’veusedinseveralrecentexamples:
<body>
<h1>MyGreatHeader</h1>
<p>Sometextformygreatwebpage.</p>
<hr>
<br>
<br>
<iframesrc=“http://nytimes.com”style=“border:5pxsolidblue;”
height=“500”width=“700”></iframe>
</body>
Givesusthiswebpage,withtheNewYorkTimesembeddedinsidetheblueframe:
Formsinput
The<form>tagallowsyoutocreateaninputformtodothingslikecollectnames,emailaddressesandsoon.Everythingthatappearsontheformisenclosedinbetweenformopeningandclosingtags:
<form>
yourstuffhere
</form>
Forexamplewecancreateinputtextboxestolettheusertypeintheircityandstate:
<form>
City:<br>
<inputtype=“text”name=“city”>
<br>
State:<br>
<inputtype=“text”name=“state”>
</form>
Otheroptionsallowyoutoaddradiobuttonsandcheckboxes.Usingradiobuttonsasanexample,tohavetheuserselectgenderasmaleorfemale,wewouldaddthefollowinglinesinbetweentheformopeningandclosingtags:
<inputtype=“radio”name=“sex”value=“male”checked>Male
<inputtype=“radio”name=“sex”value=“female”>Female
Ofcourseyouhavetoprovideameansfortheusertosubmitthedata.Youcanaddasubmitbuttonwiththisline:
<inputtype=“submit”value=“Submit”>
Tomakesomethinghappenwhentheuserclicksthesubmitbutton,suchastaketheinfoenteredaboveandstickingitintoadatabase,youneedtowriteascripttohandlethesubmitclickedaction.Thescriptitselfisoutofthescopeofthistutorial,butletssayitwasmyaction.php.Thenwewouldmodifytheopeningformtagtohavetheformexecutethisactionwhenthebuttonisclicked:
<formaction=“myaction.php”>
CSSforBi-ColoredWebPage
Inthissimpleexampleweintroducetheuseofstylesheetstochangetheappearanceofyourwebpages.Acommontaskisformattingthepagetodisplaydifferentareas,youmightwanttodisplaya2or3columnwebpageoraddheadersandfootersorasidebar.Inthisexampleweshowhowtosetupasimplesidebar,distinguishedfromthemainwebpagebycolor:
Thefirstthingtodoinordertosetthisupistoputyourstylesheetinbetweentheheadtags.Ourverysimplestylesheetwillsetthewidthofthesidebaranditsbackgroundcolor.Wealsosetthebackgroundcolorandleftmarginforthemainpartofthepage:
<head>
<styletype=“text/css”>
html,body{height:100%;margin:0}
#content{width:100%;height:100%}
#left{width:250px;height:100%;float:left;background-color:#FFFFCC}
#right{margin-left:250px;height:100%;background-color:#CCFFFF}
</style>
</head>
Inthebodysectionofthehtmlfileweuse<div>tagstosetupeachsection.Therewillbea<div>forthesidebarandmainpartofthepage.Wealsoneedanextra<div>withinwhichthesearenested.Thisisshownhere:
<divid=“content”>
</div>
Inbetweentheopeningandclosingtags,weputthe<div>tagsforeachsection.Firsthereisthesidebar.Wehavetotellthebrowserwhatstyletouse.Thisisdonebysettingtheidtoleft:
<divid=“left”>
<h2>sidebar</h2>
<p>Somesampletext</p>
</div>
Wedothesameforthemainpartofthepage:
<divid=“right”>
<h1>MyGreatWebpage</h1>
<hr>
<p>Somesampletext</p>
</div>
Nowofcourseyoucanputanythinginbetweenthedivtagsofeachsection,butweareonlyshowingsometexthereforsomesimplicity.Theentirecodeisshownhere:
<html>
<head>
<styletype=“text/css”>
html,body{height:100%;margin:0}
#content{width:100%;height:100%}
#left{width:250px;height:100%;float:left;background-color:#FFFFCC}
#right{margin-left:250px;height:100%;background-color:#CCFFFF}
</style>
</head>
<body>
<divid=“content”>
<divid=“left”>
<h2>sidebar</h2>
<p>Somesampletext</p>
</div>
<divid=“right”>
<h1>MyGreatWebpage</h1>
<hr>
<p>Somesampletext</p>
</div>
</div>
</body>
</html>
MoreTextFormattingTags
Tohighlightasectionoftext,usethemarktag.Forexample,tohavethestring“QueenofEngland”highlightedinyellowwewrite:
<p>Everyonecamefromfarandwidetoseethe<mark>QueenofEngland</mark>assherodethroughLondon.</p>
Wecanstrikethroughtextbyeitherusingthe<s>tagorthe<strike>tag.Tostrikethroughthephrase“PrinceofWales”inthissentencewecanuseeitherofthetwoexamples:
<p>Rumorsaboutwhowouldbethenext<s>PrinceofWales</s>filledtheair.</p>
<p>Rumorsaboutwhowouldbethenext<strike>PrinceofWales</strike>filledtheair.</p>
Supposeyouwanttoenclosepartofawebpageorforminabox.Thiscanbedoneusingthefieldsetandlegendtags.
<fieldset>
<legend>SomeBoxedStuff:</legend>
<p>Somesampletext.</p>
</fieldset>
Finally,thepreformattedtag<pre>allowsustotypetextandhaveitappearonthewebpageastyped.Ifwejusttype:
HellofromTimesSquare
locatedinNewYorkCity
thefinestcityinallthe
worldexceptmaybeParisor
London.
Itwillappearas:
HellofromTimesSquarelocatedinNewYorkCitythefinestcityinalltheworldexceptmaybeParisorLondon.
Ifweinsteadenterourhtmlas:
<pre>HellofromTimesSquare
locatedinNewYorkCity
thefinestcityinallthe
worldexceptmaybeParisor
London.</pre>
Thattellsthebrowsertouseourformatting,soitappearsas:
HellofromTimesSquare
locatedinNewYorkCity
thefinestcityinallthe
worldexceptmaybeParisor
London.
CSSStyleSheets
CSSmeanscascadingstylesheet.Itissimplyafilethatgoesalongwithyourhtmlfilewhichspecifiesthelookandformattingofthehtmlfile.Wewillillustratethiswithasimpleexample.
Firstcreateafilecalledthecssfile.cssandplaceitinthesamefolderasyourhtmlfile.Inthisexample,wewillseehowtospecifyhowtextwithcertaintagsappears-whatfontisused,whatstyle,andwhatsize.
Note:Commentsinacssfilearelineswhichareignoredbythebrowser.Theseareenclosedbetweenthecharacters/*…*/.
/*Examplecommentthatwouldbeignored*/
Whatyoudoinacssfileislisttagsusedinthehtmlfileandspecifyvaluesforvariousattributesenclosedincurlybraces.
tag_name{
properties
}
Forexample,wecanspecifythefontusedandtextsizeforanh1header.
h1{
font-family:Arial,‘HelveticaNeue’,Helvetica,sans-serif;
font-size:24px;
font-style:bold;
font-variant:normal;
font-weight:700;
line-height:26.3999996185303px;
}
Ifyouwantedalltextinyourhtmlfilethatwasenclosedinparagraphtags<p>tohavehelveticaneuefontwithsize12pixels,youwouldwrite:
p{
font-family:Arial,‘HelveticaNeue’,Helvetica,sans-serif;
font-size:12px;
font-style:normal;
font-variant:normal;
font-weight:400;
line-height:20px;
}
Orsupposethatwewantallquotesonourwebpagetohaveitalicfont.Wecandothisbyspecifyingthepropertiesoftheblockquotetaginourcssfile:
blockquote{
font-family:Arial,‘HelveticaNeue’,Helvetica,sans-serif;
font-size:21px;
font-style:italic;
font-variant:normal;
font-weight:400;
line-height:30px;
}
Asyoulearnmorecssyouwillbeabletomakeveryfancywebpages,butwiththissimpleexampleweareseeingsomeadvantagesofusingcss.Oneisthatwecanhaveallblockquotesappearinitalicswithotherspecifiedfontpropertieswithouthavingtotypeintagseverysingletimeinourhtmlfile.
Hereisthecompletecodeofthiscssfile:
/*TheCSSFile*/
h1{
font-family:Arial,‘HelveticaNeue’,Helvetica,sans-serif;
font-size:24px;
font-style:bold;
font-variant:normal;
font-weight:700;
line-height:26.3999996185303px;
}
h3{
font-family:Arial,‘HelveticaNeue’,Helvetica,sans-serif;
font-size:14px;
font-style:normal;
font-variant:normal;
font-weight:500;
line-height:15.3999996185303px;
}
p{
font-family:Arial,‘HelveticaNeue’,Helvetica,sans-serif;
font-size:14px;
font-style:normal;
font-variant:normal;
font-weight:400;
line-height:20px;
}
blockquote{
font-family:Arial,‘HelveticaNeue’,Helvetica,sans-serif;
font-size:21px;
font-style:italic;
font-variant:normal;
font-weight:400;
line-height:30px;
}
pre{
font-family:Arial,‘HelveticaNeue’,Helvetica,sans-serif;
font-size:13px;
font-style:normal;
font-variant:normal;
font-weight:400;
line-height:18.5714302062988px;
}
Tousethecssfile,youneedtoaddareferencetoitinyourheadersectionofthehtmlfile.Thisisplacedinbetweentheheadertags<head>and</head>.Theimportantlinetoaddis:
<linkhref=“thecssfile.css”rel=“stylesheet”type=“text/css”>
Besurethatthehrefiscorrect,orthatthe.cssfileisinthesamefolderasyourhtmlfile.Therearesomeothercodesnecessarytoincludeintheheadersectionbutwewon’tworryaboutwhattheydojustyetandjustmakesuretheyarelisted:
<html>
<head>
<title>CSSExample</title>
<metahttp-equiv=“Content-Type”
content=“text/html;charset=iso-8859-1”>
<linkhref=“thecssfile.css”rel=“stylesheet”type=“text/css”>
</head>
Thenwecanaddsomethingstoourhtmlbody:
<body>
<h1>MyGreatWebPage</h1>
<pre>Thisissomerandomtextwrittenfor<br>displayonthewebpage.Helloworld<br>helloworldhelloworldhelloworld.<br></pre>
<br>
<q></q>
<blockquote><q>Thisisthebestdayintheworld!</q></blockquote>
<br>
<br>
</body>
</html>
Nowthatwehavespecifiedthecssfileintheheader,allthetextlistedinthebodywillautomaticallytakeonthepropertiesspecified,soforinstancethequotedtextwillbeinitalicseventhoughwedidn’tadd<i>or<em>tags.
ElementandidSelectors
Althoughinthelastexamplewecreatedanexternalcssfile,thisisnotalwaysnecessary.Youcanincludeyourstylesheetsdirectlyinthe<head>,</head>tags.Let’slookatthisanddosoexaminingtwowaystoproceed.
Anelementselectorislikewedidinthepreviouslesson.Wepickanelement(orthinkofitasatypeoftag),suchasaheader,blockquote,orparagraph,andthenspecifyitsproperties.Ifyoucreateastylesheetandspecifythepropertiesforanh3header,youarecreatinganelementselector.
Forexample,wecanspecifystylesfor<p>,<h1>,and<h2>foragivenwebpage:
<head>
<style>
p{
color:blue;
text-align:center;
}
h2{
text-decoration:underline;
text-align:center;
color:red;
}
h1{
text-shadow:2px2px#0000ff;
}
</style>
<title>ExampleWebpage</title>
</head>
Anotherwaytosetstylesistouseanidselector.Inthiscaseratherthandefiningpropertiesforaspecificelementyousimplydefinethepropertiesyouwantandassignitanidentifier.
#mytag{
text-align:center;
color:green;
}
Herewehavecreatedanelementwithidentifier“mytag”.Inthiscaseyousetanhtmlelementinyourpagetohavethesepropertiesbysettingitsidattribute:
<pid=“mytag”>Hellofromvactionland.</p>
Elementandidselectorscanbemixedinthesamestylesheet.
<html>
<head>
<style>
p{
color:blue;
text-align:center;
}
h2{
text-decoration:underline;
text-align:center;
color:red;
}
#mytag{
text-align:center;
color:green;
}
h1{
text-shadow:2px2px#0000ff;
}
</style>
<title></title>
</head>
Inthiscase,ifwejustuse<p>,thetextwillbeblue,butifweuse<pid=“mytag”>,thetextwillappeargreen.Hence,wecanapplythestyleweneedatwill:
<body>
<h1>MyGreatWebPage</h1>
<p>Exampletextforaparagraph</p>
<br>
<br>
<h2>SecondHeader</h2>
<br>
<pid=“mytag”>Hellofromvactionland.</p>
<p>Hereisasecondparagraphstring.</p>
<h2id=“mytag”>ThirdHeader</h2>
</body>
Theresultingwebpageis:
Web
PageBackgrounds
Let’ssayyouwanttosetabackgroundcolorforyourwebpageandmakeheadersappearaswhitetext.Wecanchooseacyancolorforourbackground:
Thisiseasytodousing<style>.Let’slookatthedetailsandthenputittogetherfortheentirepage.Youcansetthebackgroundcolorofanobjectusingbackground-colorinyourcss.Intheexamplehere:
background-color:#01c4de;
Willgivethecolordisplayedintheimage.Tosetthebackgroundcolorfortheentirewebpage,wespecifythatwewantthistobethebackgroundcolorforthebodytag.
body{
background-color:#01c4de;
}
Wecantellthebrowserthatwewantallh1headerstobe
renderedinwhitetextusing:
h1{
color:white;
}
Totellthebrowserthatyouwanth2headerstobered,centeredandunderlinedyouwouldwrite:
h2{
text-decoration:underline;
text-align:center;
color:red;
}
Alltogetherthehtmlandcssfortheabovepageis:
<html>
<head>
<style>
body{
background-color:#01c4de;
}
p{color:blue;
text-align:center;
}
h2{
text-decoration:underline;
text-align:center;
color:red;
}
</style>
<title>CyanWebPage</title>
</head>
<body>
<h1>MyGreatWebPage</h1>
<p>Exampletextforaparagraph</p>
</body>
</html>
It’salsopossibletouseanimageforyourbackgroundratherthanasolidcolor.Supposethatwehadanimagenamedforest.jpgthatwewantedtouseforthebackground.Todothischangethebodytaginyourstylesheetto:
body{
background-image:url(“forest.jpg”);
}
Makesuretoincludethecompletepathtoyourimage.Intheexamplehere,theimagehasbeenplacedinthesamefolderasthewebpage.Withthischange,thewebpagenowloadsas:
ClassesinCSS
Inthislessonwe’regoingtotakeasteptowardsmoreadvancedCSSbyintroducingthenotionofclasses.Wewillusethistobuildawebpagelikethis:
Aclassisjustanotherwayto
identifyelementsinyourHTMLandgivethemcertainattributes.TheflexibilityoftheclassallowsyoutoapplycharacteristicstomultipleitemsinyourHTMLiftheyareidentifiedasbeingamemberofthatclass.Soinshort,aclassselectorselectsHTMLelementsinyourwebpagethathavebeenidentifiedasbeingthatclassandappliestheattributesyouspecifytoit.
Nodoubtyou’vealreadyseenclassesinHTMLfilesyou’velookedat.InyourCSSaclassisdenotedwithaperiodfollowedbythenameassignedtotheclass.YoucanhaveaclasswithoutspecifyingthetypeofHTMLtagitappliestosuchas:
.myclassname{
attributeshere
}
Oryoucanapplyittoaspecifictag,suchastheparagraphtag.Thisexamplewillsetthefontcolorofanyparagraphmarked“myblueclass”toblue:
p.myblueclass{
color:blue;
}
Tospecifythataparagraphinyourhtmlfileisamemberofthisclass,
<pclass=“myblueclass”>ThisisasampleparagraphthatusesthemyblueclassCSSclass.</p>
Rememberthatyoucanapplyaclasstomultipleelementsinapage.Forexample,wecanspecifythatallHTMLelementswithclass=“center”arecenter-alignedandhavebluetext:
.center{
text-align:center;
color:blue;
}
Thenyoucanapplythistomultipleelements:
<h1class=“center”>Headerwiththecenterclass</h1>
<p>Anormalparagraphwithoutspecialformatting</p>
<pclass=“center”>Aformattedparagraph.</p>
<p>Anothernormalparagraph</p>
Thisproduces:
Headerwiththecenterclass
Anormalparagraphwithoutspecialformatting
Aformattedparagraph.
Anothernormalparagraph
Sowe’vesavedsomelabor.Weareabletoapplythesameattributes(centerandbluetext)todifferentHTMLelements.Soletsseehowtocreatethewebpageshownatthebeginningofthischapter.
Firstletsaddtheflowerintheupperleft.
<style>
body{
margin-left:200px;
background:#5d9ab2url(“flower.jpg”)no-repeattopleft;
}
Nowletscreateaclasswiththepropertyofcenteredtext.Theclasswillbecalledcontainer:
.container{
text-align:center;
}
Thenextclasswecreatewilldrawtheredbox:
.my_box{
border:2pxsolidred;
margin-left:auto;
margin-right:auto;
width:80%;
text-align:center;
padding:8px;
}
Finallywecloseoutour<style>sheetsettingh1headerstowhite.
h1{
color:white;
}
Nowlet’swritethehtmlforthepage:
<body>
<divclass=“container”>
<divclass=“my_box”>
<h1>MyGreatWebPage</h1>
<p>Sometexttodisplay.Thisisourmostextensiveexampleofcssyet.</p>
</div>
</div>
</body>
FixedAttachments
Inthislessonwe’lllearntofixanelementonthepage.Inotherwordswhenyouscrollthepage,theelementwillremaininplacewhiletherestofthepagescrollspast.Wewillusethewebpagefromthepreviouslessonandleavetheflowerinplace.
Itsactuallyprettysimple.WeonlyneedtochangetheCSSforthebodytag,specifyingthevalueofthebackground-attachmentattribute.
ChangeyourCSSto:
body{
margins-left:200px;
background:#5d9ab2url(“flower.jpg”)no-repeattopleft;
background-attachement:fixed;
}
That’sallthereistoit!Saveyourfileandloadinthebrowseragainandyou’llfindthattheflowerstaysintheupperleftcornerofthepage.Addalargeamountoftexttoyourpagetotestthescrolling.