learn css in one day and learn it well: css for beginners with hands-on project

113

Upload: others

Post on 11-Sep-2021

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project
Page 2: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

LearnCSSInOneDayandLearnItWellCSSforBeginnerswithHands-OnProject

TheonlybookyouneedtostartcodinginCSSimmediately

http://www.learncodingfast.com/css

Copyright©2015

Allrightsreserved.Nopartofthispublicationmaybereproduced,distributed,ortransmittedinanyformorbyanymeans,includingphotocopying,recording,orotherelectronicormechanicalmethods,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembodiedincriticalreviewsandcertainothernoncommercialusespermittedbycopyrightlaw.

Page 3: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Preface

ThisbookiswrittentohelpyoulearnCSSFASTandlearnitWELL.

Thebookdoesnotassumeanypriorbackgroundincoding.Ifyouareanabsolutebeginner,you'llfindthatthisbookexplainscomplexconceptsinaneasytounderstandmanner.IfyouareanexperiencedcoderbutnewtoCSS,thisbookwillprovideyouwithenoughdepthtostartcodinginCSSimmediately.

Allexamplesandimagesinthebookarecarefullychosentodemonstrateeachconceptsothatyoucangainadeeperunderstandofthelanguage.EachCSSchapteralsocomeswithanexerciseattheendofthechapter.Theexercisesaredesignedtohelpyoufurtherstrengthenyourunderstanding.Thesourcecodeforalltheexercisescanbefoundintheappendixattheendofthebook.

Inaddition,asRichardBransonputsit:"Thebestwayoflearningaboutanythingisbydoing".Thisbookcomeswithanadditionalbonusprojectwhereyou’llbeguidedthroughthecodingofawebpageentirelyfromscratch.Theprojectusesconceptscoveredinthebookandgivesyouachancetoseehowitalltiestogether.

Youcandownloadthebonusprojectandthesourcecodeforalltheexercisesathttp://www.learncodingfast.com/css.

ContactInformation

Iwouldlovetohearfromyou.Forfeedbackorqueries,[email protected].

MoreBooksbyJamie

Page 4: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Python:LearnPythoninOneDayandLearnItWell

Page 5: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

TableOfContentsChapter1:Introduction

ToolsoftheTradeOpeninga.HTMLFile

Chapter2:BasicsofHTMLWhatisHTMLBasicStructureofaHTMLPageDoctypeStartandEndTagsTheHeadElementTheBodyElementElementsWithintheHeadElementElementsWithintheBodyElementElementsforAddingContenttothePageElementsUsedinConjunctionwithCSSElementsForAddingJavascriptCodetoWebsiteElementsForFormattingTextElementsforDefiningSectionsofaWebpageCommentsCharacterEntities

Chapter3:BasicsofCSSApplyingCSSCodeSyntaxofaCSSruleSelectinganElementSelectingClassesandIDsMoreSelectorsCaseInsensitivityOrderofPrecedenceDisplayInconsistencyCommentsExercise3Exercise3.1

Chapter4:CSSBoxModelWhatistheCSSBoxModelWidthandHeightProperties

Page 6: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

OverflowPropertyPaddingandMarginPropertiesBorderPropertiesborder-widthborder-colorborder-styleborder-radiusBorderShorthandExercise4Exercise4.1

Chapter5:PositioningandFloatingPositioningStaticPositioningRelativePositioningFixedPositioningAbsolutePositioningFloatingExercise5Exercise5.1Exercise5.2

Chapter6:DisplayandVisibilityDisplayVisibilityExercise6Exercise6.1

Chapter7:BackgroundBackgroundColorBackgroundImagebackground-imagebackground-repeatbackground-attachmentbackgroundpositionExercise7Exercise7.1

Chapter8:TextandFont

Page 7: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

FontPropertiesfont-familyfont-sizefont-stylefont-weightTextPropertiescolortext-alignmenttext-decorationletter-spacingword-spacingline-heightExercise8Exercise8.1

Chapter9:Lists,LinksandNavigationBarsCSSListslist-style-typelist-style-imagelist-style-positionlist-styleCSSLinksNavigationBarsExercise9Exercise9.1Exercise9.2

Chapter10:TablesBorder,PaddingandMarginHeightandWidthTextAlignmentBackground,FontandTextnth-child()SelectorExercise10Exercise10.1

BonusProject

ThankYou

Page 8: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

AppendixA:SourceCodeforExercises

Page 9: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Chapter1:Introduction

WelcometotheworldofCSS.Iamsogladandhonouredthatyoupickedupthisbook.Beforeweembarkonthislearningjourneytogether,letusfirstdefinewhatisCSS.

CSSstandsforCascadingStylesheetandisusedforthestylinganddesignofawebsite.Itisoneofthemanylanguagesawebprogrammerusestocreateawebsite.OtherweblanguagesincludeHTML,JavascriptandPHP,justtonameafew.

HTMLisconcernedwiththecontentandstructureofawebsite.Asawebsite’sexistenceismeaninglesswithoutcontent,knowingHTMLisessentialforanyoneinterestedinwebprogramming.ThisbookwillfirststartwithanintroductiontoHTML,coveringsomeoftheessentialbasicsyouneedtoknowaboutHTML.Whilethiscoverageisbynomeanscomprehensive,itshouldbeenoughforyoutoperformmostoftheHTMLtasksnecessary.IfyouarefamiliarwithHTML,feelfreetoskiptoChapter3.

ToolsoftheTrade

BeforewestartcodingourHTMLandCSSpages,letusfirstlookatsomeoftherecommendedtoolsfordoingwebprogramming.

Atthemostbasiclevel,youonlyneedawebbrowser(e.g.InternetExplorer,Chrome,Safari,Firefox)andatexteditor(e.g.Notepad)tostartcodingwebsites.However,unlessyoubelongtotheschoolofthoughtthatrealprogrammersshouldn’tuseanyprogrammingaid,Istronglyencourageyoutousesomeofthefreetoolsavailableonlinetomakeyourcodinglifeeasier.

Oneofthemostrecommendedtoolisanadvancedtexteditorthatofferssyntaxhighlighting.Syntaxhighlightingmeanstheeditorwilldisplaytextindifferentcolorsdependingonthepurposeofthetext.Forinstance,theeditormayuseredcolorforkeywords,blueforcommentsandgreenforvariables.Thissimplefeaturewillmakeyourcodemucheasiertoreadanddebug.Ifyouareona

Page 10: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Windowsmachine,IsuggestNotepad++(http://notepad-plus-plus.org/).ForMac,IsuggestTextWrangler(http://www.barebones.com/products/textwrangler/).Botharefreetouse.

Openinga.HTMLFile

An.HTMLfilecanbeopenedintwoways.Onewayistoopenitinawebbrowserbydoubleclickingonthefile.Thisisforviewingthepage.Anotherwayistoopenitinatext-editorforediting.Todothat,firstlaunchyourtext-editorandthenopenthefilefromwithintheeditor.

WhenworkingwithHTMLfiles,Isuggestyouopenthefileinyourbrowserandtext-editorconcurrentlyandarrangethetwowindowssothattheyareside-by-side.Thatway,youcaneditthecodeonyoureditor,saveit,andthenmoveovertoyourbrowser,refreshthepageandimmediatelychecktheeffectsofthechangesyoumadetothecode.FollowthisprocedurewhenworkingontheexercisesfromChapters3to10.

Page 11: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Chapter2:BasicsofHTML

Nowthatwe’vecoveredabasicintroductiontowebprogramming,let’sstartlearningsomeactualHTMLcode.Inthischapter,we’llbecoveringtheessentialsofHTML.IfyouarefamiliarwithHTML,youcanskipthechapterandgoaheadtoChapter3.

ForthoseofyouwhoarenewtoHTML,let’sgetstarted.

WhatisHTML

HTMLstandsforHypertextMarkupLanguageandisalanguageusedbywebprogrammerstoaddcontenttoawebpage.Amarkuplanguageissimplyalanguageforannotatingadocumenttoexplainwhatdifferentsectionsofthetextareandhowtheyshouldbepresented.Forinstance,wecanuseHTMLtospecifywhetherthecontentshouldbepresentedasalistorintableform.ThecurrentHTMLversionisHTML5.

ThenicestthingaboutHTMListhatthesourcecodeofawebpageisfreeforalltoview.ThismakesiteasyforustolearnHTMLbystudyingthecodesofotherwebpages.ToviewthesourcecodeofawebpageonWindows,simplyright-clickanywhereonthepageandselect“ViewSource”(orsomethingsimilar,suchas“ViewPageSource”,dependingonthebrowseryouuse).IfyouareonMac,clickon“View”inthemenubar,select“Developer”andthenselect“ViewSource”.

Mostofthesourcecodethatyouviewwilllookverycomplicated,especiallyifyouhavenopriorknowledgeinHTML.Don’tworryaboutthat.Soon,you’llbeabletowritesuch‘complicated’codesyourself.

TogetabetterunderstandingofhowHTML5works,let’sstartbyexaminingthebasicstructureofaHTMLdocument.

BasicStructureofaHTMLPage

Page 12: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

AnexampleofabasicHTMLdocumentisshownbelow.I’veaddednumbersbesideeachlineofthecodeforeasyreference.Thesenumbersarenotpartoftheactualcode.

1<!doctypehtml>

2<html>

3<head>

4<title>MyFirstHTMLPage</title>

5</head>

6<body>

7<p>Thisisjusttext</p>

8<imgsrc=”someimage.jpg”alt=”Justsomeimage”>

9</body>

10</html>

Asyoucanseefromthecodeabove,HTMLusesalotofanglebracketswithasinglewordenclosedinside,suchas<head>and<body>.TheseareknownastagsandeachtaghasaspecificmeaninginHTML.

Doctype

Online1,the<!doctypehtml>tagtellsthebrowserthatthisdocumentusesHTML5.Ifyoucheckthesourceofolderwebpages,youmayseesomethinglike<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN""http://www.w3.org/TR/html4/strict.dtd">.ThismeanstheyareusingotherversionsofHTML,suchasHTML4.01inthiscase.

StartandEndTags

Online2,the<html>tagtellsthebrowserthattheactualHTMLcodestartshere.MosttagsinHTMLhaveacorrespondingendtag.Theendtagforthe<html>tagisfoundonline10.Ithasanadditionalforwardslash(/)beforethewordhtml.

NotethatnotalltagsinHTMLhaveendtags.Forinstance,the<img>tag,whichisusedtoaddimagestoourwebpagedoesnothaveanendtag.Generally,thereisaneedforanendtagwhenweneedtoletthebrowserknowwheretheeffectofthetagshouldend.Forinstance,ifwewanttoboldsometextinHTML,wecanwrite

Page 13: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Thistextis<strong>important</strong>,butthistextisnot.

We’llget

Thistextisimportant,butthistextisnot.

The<strong>tagandthe</strong>tagtellsthebrowserwheretheboldeffectshouldstartandwhereitshouldend.Incontrast,thereisnoneedtotellthebrowserwhereaninsertedimageshouldend.Hence,the<img>tagdoesnotrequireanendtag.

TheHeadElement

Online3,wehavethestartoftheheadelement.

Inthebroadestsense,aHTMLdocumentismadeupoftwomainelements,theheadandthebodyelements.

Theheadelementprovidesgeneralinformationaboutthedocument,includingitsmetadata,titleandlinkstoadditionalresources.Itstartswiththe<head>tagonline3andendswiththe</head>tagonline5.Withinthe<head>...</head>tags,weencloseothertagsthatprovideallthesebehind-the-sceneinformationaboutthedocument.

Inourexample,weonlyincludedinformationaboutthetitleinourheadelement.Thetitleelement(online4)showsthetitlethatthebrowsershoulddisplayonitstitlebaroronthepage'stab.Inthiscase,thetext“MyFirstHTMLPage”willbedisplayed.We’llcovermoretagsthatareusedwithintheheadelementinalatersection.

TheBodyElement

Line6iswherethebodyelementstarts.Contentswithinthe<body>...</body>tagswillbedisplayedonthewebpage.Inourexample,thetext“Thisisjusttext”andtheimage“someimage.jpg”willbedisplayed.

Therearealotofothertagsthatwecanuseinsidethe<body>...</body>tags,

Page 14: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

suchasthe<img>tagforaddingimages,the<table>tagfordisplayingtablesandthe<ul>tagforaddingalist.We’llcoverthesetagsindetaillater.

Togetafeelofhowthisworks,youcandownloadthecodeforthischapterfromtheaccompanyingwebsite(http://learncodingfast.com/css).ThesourcecodecanbefoundintheChapter2-BasicsofHTMLfolder.DoubleclickontheHTMLfiletolaunchit.

YouwillalsobeguidedthroughthecodingofanactualHTMLdocumentwhenworkingonthebonusprojectthatcomeswiththisbook.ThesourcecodefortheprojectcanbefoundintheBonusProject\Answersfolder.

ElementsWithintheHeadElement

NowthatweunderstandhowHTMLworks,letuslookattheheadelementindetail.Asmentionedabove,theheadelementprovidesgeneralinformationaboutthedocument,suchasitsmetadata,titleandlinkstoexternalresources.Let’slookatsomeofthetagswithintheheadelement.

<meta>

The<meta>tagisincludedwithinthe<head>…</head>tagsandisusedtoprovideadditionalinformationaboutthewebsitetothebrowser,searchenginesorotherwebservices.Theseinformationwillnotbedisplayedonthepageitself.The<meta>tagdoesnothaveanendtag.

Onecommonuseofthe<meta>tagistoprovidekeywordsforsearchengines.Anexampleis:

<metaname="keywords"content="HTML,CSS,LearninOneDay">

Youmaynoticethatthistagisalotlongerthanthetagswediscussedearlier.Thisisbecausethe<meta>taghastwoattributes,nameandcontent.

nameisusedtospecifythetypeofinformationthetagcontains(keywordsinthiscase),whilecontentisusedtospecifythecontentoftheinformation.

Page 15: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Youcanalsogiveadescriptionofyourwebsiteusingthename=descriptionattribute.Anexampleis:

<metaname="description"content=”ThisismyfirstWebsite.It

teachesyouhowtouseHTMLandCSS">

Anothercommonuseofthe<meta>tagistouseittospecifyhowthebrowsershouldcontrolthepagezoomlevelanddimensions.Thisisdoneusingthename=viewportattribute.Forinstance,youcanwrite

<metaname="viewport"content="width=300,initial-scale=1">

width=300setsthewidthoftheviewporttobeequalsto300pixels.Onepixel,px,isequaltoonedotonthecomputerscreen.

Whenyousettheviewportto300pxandyouhaveanimagethatis,say,500pixelswide,youwillonlyseeaportionoftheimageastheimage’swidthislargerthanthewidthoftheviewport.Toseetherestoftheimage,youhavetoscrollthepage.Incontrast,ifyousettheviewportto500px,theentireimagewillbeshownwithoutanyscrollingneeded.Ifyousettheviewportto1000px,theentireimagewillbeshowntoo,butit’llbesmallerandoccupyonlyhalfthewidthofthescreen.

initial-scale=1setstheinitialzoomlevel(1xinthiscase)ofthepagewhenitisfirstloadedbythebrowser.

Ifyouareinterestedinfindingoutmoreabouthowtheviewportworks,youcancheckouthttps://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/UsingtheViewport/UsingtheViewport.html

<title>...</title>The<title>tagisusedfordefiningthetitlethatthebrowsershoulddisplayonitstitlebaroronthepage'stab.

<style>...</style>

The<style>tagisusedtoaddinternalCSScodetoourHTMLdocument.We’ll

Page 16: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

learnhowtodothatinChapter3.

Example:<styletype=”text/css”>

body{

}

</style>

<link>

The<link>tagisusedtolinktoanexternalresource,mostcommonlyusedtolinktoanexternalCSSstylesheet.Itdoesnotrequireanendtag.

Example:<linkrel="stylesheet"type="text/css"href="mystyle.css">

TherelandtypeattributessimplytellthebrowserthatyouarelinkingtoaCSSstylesheet.Youdonotneedtomodifythem.Theonlyattributethatyouneedtomodifyisthehrefattribute.ThisattributeisusedtostatethepathoftheCSSfile.

HowtoWritePathstoExternalFiles

ThepathofanyexternalfilealwaysstartsfromthecurrentfolderoftheHTMLdocument.Supposewehavefivefolders:‘User’,‘Documents’,‘MyWebsite’,‘MyCSS’and‘MoreCSS’withthefollowingstructure:

User>Documents>MyWebsite>MyCSS>MoreCSS

Thatis,the‘User’foldercontainsthe‘Documents’folder,whichinturncontainsthe‘MyWebsite’folder.Withinthe‘MyWesbite’folder,wehavethe‘MyCSS’folder,whichcontainsthe‘MoreCSS’folder.

IfyouareworkingonaHTMLfilein‘MyWebsite’andyouwanttolinkto‘mystyle.css’intheSAMEfolder,yousimplywritehref=“mystyle.css”.

However,if‘mystyle.css’isinthe‘MyCSS’folder(oneleveldown),youhavetowritehref=“MyCSS/mystyle.css”.Ifitisin‘MoreCSS’(twolevelsdown),

Page 17: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

youhavetowritehref=“MyCSS/MoreCSS/mystyle.css”

If‘mystyle.css’isinthe‘Documents’folder(onelevelup),youhavetouse../tomoveonelevelup.Youwritehref=“../mystyle.css”.Ifitisinthe‘User’folder,youhavetomovetwolevelsup.Youwritehref=“../../mystyle.css”.

ElementsWithintheBodyElement

Nowthatwe’vecoveredtheelementswithintheheadelement,letusmoveontothebodyelement.

ElementsforAddingContenttothePage

First,letusdiscusssomecommonlyusedelementsforaddingcontenttoourwebpage.Thesetagsareenclosedwithinthe<body>...</body>tags.

<p>...</p>

Thisistheparagraphtagandisusedtoaddtexttoapage.Anycontentwithinthetwotagswillbedisplayedasaparagraph.Bydefault,mostbrowserswilladdalinebeforeandafteraparagraph.

Example:<p>Thisisaparagraph</p>

<img>

This<img>tagisforaddingimagestoyourwebpage.Itrequiresyoutoprovidesomeadditionalinformationlikethelocationoftheimage,itsheightandwidthetc.Commonlyusedattributesofthe<img>taginclude:src:Standsfor“source”andisusedtostatethepathoftheimage.Thesrcattributemustbeprovided.

height:Forspecifyingthedesireddisplayheightoftheimage

Page 18: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

width:Forspecifyingthedesireddisplaywidthoftheimage

alt:Standsfor“alternate”andisusedtospecifythetexttodisplayiftheimagefailstoload.

Example:<imgsrc=”images/myImage.jpg”height=”100px”width=”100px”alt=”My

Image”>

Thiswillinserttheimage“myImage.jpg”ontothewebpage.Theimagewillbescaledtoasizeof100pxby100px.Iftheimagefailstoload,thetext“MyImage”willbedisplayedinstead.

<a>...</a>

The<a>tagisusedtoinsertahyperlink.Themostimportantattributeforthe<a>tagishrefwhichisusedtospecifytheURLofthepagethelinkgoesto.

Example:<ahref=”http://www.google.com”>ClickheretogotoGoogle</a>

Output:ClickheretogotoGoogle

ClickingonthelinkwillbringyoutotheGooglewebsite.

<h1>...</h1>to<h6>...</h6>

The<h1>to<h6>tagsareheadingtagsandareusedtodefineHTMLheadings.<h1>isthemostimportantheadingand<h6>istheleastimportant.Textwithinheadingtagsarenormallydisplayedwithalargerfontsizeonthebrowser,withh1havingthelargestfontsizeandh6havingthesmallest.

Example:<h1>Thisisthemostimportantheading.</h1>

<h2>Thisisthesecondmostimportantheading.</h2>

Output:

Page 19: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Thisisthemostimportantheading.Thisisthesecondmostimportantheading.

<ol>...</ol>and<li>...</li>

The<ol>tagstandsfororderedlistandisusedtocreatealistwithnumbersoralphabetsaslistmarkers.

Example:<ol>

<li>Chocolate</li>

<li>Strawberry</li>

<li>Vanilla</li>

</ol>

Output:

1.Chocolate2.Strawberry3.Vanilla

<ul>...</ul>and<li>...</li>

The<ul>tagstandsforunorderedlistandissimilartothe<ol>tag.However,insteadofusingnumbersoralphabetsaslistmarkers,itusesshapes(suchasadot,orahollowcircle).

<table>...</table>,<tr>...</tr>,<th>...<th>,<td>...</td>

The<table>tagisusedtocreateatable.<tr>standsfor“TableRow”,<th>standsfor“TableHeader”and<td>standsfor“TableData”.TablesarecreatedrowbyrowinHTML.

Example(numbersarenotpartofthecode):

1<table>

2<tr>

3<th>Name</th>

4<th>Gender</th>

5</tr>

Page 20: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

6<tr>

7<td>Abigail</td>

8<td>F</td>

9</tr>

10<tr>

11<td>Benny</td>

12<td>M</td>

13</tr>

14</table>

Thiscodewillgiveyouatablewith3rowsand2columns.Line2to5definesthefirstrowofthetable,whichisaheaderrowasthe<th>tagisused.Line6to9definesthesecondrowandlines10to13definesthethird.DependingonhowyoustylethetableinCSS,you’llgetatablesimilartotheonebelow:

ElementsUsedinConjunctionwithCSS

TherearetwospecialHTMLelementsthatdonothaveanyinherentmeaninginHTML.TheyaremainlyusedinconjunctionwithCSStostyleaspecificsectionofthewebpage.Thesetwoelementsaredivandspan.

<div>...</div>

<div>standsfor‘division’andisusedtodefineadivisionorasectioninaHTMLdocument.The<div>tagisnormallyusedinconjunctionwithCSStoformatthecontentswithinthe<div>...</div>tags.

Forinstance,ifwewrite

<div>

ThisissomedivisionintheHTMLdocument.

<ol>

<li>Chocolate</li>

<li>Strawberry</li>

<li>Vanilla</li>

</ol>

Page 21: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

</div>

wecanuseCSStoformateverythinginsidethedivtags(i.e.boththetextandtheorderedlist).We’lllearnhowtodothatinthenextchapter.

<span>...</span>

The<span>tagissimilartothe<div>tag.Themaindifferenceisthat<div>isablockelement,while<span>isaninlineelement.

Ablockelementisonethatstartsandendswithanewlinebreak.Incontrast,aninlineelementdoesnotstartorendwithalinebreak.Forinstance,ifwewrite

Thisisa<div>blockelement</div>,whilethisisan

<span>inline</span>element.

we’llget

Thisisa

blockelement

,whilethisisaninlineelement.

Asthephrase‘blockelement’istaggedwiththe<div>tag,itstartsandendsonanewline.Ontheotherhand,theword‘inline’isaninlineelementanddoesnotstartorendonanewline.Generally,wetendtouse<div>towrapsectionsofadocument,while<span>isusedtowrapsmallportionsoftext,images,etc

ElementsForAddingJavascriptCodetoWebsite

<script>...</script>

The<script>tagisusedtoaddinternalJavascriptcodetoourHTMLdocumentortolinktoanexternalscript.Javascriptisascriptinglanguagethataddsinteractivitytoourwebsite..

Example(toaddinternalJScode):<script>

document.getElementById("para1").innerHTML="Hello

JavaScript!";

</script>

Page 22: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Example(tolinktoanexternalJSscript):<scripttype=”text/javascript”src="myscripts.js"></script>

ElementsForFormattingText

<strong>...</strong>

The<strong>tagisusedtodefineimportanttext.Mostbrowserswillboldthetext.

Example:Theexaminationwillbeheldon<strong>12Janat2pm</strong>.

Latecomerswillnotbeallowedintothehall.

Output:Theexaminationwillbeheldon12Janat2pm.Latecomerswillnotbeallowedintothehall.

<em>...</em>

The<em>tagisusedtodefineemphasizedtext.Mostbrowserswilldisplaythetextinitalicsform.

Example:Theexaminationwillbeheldon12Janat2pm.Latecomers<em>will

not</em>beallowedintothehall.

Output:Theexaminationwillbeheldon12Janat2pm.Latecomerswillnotbeallowedintothehall.

ElementsforDefiningSectionsofaWebpage

HTMLalsocomeswithafewtagsfordefiningsectionsofawebpage.Thesetagsdonotdomuch,theirpurposeissimplytoindicatetothebrowseranddeveloperwhichsectionthecontenttheyenclosebelongsto.

<header>...</header>

Page 23: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Theheaderelementdefinesthetopsectionofawebpageandnormallyconsistsofthelogo/bannerofthewebsite.Donotconfusetheheaderelementwiththeheadelement.Theheadelementdefinesallthebehindthescenestuffandisnotdisplayedonthepage.Theheaderelementontheotherhanddefinescontentthatistobedisplayedatthetopofthewebsite.

<nav>...</nav>

navstandsfornavigationandisusedtodefineasetofnavigationlinks(i.e.menu).

<main>...</main>

Themainelementisusedtodefinethemainsectionofapage.

<footer>...</footer>

Thefooterelementisthecounterpartoftheheaderelementandisusedtodefinethefooterofthewebpage(i.e.thebottomsection).Theheaderandfooterelementsaresimilartothe‘header’and‘footer’sectionsofaMSWorddocument.ForWorddocuments,wenormallyusethefootertodisplaythepagenumber.Onawebsite,wenormallyuseittoincludeadditionallinksandadditionalinformation(suchascontactinformationandcopyrightinformation).

Notethatallthefourelementsabovearetobeincludedinthe<body>...</body>.Theirpurposeismainlytofurthersegmentthe<body>elementintodifferentsections.Thecodebelowshowshowtheseelementsareused.

<!doctypehtml>

<html>

<head><title>Anexample</titlte></head>

<body>

<header>

<!--InsertBannerorLogoHere-->

</header>

<nav>

<!--InsertNavigationLinksHere-->

</nav>

<main>

<!--InsertMainContentHere-->

</main>

<footer>

Page 24: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

<!--InsertFooterHere-->

</footer>

</body>

</html>

Comments

Noticethatinthepreviousexample,weusedalotofthe<!--and-->symbols?Theseareknownascomments.

Mostofthetimewhenweprogram,weneedtoaddcommentstoourcodetomakeiteasiertoreadandunderstand.Thisisextremelyimportantifweareworkingwithotherprogrammersorifweneedtoeditthesourcecodeatalaterdate.Commentsarenotdisplayedinthebrowser,theyaremerelyaddedtoexplainourcode.

ToaddcommentstoaHTMLdocuments,weusethe<!--...-->tag.

Example:<!--Thisisacomment.Itwillnotbedisplayedinthebrowser.-->

CharacterEntities

SomecharactershavepredefinedmeaningsinHTMLandarereservedforthatspecificuse.Forinstance,thelessthansign(<)isusedtostartalltags.Whathappensifweneedtodisplaythetext5<12onourwebpage?

Todothat,weneedtousecharacterentities.Characterentitiesalwaysstartwithanampersandsign(&)andendwithasemi-colon(;).Therearetwowaystodisplaythelessthansign.Wecaneitherwrite&lt;or&#60;.Thefirstisknownastheentitynamewhilethelatterisknownastheentitynumber.Anentitynameiseasiertoremember(ltstandsforlessthan)butsomebrowsersdonotsupportallentitynames.Ontheotherhand,entitynumbersarehardertorememberbutthesupportisbetter.

Commonlyusedcharacterentitiesinclude

Page 25: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Lessthansign(<)&lt;or&#60;

Greaterthansign(>)&gt;or&#62;

Ampersandsign(&)&amp;or&#38;

Forinstance,ifyouwanttodisplay5<12onyourwebsite,youwriteitas5&lt;12inyourHTMLcode.

Anothercommonlyusedcharacterentityisnon-breakingspace(&nbsp;).Anonbreakingspaceentityisusedtodisplayconsecutivespaces.Bydefault,HTMLdoesnotrecogniseconsecutivespaces.Ifyouwrite5spacesinyourHTMLcode,thebrowserwillremove4ofthemanddisplayonlyonespace.Forinstance,ifyouwrite

“Thereare5spaceshere”

thebrowserwilldisplayitas

“Thereare5spaceshere”.

Ifyouwanttodisplaymorethanonespace,youneedtowrite

“Thereare5spaces&nbsp;&nbsp;&nbsp;&nbsp;here”.

Page 26: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Chapter3:BasicsofCSS

Nowthatwe’vecoveredquiteabitofHTML,let’smoveontoCSS.CSSstandsforCascadingStylesheetandasthenamesuggests,CSSisallaboutstylingandmakingyourwebsitelookgorgeous.

ThelatestversionofCSSisCSS3.UnlikepreviousversionsofCSS(namelyCSS1andCSS2.1),CSS3splitsthelanguageintodifferentmodulessothateachmodulecanbedevelopedseparatelyatadifferentpace.EachmoduleaddsnewfeaturesorextendsthecapabilitiesoffeaturespreviouslydefinedinCSS2.1.Essentially,CSS3issimplyanextensionofCSS2.1.

ThisbookcoversthecorepropertiesofCSS2.1aswellasafewnewpropertiesthatareintroducedinCSS3.Onceyoumasterthecoreproperties,youwillhavenoproblemsmovingontomoreadvancedpropertiesthatarenewlyaddedinCSS3.Theseadvancedpropertiesallowformorefancifulstylingofyourwebsite,suchasaddingtransitionsandanimations.

Inthischapter,we’llbecoveringthebasicsofCSS,includingitssyntaxandorderofprecedence.However,beforegoingintothesyntaxofCSS,let’sfirstlearnhowtoaddCSSrulestoourwebsite.

ApplyingCSSCode

TherearethreewaystoapplyCSScodetooursite.

Thefirstisbylinkingtoanexternalfile.Thisistherecommendedmethod.Todolinking,youneedtowriteyourCSSrulesinaseparatetextfileandsaveitwitha.cssextension.ThesyntaxforaddingtherulestoyourHTMLcodeis

<linkrel="stylesheet"type="text/css"href="style.css">

Youaddthe<link>tagtotheheadelement,betweenthe<head>...</head>tags.ThefirsttwoattributesrelandtypetellthebrowserthatthisisaCSSstylesheet.Youdonotneedtomodifythem.ThelastattributehrefiswhereyouspecifythepathtotheCSSfilethatyouwanttolinkto.ACSSfileissimplya

Page 27: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

filethatcontainsCSSrules,withoutanyHTMLtags.Anexampleisshownbelow.Don’tworryifthecodedoesnotmakesensetoyou,we’llcoverthemverysoon.

body{

margin:0;

background-color:green;

}

Savethiscodeas“style.css”inthesamefolderasthe.htmlfile.Youcanthenusethe<link>tagabovetolinkthisCSSfiletoyourHTMLfile.

ThesecondmethodtoaddCSSrulestooursiteistoembedthecodedirectlyintoourHTMLsourcecode,withintheheadelement.Thisisdonewiththe<style>tag.Anexampleisshownbelow.TheembeddedCSScodestartsafterthe<style>starttagandendsbeforethe</style>endtag.

<head>

<style>

div{

color:blue;

width:100px;

height:200px;

}

</style>

</head>

ThelastmethodistouseinlineCSS.InlineCSSisspecifiedinthestarttagoftheelementyouwanttoapplyitto,usingthestyleattribute.Eachruleendswithasemi-colon(;).Anexampleis:

<divstyle="text-decoration:underline;color:blue;">Sometext</div>

Outofthethreemethods,linkingisthepreferredmethod.LinkingseparatestheHTMLcontentfromthestylingrulesandmakesiteasiertomaintainourcodes.ItisalsoextremelyusefulwhenweneedtoapplythesameCSSrulestomultiplewebpages.

EmbeddedCSS,ontheotherhand,iscommonlyusedwhentherulesonlyapplytoonewebpage.

InlineCSSishandywhenyouneedtoapplyaruletoonlyoneelement,orwhen

Page 28: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

youwanttooverrideotherCSSrulesthatapplytothesameelement.ThisisbecauseinlineCSShasahigherprecedencethanCSScodeaddedusingtheothertwomethods.We’lldiscussorderofprecedencelaterinthischapter.However,inlineCSSmixesstylingwithcontentandshouldbeavoidedwheneverpossible.

SyntaxofaCSSrule

NowthatweknowhowtoapplyCSSrulestoourHTMLfiles,let’smoveontolearnsomeactualCSScode.ThefirstthingtolearnaboutCSSisitssyntax,whichisrelativelystraightforward.Thesyntaxis:

selector{property:value;property:value;property:value;}

Forinstance,ifyouwanttostylethecontentsinsidea<div>tag,youwritetheruleas

div{

background-color:green;

font-size:12px;

}

Thefirstworddivistheselector.Ittellsthebrowserthatthesetofrulesinsidethecurlybrackets{}appliestoallelementswiththe<div>tag.

Insidethecurlybrackets,youwriteallyourdeclarations.Youstartbydeclaringthepropertythatyouwanttoset(background-colorinthefirstdeclaration),followedbyacolon(:).Next,yougivethevaluethatyouwant(greeninthiscase).Finally,youendeachdeclarationwithasemi-colon(;).

IndentationandlinebreaksdonotmatterinCSS.Youcanalsowriteyourdeclarationslikethis:

div{background-color:green;font-size:12px;}

Prettystraightforwardright?Great!Let’smoveon...

SelectinganElement

Page 29: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Intheexampleabove,therulesdeclaredinthecurlybracketswillapplytoALLelementswitha<div>tag.However,mostofthetime,wewantgreatervariation.Supposeyouwantone<div>elementtohaveafontsizeof12pxandanothertohaveafontsizeof14px.Howwouldyoudoit?

SelectingClassesandIDs

Therearebasicallytwowaystodoit.Thefirstmethodistousetheidattribute.InyourHTMLdocument,insteadofjustusingthe<div>tag,youcanaddanidattributetoit.Forinstance,youcanwrite

<divid=”para1”>

Sometext.

</div>

<divid=”para2”>

Moretext.

</div>

InourCSScode,wecanthenselecttherespectiveidbyaddinga#signinfrontoftheidname.Anexampleisshownbelow:

div{

background-color:green;

}

#para1

{

font-size:12px;

}

#para2

{

font-size:14px;

}

Thefirstruleappliestoallelementswiththe<div>tag.Thesecondruleonlyappliestotheelementwithid=”para1”.Thethirdruleonlyappliestotheelementwithid=”para2”.

Inadditiontousingtheselector#para1,youcanalsobemorespecificandwritediv#para1,withnospacebeforeandafterthe#sign.Bothmethodswillselectthesameelement,butthesecondmethodhasahigherprecedence(moreonthis

Page 30: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

later).

Notethatanidshouldbeuniquewithinapage.Two<divid=”para1”>tagsisnotallowed.One<divid=”para1”>andone<pid=”para1”>tagisalsonotallowedasbothhavethesameid.AlthoughyourHTMLandCSScodewillworkevenifyouhavetwoelementswiththesameid,problemswillarisewhenyoustartusingJavascriptorotherscriptinglanguagesonyourwebsite.

IfyouneedtoapplythesameCSSrulestotwodifferentelements,youcanuseaclass.Aclassissimilartoanid,withtheexceptionthataclassneednotbeunique.Inaddition,anidhasahigherprecedencethanaclass.

Fornow,let’sconsiderthefollowingcode:

<divclass=”myclass1”>

Sometext.

</div>

<pclass=”myclass1”>

Moretext.

</p>

<div>

Yetmoretext.

</div>

Ifyouwanttoselectall<div>elements(i.e.thefirstandthirdelement),youwrite

div{…}

Ifyouwanttoselectallelementswithclass=”myclass1”(i.e.thefirstandsecondelement),youaddadot(.)infrontoftheclassname,likethis:

.myclass1{…}

Ifyouonlywanttoselect<p>tagswithclass=”myclass1”(i.e.thesecondelement),youwrite

p.myclass{…}

Thereshouldbenospacebeforeandafterthedot.

Page 31: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Anelementcanhavemorethanoneclasses.MultipleclassesareseparatedwithaspaceintheHTMLattribute.Forinstance,thedivbelowhastwoclasses:myclass1andmyclass2.

<divclass=”myclass1myclass2”>

</div>

IfwehavethefollowingCSScode,

.myclass1{…}

.myclass2{…}

therulesforbothmyclass1andmyclass2willapplytotheabove<div>.

MoreSelectors

Inadditiontoselectinganelementbyidandclass,CSSoffersalargevarietyofwaystospecifytheelementsthatwewanttoselect.

SelectingMultipleElements

Forinstance,wecanselectmultipleelementsatonego.Ifwewanttoselectthe<div>,<p>and<ul>elements,wewrite:

div,p,ul{…}

SelectingChildElements

Ifwewanttoselectallthe<p>elementsinside<div>elements,wewrite

divp{…}

Notethatthereisnocommabetweendivandp.Inthiscase,theCSSruleswillonlyapplyto<p>elementsthatareinside<div>elements.Forinstance,ifwehavetheHTMLstructurebelow,theruleswillapplyto‘Iamaparagraphinsidediv’andnotto‘Iamastand-aloneparagraph’.

Page 32: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

<div>

<p>Iamaparagraphinsidediv</p>

</div>

<p>Iamastand-aloneparagraph</p>

Thefirstparagraph‘Iamaparagraphinsidediv’iscalledachildelementofthe<div>tagasitsstartandendtags(<p>and</p>)lieentirelywithinthe<div>...</div>tags.

SelectingbyAttribute

Youcanalsoselectanelementbasedonitsattribute.Ifyouwanttoselectallhyperlinksthatlinktohttp://www.learncodingfast.com,youwrite

a[href=”http://www.learncodingfast.com”]{…}

Thereshouldbenospacebeforethesquarebracket.IfyouhavethefollowingHTMLcode,onlythefirstlinkwillbeselected.

<ahref=”http://www.learncodingfast.com”>LearnCodingFast</a>

<ahref=”http://www.google.com”>Google</a>

SelectingPseudo-classes

Anothercommonlyusedselectoristhepseudo-classselector.Apseudo-classreferstoaspecialstateofanelement.Themostcommonpseudo-classesarethoseforthe<a>...</a>element.Ahyperlinkcanbeinoneoffourstates:

link(anunvisitedlink)visited(avisitedlink)hover(whentheusermousesoverit),oractive(whenthelinkisclicked).

Wecanselectahyperlinkbasedonthestateitisin.Forinstance,toselectthehoverstate,wewrite

a:hover{…}

Thekeywordhoverisaddedtothebackoftheaselectorusingacolon(:),withnospacesbeforeandafterthecolon.We’llcomebacktotheconceptofselecting

Page 33: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

andstylingdifferentstatesofahyperlinkinChapter9.

Inadditiontoselectingdifferentstatesofahyperlink,wecanalsousepseudo-classesistoselectchildelements.Supposewehavea<div>elementwiththree<p>childelements:

<div>

<p>Iamthefirstchild</p>

<p>Iamthesecondchild</p>

<p>Iamthethirdchild</p>

</div>

Wecanusethefirst-childpseudo-classtoselectthefirst<p>element.Wecanalsousethelast-childselectortoselectthelastchildorthenth-child(n)selectortoselectthenthchild.

Forinstance,ifwewrite

p:nth-child(2){…}

we’llbeselectingtheparagraph‘Iamthesecondchild’becauseofthenumber‘2’intheparenthesis().

SelectingPseudo-elements

Inadditiontopseudo-classes,CSSalsohastheconceptofpseudo-elements.Apseudo-elementreferstoaspecifiedpartofanelement,suchasthefirstletterorthefirstlineofanelement.

Forinstance,ifwehavethefollowing<p>element:

<p>Thisissometext.</p>

Wecanselectthefirstletter(T)bywriting

p::first-letter{…}

Notethatadoublecolonisusedinthiscase.Anotherpseudo-elementisthefirst-lineelement.Thiswillselectthefirstlineofthetext.

Page 34: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Finally,wecanusethebeforeandafterpseudo-elementstoinsertcontentbefore,orafter,thecontentofanelement.Forinstance,ifwewanttoaddanexclamationmarkafterallH1elements,wecanwrite

h1::after{

content:“!”;

}

ThiswillautomaticallyappendanexclamationmarkafterallH1elements.IfwehavethefollowingHTMLcode

<h1>Thisisaheading</h1>

we’llget

Thisisaheading!

CaseInsensitivity

Forthemostpart,CSSselectorsandrulesarecase-insensitive.Hence,youcaneitherwrite

div{

Background-color:GREEN;

}

or

DIV{

background-coloR:green;

}

Bothwillworkequallywell.Theonlyexceptiontothiscase-insensitivityiswhenselectingclassesandids.

Ifwehave

<divid=“myID”>Sometext</div>

div#myIDwillselecttheaboveelementwhilediv#MYIDwillnot.

Page 35: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

OrderofPrecedence

Nowthatwe’velearnthowtoselectelements,letusmoveontoaveryimportantconceptinCSS:orderofprecedence.

Asmentionedearlier,wecanapplyCSScodetoourwebsiteinthreedifferentways.ItiscommonforaprogrammertousemorethanonewaytoapplyCSScodetoasite.Forinstance,awebsitemayhaveCSSrulesdefinedinanexternalfileANDsomeadditionalCSSrulesembeddedwithinits<style>...</style>tags.Thismayresultinmorethanonerulebeingappliedtothesameelement.OneofthemostfrustratingexperienceaboutworkingwithCSS,especiallywhenyouarefirststartingout,iswhenyoutrytoapplyacssstyletoanelementandthepagesimplyseemstoignoreyourrule.Mostofthetime,thisisduetotheorderofprecedence.Specifically,thishappenswhenmorethanoneruleappliestothesameelement,andanotherrulehasahigherprecedencethantheoneyouarespecifying.

ThreeprinciplescontrolwhichCSSrulehasahigherprecedence.

Principle1:Themorespecifictheselector,thehighertheprecedence

Wewon’tgointodetailsabouthowtocalculatethespecificityofaselector.Themainpointtorememberisthatanidisconsideredtobemorespecificthanaclass,andaclassmorespecificthananelement.Let’sconsiderthecodebelow:

div{font-size:10px;}

#myId{font-size:12px;}

.myClass{font-size:14px;}

<divid=”myId”class=”myClass”>Sometext</div>

Sincethe<div>elementhasclass=”myClass”andid=”myId”,allthreerulesdiv,#myIdand.myClasswillapplytothe<div>element.However,asidhasthehighestprecedence,“Sometext”willbedisplayedwithafontsizeof12px.

Inaddition,anotherpointtonoteaboutspecificityisthatthemoredetailedyourselector,thehighertheprecedence.Forinstance,div#myIdhasahigher

Page 36: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

precedencethan#myId.Thisisbecausediv#myIdisconsideredtobemoredetailedasittellsusthatmyIdisanidofthedivelement.Inthesamplecodebelow,thecoloryellowwillbeapplied.

div{color:red;}

div#myId{color:yellow;}

#myId{color:blue;}

.myClass{color:green;}

<divid=”myId”class=”myClass”>Sometext</div>

Principle2:Ifnostyleisspecified,elementsinheritstylesfromtheirparentcontainer

Achildelementisanelementwhichliesentirelywithinthestartandendtagsofanotherelement.Forinstance,inthecodebelow,<p>isachildelementofthe<body>element.Sincethefontsizeof<p>isnotdefined,it’llinheritthispropertyfromthe<body>elementforwhichthepropertyisdefined.

body{

font-size:1.5em;

}

<body>

<p>Sometext</p>

</body>

Ifthefont-sizepropertyisalsonotdefinedforthe<body>element,thebrowser’sdefaultfontsizewillbeused.

Principle3:Allelsebeingequal,thelastdeclaredrulewins

SupposeyouhavethefollowingCSSdeclarationinyourHTML<head>element.

<head>

<style>

p{font-size:20px;}

</style>

</head>

FurtherdowntheHTMLdocument,youhavethefollowingHTMLcode,withaninlineCSSrule:

Page 37: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

<pstyle=”font-size:30px;”>Sometext</p>

Whichruledoyouthinkwillbeappliedtothewords“Sometext”?

Thecorrectansweristheinlinerule.Thisisbecauseallthingsbeingequal,therulethatisdeclaredlasthasthehighestprecedence.SinceinlineCSSisdeclaredwithintheHTMLcode,itisdeclaredlaterthantheembeddedCSSwhichisdeclaredintheheadsection.Hence,afontsizeof30pxwillbeapplied.

DisplayInconsistency

AnotherissuetodealwithwhenworkingwithCSSistheproblemofdisplayinconsistencyacrossbrowsers.Youmayfindthatyourwebsitelooksslightly(ordrastically)differentindifferentbrowsers.MostdisplayissuestendtooccurinolderversionsofInternetExplorer,althoughissuescanoccurinotherbrowserstoo(especiallymobilebrowsers).

Displayinconsistenciesoccurbecausedifferentbrowsersusedifferentlayoutenginestointerpretthesite’sCSScode.Forinstance,SafariandChromeusetheWebKitenginewhileFirefoxusestheGeckoengine.Oneenginemaycalculateanddisplayapagedifferentlyfromanotherengine.ForinstanceTrident,theengineusedbyInternetExplorer,automaticallywidensapage’spixelwidthforcertainpagedesigns.Thiscanleadtothesidebarbeingpushedtothebottomduetoinsufficientwidth.

AnotherproblemcausingdisplayinconsistencyisthelackofuniversalsupportforsomeCSSproperties.Somepropertiesarenotsupportedbyallbrowsers.Youcangotothesitehttp://www.caniuse.comtocheckifacertainCSSpropertyissupportedbythebrowserthatyouaredevelopingfor.

Sometimes,acertainCSSpropertyissupportedbyaparticularbrowseronlywhenweaddaprefixtoourCSSrules.ThisisespeciallytruefornewerpropertiesinCSS3.Anexampleisthecolumn-countpropertyinCSS3.Thispropertydividesanelementintomultiplecolumns.Forinstance,wecandivideadivelementintothreecolumnsbywritingcolumn-count:3.

ThispropertyisnotsupportedbyolderversionsofFirefox,Chrome,Safariand

Page 38: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Opera.Toenablethepropertytoworkonthesebrowsers,youhavetowriteitasthreedeclarations,

-webkit-column-count:3;

-moz-column-count:3;

column-count:3;

insteadofjust

column-count:3;

The-webkit-prefixaddssupportforolderversionsofChrome,SafariandOperawhilethe-moz-prefixaddssupportforFirefox.Inaddition,wealsohavethe-ms-prefixthataddssupportforInternetExplorer.

Whencreatingyourwebsite,itisusefultotestitonvariousbrowserstoensurethatnothingisbroken.Thewaytofixa‘broken’displaydependsontheissuecausingit.Ifyouarereallystuck,Isuggestsearchingorpostingthequestiononhttp://stackoverflow.com,whichisaveryusefulonlinecommunityforprogrammers.

Comments

Thelastthingtocoverinthischapteriscomments.InCSS,weaddcommentstoourcodeusingthe/*...*/symbols.Anexampleisasfollows:

/*

Therulesbelowarecomments.

p{

background-color:black;

font-size:20px;

color:white;

}

*/

Everythingbetweenthe/*and*/symbolsisignoredbythebrowser.

Exercise3

Page 39: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Downloadthesourcecodeforthisexercisefromhttp://learncodingfast.com/cssandunzipthefile.ThesourcecodeforthisexercisecanbefoundintheChapter3-BasicsofCSSfolder.

Exercise3.1

1.OpenthefileChapter3-BasicsofCSS.htmlconcurrentlyinyourbrowserandtexteditor.

2.First,lookforthefollowinglinesinthesourcecodeinyourtexteditor:

p{

background-color:yellow;

}

Thisselectsallthe<p>elementsandsetstheirbackgroundcolorstoyellow.Theline'Thisissometextinthedivelement.'isnotselectedbecauseitisnotwithinany<p>...</p>tags.

3.Nowlet’strychangingtherulefrom

p{

background-color:yellow;

}

to

P{

Background-coloR:YELLOW;

}

Savethefileinyourtexteditorandrefreshyourbrowser.Noticethatnothingchanges?ThisisbecauseCSSisnotcase-sensitiveinmostcases.

4.Now,letustrytoselectdifferentHTMLelementsandobservewhichelementsendupwithayellowbackground.Foreachitembelow,simplychangetheselectoronline6intheHTMLfiletotherequiredselector.

First,let’sselecttheelementwithclass="myClassPara".Todothat,changethepselectorintheCSSruleto.myClassPara.Savethefileinthe

Page 40: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

editorandrefreshthepageinthebrowser.Noticewhichparagraphisselectednow.

5.Nowchangetheselectorto.myclasspara.Noticethatnothingisselectednow?ThatisbecauseCSSiscase-sensitivewhenselectingclassesandids.

6.Next,let'sselecttheelementwithid="myIDPara".Trydoingityourself.

Gotit?Youcanchange.myClassParatoeitherp#myIDParaorjust#myIDPara.Noticewhichparagraphisselected.

Trychanging#myIDParato#MYIDPARA.Noticethatnothingisselected?

7.Next,let’slearnhowtoselectmorethanoneelements.Tryselectingboththeh1andh2elements.

Thewaytodoitissimplytochangetheselectortoh1,h2.8.Nexttryselectingthedivelement.

Todoit,simplychangetheselectortodiv.

9.Now,let'sselectthepelementinsidethedivelement.Todothis,wewritedivpastheselector.Noticewhichelementsareselected.

10.Next,tryselectingallthelink(<a>)elements.

Whatdoyounotice?Thelinksarenowhighlightedinyellowright?

11.Next,we’llnarrowdownourselectionbasedonHTMLattributes.Tryselectingthelinkwithhref="http://www.learncodingfast.com".Thecorrectwaytodothisiswithsquarebracketsasfollows:

a[href=”http://www.learncodingfast.com”]

Tryit.Onlythefirstlinkwillhaveayellowbackgroundnow.

Page 41: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

12.Next,we’llusethepseudo-classselectortochangethebackgroundcolorofalllinkelementswhenwehoveroverthem.Trychanging

a[href=”http://www.learncodingfast.com”]

toa:hover

Savethefileandrefreshthebrowser.Noticethatnothingisselected?Nowhoveryourmouseoveranyofthehyperlinksandobservewhathappens.

13.Next,let’strytoselectthesecondchildelementofthedivelement.Youdothatbychangingtheselectorto

p:nth-child(2)

14.Now,let’stryselectingthefirstletterofall<p>elements.Youusethepseudo-elementfirst-lettertodothat.Changetheselectorto

p::first-letter

15.Next,let’slookatwhathappenswhenanelementhasmorethanoneclasses.Changetheselectorbackto.myClassParaandaddthefollowingCSScodejustbeforethe</style>tag.

.mySecondClassPara{

text-decoration:underline;

}

NoticewhichparagraphisbothyellowinbackgroundANDunderlined.Thisisbecausethatparagraphhastwoclasses:myClassParaandmySecondClassPara.Therefore,bothrulesapplytoit.

16.Finally,let’stryaddinganexclamationmarktotheendofall<p>elements.We’llusetheafterpseudo-elementtodothat.AddthefollowingCSScodejustbeforethe</style>tag.

p::after{

content:“!”;

}

Page 42: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Chapter4:CSSBoxModel

Sofar,we’vecoveredthebasicsofHTMLandCSS.Inthischapter,we’llstarttodosomeactualCSScoding.Specifically,we’lllearnabouttheCSSboxmodelandlookathowwecanmodifythelookandfeelofaboxinCSS.

WhatistheCSSBoxModel

AllelementsinCSSaretreatedasboxes.CSSboxesconsistofmargins,borders,padding,andtheactualcontentasshownbelow.

Thethickblacklineistheborder.Withintheborderisthepaddingandtheactualcontent.Outsidetheborderisthemarginofthebox.Thethicknessofthepadding,borderandmargincanallbemodifiedwithCSS.Tounderstandhowthisboxmodelworks,let’sanalyzethecodebelow.Youcandownloadthiscodeathttp://learncodingfast.com/css.

<!doctypehtml>

<html>

<head><title>Chapter4-CSSBoxModel</title>

<styletype="text/css">

#box1{

margin:20px;

Page 43: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

padding:10px;

border:5pxsolidblack;

width:100px;

height:100px;

text-align:justify;

float:left;

}

#box2{

margin:20px;

padding:50px;

border:5pxsolidblack;

width:100px;

height:100px;

text-align:justify;

float:left;

}

</style></head>

<body>

<divid="box1">LearnCSSinOneDayandLearnItWell.CSSiseasy.

</div>

<divid="box2">LearnCSSinOneDayandLearnItWell.CSSiseasy.

</div>

<p>skajdfhadlcvkasjcnlkajshvnaclaksjdclkasjdckasjcnkas

djvcnksamcnlkasdjnskajdfhadlcvkasjcnlkajshvnaclaks

jdclkasjdckasjcnkasdjvcnksamcnlkasdjnskajdfhadlcvkasj

cnlkajshvnaclaksjdclkasjdckasjcnkasdjvcnksamcnlkasd

jn</p>

</body>

</html>

Ifyourunthiscode,you’llgettheboxesbelow.Thegibberishtextbesideandbelowtheboxesisaddedtoshowthemargin.

Page 44: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Thiscodedefinestwoboxeswithwidthandheightof100pixels.Thiswidthandheightreferstothedimensionsofthecontentareaonly.

Thefirstbox(box1)hasapaddingof10pixels(px)aroundthecontentarea.Aroundthepadding,ithasasolidblackborderof5px.Thetotalwidthofbox1(includingitsborder)is100(contentarea)+10*2(paddingonbothsides)+5*2(borderonbothsides)=130px.Thesameappliesfortheheight.

Thesecondbox(box2)hasapaddingof50px.Despitebox2beingmuchlargerthanbox1,noticethatthetext“LearnCSSinOneDayandLearnItWell.CSSiseasy.”stilloccupiesthesamearea?Thisisbecausethecontentareaisdeterminedbythewidthandheightproperties,notbythepadding.box2hasatotalwidthof100+50*2+5*2=210px.Itsheightisalso210px.

Outsidetheborder,wehaveamarginof20pxforbothboxes.Noticetheresomespacebetweenthegibberishtextandtheboxes?Thatisthemargin.

Tryplayingaroundwiththecodeabitandchangingthevaluesofthewidth,height,padding,marginandborderproperties.Observewhatisaffectedbyeachchange.Youshouldnoticethatwidthandheightaffectsthecontentarea.Marginaffectstheareaoutsidetheborderwhilepaddingaffectstheareainside.Borderisofcoursetheborderofthebox.We’llcovereachofthesepropertiesindetailnext.

Page 45: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

WidthandHeightProperties

ThewidthandheightpropertiesofaCSSboxspecifythedimensionsofthecontentarea(excludingthepadding,borderandmargin).Thevaluesarenormallygiveninpixelsorasapercentage.Forinstance,thecodeinourexamplesetsthewidthandheightofbothbox1andbox2to100px.Youcanalsosetthewidthto80%.Theboxes’contentareawillthenoccupy80%ofthewidthofthepage.Finally,youcansettheheightandwidthtoauto.Inthiscase,thebrowserwillcalculatethesevaluesautomatically,basedontheamountofspaceneededtodisplaythecontentinsidethebox.

OverflowProperty

Sometimes,thewidthandheightofthecontentareamaybetoosmalltoaccommodatethecontentsinsidethebox.Bydefaultthecontentwillflowoutoftheboxandoverlapothercontents.Thisresultsinaverybadlyformattedwebpage.Ifyoudonotwantthistohappen,youcanusetheoverflowproperty.Thediagrambelowshowshowcontentisdisplayedusingdifferentvaluesfortheoverflowproperty(visible,hidden,scrollandauto).

Page 46: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

PaddingandMarginProperties

Paddingsandmarginsarebothtransparent.Hencewecannotchangetheircolor.However,wecanspecifytheirwidth.Themostcommonlyusedunitforspecifyingwidthisthepixel.Ifyouwantthemargintobe10pixels,youwritemargin:10px;.Thereshouldnotbeanyspacebetween10andpx.

Theexamplesbelowshowfourdifferentsyntaxesforspecifyingmarginwidth.Thesameworksforpaddings.Justchangethepropertynamefrommargintopadding.

Syntax1margin:25px;

Thissyntaxsetsallfourmarginsto25px.

Syntax2margin:25px50px;

Page 47: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Thissyntaxsetsthetopandbottommarginsto25px;theleftandrightmarginsto50px.

Syntax3margin-top:25px;

margin-right:50px;

margin-bottom:60px;

margin-left:10px;

Thissyntaxsetstheindividualmarginsseparately.

Syntax4margin:25px50px60px10px;

Thissyntaxisashorthandforsyntax3.Thefournumbersspecifythevaluesoftheindividualmargins,startingfromthetopandcontinuinginaclockwisedirection.Hencetopmarginis25px;rightis50px,bottom60pxandleft10px.

Inadditiontohavingpositivevalues,marginscanhavenegativevalues.Anegativemarginwillresultinoverlappingorhiddencontent.Forinstance,ifwechangethemarginofbox2frommargin:20px;tomargin:20px20px20px-50px;(i.e.margin-leftischangedto-50px),we’llgetthefollowing:

Notethatwhilemarginscanhavenegativevalues,paddingscannothavenegativevalues.

Marginsarealsocommonlyusedtoalignblockelements.Bydefault,blockelementstakeupthefullwidthavailable.However,youcanchangethiswidth

Page 48: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

usingthewidthproperty.Forinstance,thecodebelowchangesthewidthofanelementto80%.Youcanthencenteraligntheelementbysettingtheleftandrightmarginstoauto.

width:80%;

margin:0auto;

Themarginruleabovesetsthetopandbottommarginsto0px(theunitpxisoptionalifthevalueis0)andtheleftandrightmarginstoauto.Whenmarginsaresettoauto,thebrowserwillevenlydistributetheremainingwidthtotheleftandrightmargin,resultinginacenteralignedelement.

BorderProperties

CSSborderpropertiesallowyoutosetthewidth,color,styleandradiusofanelement'sborder.

border-width

Tosetthethicknessoftheborder,youusetheborder-widthproperty.Borderwidthisnormallysetinpixels.Alternatively,youcanuseoneofthreepredefinedvalues:thin,mediumorthick.Borderpropertiesaresetusingthesamesyntaxesasmarginsandpaddings.

Examples:

border-width:25px;

willsetallbordersto25px.

border-width:25pxthin;

willsetthetopandbottomwidthto25pxandtheleftandrightwidthtothin.

border-top-width:30px;

willsetthetopborderto30px.

border-color

Tosetbordercolor,youusethepropertyborder-color.Thevalueofthis

Page 49: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

propertycanbesetbyspecifyingapredefinedcolorname,suchasgreen,redandyellowetc.Atotalof140suchnamesaredefinedinCSS.Thesitehttp://www.w3schools.com/cssref/css_colornames.aspgivesacompletelistofthesenames.Inaddition,youcanalsosetthecolortotransparent,bywritingborder-color:transparent;.

AnothermethodtospecifybordercoloristousetheRGBnotation(e.g.rgb(0,255,0)).Allwebcolorsarerepresentedbythreeprimarycolors:Red,GreenandBlue.Ifyouwritergb(0,255,0),itmeansyouwantthesecondcolor(i.e.green)tohaveanintensityof255(themaximumintensity),andthefirstandthirdcolors(redandbluerespectively)tohaveanintensityof0(theleast).Thiswillsimplygiveyouthecolorgreen.

InadditiontousingtheRGBnotation,youcanalsousethehexadecimalnotation,whichuses6digitstorepresentcolor.Thefirsttwonumbersrepresentthehexadecimalvaluefortheintensityof‘red’,thenexttworepresent‘green’andthelasttworepresent‘blue’.Oftenacolortoolisusedtogeneratethesehexadecimalvalues.Checkoutthesitehttp://instant-eyedropper.com/foronesuchfreetool.

Alternatively,youcangotohttp://html-color-codes.info/wherethere’sacolorchartforyoutoselectthecolorthatyouwant.Clickonitandyou’llbegiventhecorrespondinghexadecimalvalue.

Examples:

border-color:rgb(255,0,0);

willsetallborderstored.

border-color:redgreen;

willsetthetopandbottomborderstoredandtheleftandrightborderstogreen.

border-top-color:#12005F;

willsetthetopborderto#12005F.

border-style

Tosetborderstyle,youusethepropertyborder-style.Theacceptablevaluesare:none,dotted,dashed,solid,double,groove,ridge,insetandoutset.

Page 50: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Forinstance,ifyouwrite

border-style:soliddotted;

thetopandbottomborderwillbesolidwhiletheleftandrightwillbedotted.Ifyouwanttosetthestyleindividually,youcanwrite

border-top-style:solid;

border-left-style:dotted;

border-radius

Theborder-radiuspropertyisusedtocreateborderswithroundedcorners.Thevalueisnormallygiveninpixelorpercentage.

Borderradiuscanbesetindividuallyforthefourcorners.Thefourcornersaretop-left,top-right,bottom-rightandbottom-left.

Examples:

border-radius:5px;

setstheborderradiiofallcornersto5px.

border-radius:10px20px;

setsthetop-leftandbottom-right(i.e.thetwocornersdiagonallyoppositeeachother)radiito10pxandthetop-rightandbottom-leftradiito20px.

border-radius:25px5px050px;

setsthevaluesoftheindividualcorners,startingfromthetop-leftcornerandcontinuinginaclockwisedirection.

border-top-left-radius:10px;

setsthetop-leftborderradiusto10px.

Iftheelementhaswidthandheightof100px,paddingof20pxandborderwidthof50px(totalwidthandtotalheight=100+20*2+50*2=240px),settingtheborderradiusto120px(240dividedby2)willgiveyouacircleinsteadofasquare.

BorderShorthand

Page 51: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Theborderpropertyisashorthandforspecifyingborderwidth,styleandcolorinoneline,insteadofdoingitseparately.Simplywriteborder:5pxsolidgreen;

Thevaluesareforwidth(5px),style(solid)andcolor(green)respectively.Borderradiusisnotincludedinthisshorthand.

Exercise4

Downloadthesourcecodeforthisexercisefromhttp://learncodingfast.com/cssandunzipthefile.ThesourcecodeforthisexercisecanbefoundintheChapter4-CSSBoxModelfolder.

Exercise4.1

1.OpenthefileChapter4-CSSBoxModel.htmlconcurrentlyinyourbrowserandtexteditor.

2.Resizeyourbrowserwindowandobservehowthegibberishtextflowsaroundthebiggerbox.

3.ModifytheCSSdeclarationforbox1bychangingwidth:100px;andheight:100px;toeachofthefollowing:

(a)width:200px;height:200px;(b)width:60%;(c)height:auto;width:auto;

Savethefileinthetexteditorandrefreshthepageinthebrowser.Noticewhathappenstobox1ineachcase.

4.Nowchangethewidthandheightofbox1backto100pxandchangethetextbetweenthetags<divid="box1">...</div>to:

“LearnCSSinOneDayandLearnItWell.Thisexampleshowswhathappenswhentextoverflowsthedimensionofthebox.”

Page 52: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Next,addeachofthefollowingtotheCSSdeclarationofbox1andnoticewhathappensineachcase:

(a)overflow:visible;(b)overflow:hidden;(c)overflow:scroll;(d)overflow:auto;

5.ModifytheCSSdeclarationforbox1bychangingmargin:20px;toeachofthefollowingandnoticewhathappenstothespacearoundbox1ineachcase:(a)margin:50px;(b)margin:-50px;(c)margin:25px200px;(d)margin:25px50px60px10px;

6.Removethemarginrulesforbox1andaddthe4linesbelow:

margin-top:25px;

margin-right:50px;

margin-bottom:60px;

margin-left:10px;

Noticeanychangestobox1?Thereshouldbenochangeasthisisthesameas5(d)above.

7.Removethemarginrulesforbox1andaddthelinebelow:

margin:0auto;

Next,changethewidthofbox1to80%.Finally,removethelinefloat:left;.Noticewhathappens.(We’llexplainwhatfloatdoesinthenextchapter).box1isnowcenter-aligned.

8.Now,let’sworkonbox2.ModifytheCSSdeclarationforbox2bychangingpadding:50px;toeachofthefollowingandnoticewhathappensinsidebox2.

(a)padding:25px;

Page 53: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

(b)padding:-10px;(refertonotebelow)(c)padding:25px50px;(d)padding:25px50px60px10px;

8(b)willnotworkaspaddingscannothavenegativevalues.You’lljustendupwithapaddingof0pixel.

9.Removethepaddingrulesforbox2andaddthe4linesbelow:

padding-top:25px;

padding-right:50px;

padding-bottom:60px;

padding-left:10px;

Noticeanychangestobox2?Thereshouldbenochangeasthisisthesameas8(d)above.

10.Nowlet'schangetheborderstyleforbox2.Removethelineborder:5pxsolidblack;fromtheCSSdeclarationofbox2andaddeachofthefollowing.Noticewhathappenstotheborderineachcase:

(a)border-style:soliddotted;(b)border-style:nonedasheddoublegroove;(c)border-style:inset;(d)border-style:outset;

11.Next,removetheborder-styleruleforbox2andaddthefollowing:

border-top-style:dotted;

border-left-style:double;

12.Nowremovetherulesfrompart11andchangeborderstyletosolid(border-style:solid;)

Nextaddeachofthefollowingrules.Noticewhathappenstobox2ineachcase.

(a)border-width:25px;(b)border-width:25pxthin;(c)border-top-width:30px;

Page 54: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

13.Nowwearegoingtochangethebordercolorforbox2.Tryaddingeachofthefollowingrules:

(a)border-color:rgb(255,0,0);(b)border-color:redgreen;(c)border-top-color:#12FF5F;

14.Next,we'lltrythebordershorthand.Removealltheborderpropertiesforbox2.Addthefollowing:

border:5pxsolidgreen;

15.Now,let’strytheborder-radiusproperty.Tryeachofthefollowing:

(a)border-radius:20px;(b)border-radius:10px20px;(c)border-radius:25px5px050px;(d)border-top-left-radius:10px;

16.Finally,let’strytocreateacircle.First,changethewidthandheightofbox2to100px,paddingto20pxandtheproperty

border:5pxsolidgreen;

toborder:50pxsolidgreen;.

Now,removeallpreviousrulesforborderradiusandaddthefollowingrule:

border-radius:120px;

Youendupwithacircleright?That’sbecausetheborderradiusishalfofthetotalheight(andwidth)ofbox2.

Page 55: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Chapter5:PositioningandFloating

NowthatweunderstandtheCSSboxmodel,let’slookathowtouseCSStospecifythearrangementoftheseboxesonourwebpages.Inthischapter,we’llbelookingattwoofthemostimportantconceptsinCSS:positioningandfloating.Together,thesetwopropertieshandlethelayoutofourwebpages.

Positioning

TheCSSpositioningpropertyallowsyoutopositionanelementandspecifywhichelementshouldbeontopincaseofanoverlap.

Therearefourmethodstopositionanelement.Tounderstandhowthefourmethodswork,Istronglyencourageyoutotryouttheexerciseattheendofthischapter.Thisisatopicthatisdifficulttounderstandwithoutahands-onapproach.

StaticPositioning

Thefirstpositioningmethodisstaticpositioning.Staticdoesn'tmeanmuch,itjustmeansthattheelementsarepositionedaccordingtothenormalflowofthepage.AllHTMLelementsarepositionedusingthismethodbydefault.Ifyouwanttospecifythatstaticpositioningbeused(forinstancetooverrideanotherpositioningruleforthesameelement),youwrite

position:static;

RelativePositioning

Thesecondmethodtopositionanelementistherelativepositioningmethod.Thismethodpositionsanelementrelativetoitsnormalposition.Normalpositionreferstothedefaultpositionoftheelementwhennopositioningruleisspecifiedorwhenstaticpositioningisused.

Page 56: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Supposewehavetwoboxes,box1andbox2withnopositioningspecified.Ifwecreatebox2afterbox1inourHTMLcode,box2willbepositionedbelowbox1bydefault(refertocodebelow).

<!DOCTYPEhtml>

<html>

<head>

<style>

#box1{

/*Somerulesforstylingbox1*/

}

#box2{

/*Somerulesforstylingbox2*/

}

</style>

</head>

<body>

<divid="box1">Box1</div>

<divid="box2">Box2</div>

</body>

</html>

NowsupposeweaddthefollowingrulestotheCSSdeclarationofbox2.

position:relative;

left:150px;

top:50px;

Whatwe’vedoneischangethepositioningofbox2torelativepositioning.

Page 57: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Theimageaboveshowsthepositionofbox2whenrelativepositioningisused.Awhitedottedboxisaddedtoshowtheoriginalpositionofbox2.

Whenrelativepositioningisapplied,box2ismovedrelativetoitsnormalposition.Thelinetop:50px;movesthebox50pxawayfromthetopoftheoriginalpositionandthelineleft:150px;movesit150pxawayfromtheleft.

Youcanalsousetherightandbottompropertiestopositionbox2.Forinstance,bottom:50px;willmovebox250pxupfromtheoriginalbottomofbox2whileright:50px;willmoveit50pxleftfromtheoriginalrightedgeofbox2.Inaddition,youcanusenegativepixelstopositiontheboxes(e.g.left:-50px)

TrytheexerciseforChapter5andplayaroundwiththevaluestoseehowallthesework.

Notethatwhenrelativepositioningisused,theelementcanendupoverlappingotherelements.

Ifyouwanttospecifywhichelementshouldbeinfront,youhavetousethez-indexproperty.Thez-indexpropertyworksonanyelementthathasapositionofeitherrelative,fixedorabsolute(i.e.notstatic).Anelementwithgreaterz-indexvaluewillbepositionedinfrontofanelementwithalowerz-indexvalue.

Page 58: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Supposeyouhavetwoboxes,greenBoxandredBox,andtheyoverlapeachother.Ifyoudeclarethez-indexofgreenBoxasz-index:1;

andthez-indexofredBoxas

z-index:2;

redBoxwillbeontopofgreenBoxasithasagreaterz-indexvalue.

FixedPositioning

Thethirdpositioningmethodisfixedpositioning.Asthenamesuggests,anelementthatispositionedusingthefixedmethodwillalwaysstayatitsassignedlocation;itwillnotmoveevenwhenthepageisscrolled.Fixedpositioningiscommonlyusedtopositionsocialsharingbuttonsatthesideofawebpage.Tousefixedpositioning,wewrite

position:fixed;

Whenusingfixedpositioning,wecanusethetoppropertytospecifythenumberofpixelstheboxshouldbefromthetopofthepagewhiletheleftpropertyspecifiesthenumberofpixelsitshouldbefromtheleftofthepage.

Inadditiontotopandleft,therearealsotherightandbottomproperties,whichspecifythenumberofpixelstheboxshouldbefromtherightsideandbottomofthepagerespectively.

AbsolutePositioning

Thefinalmethodisabsolutepositioning.

Whenabsolutepositioningisused,anelementispositionedrelativetothefirstparentelementthathasapositionotherthanstatic.Ifnosuchelementisfound,itispositionedrelativetothepage.

Forinstance,supposewehavethefollowingHTMLcode:

Page 59: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

<divid="box1">ContentinBox1</div>

<divid="box2">ContentinBox2</div>

andthefollowingCSSdeclaration:

#box1{

position:relative;

}

#box2{

position:absolute;

top:50px;

left:150px;

}

Assumingthatbox2isnotachildelementofanyelementthathasanonstaticpositioning,it’llbepositionedrelativetothepage.Thatis,itispositioned50pxfromthetopofthepageand150pxfromtheleft.

However,ifwechangetheHTMLstructureto

<divid="box1">ContentinBox1

<divid="box2">ContentinBox2</div>

</div>

box2isnowachildelementofbox1.Hencebox2willbepositionedrelativetobox1.Itisnow50pxdownfromthetopand150pxrightfromtheleftsideofbox1.

Inaway,absolutepositioningissimilartorelativepositioning,exceptthattheelementispositionedrelativetoitsparentelementinsteadofitsnormalposition.

Floating

ThenextCSSpropertywearegoingtodiscussisfloating.

Floatingisatechniqueusedtoarrangeelementsonapage.Theideaissimilartoputtingbooksontoabookshelf.Imagineyouhaveastackofbooksofvaryingthicknessandheightandyouneedtoputallthebooksontoabookshelf.Inaddition,youarenotallowedtorearrangethebooks.Thatis,thebooksmustbe

Page 60: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

placedontothebookshelfinthesameorderastheywereintheoriginalstack.

ToperformthistaskCSS-style,we’llstartwiththetoprow.We’llputthebooksonebyoneontothetoprow,startingfromlefttoright.Supposethetoprowisalmostfullandyouhaveabookthatistoothicktofitontothetoprow.Whatdoyoudo?You’llmovetothenextrowbelowit,right?Well,CSSdoesitalittledifferently.CSSwilltrytofitthis‘book’ontothesamerow,belowtheprevious‘book’,aslongasthereissomespacebelowit(refertoBox5inthenextdiagram).Thismethodofstackingthebooksissimilartodoingafloat:leftinCSS.

Alternatively,youcandoafloat:rightinCSS.Thisisequivalenttostartingfromthetoprowbutstackingthebooksfromrighttoleft.

ToseehowthisworksinCSS,supposewehave7divboxesofvaryingheightsandwidthsthatarefloatedleft(refertocodebelow):

<!doctypehtml>

<html>

<head><title>CSSFloat</title>

<styletype="text/css">

div{

padding:10px;

border:1pxdashedblack;

margin:5px;

float:left;

}

#box1{

width:60px;

height:100px;

}

#box2{

width:100px;

height:20px;

}

#box3{

width:50px;

height:150px;

}

#box4{

width:20px;

height:50px;

Page 61: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

}

#box5{

width:150px;

height:120px;

}

#box6{

width:120px;

height:70px;

}

#box7{

width:25px;

height:80px;

}

</style></head>

<body>

<divid="box1">Box1</div>

<divid="box2">Box2</div>

<divid="box3">Box3</div>

<divid="box4">Box4</div>

<divid="box5">Box5</div>

<divid="box6">Box6</div>

<divid="box7">Box7</div>

</body>

</html>

Ifwerunthiscode,we’llgetsomethinglikethenextimage.

Page 62: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Noticehowtheboxesarearrangedfromlefttoright,startingfromthetop.Asbox5istoothicktofitintothetoprow,CSSplacesitbelowthepreviousbox.

Nowsupposeinadditiontothese7boxes,wealsohavethefollowingtextthatwewanttodisplayonthesite.

<p>Thisissometextthatisnotfloated.</p>

<p>Thisismoretextthatisnotfloated.</p>

<p>Thisisyetmoretextthatisnotfloated.</p>

IftheseparagraphsareincludedintheHTMLdocumentafterthedivboxes,we’llgetthediagrambelow.Theseparagraphswilljust‘squeeze’intowhateverspaceisavailable.

Page 63: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Ifyoudonotwantthattohappen,youcanclearthefloatbyusingtheclear:bothproperty.Todothat,makethefollowingadditiontotheCSSdeclaration:

.clearFloat{clear:both;}

Tousethisclass,weaddittothefirst<p>tag:

<pclass="clearFloat">Thisissometextthatisnotfloated.</p>

YouonlyneedtoaddtheclearFloatclasstothefirst<p>tag.Onceyouclearthefloat,thetextwillnolongerwraparoundtheboxes.

That’sthegistofhowpositioningandfloatingworksinCSS.IstronglyencourageyoutotrytheexercisesforthisChaptertogetabetterunderstandingofthesetwoconcepts.

Exercise5

Downloadthesourcecodeforthisexercisefromhttp://learncodingfast.com/cssandunzipthefile.ThesourcecodeforthisexercisecanbefoundintheChapter5-PositioningandFloatingfolder.

Page 64: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Exercise5.1

1.OpenthefileChapter5-Positioning.htmlconcurrentlyinyourbrowserandtexteditor.

2.Addtheruleposition:static;totheCSSdeclarationfor#box1and#box2andobservewhathappenstothepositionsofthetwoboxes.

Nothingchangesright?That'sbecauseallHTMLelementsarepositionedusingstaticpositioningbydefault.

3.Removetheruleposition:static;fromtheCSSdeclarationfor#box1and#box2.AddthefollowinglinestotheCSSdeclarationof#box2.

position:relative;

top:50px;

left:70px;

Observewhathappenstothepositionofthesecondbox.3.Itisnow50pxfromthetopand10pxfromtheleftofitsnormalposition.

Playaroundwithdifferentvaluesforthetopandleftpropertiesandseewhathappenstothepositionofbox2.Trynegativevaluesaswell.Youcanalsotryusingtherightandbottomproperties.

4.NowchangetheCSSdeclarationof#box2backto

position:relative;

top:50px;

left:70px;

Noticethatthetextispartiallyhiddenbytheredbox?

Ifyouwantthetexttoappearinfrontoftheredbox,addthefollowinglinestotheCSSdeclarationofp.

position:relative;

z-index:2;

Youcansetthepositiontoeitherrelative,absoluteorfixed.Itdoesnot

Page 65: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

matteraslongasitisnotstatic.

Next,addthelinez-index:1;totheCSSdeclarationof#box2.Refreshthepage.Thetextshouldnowbeinfrontoftheredboxsincethez-indexofthetextisgreaterthanthez-indexoftheredbox..

Ifyouwanttheredboxtobeinfrontofthetextinstead,justchangethez-indexof#box2toavaluegreaterthan2.

5.Now,changetheheightof#box1to5000pxandthepositioningof#box2tofixed(position:fixed;).

Scrollthepage.5.Theredboxdoesnotmoveasitusesfixedpositioningnow.

6.Changethepositioningfor#box2backtorelativeandtheheightof#box1backto100px.Addthefollowinglinejustbeforethe<p>tagintheHTMLcodeatthebottomofthefile.

<divid="box3"></div>

NowaddthefollowingCSSdeclarationtostylebox3.#box3{

position:absolute;

top:50px;

left:150px;

background-color:yellow;

width:50px;

height:50px;

padding:20px;

border:5pxdottedblack;

margin:10px;

}

box3usesabsolutepositioningandsinceitisnotachildelementofany<div>elements,itispositionedrelativetothepage.Thatis,itispositioned50pxfromthetopofthepageand150pxfromtheleft.

7.Nowchangethe<div>codeforthethreeboxestothefollowing:

<divid="box1"></div>

<divid="box2">

Page 66: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

<divid="box3"></div>

</div>

box3isnowachildelementofbox2.Thereforeitispositioned50pxdownfromthetopand150pxrightfromtheleftsideofbox2asitisnowpositionedrelativetobox2.

Exercise5.2

1.OpenthefileChapter5-Floating.htmlconcurrentlyinyourbrowserandtexteditor.

2.Resizeyourbrowser-windowtoseewhathappenswhenthe<div>elementsdonothaveenoughroom.

3.ModifytheCSSdeclarationfordivbychangingfloat:left;tofloat:right;.Observewhathappenstothepositionsoftheboxes.

4.Nowchangetherulebacktofloat:left;andaddthecodebelowtotheHTMLcode,justabovethe</body>tag.

<p>Thisissometextthatisnotfloated.</p>

<p>Thisismoretextthatisnotfloated.</p>

<p>Thisisyetmoretextthatisnotfloated.</p>

Refreshthepageandobservewherethetextis.Resizethebrowserwindowtoseewhathappenswhenthewidthofthepageisnarrow.

5.Next,addthecode

.clearFloat{clear:both;}

totheCSSdeclarationjustabovethe</style>tag.

Changethefirst<p>tagto<pclass="clearFloat">andobservewhathappens.

Page 67: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Chapter6:DisplayandVisibility

Congratulations.YouhavenowlearnedafairbitofCSS.Infact,wehavecoveredmostoftheimportantconceptsinCSS,includingtheCSSboxmodelandtheideaoffloatingandpositioning.Inthischapter,we’lllookathowtopulladisappearingactinCSS.

That’sright.CSShasnotone,buttwo,propertiesthatallowustoremoveorhideanelement.Thesetwopropertiesarethedisplayandvisibilityproperties.

Display

TheCSSdisplaypropertyisusedtomodifyhowanelementisdisplayed.Therearethreecommonlyusedvalues:none,inlineandblock.

Thefirstvalue‘none’makesanelementdisappear.Thepagewillbedisplayedasiftheelementisnotthere.

Thesecondvalue‘inline’causesanelementtobedisplayedasaninlineelement.WebrieflytalkedaboutinlineelementsinChapter2whendiscussingthedifferencebetween<div>and<span>.Recallthataninlineelementdoesnotstartandendwithanewline.Anothercharacteristicofaninlineelementisthatitwillonlytakeupasmuchheightandwidthasitneeds.Hence,thereisnopointspecifyingtheheightandwidthofaninlineelement.

Incontrast,ablockelementstartsandendswithanewlineanditsheightandwidthcanbechanged.Ifyouwantanelementtobedisplayedasablockelement,youusethe‘block’value.

Example:

display:none;

Visibility

Page 68: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

TheCSSvisibilitypropertyisusedtohideanelement.Youdothatbywritingvisibility:hidden;.

Thedifferencebetweenvisibility:hiddenanddisplay:noneisthatfortheformer,theelementishiddenbutstilltakesupspace.Usingthevisibilitypropertyisjustlikewearinganinvisiblecloak.Theelementisstillthere,eventhoughyoucan’tseeit.

Incontrast,whenyouusedisplay:none,theelementisessentiallyremovedfromthepageandthepagewilldisplayasiftheelementdoesnotexistatall.

Forinstance,supposethetwopropertiesareappliedtotheword“magic”inthesentence“Thisisjustlikemagic.Youcanmakewordsdisappear.”below:

Forvisibility:hidden;you’llget“Thisisjustlike.Youcanmakewordsdisappear.”

Fordisplay:none;you’llget“Thisisjustlike.Youcanmakewordsdisappear.”

Exercise6

Downloadthesourcecodeforthisexercisefromhttp://learncodingfast.com/cssandunzipthefile.ThesourcecodeforthisexercisecanbefoundintheChapter6-DisplayandVisibilityfolder.

Exercise6.1

1.OpenthefileChapter6-DisplayandVisibility.htmlconcurrentlyinyourbrowserandtexteditor.

2.ChangetheheightandwidthintheCSSdeclarationfor#displaydemo.Observewhathappenstotheyellowbox.

Nothingchangesright?Theyellowboxisdeclaredasaninlineelement.Henceitwillonlytakeupasmuchwidthandheightasitneeds.Infact,youcanremovetheheightandwidthpropertiesandnothingwillchange.

Page 69: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

3.Nowchangethedisplaypropertyof#displaydemofromdisplay:inline;todisplay:block;.Whathappens?

Theyellowboxisnowdisplayedasablockelement.Itstartsandendswithanewline.Ifyouhavedeclareditswidthandheight,thewidthandheightwillbethevaluesyouspecified.Ifyouhavenotspecifieditswidthandheight,theyellowboxwilloccupythefullwidthofthepage.Itwilltakeupasmuchheightasitneeds.

4.TrychangingtheheightandwidthintheCSSdeclarationfor#displaydemo.Observewhathappens.

5.Now,let’smoveontothevisibilityproperty.ChangetheCSSdeclarationof#magicfromdisplay:inline;tovisibility:hidden;.Observewhathappenstotheword'magic'inthebluesentence.

6.Next,changetheCSSdeclarationof#magicfromvisibility:hidden;todisplay:none;.Observewhathappens.

Page 70: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Chapter7:Background

Inthischapter,we’lllearnhowtochangethebackgroundpropertiesofanelement.Thesepropertiesincludechangingitsbackgroundcolorandbackgroundimage.

Forastart,letusfirstlookathowtochangethebackgroundcolor.

BackgroundColor

Todeclarethebackgroundcolorofanelement,weusethebackground-colorproperty.SimilartohowwespecifythebordercolorofourCSSboxes,wecandeclarethebackgroundcolorofanelementusingoneofthreenotations:colorname,rgbnotationorhexadecimalnotation.

Examples:

background-color:green;

background-color:rgb(0,255,0);

background-color:#00FF00;

BackgroundImage

Ifyoufinditplaintojustusecolorasthebackgroundofanelement,youcanchoosetouseanimage.CSSallowsusgreatflexibilityinhowwewanttheimagetobedisplayed.

background-image

Touseanimageasthebackground,wespecifytheURLtotheimageusingthebackground-imageproperty.

Example:

background-image:url(“image1.jpg”);

Page 71: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

background-repeat

Bydefault,thebackgroundimageisplacedatthetop-leftcorneroftheelement,andrepeatedbothverticallyandhorizontally.Ifyoudonotwantthebackgroundimagetoberepeated,youcanusethebackground-repeatpropertytochangeit.Thefollowinglistshowssomecommonlyusedvaluesforthebackground-repeatproperty:

repeat

Thisisthedefault.Imagewillberepeatedhorizontallyandvertically.

repeat-x

Imagewillonlyberepeatedhorizontally.

repeaty

Imagewillonlyberepeatedvertically.

no-repeat

Imagewillnotberepeated.

Example:

background-repeat:repeat-x;

background-attachment

Thebackground-attachmentpropertyspecifieswhetherthebackgroundimageshouldbefixedorscrollwiththepage.Thetwocommonlyusedvaluesarefixedandscroll.Thedefaultisscroll.Trytheexerciseattheendofthischaptertoseehowthisworks.

Example:

background-attachment:scroll;

backgroundposition

Thebackgroundpositionpropertyisveryusefulifyouwanttospecifywhich

Page 72: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

areaofthebackgroundimageyouwanttodisplay.

Supposeyouhaveanelementwithwidthandheight100pxeach.Ifthebackgroundimagethatyouusehaswidth200pxandheight300px,onlyaportionofthebackgroundimagewillbedisplayedastheimageislargerthanthesizeoftheelement.

Forinstance,ifyouusetheimageabove(200pxby300px)asthebackgroundimageofa100pxby100pxelement,onlyAreaA(topleft)willbedisplayedbydefault.WhatifyouwanttodisplayAreaFinstead?Todothat,youneedtochangethevalueofthebackgroundpositionproperty.

Themostcommonwaytospecifythebackgroundpositionvalueistousepixels.Thesyntaxis:

backgroundposition:xposypos;

Tounderstandhowthissyntaxworks,let’simagineapieceofcardboardwitha100pxby100pxholeinthemiddle.ThisholeinthecardboardrepresentstheHTMLelement.Nowimagineyourbackgroundimageisunderneaththatcardboard.Bydefault,theimagewillbealignedsuchthatAreaAisshownthroughtheholeinthecardboard.IfyouwanttodisplayAreaFinstead,youhavetoshifttheimage(notthecardboard)100pxtotheleftand200pxup.To

Page 73: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

achievethiswithCSS,youwrite:

backgroundposition:-100px-200px;

Thefirstnumber(-100px)shiftstheimagehorizontally.Ifthisnumberispositive,theimageisshiftedtotheright.Ifnegative,itisshiftedtotheleft.

Thesecondnumber(-200px)shiftstheimagevertically.Ifthisnumberispositive,theimageisshifteddown.Ifnegative,itisshiftedup.

ThebestwaytounderstandthisconceptistotrytheexercisesforthisChapter.IstronglyencourageyoutodothembeforemovingontoChapter8.

Exercise7

Downloadthesourcecodeforthisexercisefromhttp://learncodingfast.com/cssandunzipthefile.ThesourcecodeforthisexercisecanbefoundintheChapter7-Backgroundfolder.

Exercise7.1

1.OpenthefileChapter7-Background.htmlconcurrentlyinyourbrowserandtexteditor.

2.Scrollthepageinyourbrowserwindow.TheLearnCodingFastlogoissetasthebackgroundforthebodyelement.Noticewhathappenstothelogoasyouscroll.

NowintheCSSdeclarationforbody,changebackground-attachment:fixed;tobackground-attachment:scroll;.Refreshandscrollthepage.Noticewhathappens.

3.Next,changebackground-repeat:repeat-x;inthebodyCSSrulestoeachofthefollowingandnoticewhathappenstothebackgroundlogo.

(a)background-repeat:repeat;(b)background-repeat:no-repeat;(c)background-repeat:repeaty;

Page 74: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Noticewhathappensineachcase.

4.Next,changebackground-color:white;tobackground-color:#0000FF;.Thisshouldchangethebackgroundcolorofthepagetoblue.

5.Finally,wearegoingtolookatthebackgroundpositionproperty.We’llbemodifyingtherulesfor#box1intheexamplesthatfollow.Theimageusedinthisexampleis‘backgroundposition.png’storedinthesamefolder.Havealookattheimagebeforeproceeding.

Noticethatwhenbackgroundpositionissetto00(thedefault),areaAisdisplayed.ChangingthebackgroundpositionpropertywillshiftthebackgroundimagewithreferencetoareaA.

InthesourcecodeCSSdeclarationfor#box1,changebackgroundposition:00;to

(a)backgroundposition:-100px0;Thisshiftsthebackgroundimage100pxtotheleft.AsthedefaultareashownisAreaA,aftershifting100pxtotheleft,youshouldgetAreaB.

(b)backgroundposition:100px0;Thisshiftsthebackgroundimage100pxtotheright.Asthebackground-repeatpropertyissettono-repeat,noimagewillbedisplayed.Thisisbecausethebackgroundimagehasshiftedoutoftheboundariesofbox1.

(c)backgroundposition:0-100px;Thisshiftsthebackgroundimage100pxup.YoushouldgetAreaC.

(d)backgroundposition:0100px;Thisshiftsthebackgroundimage100pxdown.Noimagewillbedisplayedasthebackgroundimagehasshiftedoutoftheboundariesofbox1.

(e)backgroundposition:-100px-100px;Trytofigureoutwhichareayou’llget.

Page 75: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Chapter8:TextandFont

TextandfontpropertiesinCSSareusedtoformattheappearanceofwordsandtextonawebpage.Thefontpropertyisconcernedwithhowthecharacterslook,suchaswhethertheyare‘fat’or‘thin’,‘big’or‘small’,andwhatfonttypetouse.Thetextpropertyisusedtostyleeverythingelse.Inthischapter,we’llbecoveringthetextandfontpropertiescommonlyused.

FontProperties

font-family

Thefont-familypropertyisusedtosetthefonttype.

Therearethreemaincategoriesoffonttypes:serif,sanserifandmonospace.

Seriffontshaveasmalllineattheendofsomecharacters.Examplesinclude“TimesNewRoman”andGeorgia.

SanSeriffontsdonothavelinesattheendofcharacters.ExamplesincludeArialandVerdana.

Monospacefontsusethesameamountofspaceforallcharacters.Forinstance,theletter‘i’hasthesamewidthastheletter‘a’.Examplesofmonospacefontsinclude“CourierNew”and“LucidaConsole”.

Whenspecifyingthefont-familyproperty,youshouldalwaysincludeseveralfontnamessothatifthebrowserdoesnotsupportthefirstfont,itcantrythenextfontuntilitfindsonethatitsupports.Startwithamorespecificfont(suchas“TimesNewRoman”)andendwithagenericfontfamily.Ifthefontnameismorethanoneword,quotationmarksshouldbeused.

Example:

font-family:"TimesNewRoman",Times,serif;

Page 76: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

font-size

Thefont-sizepropertysetsthesizeofthetext.Fontsizecanbesetwithpixels(px),em,percentage(%)orbyusingkeywords.

Usingpx

Thedefaultfontsizeusedonmostbrowsersis16pixels.Ifyouwantyoursitetodisplaywithadifferentfontsize,youcanspecifyitlikethis:font-size:20px;.

Usingem

Anemisisequaltothecurrentfontsize.Iftheelementisthechildofanotherelement,thecurrentfontsizeisthefontsizeoftheparentelement.Iftheelementisnotachildofanyelement,thecurrentfontsizeisthebrowser’sdefaultfontsize.Asmentionedabove,thedefaultfontsizeusedonmostbrowsersis16px.Hencebydefault1em=16px.

However,thisdefaultfontsizecanbechangedbychangingthebrowser’ssetting.Forinstance,tochangethedefaultfontsizeonFirefox,clickonthemenubutton(therightmostbuttonwiththreehorizontallines),select“Options’andfinallyselectthe“Content’tab.Youcanthenchangethecurrentfontsizeunderthe‘Fonts&Colors’section.

Iftheusersetsthedefaultfontsizeto20px,1embecomes20px.Ifyouwantthefontsizetobe1.5timesthecurrentfontsize,yousimplywrite1.5em.Theemisthepreferedunitsizeusedbymostdevelopersasthedefaultfontsizecanbecustomisedbytheuser.

UsingPercentage

Percentageissimilartoem.200%simplymeans2timesthecurrentfontsize.Hence,200%=2em.

UsingKeywords

Thefinalwaytospecifyfontsizeistousekeywords.Commonlyusedkeywords

Page 77: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

arexx-small,x-small,small,medium(thisisthedefault),large,x-largeandxx-large.

Examples:

font-size:40px;

font-size:1.5em;

font-size:120%;

font-size:large;

font-style

Thefont-stylepropertyisusedtospecifyitalictext.Thetwocommonvaluesarenormalanditalic.Normalwilldisplaytextwithnoitalicwhileitalicdisplaystextinitalic.

Example:

font-style:italic;

font-weight

Thefont-weightpropertyisthecounterpartoffont-style.Whilefont-styleisusedtospecifyitalictext,font-weightisusedtospecifyboldtext.Commonlyusedvaluesincludenormal,bold,bolderandlighter.Alternatively,youcanalsospecifythethicknessofthecharactersusingnumbersinmultiplesof100,from100(thinnest)to900(thickest).400isthenormalthickness,and700isthesameasbold.

However,notethatmostwebbrowsersonlysupportnormalandboldfontweights.Inthatcase,100-500correspondtonormalwhile600andabovecorrespondtobold.

Examples:

font-weight:bold;

font-weight:300;

Page 78: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

TextProperties

CSStextpropertiesallowyoutosetpropertiesthatarenotrelatedtothefontofthetext.Commonpropertiesincludetextcolor,textalignment,textdecoration,letterspacing,wordspacingandlineheight.

color

TheCSScolorpropertyspecifiesthecolorofthetext.SimilartowhatwelearnedinChapter4regardingtheborder-colorproperty,textcolorcanbespecifiedinoneofthreeways:usingacolorname,aRGBvalueorahexvalue.

Examples:

color:blue;

color:#00ff00;

color:rgb(255,0,0);

text-alignment

Thetext-alignmentpropertyallowsustospecifywhetherwewanttexttobecentered,oralignedtotheleftorright,orjustified.Thecommonlyusedvaluesareleft,right,centerandjustify.

Example:

text-align:center;

text-decoration

Thetext-decorationpropertyismainlyusedtospecifywhetherthetextshouldbedecoratedwithaline.Thecommonlyusedvaluesarenone(i.e.justnormaltext,nodecoration),underline,overline(alineabovethetext)andline-through(alinethroughthetext).

Thispropertyiscommonlyusedtoremoveunderlinesfromhyperlinks.Bydefault,mostbrowserswilldisplayhyperlinksinblue,withanunderline.Youcanusethecodetext-decoration:none;toremovetheunderline.

Page 79: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Example:

text-decoration:none;

letter-spacing

Letterspacingisusedtoincreaseordecreasethespacingbetweenlettersinaword.Youspecifytheamountofspacinginpixels.Toincreasethespacing,useapositivevalue.Todecreaseit,useanegativevalue.

Forinstance,letter-spacing:2px;willcausetheletterstobespaced2pixelsapart.letter-spacing:-1px;willcausetheletterstobecrampedtogether,overlappingeachotherby1pixel.

Example:

letter-spacing:2px;

word-spacing

Wordspacing,ontheotherhand,isusedtoincreaseordecreasethespacingbetweenwordsintext.Similartoletter-spacing,youspecifytheamountofspacinginpixels,usingpositivetoincreasethespacingandnegativetodecreaseit.

Example:

word-spacing:2px;

line-height

Lineheightisusedtosetthespacingbetweeneachlineoftext.Thispropertycanbesetusinganumber,aspecificlength,orapercentage.

Whenusinganumbertospecifyline-height,thegivennumberwillbemultipliedwiththecurrentfontsizetogivethelineheight.Forinstance,line-height:2willresultinalineheightof32pxifthecurrentfontsizeis16px.

Page 80: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Whenusinglengthtospecifyline-height,unitssuchaspx(pixel),em,cm,pt(point,where1point=1/72of1in)etccanbeused.

Whenusingpercentage,thegivenpercentagewillbemultipliedwiththecurrentfontsizetogivethelineheight.Forinstance,line-height:50%willresultinaline-heightof8pxifthecurrentfontsizeis16px.Notethatline-heightdoesnotalterthefontsize.Alineheightof8pxwillresultinthelinesoverlappingeachother.

Examples:

line-height:20px;

line-height:120%;

Tohaveabetterunderstandingofhoweachofthesepropertieswork,trytheexercisebelow.

Exercise8

Downloadthesourcecodeforthisexercisefromhttp://learncodingfast.com/cssandunzipthefile.ThesourcecodeforthisexercisecanbefoundintheChapter8-FontandTextfolder.

Exercise8.1

1.OpenthefileChapter8-FontandText.htmlconcurrentlyinyourbrowserandtexteditor.

2.ModifytheCSSpropertyfont-familyandobservewhathappenstothesampletext.ThecurrentfontfamilyisSansSerif.Tryeachofthefollowing:

(a)font-family:Verdana,Arial,Helvetica,sans-serif;(b)font-family:Courier,"LucidaConsole",monospace;

3.ModifytheCSSpropertyfont-sizeandobservewhathappenstothesampletextineachofthefollowingcases.Try

Page 81: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

(a)font-size:40px;(b)font-size:1.5em;(c)font-size:x-small;(d)font-size:120%;

4.ModifytheCSSpropertyfont-styleandobservewhathappenstothesampletext.Try

(a)font-style:italic;

5.ModifytheCSSpropertyfont-weightandobservewhathappenstothesampletext.Try

(a)font-weight:bold;(b)font-weight:300;

6.ModifytheCSSpropertycolorandobservewhathappenstothesampletext.Try

(a)color:blue;(b)color:#00ff00;(c)color:rgb(255,0,0);

7.ModifytheCSSpropertytext-alignandobservewhathappenstothesampletext.Bydefault,thetextinthisparagraphisleftaligned.Nowtryeachofthefollowing:

(a)text-align:justify;(b)text-align:right;(c)text-align:center;

8.ModifytheCSSpropertytext-decorationandobservewhathappenstothesampletext.Try

(a)text-decoration:underline;(b)text-decoration:overline;(c)text-decoration:line-through;

Page 82: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

9.ModifytheCSSpropertyletter-spacingandobservewhathappenstothesampletext.Try

(a)letter-spacing:5px;(b)letter-spacing:-5px;

10.Changeletter-spacingbackto0px.ModifytheCSSpropertyword-spacingandobservewhathappenstothesampletext.Try

(a)word-spacing:10px;(b)word-spacing:-20px;

11.Changeword-spacingbackto0px.ModifytheCSSpropertyline-heightandobservewhathappenstothesampletext.Try

(a)line-height:2;(b)line-height:25px;(c)line-height:30%;

Page 83: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Chapter9:Lists,LinksandNavigationBars

Inthischapter,we’llbelookingatCSSpropertiesforstylinghyperlinksandlists.Inaddition,we’llcombinebothconceptsanddiscusshowtocreatenavigationbarscommonlyseenonwebpages.Ready?Let’sfirststartwithCSSlist.

CSSLists

RecallthatinHTML,wecancreatetwodifferenttypesoflist:orderedlistandunorderedlist?WecanstyletheselistsusingCSSlistproperties.

list-style-type

Thelist-style-typepropertyallowsyoutosetlistitemmarkersforyourlists.Listitemmarkersrefertothosebullets/numbers/lettersontheleftofeachlistitem.

Fororderedlists,wecanspecifythetypeofnumbersorletterswewanttouseasmarkers.Forinstance,ifwewanttouseromannumbers(e.g.i,ii,iii)asitemmarkers,wecanwritelist-style-type:lower-roman;.

Othercommonlyusedmarkersinclude:

decimal(thisisthedefault),decimal-leading-zero(numberwithaleadingzero,e.g.01,02..),lower-alpha(e.g.a,b,c..),lower-greek(e.g.α,β,γ..),upper-alpha(e.g.A,B,C..)andupper-roman(e.g.I,II,III…).

Forunorderedlist,youcanspecifytheshapethatyouwanttouseasthebullet.Thedefaultmarkerisadisc(afilledcircle).Youcanchangethattoeitherasquareoracircle.

Inaddition,youcanalsochoosenottouseanyitemmarkerforyourlist.Todo

Page 84: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

that,youwritelist-style-type:none;.Thisiscommonlydonewhencreatingnavigationbars.

Examples:

list-style-type:lower-roman;

list-style-type:circle;

list-style-type:none;

list-style-image

Ifyoudonotfancyanyoftheprovidedliststyles,youcanchoosetouseanimageasthelistitemmarker.Todothat,youusethelist-style-imagepropertytospecifytheurloftheimagetouse.

Examples:

list-style-image:url(‘myMarker.gif’);

list-style-position

Thelist-style-positionpropertyisusedtospecifywhetherthelistitemmarkersshouldappearinsideoroutsidethecontentflow.Therearetwoacceptablevalues:insideandoutside.

Bydefault,listitemsaredisplayedwithacertainamountofindentation.Iflist-style-positionissettoinside,thelistitemmarkersaredisplayedaftertheindentation.Theindentationisrepresentedbytheleftedgeoftheboxesintheimagebelow.Iflist-style-positionissettooutside,themarkersare

Page 85: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

displayedbeforetheindentation.

Inotherwords,list-style-position:insidewillresultinmoreindentationthanlist-style-position:outside.Thedefaultpositionisoutside.

Examples:

list-style-position:outside;

list-style

list-styleisashorthandpropertyforsettingallthelistproperties(i.e.list-style-type,list-style-positionandlist-style-image)inonedeclaration.Ifanyvalueismissing,thedefaultvalueforthemissingpropertywillbeused.

Examples:

list-style:squareinsideurl("myMarker.gif");

CSSLinks

HyperlinkscanbestyledusinganyoftheCSSpropertiesdiscussedinpreviouschapters.Youcanstylethebackgroundcolorusingthebackground-colorproperty.Thiswillgivethelinkahighlightedappearance.YoucanalsousethetextandfontpropertiescoveredinChapter8tochangethefontsize,fontstyle,textcolor,textdecorationetc.

Inaddition,wecanchoosetostylehyperlinksbasedonthestatetheyarein.

Page 86: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Linkscanbeinoneoffourstates:

link(anunvisitedlink)visited(avisitedlink)hover(whentheusermousesoverit),oractive(whenthelinkisclicked).

Tospecifythestate,wewritea:link,a:visited,a:hoverora:active.Youshouldalwaysspecifythe4statesintheorderabove.

Examples:

a{

text-decoration:none;

}

a:link{

color:#0000FF;

}

a:visited{

color:#00FF00;

}

a:hover{

color:#FFFF00;

}

a:active{

color:#FF00FF;

}

NavigationBars

NavigationbarsarecommonlycreatedasanunorderedlistinHTMLandstyledusinglistandlinkpropertiesinCSS.

Let’strycreatingourownnavigationbar.First,weneedtocreateanunorderedlistofitemsforourmenuandmakethelistitemsclickable(ashyperlinks).

<ul>

<li><ahref=”home.html”>Home</a></li>

<li><ahref=”htmltutorial.html”>HTMLTutorial</a></li>

Page 87: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

<li><ahref=”csstutorial.html”>CSSTutorial</a></li>

<li><ahref=”javascripttutorial.html”>JavascriptTutorial</a>

</li>

</ul>

Next,let’saddthefollowingdeclarationtoourCSSstyletoremovethedefaultbulletfromthelist.

ul{

list-style-type:none;

}

Now,wehavetostylethehyperlinks.We’lluseablockdisplaywhichallowsustospecifythewidthofthelinks.Inaddition,we’llcenteralignthetextandremoveallunderlines.We’llalsoaddabackgroundcolortoourlinks.

a{

display:block;

width:160px;

text-align:center;

text-decoration:none;

background-color:#00FF00;

}

Finally,ifwewantthenavigationbartobeahorizontalbar,weneedtofloatthelistitemsleft.Otherwise,thelistitemswillbedisplayedasaverticalbar.

li{

float:left;

}

Thereyougo!We’vejustcreatedasimplehorizontalnavigationbar.Thesourcecodeforthisnavigationbarisgivenaspartoftheexerciseforthischapter.Playaroundwithitandtrytomakeitmorevisuallyappealing.Youcanalsospecifydifferentstylesforthefourdifferentlinkstates.

Thismethodisjustoneofthemethodstocreateanavigationbar.Theaccompanyingprojectforthisbookwilldemonstrateadifferentmethod.

Exercise9

Downloadthesourcecodeforthisexercisefromhttp://learncodingfast.com/css

Page 88: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

andunzipthefile.ThesourcecodeforthisexercisecanbefoundintheChapter9-Lists,LinksandNavigationBarsfolder.

Exercise9.1

1.OpenthefileChapter9-ListandLinks.htmlconcurrentlyinyourbrowserandtexteditor.

2.ModifytheCSSdeclarationforolandobservewhathappenstothe'CarsOrderedList'.Tryeachofthefollowing:

(a)list-style-type:decimal-leading-zero;(b)list-style-type:lower-roman;(c)list-style-type:upper-roman;(d)list-style-type:upper-alpha;(e)list-style-type:lower-alpha;(f)list-style-type:lower-greek;(g)list-style-type:none;

3.ModifytheCSSdeclarationforulandobservewhathappenstothe'CarsUnorderedList'.Tryeachofthefollowing:

(a)list-style-type:circle;(b)list-style-type:square;(c)list-style-type:none;(d)list-style-type:disc;

4.AddthefollowingruletotheCSSdeclarationforul:

list-style-position:outside;

Refreshthebrowser.Nothingchangesright?Thatisbecauselist-style-position:outside;isthedefault.Nowchangelist-style-position:outside;tolist-style-position:inside;.You’llnoticethattheunorderedlistisshiftedslightlytotheright(i.e.there’smoreindentation).

5.Removethelist-style-typepropertyforulandaddthefollowinginstead:

Page 89: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

(a)list-style-image:url("myMarker.gif");

Observewhathappenstothe'CarsUnorderedList'.

6.Nowlet’slookathowtostylehyperlinks.Tryaddingthefollowingrulestothestatedselector:

(a)Addcolor:green;toa:link{}andobservewhathappenstothe‘ClickMe’link.(b)Addfont-size:2em;toa:active{}andclickonthelink.

(c)Addbackground-color:red;toa:hover{}andhoveryourmouseoverthelink.

Exercise9.2

1.OpenthefileChapter9-NavigationBar.htmlconcurrentlyinyourbrowserandtexteditor.

2.ThispageshowsanexampleofhowahorizontalnavigationbarcanbecreatedusingCSSrulesforlistsandlinks.Thestepsareexplainedinthebook.StudythecodeandtrymodifyingtheCSSdeclarationtoimprovethedesignofthisnavigationbar.

Page 90: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Chapter10:Tables

HTMLtablesareuglylookingbydefault.However,withsomesimpleCSSstyling,wecaneasilyconvertthemintogorgeouslookingtables.Inthischapter,we’lllookathowtodothat.

Border,PaddingandMargin

Thefirstsetofpropertieswe’llbelookingatistheborder,paddingandmarginproperties.RecallwetalkedaboutthesepropertieswhendiscussingtheCSSboxmodel?HTMLtables(<table>)andtablecells(<th>and<td>)followthesameboxmodelasotherCSSelementsandcanthereforebestyledusingtheseproperties.

Tounderstandhowthiswork,refertothediagrambelow(thewords‘TableMargin’and‘TablePadding’areaddedforreferenceanddonotexistontheactualtable).

Page 91: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

TheCSSrulesforthistableareasfollows:

table{

border:dashed1pxblack;

padding:50px;

margin:60px;

}

th{

border:solid1pxblack;

padding:30px;

text-align:center;

}

td{

border:solid1pxblack;

padding:20px;

}

Thedottedlineisthetable’sborder.Spacesurroundingthedottedborderisthetable’smargin(declaredtobe60px)andspacewithinthedottedborderisits

Page 92: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

padding(50px).

Thefirstrow(Firstname,Lastname,Age)isdefinedasthetableheadingusingthe<th>tag.Spacesurroundingthewords‘Firstname’,‘Lastname’and‘Age’isthepaddingforthe<th>element(30px).

Thesecond,thirdandfourthrowisdefinedusingthe<td>tag.Spacesurroundingwordslike‘Derek’,‘Aaron’and‘31’isthepaddingforthe<td>element(20px).

Nomarginsaredeclaredforthe<th>and<td>elementsasmarginsareignoredfortablecells.Hence,wecannotspecifythespacingbetweenthecells.Bydefault,there’llbeasmallgapbetweenindividualtablecells.Inaddition,there’salsoagapbetweenthetable’sborder(thedottedline)andthebordersofthecells(thesolidlines)evenifyousettablepaddingto0px.Ifyouonlywantoneborder,youhavetousetheborder-collapseproperty:

border-collapse:collapse;

We’llhaveachancetoplayaroundwiththeborder,paddingandmarginpropertieswhenwedotheexerciseforthischapter.Fornow,let’smoveontothenextproperty.

HeightandWidth

Thewidthandheightofatablecanbesetusingthewidthandheightproperties.Thevaluesarenormallygiveninpixelsorasapercentage.Forinstance,thecodebelowsetsthetablewidthtobe100%oftheparentelementandtheheighttobe500px.

table{

width:100%;

height:500px;

}

Youcanalsousetheheightpropertyatthetr,thortdlevel.Forinstance,ifyouwantthetableheaderrowtohaveaheightof100px,youcanwriteth{

height:100px;

}

Page 93: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Inaddition,youcansetthewidthpropertyatthetablecelllevel(i.e.forthetdandthelements).Ifyouwantthetablecellstohaveawidthof200px,youcanwrite

th{

width:200px;

}

Ifyouwanttostyleindividualcolumns,youcanusetheid/classattributetodoit.Forinstanceifyouhavethetablestructurebelow:

<table>

<tr>

<thid=”firstColumn”>FirstColumn</th>

<thid=”secondColumn”>FirstColumn</th>

</tr>

<tr>

<td>Somedata</th>

<td>Moredata</th>

</tr>

</table>

youcansetthewidthofthetablecolumnsindividuallylikethis:

#firstColumn{

width:40%;

}

#secondColumn{

width:60%;

}

TextAlignment

Textwithintablecellscanbealignedhorizontallyusingthetext-alignpropertyandverticallyusingthevertical-alignproperty.Thecommonlyusedvaluesforthetext-alignpropertyarecenter,left,rightandjustify.Thecommonlyusedvaluesforthevertical-alignpropertyaretop,middleandbottom.

Examples:

Page 94: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

th{

text-align:center;

vertical-align:middle;

}

Background,FontandText

Tablescanalsobestyledusingpropertiesforbackground,fontandtextcoveredinChapter7and8.Forinstance,thecodebelowwillsetthetextcolorof<th>elementstowhiteandgivetheelementsagreenbackgroundcolor.

th{

background-color:green;

color:white;

}

nth-child()Selector

Sometimeswhenwehaveaverylargetablewithalotofrows,thetablemaybedifficulttoread.Onewaytoimprovethereadabilityoflargetablesistocoloralternatingrows.Thiscanbeeasilyachievedwiththenth-child()selector.

Tocolorevenrows,wewrite

tr:nth-child(even){

background-color:lightgreen;

}

Tocoloroddrows,wewrite

tr:nth-child(odd){

background-color:lightgray;

}

Exercise10

Downloadthesourcecodeforthisexercisefromhttp://learncodingfast.com/css

Page 95: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

andunzipthefile.ThesourcecodeforthisexercisecanbefoundintheChapter10-Tablesfolder.

Exercise10.1

1.OpenthefileChapter10-Tables.htmlconcurrentlyinyourbrowserandtexteditor.

2.ModifytheCSSdeclarationfortableandobservewhathappenstothetable.Tryaddingthefollowingandobservewhathappensineachcase:

(a)padding:50px;(b)margin:30px;(c)border-collapse:collapse;(d)Changeborder:dashed1pxblack;toborder:solid2pxgreen;

3.ModifytheCSSdeclarationforthandobservewhathappenstothetable.Tryadding:

(a)padding:50px;(b)margin:30px;(Marginruleswillbeignored.Tryit)

Repeatthesamefortd.

4.RemovethepaddingandmarginpropertiesfromPart3forbothtdandth.ModifytheCSSdeclarationfortableandobservewhathappenstothetable.Tryaddingeachofthefollowing:

(a)width:300px;

(b)width:50%;Noticethatthewidthofthetableisnow50%oftheredbox.

(c)height:500px;

(d)height:80%;Noticethattheheightofthetableisnow80%oftheredbox.

Page 96: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

5.RemovetheheightandwidthpropertiesfortablefromPart4.ModifytheCSSdeclarationforthandobservewhathappenstothetable.Trychangingtheheightpropertyto:

(a)height:100px;

Removetheheightpropertyfromthandaddittotd.Noticewhathappens.Repeatthesamefortr.

6.ModifytheCSSdeclarationforthandobservewhathappenstothetable.Trychangingthewidthpropertyto:

(a)width:100px;

Removethewidthpropertyfromthandaddittotd.Noticewhathappens.Thereshouldbenodifferenceaswhetheryousetthewidthofatablecellatthethortdlevel,thatwidthwillaffectbothelements.

7.Addtheattributesid=”firstColumn”,id=”secondColumn”andid=”thirdColumn”tothefirst,secondandthird<th>starttagsrespectively.Next,addthefollowingCSSrulestoadjustthewidthofthethreecolumnsseparately:

#firstColumn{

width:100px;

}

#secondColumn{

width:200px;

}

#thirdColumn{

width:50px;

}

Refreshthepageandobservewhathappens.Tryadjustingthewidthwithdifferentvalues.

8.ModifytheCSSdeclarationfortrandobservewhathappenstothetable.Tryadding:

(a)text-align:center;(b)vertical-align:top;

Page 97: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Removetheabovepropertiesfromtrandaddthemtoth.Noticewhathappens.Repeatthesamefortd.Ifyoudonotseeanydifference,tryincreasingthewidthofthetableand/ortheheightoftherows.

9.ModifytheCSSdeclarationfortrandobservewhathappenstothetable.Tryadding:

(a)background-color:green;(b)color:white;

Removetheabovepropertiesfromtrandaddthemtoth.Noticewhathappens.

Now,removethepropertiesfromthandaddthemtotd.

10.Finally,let’strycoloringalternatingrows.Removethebackground-colorandcolorrulesfromtdfirst.Next,addthefollowingcodeandobservewhathappens.

tr:nth-child(even){

background-color:lightgreen;

}

tr:nth-child(odd){

background-color:lightgray;

}

Page 98: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

BonusProject

Congratulations!We’venowcoveredenoughfundamentalsofCSS(andHTML)tostartcodingourfirstwebpagefromscratch.ThebestwaytolearnCSSisbydoing.Hence,I’veincludedabonusprojectwiththisbookwhereyou’llbeguidedthroughthecodingofawebpageforafictitioustravelagency.Youcancheckoutthedemofortheprojectathttp://www.learncodingfast.com/demo/jetspeed.html.

InitiallyIintendedtoincludetheprojectattheendofthebook.However,giventhegraphicalnatureofCSS,Idecidedthatincludingalltheinstructionsandimagesfortheprojectinakindlebookisnotideal.Therefore,IcreatedaseparatePDFfilefortheprojectthatyoucandownloadathttp://learncodingfast.com/css.

Istronglyencourageyoutotrytheprojectasit’llgiveyouachancetoseehowalltheconceptsthatyou’velearntinthisbooktietogether.Workingthroughtheprojectwillhelpsolidifyyourlearningandfillallthegapsthatyoumayhave.

Havefuncoding!

Page 99: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

ThankYouWe’vecometotheendofthebook.ThankyouforreadingthisbookandIhopeyouhaveenjoyedthebook.Moreimportantly,IsincerelyhopethebookhashelpedyoumasterthefundamentalsofCSS.

IknowyoucouldhavepickedfromadozenofbooksonCSS,butyoutookachancewiththisbook.Thankyouonceagainfordownloadingthisbookandreadingallthewaytotheend.Pleasetrytheexercisesandthebonusproject.You’lllearnalotbydoing.

NowI’dliketoaskfora“small”favor.CouldyoupleasetakeaminuteortwotoleaveareviewforthisbookonAmazon?

Thisfeedbackwillhelpmetremendouslyandwillhelpmecontinuetowritemoreguidesonprogramming.Ifyoulikethebookorhaveanysuggestionsforimprovement,pleaseletmeknow.Iwillbedeeplygrateful.:)

Lastbutnotleast,rememberyoucandownloadthesourcecodefortheprojectandtheexercisesathttp://www.learncodingfast.com/css.

[email protected].

Page 100: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

AppendixA:SourceCodeforExercises

Exercise3.1

<!doctypehtml><html><head><title>Chapter3-BasicsofCSS</title><style>p{

background-color:yellow;

}

</style></head><body><h1>Chapter3-BasicsofCSS</h1><h2>CSSSelectors</h2>

<p>Thisexerciseusesbackgroundcolortohelpusfigureoutwhichelementweareselecting.Thisparagraphhasnoclassorid.</p>

<pid="myIDPara">Thisparagraphhasid="myIDPara".</p>

<pclass="myClassPara">Thisparagraphhasclass="myClassPara".</p>

<pclass="myClassParamySecondClassPara">Thisparagraphhasclass="myClassPara"andclass="mySecondClassPara".</p>

<div>Thisissometextinthedivelement.

<p>Thisparagraphisthefirstchildelementofthe'div'element.</p><p>Thisparagraphisthesecondchildelementofthe'div'element.</p><p>Thisparagraphisthethirdchildelementofthe'div'element.</p></div>

Page 101: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

<ahref="http://www.learncodingfast.com">LearnCodingFast</a><br><ahref="http://www.google.com">Google</a>

</body></html>

Page 102: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Exercise4.1

<!doctypehtml><html><head><title>Chapter4-CSSBoxModel</title><styletype="text/css">#box1{margin:20px;padding:10px;border:5pxsolidblack;width:100px;height:100px;text-align:justify;float:left;

}

#box2{margin:20px;padding:50px;border:5pxsolidblack;width:100px;height:100px;text-align:justify;float:left;

}

</style></head><body>

<divid="box1">LearnCSSinOneDayandLearnItWell.CSSiseasy.</div><divid="box2">LearnCSSinOneDayandLearnItWell.CSSiseasy.</div>

<p>skajdfhadlcvkasjcnlkajshvnaclaksjdclkasjdckasjcnkasdjvcnksamcnlkasdjnskajdfhadlcvkasjcnlkajshvnaclaksjdclkasjdckasjcnkasdjvcnksamcnlkasdjnskajdfhadlcvkasjcnlkajshvnaclaksjdclkasjdckasjcnkasdjvcnksamcnlkasdjn</p></body></html>

Page 103: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Exercise5.1

<!DOCTYPEhtml><html><head><title>Chapter5-Positioning</title><styletype="text/css">#box1{background-color:green;width:100px;height:100px;padding:10px;border:5pxsolidblack;margin:20px;

}

#box2{background-color:red;width:50px;height:50px;padding:20px;border:5pxdottedblack;margin:10px;

}

p{

}

</style></head><body><divid="box1"></div><divid="box2"></div><p>Thisissometextaddedtodemonstratetheconceptofoverlapping.</p></body></html>

Exercise5.2

Page 104: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

<!doctypehtml><html><head><title>Chapter5-Floating</title><styletype="text/css">div{

padding:10px;border:1pxdashedblack;margin:5px;float:left;

}

#box1{width:60px;height:100px;

}

#box2{width:100px;height:20px;

}

#box3{width:50px;height:150px;

}

#box4{width:20px;height:50px;

}

#box5{width:150px;height:120px;

Page 105: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

}

#box6{width:120px;

height:70px;

}

#box7{width:25px;height:80px;

}

</style></head>

<body><divid="box1">Box1</div><divid="box2">Box2</div><divid="box3">Box3</div><divid="box4">Box4</div><divid="box5">Box5</div><divid="box6">Box6</div><divid="box7">Box7</div>

</body></html>

Page 106: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Exercise6.1

<!doctypehtml><html><head><title>Chapter6-DisplayandVisibility</title><styletype="text/css">

#displaydemo{border:1pxdashedblack;

background-color:yellow;display:inline;width:100px;height:100px;

}

#magic{display:inline;

}

#magicsentence{color:blue;font-size:2em;

}

</style></head>

<body><p>This<spanid="displaydemo">yellowbox</span>isusedto

demonstratethedifferencebetweenaninlineandablockelement.</p><pid="magicsentence">"Thisisjustlike<spanid="magic">magic</span>.Youcanmakewordsdisappear."</p></body></html>

Page 107: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Exercise7.1

<!doctypehtml><html><head><title>Chapter7-Background</title><styletype="text/css">

body{background-color:white;background-image:url("learncodingfast.png");background-repeat:repeat-x;background-attachment:fixed;

}

#box1{width:100px;height:100px;background-repeat:no-repeat;background-color:blue;background-image:url("backgroundposition.png");backgroundposition:00;

}

#box2{height:1000px;

}

</style></head><body><divid="box1"></div><divid="box2"></div></body></html>

Page 108: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Exercise8.1

<!doctypehtml><html><head><title>Chapter8-FontandText</title>

<styletype="text/css">

#sampletext{width:300px;border:1pxsolidblack;padding:20px;font-family:Times,"TimesNewRoman",Georgia,serif;font-size:1em;font-style:normal;font-weight:normal;color:black;text-align:left;text-decoration:none;letter-spacing:0px;word-spacing:0px;line-height:1;

}

</style></head><body><h3>SampleText</h3><pid="sampletext">Thisparagraphoftextisusedtodemonstratetheeffectsofvariousfontandtextproperties.ModifytheCSSdeclarationfor"sampletext"andobservewhathappenstothisparagraphoftext.Aborderisgiventothisparagraphoftextinordertoshowtheeffectof'justify'.</p></body></html>

Page 109: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Exercise9.1

<!doctypehtml><html><head><title>Chapter9-ListsandLinks</title>

<styletype="text/css">

body{padding-left:20px;}div{font-weight:bold;text-decoration:underline;font-size:1.2em;padding-top:5px;}ol{list-style-type:decimal;

}

ul{list-style-type:disc;

}

a{text-decoration:none;}a:link{}a:visited{}a:hover{}a:active{}</style>

</head><body><div>StylingHTMLLists</div><p>ThissectionistodemonstratehowyoucanstyleorderedandunorderedlistsinCSS</p>CarsOrderedList<ol><li>Ford</li><li>Honda</li><li>Toyota</li>

Page 110: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

</ol>CarsUnorderedList<ul><li>Ford</li><li>Honda</li><li>Toyota</li></ul><hr><div>StylingHyperlinks</div><p>ThissectionistodemonstratehowyoucanstylehyperlinksinCSS</p><ahref="somepage.html">ClickMe</a></body></html>

Exercise9.2

<!DOCTYPEhtml><html><head><title>Chapter9-NavigationBar</title><style>ul{

list-style-type:none;

}

a{display:block;width:160px;text-align:center;text-decoration:none;background-color:#00FF00;

}

li{float:left;

Page 111: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

}

</style></head><body><ul>

<li><ahref="home.html">Home</a></li><li><ahref="htmltutorial.html">HTMLTutorial</a></li><li><ahref="csstutorial.html">CSSTutorial</a></li><li><ahref="javascripttutorial.html">JavascriptTutorial</a></li>

</ul></body></html>

Page 112: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

Exercise10.1

<!DOCTYPEhtml><html><head><title>Chapter10-Tables</title><style>div{width:100%;height:600px;border:redsolid1px;

}

table{border:dashed1pxblack;

}

th{border:solid1pxblack;

}

td{border:solid1pxblack;

}

tr{

}

</style></head><body>Thetablebelowisachildelementoftheredbox.Theredboxisaddedtoshow

Page 113: Learn CSS in One Day and Learn It Well: CSS for Beginners with Hands-on Project

theeffectsoftheheightandwidthpropertiesfor'table'.<br><br><div><table><tr><th>Firstname</th><th>Lastname</th><th>Age</th></tr><tr><td>Derek</td><td>Lee</td><td>24</td></tr><tr><td>Aaron</td><td>Flynn</td><td>16</td></tr><tr><td>Joe</td><td>Murphy</td><td>31</td></tr></table></div></body></html>