table of contents · table of contents preface introduction to css a brief history of css adding...

173

Upload: others

Post on 30-May-2020

18 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS
Page 2: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

TableofContentsPreface

IntroductiontoCSS

AbriefhistoryofCSS

AddingCSStoanHTMLpage

Selectors

Cascade

Specificity

Inheritance

Import

Attributeselectors

Pseudo-classes

Pseudo-elements

Colors

Units

url

calc

Backgrounds

Comments

CustomProperties

Fonts

Typography

BoxModel

Border

Padding

Margin

BoxSizing

Display

Positioning

Floatingandclearing

z-index

2

Page 3: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

CSSGrid

Flexbox

Tables

Centering

Lists

Mediaqueriesandresponsivedesign

FeatureQueries

Filters

Transforms

Transitions

Animations

NormalizingCSS

Errorhandling

Vendorprefixes

CSSforprint

3

Page 4: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Preface

Welcome!IwrotethisbooktohelpyouquicklylearnCSSandgetfamiliarwiththeadvancedCSStopics.

CSS,ashorthandforCascadingStyleSheets,isoneofthemainbuildingblocksoftheWeb.Itshistorygoesbacktothe90'sandalongwithHTMLithaschangedalotsinceitshumblebeginnings.

HavingcreatedwebsitessincebeforeCSSexisted,Ihaveseenitsevolution.

CSSisanamazingtool,andinthelastfewyearsithasgrownalot,introducingmanyfantasticfeatureslikeCSSGrid,FlexboxandCSSCustomProperties.

Thishandbookisaimedatavastaudience.

First,thebeginner.IexplainCSSfromzeroinasuccinctbutcomprehensiveway,soyoucanusethisbooktolearnCSSfromthebasics.

Then,theprofessional.CSSisoftenconsideredlikeasecondarythingtolearn,especiallybyJavaScriptdevelopers.TheyknowCSSisnotarealprogramminglanguage,theyareprogrammersandthereforetheyshouldnotbotherlearningCSStherightway.Iwrotethisbookforyou,too.

Next,thepersonthatknowsCSSfromafewyearsbuthasn'thadtheopportunitytolearnthenewthingsinit.We'lltalkextensivelyaboutthenewfeaturesofCSS,theonesthataregoingtobuildthewebofthenextdecade.

CSShasimprovedalotinthepastfewyearsandit'sevolvingfast.

Evenifyoudon'twriteCSSforaliving,knowinghowCSSworkscanhelpsaveyousomeheadacheswhenyouneedtounderstanditfromtimetotime,forexamplewhiletweakingawebpage.

Thankyouforgettingthisebook.MygoalwithitistogiveyouaquickyetcomprehensiveoverviewofCSS.

Flavio

[email protected],onTwitter@flaviocopes.

Mywebsiteisflaviocopes.com.

Preface

4

Page 5: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Preface

5

Page 6: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

IntroductiontoCSSCSS(anabbreviationofCascadingStyleSheets)isthelanguagethatweusetostyleanHTMLfile,andtellthebrowserhowshoulditrendertheelementsonthepage.

InthisbookItalkexclusivelyaboutstylingHTMLdocuments,althoughCSScanbeusedtostyleotherthingstoo.

ACSSfilecontainsseveralCSSrules.

Eachruleiscomposedby2parts:

theselectorthedeclarationblock

Theselectorisastringthatidentifiesoneormoreelementsonthepage,followingaspecialsyntaxthatwe'llsoontalkaboutextensively.

Thedeclarationblockcontainsoneormoredeclarations,inturncomposedbyapropertyandvaluepair.

ThoseareallthethingswehaveinCSS.

Carefullyorganisingproperties,associatingthemvalues,andattachingthosetospecificelementsofthepageusingaselectoristhewholeargumentofthisebook.

HowdoesCSSlooklikeACSSrulesethasonepartcalledselector,andtheotherpartcalleddeclaration.Thedeclarationcontainsvariousrules,eachcomposedbyaproperty,andavalue.

Inthisexample, pistheselector,andappliesonerulewhichsetsthevalue 20pxtothefont-sizeproperty:

p{

font-size:20px;

}

Multiplerulesarestackedoneaftertheother:

p{

font-size:20px;

}

a{

IntroductiontoCSS

6

Page 7: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

color:blue;

}

Aselectorcantargetoneormoreitems:

p,a{

font-size:20px;

}

anditcantargetHTMLtags,likeabove,orHTMLelementsthatcontainacertainclassattributewith .my-class,orHTMLelementsthathaveaspecific idattributewith #my-id.

Moreadvancedselectorsallowyoutochooseitemswhoseattributematchesaspecificvalue,oralsoitemswhichrespondtopseudo-classes(moreonthatlater)

SemicolonsEveryCSSruleterminateswithasemicolon.Semicolonsarenotoptional,exceptafterthelastrule,butIsuggesttoalwaysusethemforconsistencyandtoavoiderrorsifyouaddanotherpropertyandforgettoaddthesemicolononthepreviousline.

FormattingandindentationThereisnofixedruleforformatting.ThisCSSisvalid:

p

{

font-size:20px;

}

a{color:blue;}

butapaintosee.Sticktosomeconventions,liketheonesyouseeintheexamplesabove:stickselectorsandtheclosingbracketstotheleft,indent2spacesforeachrule,havetheopeningbracketonthesamelineoftheselector,separatedbyonespace.

Correctandconsistentuseofspacingandindentationisavisualaidinunderstandingyourcode.

IntroductiontoCSS

7

Page 8: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

IntroductiontoCSS

8

Page 9: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

AbriefhistoryofCSSBeforemovingon,IwanttogiveyouabriefrecapofthehistoryofCSS.

CSSwasgrownoutofthenecessityofstylingwebpages.BeforeCSSwasintroduced,peoplewantedawaytostyletheirwebpages,whichlookedallverysimilarand"academic"backintheday.Youcouldn'tdomuchintermsofpersonalisation.

HTML3.2introducedtheoptionofdefiningcolorsinlineasHTMLelementattributes,andpresentationaltagslike centerand font,butthatescalatedquicklyintoafarfromidealsituation.

CSSletusmoveeverythingpresentation-relatedfromtheHTMLtotheCSS,sothatHTMLcouldgetbackbeingtheformatthatdefinesthestructureofthedocument,ratherthanhowthingsshouldlookinthebrowser.

CSSiscontinuouslyevolving,andCSSyouused5yearsagomightjustbeoutdated,asnewidiomaticCSStechniquesemergedandbrowserschanged.

It'shardtoimaginethetimeswhenCSSwasbornandhowdifferentthewebwas.

Atthetime,wehadseveralcompetingbrowsers,themainonesbeingInternetExplorerorNetscapeNavigator.

PageswerestyledbyusingHTML,withspecialpresentationaltagslike boldandspecialattributes,mostofwhicharenowdeprecated.

Thismeantyouhadalimitedamountofcustomisationopportunities.

Thebulkofthestylingdecisionswerelefttothebrowser.

Also,youbuiltasitespecificallyforoneofthem,becauseeachoneintroduceddifferentnon-standardtagstogivemorepowerandopportunities.

Soonpeoplerealisedtheneedforawaytostylepages,inawaythatwouldworkacrossallbrowsers.

Aftertheinitialideaproposedin1994,CSSgotitsfirstreleasein1996,whentheCSSLevel1("CSS1")recommendationwaspublished.

CSSLevel2("CSS2")gotpublishedin1998.

Sincethen,workbeganonCSSLevel3.TheCSSWorkingGroupdecidedtospliteveryfeatureandworkonitseparately,inmodules.

AbriefhistoryofCSS

9

Page 10: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Browsersweren'tespeciallyfastatimplementingCSS.Wehadtowaituntil2002tohavethefirstbrowserimplementthefullCSSspecification:IEforMac,asnicelydescribedinthisCSSTrickspost:https://css-tricks.com/look-back-history-css/

InternetExplorerimplementedtheboxmodelincorrectlyrightfromthestart,whichledtoyearsofpaintryingtohavethesamestyleappliedconsistentlyacrossbrowsers.Wehadtousevarioustricksandhackstomakebrowsersrenderthingsaswewanted.

Todaythingsaremuch,muchbetter.WecanjustusetheCSSstandardswithoutthinkingaboutquirks,mostofthetime,andCSShasneverbeenmorepowerful.

Wedon'thaveofficialreleasenumbersforCSSanymorenow,buttheCSSWorkingGroupreleasesa"snapshot"ofthemodulesthatarecurrentlyconsideredstableandreadytobeincludedinbrowsers.Thisisthelatestsnapshot,from2018:https://www.w3.org/TR/css-2018/

CSSLevel2isstillthebasefortheCSSwewritetoday,andwehavemanymorefeaturesbuiltontopofit.

AbriefhistoryofCSS

10

Page 11: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

AddingCSStoanHTMLpageCSSisattachedtoanHTMLpageindifferentways.

1:Usingthe linktagThe linktagisthewaytoincludeaCSSfile.ThisisthepreferredwaytouseCSSasit'sintendedtobeused:oneCSSfileisincludedbyallthepagesofyoursite,andchangingonelineonthatfileaffectsthepresentationofallthepagesinthesite.

Tousethismethod,youadda linktagwiththe hrefattributepointingtotheCSSfileyouwanttoinclude.Youadditinsidethe headtagofthesite(notinsidethe bodytag):

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

The reland typeattributesarerequiredtoo,astheytellthebrowserwhichkindoffilewearelinkingto.

2:usingthe styletagInsteadofusingthe linktagtopointtoseparatestylesheetcontainingourCSS,wecanaddtheCSSdirectlyinsidea styletag.Thisisthesyntax:

<style>

...ourCSS...

</style>

UsingthismethodwecanavoidcreatingaseparateCSSfile.Ifindthisisagoodwaytoexperimentbefore"formalising"CSStoaseparatefile,ortoaddaspeciallineofCSSjusttoafile.

3:inlinestylesInlinestylesarethethirdwaytoaddCSStoapage.Wecanadda styleattributetoanyHTMLtag,andaddCSSintoit.

<divstyle="">...</div>

AddingCSStoanHTMLpage

11

Page 12: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Example:

<divstyle="background-color:yellow">...</div>

AddingCSStoanHTMLpage

12

Page 13: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

SelectorsAselectorallowsustoassociateoneormoredeclarationstooneormoreelementsonthepage.

BasicselectorsSupposewehavea pelementonthepage,andwewanttodisplaythewordsintoitusingtheyellowcolor.

Wecantargetthatelementusingthisselector p,whichtargetsalltheelementusingthe ptaginthepage.AsimpleCSSruletoachievewhatwewantis:

p{

color:yellow;

}

EveryHTMLtaghasacorrespondingselector,forexample: div, span, img.

Ifaselectormatchesmultipleelements,alltheelementsinthepagewillbeaffectedbythechange.

HTMLelementshave2attributeswhichareverycommonlyusedwithinCSStoassociatestylingtoaspecificelementonthepage: classand id.

Thereisonebigdifferencebetweenthosetwo:insideanHTMLdocumentyoucanrepeatthesame classvalueacrossmultipleelements,butyoucanonlyusean idonce.Asacorollary,usingclassesyoucanselectanelementwith2ormorespecificclassnames,somethingnotpossibleusingids.

Classesareidentifiedusingthe .symbol,whileidsusingthe #symbol.

Exampleusingaclass:

<pclass="dog-name">

Roger

</p>

.dog-name{

color:yellow;

}

Selectors

13

Page 14: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Exampleusinganid:

<pid="dog-name">

Roger

</p>

#dog-name{

color:yellow;

}

CombiningselectorsSofarwe'veseenhowtotargetanelement,aclassoranid.Let'sintroducemorepowerfulselectors.

Targetinganelementwithaclassorid

Youcantargetaspecificelementthathasaclass,orid,attached.

Exampleusingaclass:

<pclass="dog-name">

Roger

</p>

p.dog-name{

color:yellow;

}

Exampleusinganid:

<pid="dog-name">

Roger

</p>

p#dog-name{

color:yellow;

}

Whywouldyouwanttodothat,iftheclassoridalreadyprovidesawaytotargetthatelement?Youmighthavetodothattohavemorespecificity.We'llseewhatthatmeanslater.

Selectors

14

Page 15: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Targetingmultipleclasses

Youcantargetanelementwithaspecificclassusing .class-name,asyousawpreviously.Youcantargetanelementwith2(ormore)classesbycombiningtheclassnamesseparatedwithadot,withoutspaces.

Example:

<pclass="dog-nameroger">

Roger

</p>

.dog-name.roger{

color:yellow;

}

Combiningclassesandids

Inthesameway,youcancombineaclassandanid.

Example:

<pclass="dog-name"id="roger">

Roger

</p>

.dog-name#roger{

color:yellow;

}

GroupingselectorsYoucancombineselectorstoapplythesamedeclarationstomultipleselectors.Todoso,youseparatethemwithacomma.

Example:

<p>

Mydognameis:

</p>

<spanclass="dog-name">

Roger

</span>

Selectors

15

Page 16: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

p,.dog-name{

color:yellow;

}

Youcanaddspacesinthosedeclarationstomakethemmoreclear:

p,

.dog-name{

color:yellow;

}

FollowthedocumenttreewithselectorsWe'veseenhowtotargetanelementinthepagebyusingatagname,aclassoranid.

Youcancreateamorespecificselectorbycombiningmultipleitemstofollowthedocumenttreestructure.Forexample,ifyouhavea spantagnestedinsidea ptag,youcantargetthatonewithoutapplyingthestyletoa spantagnotincludedina ptag:

<span>

Hello!

</span>

<p>

Mydognameis:

<spanclass="dog-name">

Roger

</span>

</p>

pspan{

color:yellow;

}

Seehowweusedaspacebetweenthetwotokens pand span.

Thisworkseveniftheelementontherightismultiplelevelsdeep.

Tomakethedependencystrictonthefirstlevel,youcanusethe >symbolbetweenthetwotokens:

p>span{

color:yellow;

}

Selectors

16

Page 17: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Inthiscase,ifa spanisnotafirstchildrenofthe pelement,it'snotgoingtohavethenewcolorapplied.

Directchildrenwillhavethestyleapplied:

<p>

<span>

Thisisyellow

</span>

<strong>

<span>

Thisisnotyellow

</span>

</strong>

</p>

Adjacentsiblingselectorsletusstyleanelementonlyifprecededbyaspecificelement.Wedosousingthe +operator:

Example:

p+span{

color:yellow;

}

Thiswillassignthecoloryellowtoallspanelementsprecededbya pelement:

<p>Thisisaparagraph</p>

<span>Thisisayellowspan</span>

Wehavealotmoreselectorswecanuse:

attributeselectorspseudoclassselectorspseudoelementselectors

We'llfindallabouttheminthenextsections.

Selectors

17

Page 18: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

CascadeCascadeisafundamentalconceptofCSS.Afterall,it'sinthenameitself,thefirstCofCSS-CascadingStyleSheets-itmustbeanimportantthing.

Whatdoesitmean?

Cascadeistheprocess,oralgorithm,thatdeterminesthepropertiesappliedtoeachelementonthepage.TryingtoconvergefromalistofCSSrulesthataredefinedinvariousplaces.

Itdoessotakinginconsideration:

specificityimportanceinheritanceorderinthefile

Italsotakescareofresolvingconflicts.

TwoormorecompetingCSSrulesforthesamepropertyappliedtothesameelementneedtobeelaboratedaccordingtotheCSSspec,todeterminewhichoneneedstobeapplied.

EvenifyoujusthaveoneCSSfileloadedbyyourpage,thereisotherCSSthatisgoingtobepartoftheprocess.Wehavethebrowser(useragent)CSS.Browserscomewithadefaultsetofrules,alldifferentbetweenbrowsers.

ThenyourCSScomeintoplay.

Thenthebrowserappliesanyuserstylesheet,whichmightalsobeappliedbybrowserextensions.

Allthoserulescomeintoplaywhilerenderingthepage.

We'llnowseetheconceptsofspecificityandinheritance.

Cascade

18

Page 19: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

SpecificityWhathappenswhenanelementistargetedbymultiplerules,withdifferentselectors,thataffectthesameproperty?

Forexample,let'stalkaboutthiselement:

<pclass="dog-name">

Roger

</p>

Wecanhave

.dog-name{

color:yellow;

}

andanotherrulethattargets p,whichsetsthecolortoanothervalue:

p{

color:red;

}

Andanotherrulethattargets p.dog-name.Whichruleisgoingtotakeprecedenceovertheothers,andwhy?

Enterspecificity.Themorespecificrulewillwin.Iftwoormoreruleshavethesamespecificity,theonethatappearslastwins.

Sometimeswhatismorespecificinpracticeisabitconfusingtobeginners.Iwouldsayit'salsoconfusingtoexpertsthatdonotlookatthoserulesthatfrequently,orsimplyoverlookthem.

HowtocalculatespecificitySpecificityiscalculatedusingaconvention.

Wehave4slots,andeachoneofthemstartsat0: 00000.Theslotattheleftisthemostimportant,andtherightmostoneistheleastimportant.

Likeitworksfornumbersinthedecimalsystem: 1000ishigherthan 0100.

Specificity

19

Page 20: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Slot1

Thefirstslot,therightmostone,istheleastimportant.

Weincreasethisvaluewhenwehaveanelementselector.Anelementisatagname.Ifyouhavemorethanoneelementselectorintherule,youincrementaccordinglythevaluestoredinthisslot.

Examples:

p{}/*0001*/

span{}/*0001*/

pspan{}/*0002*/

p>span{}/*0002*/

divp>span{}/*0003*/

Slot2

Thesecondslotisincrementedby3things:

classselectorspseudo-classselectorsattributeselectors

Everytimearulemeetsoneofthose,weincrementthevalueofthesecondcolumnfromtheright.

Examples:

.name{}/*0010*/

.users.name{}/*0020*/

[href$='.pdf']{}/*0010*/

:hover{}/*0010*/

Ofcourseslot2selectorscanbecombinedwithslot1selectors:

div.name{}/*0011*/

a[href$='.pdf']{}/*0011*/

.picturesimg:hover{}/*0021*/

Onenicetrickwithclassesisthatyoucanrepeatthesameclassandincreasethespecificity.Forexample:

.name{}/*0010*/

.name.name{}/*0020*/

.name.name.name{}/*0030*/

Specificity

20

Page 21: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Slot3

Slot3holdsthemostimportantthingthatcanaffectyourCSSspecificityinaCSSfile:theid.

Everyelementcanhavean idattributeassigned,andwecanusethatinourstylesheettotargettheelement.

Examples:

#name{}/*0100*/

.user#name{}/*0110*/

#namespan{}/*0101*/

Slot4

Slot4isaffectedbyinlinestyles.AnyinlinestylewillhaveprecedenceoveranyruledefinedinanexternalCSSfile,orinsidethe styletaginthepageheader.

Example:

<pstyle="color:red">Test</p>/*1000*/

EvenifanyotherruleintheCSSdefinesthecolor,thisinlinestyleruleisgoingtobeapplied.Exceptforonecase-if !importantisused,whichfillstheslot5.

ImportanceSpecificitydoesnotmatterifaruleendswith !important:

p{

font-size:20px!important;

}

Thatrulewilltakeprecedenceoveranyrulewithmorespecificity

Adding !importantinaCSSruleisgoingtomakethatrulebemoreimportantthananyotherrule,accordingtothespecificityrules.Theonlywayanotherrulecantakeprecedenceistohave !importantaswell,andhavehigherspecificityintheotherlessimportantslots.

Tips

Specificity

21

Page 22: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Ingeneralyoushouldusetheamountofspecificityyouneed,butnotmore.Inthisway,youcancraftotherselectorstooverwritetherulessetbyprecedingruleswithoutgoingmad.

!importantisahighlydebatedtoolthatCSSoffersus.ManyCSSexpertsadvocateagainstusingit.IfindmyselfusingitespeciallywhentryingoutsomestyleandaCSSrulehassomuchspecificitythatIneedtouse !importanttomakethebrowserapplymynewCSS.

Butgenerally, !importantshouldhavenoplaceinyourCSSfiles.

Usingthe idattributetostyleCSSisalsodebatedalot,sinceithasaveryhighspecificity.Agoodalternativeistouseclassesinstead,whichhavelessspecificity,andsotheyareeasiertoworkwith,andtheyaremorepowerful(youcanhavemultipleclassesforanelement,andaclasscanbereusedmultipletimes).

ToolstocalculatethespecificityYoucanusethesitehttps://specificity.keegan.st/toperformthespecificitycalculationforyouautomatically.

It'susefulespeciallyifyouaretryingtofigurethingsout,asitcanbeanicefeedbacktool.

Specificity

22

Page 23: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

InheritanceWhenyousetsomepropertiesonaselectorinCSS,theyareinheritedbyallthechildrenofthatselector.

Isaidsome,becausenotallpropertiesshowthisbehaviour.

Thishappensbecausesomepropertiesmakesensetobeinherited.ThishelpsuswriteCSSmuchmoreconcisely,sincewedon'thavetoexplicitlysetthatpropertyagainoneverysinglechildren.

Someotherpropertiesmakemoresensetonotbeinherited.

Thinkaboutfonts:youdon'tneedtoapplythe font-familytoeverysingletagofyourpage.Yousetthe bodytagfont,andeverychildreninheritsit,alongwithotherproperties.

The background-colorproperty,ontheotherhand,makeslittlesensetobeinherited.

PropertiesthatinheritHereisalistofthepropertiesthatdoinherit.Thelistisnon-comprehensive,butthoserulesarejustthemostpopularonesyou'lllikelyuse:

border-collapseborder-spacingcaption-sidecolorcursordirectionempty-cellsfont-familyfont-sizefont-stylefont-variantfont-weightfont-size-adjustfont-stretchfontletter-spacingline-heightlist-style-image

Inheritance

23

Page 24: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

list-style-positionlist-style-typelist-styleorphansquotestab-sizetext-aligntext-align-lasttext-decoration-colortext-indenttext-justifytext-shadowtext-transformvisibilitywhite-spacewidowsword-breakword-spacing

IgotitfromthisniceSitepointarticleonCSSinheritance.

ForcingpropertiestoinheritWhatifyouhaveapropertythat'snotinheritedbydefault,andyouwantitto,inachildren?

Inthechildren,yousetthepropertyvaluetothespecialkeyword inherit.

Example:

body{

background-color:yellow;

}

p{

background-color:inherit;

}

ForcingpropertiestoNOTinheritOnthecontrary,youmighthaveapropertyinheritedandyouwanttoavoidso.

Inheritance

24

Page 25: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Youcanusethe revertkeywordtorevertit.Inthiscase,thevalueisrevertedtotheoriginalvaluethebrowsergaveitinitsdefaultstylesheet.

Inpracticethisisrarelyused,andmostofthetimesyou'lljustsetanothervalueforthepropertytooverwritethatinheritedvalue.

OtherspecialvaluesInadditiontothe inheritand revertspecialkeywordswejustsaw,youcanalsosetanypropertyto:

initial:usethedefaultbrowserstylesheetifavailable.Ifnot,andifthepropertyinheritsbydefault,inheritthevalue.Otherwisedonothing.unset:ifthepropertyinheritsbydefault,inherit.Otherwisedonothing.

Inheritance

25

Page 26: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

ImportFromanyCSSfileyoucanimportanotherCSSfileusingthe @importdirective.

Hereishowyouuseit:

@importurl(myfile.css)

url()canmanageabsoluteorrelativeURLs.

Oneimportantthingyouneedtoknowisthat @importdirectivesmustbeputbeforeanyotherCSSinthefile,ortheywillbeignored.

YoucanusemediadescriptorstoonlyloadaCSSfileonthespecificmedia:

@importurl(myfile.css)all;

@importurl(myfile-screen.css)screen;

@importurl(myfile-print.css)print;

Import

26

Page 27: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

AttributeselectorsWealreadyintroducedseveralofthebasicCSSselectors:usingelementselectors,class,id,howtocombinethem,howtotargetmultipleclasses,howtostyleseveralselectorsinthesamerule,howtofollowthepagehierarchywithchildanddirectchildselectors,andadjacentsiblings.

Inthissectionwe'llanalyzeattributeselectors,andwe'lltalkaboutpseudoclassandpseudoelementselectorsinthenext2sections.

AttributepresenceselectorsThefirstselectortypeistheattributepresenceselector.

Wecancheckifanelementhasanattributeusingthe []syntax. p[id]willselectall ptagsinthepagethathavean idattribute,regardlessofitsvalue:

p[id]{

/*...*/

}

ExactattributevalueselectorsInsidethebracketsyoucanchecktheattributevalueusing =,andtheCSSwillbeappliedonlyiftheattributematchestheexactvaluespecified:

p[id="my-id"]{

/*...*/

}

MatchanattributevalueportionWhile =letuscheckforexactvalue,wehaveotheroperators:

*=checksiftheattributecontainsthepartial̂ =checksiftheattributestartswiththepartial$=checksiftheattributeendswiththepartial|=checksiftheattributestartswiththepartialandit'sfollowedbyadash(commoninclasses,forexample),orjustcontainsthepartial

Attributeselectors

27

Page 28: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

~=checksifthepartialiscontainedintheattribute,butseparatedbyspacesfromtherest

Allthecheckswementionedarecasesensitive.

Ifyouaddan ijustbeforetheclosingbracket,thecheckwillbecaseinsensitive.It'ssupportedinmanybrowsersbutnotinall,checkhttps://caniuse.com/#feat=css-case-insensitive.

Attributeselectors

28

Page 29: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Pseudo-classesPseudoclassesarepredefinedkeywordsthatareusedtoselectanelementbasedonitsstate,ortotargetaspecificchild.

Theystartwithasinglecolon :.

Theycanbeusedaspartofaselector,andtheyareveryusefultostyleactiveorvisitedlinksforexample,changethestyleonhover,focus,ortargetthefirstchild,oroddrows.Veryhandyinmanycases.

Thesearethemostpopularpseudoclassesyouwilllikelyuse:

Pseudoclass Targets

:activeanelementbeingactivatedbytheuser(e.g.clicked).Mostlyusedonlinksorbuttons

:checked acheckbox,optionorradioinputtypesthatareenabled

:default thedefaultinasetofchoices(like,optioninaselectorradiobuttons)

:disabled anelementdisabled

:empty anelementwithnochildren

:enabled anelementthat'senabled(oppositeto :disabled)

:first-

child thefirstchildofagroupofsiblings

:focus theelementwithfocus

:hover anelementhoveredwiththemouse

:last-child thelastchildofagroupofsiblings

:link alinkthat'snotbeenvisited

:not() anyelementnotmatchingtheselectorpassed.E.g. :not(span)

:nth-

child() anelementmatchingthespecifiedposition

:nth-last-

child() anelementmatchingthespecificposition,startingfromtheend

:only-child anelementwithoutanysiblings

:required aformelementwiththe requiredattributeset

:root

representsthe htmlelement.It'sliketargeting html,butit'smorespecific.UsefulinCSSVariables.

:targettheelementmatchingthecurrentURLfragment(forinnernavigationinthepage)

Pseudo-classes

29

Page 30: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

:valid formelementsthatvalidatedclient-sidesuccessfully

:visited alinkthat'sbeenvisited

Let'sdoanexample.Acommonone,actually.Youwanttostylealink,soyoucreateaCSSruletotargetthe aelement:

a{

color:yellow;

}

Thingsseemtoworkfine,untilyouclickonelink.Thelinkgoesbacktothepredefinedcolor(blue)whenyouclickit.Thenwhenyouopenthelinkandgobacktothepage,nowthelinkisblue.

Whydoesthathappen?

Becausethelinkwhenclickedchangesstate,andgoesinthe :activestate.Andwhenit'sbeenvisited,itisinthe :visitedstate.Forever,untiltheuserclearsthebrowsinghistory.

So,tocorrectlymakethelinkyellowacrossallstates,youneedtowrite

a,

a:visited,

a:active{

color:yellow;

}

:nth-child()deservesaspecialmention.Itcanbeusedtotargetoddorevenchildrenwith:nth-child(odd)and :nth-child(even).

Itiscommonlyusedinliststocoloroddlinesdifferentlyfromevenlines:

ul:nth-child(odd){

color:white;

background-color:black;

}

Youcanalsouseittotargetthefirst3childrenofanelementwith :nth-child(-n+3).Oryoucanstyle1inevery5elementswith :nth-child(5n).

Somepseudoclassesarejustusedforprinting,like :first, :left, :right,soyoucantargetthefirstpage,alltheleftpages,andalltherightpages,whichareusuallystyledslightlydifferently.

Pseudo-classes

30

Page 31: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Pseudo-classes

31

Page 32: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Pseudo-elementsPseudo-elementsareusedtostyleaspecificpartofanelement.

Theystartwithadoublecolon ::.

Sometimesyouwillspottheminthewildwithasinglecolon,butthisisonlyasyntaxsupportedforbackwardscompatibilityreasons.Youshoulduse2colonstodistinguishthemfrompseudo-classes.

::beforeand ::afterareprobablythemostusedpseudo-elements.Theyareusedtoaddcontentbeforeorafteranelement,likeiconsforexample.

Here'sthelistofthepseudo-elements:

Pseudo-element Targets

::after createsapseudo-elementaftertheelement

::before createsapseudo-elementbeforetheelement

::first-letter canbeusedtostylethefirstletterofablockoftext

::first-line canbeusedtostylethefirstlineofablockoftext

::selection targetsthetextselectedbytheuser

Let'sdoanexample.Sayyouwanttomakethefirstlineofaparagraphslightlybiggerinfontsize,acommonthingintypography:

p::first-line{

font-size:2rem;

}

Ormaybeyouwantthefirstlettertobebolder:

p::first-letter{

font-weight:bolder;

}

::afterand ::beforeareabitlessintuitive.IrememberusingthemwhenIhadtoaddiconsusingCSS.

Youspecifythe contentpropertytoinsertanykindofcontentafterorbeforeanelement:

p::before{

content:url(/myimage.png);

}

Pseudo-elements

32

Page 33: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

.myElement::before{

content:"HeyHey!";

}

Pseudo-elements

33

Page 34: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

ColorsBydefaultanHTMLpageisrenderedbywebbrowsersquitesadlyintermsofthecolorsused.

Wehaveawhitebackground,blackcolor,andbluelinks.That'sit.

LuckilyCSSgivesustheabilitytoaddcolorstoourdesigns.

Wehavetheseproperties:

color

background-color

border-color

Allofthemacceptacolorvalue,whichcanbeindifferentforms.

NamedcolorsFirst,wehaveCSSkeywordsthatdefinecolors.CSSstartedwith16,buttodaythereisahugenumberofcolorsnames:

aliceblue

antiquewhite

aqua

aquamarine

azure

beige

bisque

black

blanchedalmond

blue

blueviolet

brown

burlywood

cadetblue

chartreuse

chocolate

coral

cornflowerblue

cornsilk

crimson

Colors

34

Page 35: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

cyan

darkblue

darkcyan

darkgoldenrod

darkgray

darkgreen

darkgrey

darkkhaki

darkmagenta

darkolivegreen

darkorange

darkorchid

darkred

darksalmon

darkseagreen

darkslateblue

darkslategray

darkslategrey

darkturquoise

darkviolet

deeppink

deepskyblue

dimgray

dimgrey

dodgerblue

firebrick

floralwhite

forestgreen

fuchsia

gainsboro

ghostwhite

gold

goldenrod

gray

green

greenyellow

grey

honeydew

hotpink

indianred

Colors

35

Page 36: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

indigo

ivory

khaki

lavender

lavenderblush

lawngreen

lemonchiffon

lightblue

lightcoral

lightcyan

lightgoldenrodyellow

lightgray

lightgreen

lightgrey

lightpink

lightsalmon

lightseagreen

lightskyblue

lightslategray

lightslategrey

lightsteelblue

lightyellow

lime

limegreen

linen

magenta

maroon

mediumaquamarine

mediumblue

mediumorchid

mediumpurple

mediumseagreen

mediumslateblue

mediumspringgreen

mediumturquoise

mediumvioletred

midnightblue

mintcream

mistyrose

moccasin

Colors

36

Page 37: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

navajowhite

navy

oldlace

olive

olivedrab

orange

orangered

orchid

palegoldenrod

palegreen

paleturquoise

palevioletred

papayawhip

peachpuff

peru

pink

plum

powderblue

purple

rebeccapurple

red

rosybrown

royalblue

saddlebrown

salmon

sandybrown

seagreen

seashell

sienna

silver

skyblue

slateblue

slategray

slategrey

snow

springgreen

steelblue

tan

teal

thistle

Colors

37

Page 38: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

tomato

turquoise

violet

wheat

white

whitesmoke

yellow

yellowgreen

plus tranparent,and currentColorwhichpointstothe colorproperty,forexampleusefultomakethe border-colorinheritit.

TheyaredefinedintheCSSColorModule,Level4.Theyarecaseinsensitive.

Wikipediahasanicetablewhichletsyoupicktheperfectcolorbyitsname.

Namedcolorsarenottheonlyoption.

RGBandRGBaYoucanusethe rgb()functiontocalculateacolorfromitsRGBnotation,whichsetsthecolorbasedonitsred-green-blueparts.From0to255:

p{

color:rgb(255,255,255);/*white*/

background-color:rgb(0,0,0);/*black*/

}

rgba()letsyouaddthealphachanneltoenteratransparentpart.Thatcanbeanumberfrom0to1:

p{

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

}

HexadecimalnotationAnotheroptionistoexpresstheRGBpartsofthecolorsinthehexadecimalnotation,whichiscomposedby3blocks.

Black,whichis rgb(0,0,0)isexpressedas #000000or #000(wecanshortcutthe2numbersto1iftheyareequal).

Colors

38

Page 39: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

White, rgb(255,255,255)canbeexpressedas #ffffffor #fff.

Thehexadecimalnotationletsexpressanumberfrom0to255injust2digits,sincetheycangofrom0to"15"(f).

Wecanaddthealphachannelbyadding1or2moredigitsattheend,forexample#00000033.Notallbrowserssupporttheshortenednotation,souseall6digitstoexpresstheRGBpart.

HSLandHSLaThisisamorerecentadditiontoCSS.

HSL=HueSaturationLightness.

Inthisnotation,blackis hsl(0,0%,0%)andwhiteis hsl(0,0%,100%).

IfyouaremorefamiliarwithHSLthanRGBbecauseofyourpastknowledge,youcandefinitelyusethat.

Youalsohave hsla()whichaddsthealphachanneltothemix,againanumberfrom0to1:hsl(0,0%,0%,0.5)

Colors

39

Page 40: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

UnitsOneofthethingsyou'lluseeverydayinCSSareunits.Theyareusedtosetlengths,paddings,margins,alignelementsandsoon.

Thingslike px, em, rem,orpercentages.

Theyareeverywhere.Therearesomeobscureones,too.We'llgothrougheachoftheminthissection.

PixelsThemostwidelyusedmeasurementunit.Apixeldoesnotactuallycorrelatetoaphysicalpixelonyourscreen,asthatvaries,alot,bydevice(thinkhigh-DPIdevicesvsnon-retinadevices).

Thereisaconventionthatmakethisunitworkconsistentlyacrossdevices.

PercentagesAnotherveryusefulmeasure,percentagesletyouspecifyvaluesinpercentagesofthatparentelement'scorrespondingproperty.

Example:

.parent{

width:400px;

}

.child{

width:50%;/*=200px*/

}

Real-worldmeasurementunitsWehavethosemeasurementunitswhicharetranslatedfromtheoutsideworld.Mostlyuselessonscreen,theycanbeusefulforprintstylesheets.Theyare:

cmacentimeter(mapsto37.8pixels)mmamillimeter(0.1cm)qaquarterofamillimeterinaninch(mapsto96pixels)

Units

40

Page 41: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

ptapoint(1inch=72points)pcapica(1pica=12points)

Relativeunitsemisthevalueassignedtothatelement's font-size,thereforeitsexactvaluechangesbetweenelements.Itdoesnotchangedependingonthefontused,justonthefontsize.Intypographythismeasuresthewidthofthe mletter.remissimilarto em,butinsteadofvaryingonthecurrentelementfontsize,itusestherootelement( html)fontsize.Yousetthatfontsizeonce,and remwillbeaconsistentmeasureacrossallthepage.exislike em,butinsertedofmeasuringthewidthof m,itmeasurestheheightofthexletter.Itcanchangedependingonthefontused,andonthefontsize.chislike exbutinsteadofmeasuringtheheightof xitmeasuresthewidthof 0(zero).

Viewportunitsvwtheviewportwidthunitrepresentsapercentageoftheviewportwidth. 50vwmeans50%oftheviewportwidth.vhtheviewportheightunitrepresentsapercentageoftheviewportheight. 50vhmeans50%oftheviewportheight.vmintheviewportminimumunitrepresentstheminimumbetweentheheightorwidthintermsofpercentage. 30vministhe30%ofthecurrentwidthorheight,dependingwhichoneissmallervmaxtheviewportmaximumunitrepresentsthemaximumbetweentheheightorwidthintermsofpercentage. 30vmaxisthe30%ofthecurrentwidthorheight,dependingwhichoneisbigger

Fractionunitsfrarefractionunits,andtheyareusedinCSSGridtodividespaceintofractions.

We'lltalkabouttheminthecontextofCSSGridlateron.

Units

41

Page 42: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

urlWhenwetalkaboutbackgroundimages, @import,andmore,weusethe url()functiontoloadaresource:

div{

background-image:url(test.png);

}

InthiscaseIusedarelativeURL,whichsearchesthefileinthefolderwheretheCSSfileisdefined.

Icouldgoonelevelback

div{

background-image:url(../test.png);

}

orgointoafolder

div{

background-image:url(subfolder/test.png);

}

OrIcouldloadafilestartingfromtherootofthedomainwheretheCSSishosted:

div{

background-image:url(/test.png);

}

OrIcoulduseanabsoluteURLtoloadanexternalresource:

div{

background-image:url(https://mysite.com/test.png);

}

url

42

Page 43: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

calcThe calc()functionletsyouperformbasicmathoperationsonvalues,andit'sespeciallyusefulwhenyouneedtoaddorsubtractalengthvaluefromapercentage.

Thisishowitworks:

div{

max-width:calc(80%-100px)

}

Itreturnsalengthvalue,soitcanbeusedanywhereyouexpectapixelvalue.

Youcanperform

additionsusing +subtractionsusing -multiplicationusing *divisionusing /

Onecaveat:withadditionandsubtraction,thespacearoundtheoperatorismandatory,otherwiseitdoesnotworkasexpected.

Examples:

div{

max-width:calc(50%/3)

}

div{

max-width:calc(50%+3px)

}

calc

43

Page 44: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

BackgroundsThebackgroundofanelementcanbechangedusingseveralCSSproperties:

background-color

background-image

background-clip

background-position

background-origin

background-repeat

background-attachment

background-size

andtheshorthandproperty background,whichallowstoshortendefinitionsandgroupthemonasingleline.

background-coloracceptsacolorvalue,whichcanbeoneofthecolorkeywords,oran rgbor hslvalue:

p{

background-color:yellow;

}

div{

background-color:#333;

}

Insteadofusingacolor,youcanuseanimageasbackgroundtoanelement,byspecifyingtheimagelocationURL:

div{

background-image:url(image.png);

}

background-clipletsyoudeterminetheareausedbythebackgroundimage,orcolor.Thedefaultvalueis border-box,whichextendsuptotheborderouteredge.

Othervaluesare

padding-boxtoextendthebackgrounduptothepaddingedge,withoutthebordercontent-boxtoextendthebackgrounduptothecontentedge,withoutthepaddinginherittoapplythevalueoftheparent

Backgrounds

44

Page 45: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Whenusinganimageasbackgroundyouwillwanttosetthepositionoftheimageplacementusingthe background-positionproperty: left, right, centerareallvalidvaluesfortheXaxis,and top, bottomfortheYaxis:

div{

background-position:topright;

}

Iftheimageissmallerthanthebackground,youneedtosetthebehaviorusing background-repeat.Shouldit repeat-x, repeat-yor repeatonalltheaxis?Thislastoneisthedefaultvalue.Anothervalueis no-repeat.

background-originletsyouchoosewherethebackgroundshouldbeapplied:totheentireelementincludingpadding(default)using padding-box,totheentireelementincludingtheborderusing border-box,totheelementwithoutthepaddingusing content-box.

With background-attachmentwecanattachthebackgroundtotheviewport,sothatscrollingwillnotaffectthebackground:

div{

background-attachment:fixed;

}

Bydefaultthevalueis scroll.Thereisanothervalue, local.ThebestwaytovisualizetheirbehavioristhisCodepen.

Thelastbackgroundpropertyis background-size.Wecanuse3keywords: auto, coverandcontain. autoisthedefault.

coverexpandstheimageuntiltheentireelementiscoveredbythebackground.

containstopsexpandingthebackgroundimagewhenonedimension(xory)coversthewholesmallestedgeoftheimage,soit'sfullycontainedintotheelement.

Youcanalsospecifyalengthvalue,andifsoitsetsthewidthofthebackgroundimage(andtheheightisautomaticallydefined):

div{

background-size:100%;

}

Ifyouspecify2values,oneisthewidthandthesecondistheheight:

div{

background-size:800px600px;

Backgrounds

45

Page 46: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

}

Theshorthandproperty backgroundallowstoshortendefinitionsandgroupthemonasingleline.

Thisisanexample:

div{

background:url(bg.png)topleftno-repeat;

}

Ifyouuseanimage,andtheimagecouldnotbeloaded,youcansetafallbackcolor:

div{

background:url(image.png)yellow;

}

Youcanalsosetagradientasbackground:

div{

background:linear-gradient(#fff,#333);

}

Backgrounds

46

Page 47: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

CommentsCSSgivesyoutheabilitytowritecommentsinaCSSfile,orinthe styletaginthepageheader

Theformatisthe /*thisisacomment*/C-style(orJavaScript-style,ifyouprefer)comments.

Thisisamultilinecomment.Untilyouaddtheclosing */token,theallthelinesfoundaftertheopeningonearecommented.

Example:

#name{display:block;}/*Nicerule!*/

/*#name{display:block;}*/

#name{

display:block;/*

color:red;

*/

}

CSSdoesnothaveinlinecomments,like //inCorJavaScript.

Payattentionthough-ifyouadd //beforearule,therulewillnotbeapplied,lookinglikethecommentworked.Inreality,CSSdetectedasyntaxerrorandduetohowitworksitignoredthelinewiththeerror,andwentstraighttothenextline.

Knowingthisapproachletsyoupurposefullywriteinlinecomments,althoughyouhavetobecarefulbecauseyoucan'taddrandomtextlikeyoucaninablockcomment.

Forexample:

//Nicerule!

#name{display:block;}

Inthiscase,duetohowCSSworks,the #nameruleisactuallycommentedout.Youcanfindmoredetailshereifyoufindthisinteresting.Toavoidshootingyourselfinthefoot,justavoidusinginlinecommentsandrelyonblockcomments.

Comments

47

Page 48: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

CustomPropertiesInthelastfewyearsCSSpreprocessorshadalotofsuccess.ItwasverycommonforgreenfieldprojectstostartwithLessorSass.Andit'sstillaverypopulartechnology.

Themainbenefitsofthosetechnologiesare,inmyopinion:

TheyallowtonestselectorsTheprovideaneasyimportsfunctionalityTheygiveyouvariables

ModernCSShasanewpowerfulfeaturecalledCSSCustomProperties,alsocommonlyknownasCSSVariables.

CSSisnotaprogramminglanguagelikeJavaScript,Python,PHP,RubyorGowherevariablesarekeytodosomethinguseful.CSSisverylimitedinwhatitcando,andit'smainlyadeclarativesyntaxtotellbrowsershowtheyshoulddisplayanHTMLpage.

Butavariableisavariable:anamethatreferstoavalue,andvariablesinCSShelpsreducerepetitionandinconsistenciesinyourCSS,bycentralizingthevaluesdefinition.

AnditintroducesauniquefeaturethatCSSpreprocessorswon'tneverhave:youcanaccessandchangethevalueofaCSSVariableprogrammaticallyusingJavaScript.

ThebasicsofusingvariablesACSSVariableisdefinedwithaspecialsyntax,prependingtwodashestoaname( --variable-name),thenacolonandavalue.Likethis:

:root{

--primary-color:yellow;

}

(moreon :rootlater)

Youcanaccessthevariablevalueusing var():

p{

color:var(--primary-color)

}

ThevariablevaluecanbeanyvalidCSSvalue,forexample:

CustomProperties

48

Page 49: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

:root{

--default-padding:30px30px20px20px;

--default-color:red;

--default-background:#fff;

}

CreatevariablesinsideanyelementCSSVariablescanbedefinedinsideanyelement.Someexamples:

:root{

--default-color:red;

}

body{

--default-color:red;

}

main{

--default-color:red;

}

p{

--default-color:red;

}

span{

--default-color:red;

}

a:hover{

--default-color:red;

}

Whatchangesinthosedifferentexamplesisthescope.

VariablesscopeAddingvariablestoaselectormakesthemavailabletoallthechildrenofit.

Intheexampleaboveyousawtheuseof :rootwhendefiningaCSSvariable:

:root{

--primary-color:yellow;

}

:rootisaCSSpseudo-classthatidentifiestherootelementofatree.

CustomProperties

49

Page 50: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

InthecontextofanHTMLdocument,usingthe :rootselectorpointstothe htmlelement,exceptthat :roothashigherspecificity(takespriority).

InthecontextofanSVGimage, :rootpointstothe svgtag.

AddingaCSScustompropertyto :rootmakesitavailabletoalltheelementsinthepage.

Ifyouaddavariableinsidea .containerselector,it'sonlygoingtobeavailabletochildrenof.container:

.container{

--secondary-color:yellow;

}

andusingitoutsideofthiselementisnotgoingtowork.

Variablescanbereassigned:

:root{

--primary-color:yellow;

}

.container{

--primary-color:blue;

}

Outside .container, --primary-colorwillbeyellow,butinsideitwillbeblue.

YoucanalsoassignoroverwriteavariableinsidetheHTMLusinginlinestyles:

<mainstyle="--primary-color:orange;">

<!--...-->

</main>

CSSVariablesfollowthenormalCSScascadingrules,withprecedencesetaccordingtospecificity

InteractingwithaCSSVariablevalueusingJavaScriptThecoolestthingwithCSSVariablesistheabilitytoaccessandeditthemusingJavaScript.

Here'showyousetavariablevalueusingplainJavaScript:

constelement=document.getElementById('my-element')

CustomProperties

50

Page 51: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

element.style.setProperty('--variable-name','a-value')

Thiscodebelowcanbeusedtoaccessavariablevalueinstead,incasethevariableisdefinedon :root:

conststyles=getComputedStyle(document.documentElement)

constvalue=String(styles.getPropertyValue('--variable-name')).trim()

Or,togetthestyleappliedtoaspecificelement,incaseofvariablessetwithadifferentscope:

constelement=document.getElementById('my-element')

conststyles=getComputedStyle(element)

constvalue=String(styles.getPropertyValue('--variable-name')).trim()

HandlinginvalidvaluesIfavariableisassignedtoapropertywhichdoesnotacceptthevariablevalue,it'sconsideredinvalid.

Forexampleyoumightpassapixelvaluetoa positionproperty,oraremvaluetoacolorproperty.

Inthiscasethelineisconsideredinvalidandignored.

BrowsersupportBrowsersupportforCSSVariablesisverygood,accordingtoCanIUse.

CSSVariablesareheretostay,andyoucanusethemtodayifyoudon'tneedtosupportInternetExplorerandoldversionsoftheotherbrowsers.

IfyouneedtosupportolderbrowsersyoucanuselibrarieslikePostCSSorMyth,butyou'lllosetheabilitytointeractwithvariablesviaJavaScriptortheBrowserDeveloperTools,astheyaretranspiledtogoodoldvariable-lessCSS(andassuch,youlosemostofthepowerofCSSVariables).

CSSVariablesarecasesensitiveThisvariable:

--width:100px;

CustomProperties

51

Page 52: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

isdifferentthan:

--Width:100px;

MathinCSSVariablesTodomathinCSSVariables,youneedtouse calc(),forexample:

:root{

--default-left-padding:calc(10px*2);

}

MediaquerieswithCSSVariablesNothingspecialhere.CSSVariablesnormallyapplytomediaqueries:

body{

--width:500px;

}

@mediascreenand(max-width:1000px)and(min-width:700px){

--width:800px;

}

.container{

width:var(--width);

}

Settingafallbackvalueforvar()var()acceptsasecondparameter,whichisthedefaultfallbackvaluewhenthevariablevalueisnotset:

.container{

margin:var(--default-margin,30px);

}

CustomProperties

52

Page 53: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

CustomProperties

53

Page 54: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

FontsAtthedawnofthewebyouonlyhadahandfuloffontsyoucouldchoosefrom.

Thankfullytodayyoucanloadanykindoffontonyourpages.

CSShasgainedmanynicecapabilitiesovertheyearsinregardstofonts.

The fontpropertyistheshorthandforanumberofproperties:

font-family

font-weight

font-stretch

font-style

font-size

Let'sseeeachoneofthemandthenwe'llcover font.

Thenwe'lltalkabouthowtoloadcustomfonts,using @importor @font-face,orbyloadingafontstylesheet.

font-family

Setsthefontfamilythattheelementwilluse.

Why"family"?Becausewhatweknowasafontisactuallycomposedofseveralsub-fonts.whichprovideallthestyle(bold,italic,light..)weneed.

Here'sanexamplefrommyMac'sFontBookapp-theFiraCodefontfamilyhostsseveraldedicatedfontsunderneath:

Fonts

54

Page 55: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Thispropertyletsyouselectaspecificfont,forexample:

body{

font-family:Helvetica;

}

Youcansetmultiplevalues,sothesecondoptionwillbeusedifthefirstcannotbeusedforsomereason(ifit'snotfoundonthemachine,orthenetworkconnectiontodownloadthefontfailed,forexample):

body{

font-family:Helvetica,Arial;

}

Iusedsomespecificfontsuptonow,oneswecallWebSafeFonts,astheyarepre-installedondifferentoperatingsystems.

WedividetheminSerif,Sans-Serif,andMonospacefonts.Here'salistofsomeofthemostpopularones:

Serif

GeorgiaPalatinoTimesNewRomanTimes

Sans-Serif

Fonts

55

Page 56: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

ArialHelveticaVerdanaGenevaTahomaLucidaGrandeImpactTrebuchetMSArialBlack

Monospace

CourierNewCourierLucidaConsoleMonaco

Youcanuseallofthoseas font-familyproperties,buttheyarenotguaranteedtobethereforeverysystem.Othersexist,too,withavaryinglevelofsupport.

Youcanalsousegenericnames:

sans-serifafontwithoutligaturesserifafontwithligaturesmonospaceafontespeciallygoodforcodecursiveusedtosimulatehandwrittenpiecesfantasythenamesaysitall

Thosearetypicallyusedattheendofa font-familydefinition,toprovideafallbackvalueincasenothingelsecanbeapplied:

body{

font-family:Helvetica,Arial,sans-serif;

}

font-weight

Thispropertysetsthewidthofafont.Youcanusethosepredefinedvalues:

normalboldbolder(relativetotheparentelement)lighter(relativetotheparentelement)

Fonts

56

Page 57: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Orusingthenumerickeywords

100200300400,mappedto normal500600700mappedto bold800900

where100isthelightestfont,and900istheboldest.

Someofthosenumericvaluesmightnotmaptoafont,becausethatmustbeprovidedinthefontfamily.Whenoneismissing,CSSmakesthatnumberbeatleastasboldastheprecedingone,soyoumighthavenumbersthatpointtothesamefont.

font-stretch

Allowstochooseanarroworwidefaceofthefont,ifavailable.

Thisisimportant:thefontmustbeequippedwithdifferentfaces.

Valuesallowedare,fromnarrowertowider:

ultra-condensed

extra-condensed

condensed

semi-condensed

normal

semi-expanded

expanded

extra-expanded

ultra-expanded

font-style

Allowsyoutoapplyanitalicstyletoafont:

p{

font-style:italic;

}

Fonts

57

Page 58: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Thispropertyalsoallowsthevalues obliqueand normal.Thereisverylittle,ifany,differencebetweenusing italicand oblique.Thefirstiseasiertome,asHTMLalreadyoffersan ielementwhichmeansitalic.

font-size

Thispropertyisusedtodeterminethesizeoffonts.

Youcanpass2kindsofvalues:

1. alengthvalue,like px, em, remetc,orapercentage2. apredefinedvaluekeyword

Inthesecondcase,thevaluesyoucanuseare:

xx-smallx-smallsmallmediumlargex-largexx-largesmaller(relativetotheparentelement)larger(relativetotheparentelement)

Usage:

p{

font-size:20px;

}

li{

font-size:medium;

}

font-variant

Thispropertywasoriginallyusedtochangethetexttosmallcaps,andithadjust3validvalues:

normal

inherit

small-caps

Fonts

58

Page 59: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Smallcapsmeansthetextisrenderedin"smallercaps"besideitsuppercaseletters.

font

The fontpropertyletsyouapplydifferentfontpropertiesinasingleone,reducingtheclutter.

Wemustatleastset2properties, font-sizeand font-family,theothersareoptional:

body{

font:20pxHelvetica;

}

Ifweaddotherproperties,theyneedtobeputinthecorrectorder.

Thisistheorder:

font:<font-stretch><font-style><font-variant><font-weight><font-size><line-height><

font-family>;

Example:

body{

font:italicbold20pxHelvetica;

}

section{

font:small-capsbold20pxHelvetica;

}

Loadingcustomfontsusing @font-face@font-faceletsyouaddanewfontfamilyname,andmapittoafilethatholdsafont.

Thisfontwillbedownloadedbythebrowserandusedinthepage,andit'sbeensuchafundamentalchangetotypographyontheweb-wecannowuseanyfontwewant.

Wecanadd @font-facedeclarationsdirectlyintoourCSS,orlinktoaCSSdedicatedtoimportingthefont.

InourCSSfilewecanalsouse @importtoloadthatCSSfile.

A @font-facedeclarationcontainsseveralpropertiesweusetodefinethefont,includingsrc,theURI(oneormoreURIs)tothefont.Thisfollowsthesame-originpolicy,whichmeansfontscanonlybedownloadedformthecurrentorigin(domain+port+protocol).

Fonts

59

Page 60: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Fontsareusuallyintheformats

woff(WebOpenFontFormat)woff2(WebOpenFontFormat2.0)eot(EmbeddedOpenType)otf(OpenTypeFont)ttf(TrueTypeFont)

Thefollowingpropertiesallowustodefinethepropertiestothefontwearegoingtoload,aswesawabove:

font-family

font-weight

font-style

font-stretch

AnoteonperformanceOfcourseloadingafonthasperformanceimplicationswhichyoumustconsiderwhencreatingthedesignofyourpage.

Fonts

60

Page 61: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

TypographyWealreadytalkedaboutfonts,butthere'smoretostylingtext.

Inthissectionwe'lltalkaboutthefollowingproperties:

text-transform

text-decoration

text-align

vertical-align

line-height

text-indent

text-align-last

word-spacing

letter-spacing

text-shadow

white-space

tab-size

writing-mode

hyphens

text-orientation

direction

line-break

word-break

overflow-wrap

text-transform

Thispropertycantransformthecaseofanelement.

Thereare4validvalues:

capitalizetouppercasethefirstletterofeachworduppercasetouppercaseallthetextlowercasetolowercaseallthetextnonetodisabletransformingthetext,usedtoavoidinheritingtheproperty

Example:

p{

text-transform:uppercase;

}

Typography

61

Page 62: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

text-decoration

Thispropertyissedtoadddecorationstothetext,including

underline

overline

line-through

blink

none

Example:

p{

text-decoration:underline;

}

Youcanalsosetthestyleofthedecoration,andthecolor.

Example:

p{

text-decoration:underlinedashedyellow;

}

Validstylevaluesare solid, double, dotted, dashed, wavy.

Youcandoallinoneline,orusethespecificproperties:

text-decoration-line

text-decoration-color

text-decoration-style

Example:

p{

text-decoration-line:underline;

text-decoration-color:yellow;

text-decoration-style:dashed;

}

text-align

Typography

62

Page 63: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Bydefaulttextalignhasthe startvalue,meaningthetextstartsatthe"start",origin0,0oftheboxthatcontainsit.Thismeanstopleftinleft-to-rightlanguages,andtoprightinright-to-leftlanguages.

Possiblevaluesare start, end, left, right, center, justify(nicetohaveaconsistentspacingatthelineends):

p{

text-align:right;

}

vertical-align

Determineshowinlineelementsareverticallyaligned.

Wehaveseveralvaluesforthisproperty.Firstwecanassignalengthorpercentagevalue.Thoseareusedtoalignthetextinapositionhigherorlower(usingnegativevalues)thanthebaselineoftheparentelement.

Thenwehavethekeywords:

baseline(thedefault),alignsthebaselinetothebaselineoftheparentelementsubmakesanelementsubscripted,simulatingthe subHTMLelementresultsupermakesanelementsuperscripted,simulatingthe supHTMLelementresulttopalignthetopoftheelementtothetopofthelinetext-topalignthetopoftheelementtothetopoftheparentelementfontmiddlealignthemiddleoftheelementtothemiddleofthelineoftheparentbottomalignthebottomoftheelementtothebottomofthelinetext-bottomalignthebottomoftheelementtothebottomoftheparentelementfont

line-height

Thisallowsyoutochangetheheightofaline.Eachlineoftexthasacertainfontheight,butthenthereisadditionalspacingverticallybetweenthelines.That'sthelineheight:

p{

line-height:0.9rem;

}

text-indent

Indentthefirstlineofaparagraphbyasetlength,orapercentageoftheparagraphwidth:

Typography

63

Page 64: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

p{

text-indent:-10px;

}

text-align-last

Bydefaultthelastlineofaparagraphisalignedfollowingthe text-alignvalue.Usethispropertytochangethatbehavior:

p{

text-align-last:right;

}

word-spacing

Modifiesthespacingbetweeneachword.

Youcanusethe normalkeyword,toresetinheritedvalues,orusealengthvalue:

p{

word-spacing:2px;

}

span{

word-spacing:-0.2em;

}

letter-spacing

Modifiesthespacingbetweeneachletter.

Youcanusethe normalkeyword,toresetinheritedvalues,orusealengthvalue:

p{

letter-spacing:0.2px;

}

span{

letter-spacing:-0.2em;

}

text-shadow

Typography

64

Page 65: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Applyashadowtothetext.Bydefaultthetexthasnowshadow.

Thispropertyacceptsanoptionalcolor,andasetofvaluesthatset

theXoffsetoftheshadowfromthetexttheYoffsetoftheshadowfromthetexttheblurradius

Ifthecolorisnotspecified,theshadowwillusethetextcolor.

Examples:

p{

text-shadow:0.2px2px;

}

span{

text-shadow:yellow0.2px2px3px;

}

white-space

SetshowCSShandlesthewhitespace,newlinesandtabsinsideanelement.

Validvaluesthatcollapsewhitespaceare:

normalcollapseswhitespace.Addsnewlineswhennecessaryasthetextreachesthecontainerendnowrapcollapseswhitespace.Doesnotaddanewlinewhenthetextreachestheendofthecontainer,andsuppressesanylinebreakaddedtothetextpre-linecollapseswhitespace.Addsnewlineswhennecessaryasthetextreachesthecontainerend

Validvaluesthatpreservewhitespaceare:

prepreserveswhitespace.Doesnotaddanewlinewhenthetextreachestheendofthecontainer,butpreserveslinebreakaddedtothetextpre-wrappreserveswhitespace.Addsnewlineswhennecessaryasthetextreachesthecontainerend

tab-size

Setsthewidthofthetabcharacter.Bydefaultit's8,andyoucansetanintegervaluethatsetsthecharacterspacesittakes,oralengthvalue:

Typography

65

Page 66: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

p{

tab-size:2;

}

span{

tab-size:4px;

}

writing-mode

Defineswhetherlinesoftextarelaidouthorizontallyorvertically,andthedirectioninwhichblocksprogress.

Thevaluesyoucanuseare

horizontal-tb(default)vertical-rlcontentislaidoutvertically.Newlinesareputontheleftofthepreviousvertical-lrcontentislaidoutvertically.Newlinesareputontherightoftheprevious

hyphens

Determinesifhyphensshouldbeautomaticallyaddedwhengoingtoanewline.

Validvaluesare

none(default)manualonlyaddanhyphenwhenthereisalreadyavisiblehyphenorahiddenhyphen(aspecialcharacter)autoaddhyphenswhendeterminedthetextcanhaveahyphen.

text-orientation

When writing-modeisinaverticalmode,determinestheorientationofthetext.

Validvaluesare

mixedisthedefault,andifalanguageisvertical(likeJapanese)itpreservesthatorientation,whilerotatingtextwritteninwesternlanguagesuprightmakesalltextbeverticallyorientedsidewaysmakesalltexthorizontallyoriented

direction

Typography

66

Page 67: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Setsthedirectionofthetext.Validvaluesare ltrand rtl:

p{

direction:rtl;

}

word-break

Thispropertyspecifieshowtobreaklineswithinwords.

normal(default)meansthetextisonlybrokenbetweenwords,notinsideawordbreak-allthebrowsercanbreakaword(butnohyphensareadded)keep-allsuppresssoftwrapping.MostlyusedforCJK(Chinese/Japanese/Korean)text.

SpeakingofCJKtext,theproperty line-breakisusedtodeterminehowtextlinesbreak.I'mnotanexpertwiththoselanguages,soIwillavoidcoveringit.

overflow-wrap

Ifawordistoolongtofitaline,itcanoverflowoutsideofthecontainer.

Thispropertyisalsoknownas word-wrap,althoughthatisnon-standard(butstillworksasanalias)

Thisisthedefaultbehavior( overflow-wrap:normal;).

Wecanuse:

p{

overflow-wrap:break-word;

}

tobreakitattheexactlengthoftheline,or

p{

overflow-wrap:anywhere;

}

ifthebrowserseesthere'sasoftwrapopportunitysomewhereearlier.Nohyphensareadded,inanycase.

Thispropertyisverysimilarto word-break.Wemightwanttochoosethisoneonwesternlanguages,while word-breakhasspecialtreatmentfornon-westernlanguages.

Typography

67

Page 68: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Typography

68

Page 69: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

BoxModelEveryCSSelementisessentiallyabox.Everyelementisagenericbox.

TheboxmodelexplainsthesizingoftheelementsbasedonafewCSSproperties.

Fromtheinsidetotheoutside,wehave:

thecontentareapaddingbordermargin

ThebestwaytovisualizetheboxmodelistoopenthebrowserDevToolsandcheckhowitisdisplayed:

HereyoucanseehowFirefoxtellsmethepropertiesofa spanelementIhighlighted.Iright-clickedonit,pressedInspectElement,andwenttotheLayoutpaneloftheDevTools.

See,thelightbluespaceisthecontentarea.Surroundingitthereisthepadding,thentheborderandfinallythemargin.

Bydefault,ifyousetawidth(orheight)ontheelement,thatisgoingtobeappliedtothecontentarea.Allthepadding,border,andmargincalculationsaredoneoutsideofthevalue,soyouhavetotakethisinmindwhenyoudoyourcalculation.

YoucanchangethisbehaviorusingBoxSizing.

BoxModel

69

Page 70: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

BoxModel

70

Page 71: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

BorderTheborderisathinlayerbetweenpaddingandmargin.Editingtheborderyoucanmakeelementsdrawtheirperimeteronscreen.

Youcanworkonbordersbyusingthoseproperties:

border-style

border-color

border-width

Theproperty bordercanbeusedasashorthandforallthoseproperties.

border-radiusisusedtocreateroundedcorners.

Youalsohavetheabilitytouseimagesasborders,anabilitygiventoyouby border-imageanditsspecificseparateproperties:

border-image-source

border-image-slice

border-image-width

border-image-outset

border-image-repeat

Let'sstartwith border-style.

TheborderstyleThe border-stylepropertyletsyouchoosethestyleoftheborder.Theoptionsyoucanuseare:

dotted

dashed

solid

double

groove

ridge

inset

outset

none

hidden

Border

71

Page 72: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

CheckthisCodepenforaliveexample

Thedefaultforthestyleis none,sotomaketheborderappearatallyouneedtochangeittosomethingelse. solidisagoodchoicemostofthetimes.

Youcansetadifferentstyleforeachedgeusingtheproperties

border-top-style

border-right-style

border-bottom-style

border-left-style

oryoucanuse border-stylewithmultiplevaluestodefinethem,usingtheusualTop-Right-Bottom-Leftorder:

p{

border-style:soliddottedsoliddotted;

}

Theborderwidthborder-widthisusedtosetthewidthoftheborder.

Border

72

Page 73: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Youcanuseoneofthepre-definedvalues:

thin

medium(thedefaultvalue)thick

orexpressavalueinpixels,emorremoranyothervalidlengthvalue.

Example:

p{

border-width:2px;

}

Youcansetthewidthofeachedge(Top-Right-Bottom-Left)separatelybyusing4values:

p{

border-width:2px1px2px1px;

}

oryoucanusethespecificedgeproperties border-top-width, border-right-width, border-bottom-width, border-left-width.

Thebordercolorborder-colorisusedtosetthecoloroftheborder.

Ifyoudon'tsetacolor,theborderbydefaultiscoloredusingthecolorofthetextintheelement.

Youcanpassanyvalidcolorvalueto border-color.

Example:

p{

border-color:yellow;

}

Youcansetthecolorofeachedge(Top-Right-Bottom-Left)separatelybyusing4values:

p{

border-color:blackredyellowblue;

}

Border

73

Page 74: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

oryoucanusethespecificedgeproperties border-top-color, border-right-color, border-bottom-color, border-left-color.

ThebordershorthandpropertyThose3propertiesmentioned, border-width, border-styleand border-colorcanbesetusingtheshorthandproperty border.

Example:

p{

border:2pxblacksolid;

}

Youcanalsousetheedge-specificproperties border-top, border-right, border-bottom,border-left.

Example:

p{

border-left:2pxblacksolid;

border-right:3pxreddashed;

}

Theborderradiusborder-radiusisusedtosetroundedcornerstotheborder.Youneedtopassavaluethatwillbeusedastheradiusofthecirclethatwillbeusedtoroundtheborder.

Usage:

p{

border-radius:3px;

}

Youcanalsousetheedge-specificproperties border-top-left-radius, border-top-right-radius, border-bottom-left-radius, border-bottom-right-radius.

Usingimagesasborders

Border

74

Page 75: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Oneverycoolthingwithbordersistheabilitytouseimagestostylethem.Thisletsyougoverycreativewithborders.

Wehave5properties:

border-image-source

border-image-slice

border-image-width

border-image-outset

border-image-repeat

andtheshorthand border-image.Iwon'tgoinmuchdetailshereasimagesasborderswouldneedamorein-depthcoverageastheoneIcandointhislittlechapter.IrecommendreadingtheCSSTricksalmanacentryonborder-imageformoreinformation.

Border

75

Page 76: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

PaddingThe paddingCSSpropertyiscommonlyusedinCSStoaddspaceintheinnersideofanelement.

Remember:

marginaddsspaceoutsideanelementborderpaddingaddsspaceinsideanelementborder

Specificpaddingpropertiespaddinghas4relatedpropertiesthatalterthepaddingofasingleedgeatonce:

padding-top

padding-right

padding-bottom

padding-left

Theusageofthoseisverysimpleandcannotbeconfused,forexample:

padding-left:30px;

padding-right:3em;

Usingthe paddingshorthandpaddingisashorthandtospecifymultiplepaddingvaluesatthesametime,anddependingonthenumberofvaluesentered,itbehavesdifferently.

1value

Usingasinglevalueappliesthattoallthepaddings:top,right,bottom,left.

padding:20px;

2values

Using2valuesappliesthefirsttobottom&top,andthesecondtoleft&right.

padding:20px10px;

Padding

76

Page 77: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

3values

Using3valuesappliesthefirsttotop,thesecondtoleft&right,thethirdtobottom.

padding:20px10px30px;

4values

Using4valuesappliesthefirsttotop,thesecondtoright,thethirdtobottom,thefourthtoleft.

padding:20px10px5px0px;

So,theorderistop-right-bottom-left.

Valuesacceptedpaddingacceptsvaluesexpressedinanykindoflengthunit,themostcommononesarepx,em,rem,butmanyothersexist.

Padding

77

Page 78: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

MarginThe marginCSSpropertyiscommonlyusedinCSStoaddspacearoundanelement.

Remember:

marginaddsspaceoutsideanelementborderpaddingaddsspaceinsideanelementborder

Specificmarginpropertiesmarginhas4relatedpropertiesthatalterthemarginofasingleedgeatonce:

margin-top

margin-right

margin-bottom

margin-left

Theusageofthoseisverysimpleandcannotbeconfused,forexample:

margin-left:30px;

margin-right:3em;

Usingthe marginshorthandmarginisashorthandtospecifymultiplemarginsatthesametime,anddependingonthenumberofvaluesentered,itbehavesdifferently.

1value

Usingasinglevalueappliesthattoallthemargins:top,right,bottom,left.

margin:20px;

2values

Using2valuesappliesthefirsttobottom&top,andthesecondtoleft&right.

margin:20px10px;

Margin

78

Page 79: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

3values

Using3valuesappliesthefirsttotop,thesecondtoleft&right,thethirdtobottom.

margin:20px10px30px;

4values

Using4valuesappliesthefirsttotop,thesecondtoright,thethirdtobottom,thefourthtoleft.

margin:20px10px5px0px;

So,theorderistop-right-bottom-left.

Valuesacceptedmarginacceptsvaluesexpressedinanykindoflengthunit,themostcommononesarepx,em,rem,butmanyothersexist.

Italsoacceptspercentagevalues,andthespecialvalue auto.

Using autotocenterelementsautocanbeusedtotellthebrowsertoselectautomaticallyamargin,andit'smostcommonlyusedtocenteranelementinthisway:

margin:0auto;

Assaidabove,using2valuesappliesthefirsttobottom&top,andthesecondtoleft&right.

ThemodernwaytocenterelementsistouseFlexbox,andits justify-content:center;directive.

OlderbrowsersofcoursedonotimplementFlexbox,andifyouneedtosupportthem margin:0auto;isstillagoodchoice.

Usinganegativemargin

Margin

79

Page 80: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

marginistheonlypropertyrelatedtosizingthatcanhaveanegativevalue.It'sextremelyuseful,too.Settinganegativetopmarginmakesanelementmoveoverelementsbeforeit,andgivenenoughnegativevalueitwillmoveoutofthepage.

Anegativebottommarginmovesuptheelementsafterit.

Anegativerightmarginmakesthecontentoftheelementexpandbeyonditsallowedcontentsize.

Anegativeleftmarginmovestheelementleftovertheelementsthatprecedeit,andgivenenoughnegativevalueitwillmoveoutofthepage.

Margin

80

Page 81: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

BoxSizingThedefaultbehaviorofbrowserswhencalculatingthewidthofanelementistoapplythecalculatedwidthandheighttothecontentarea,withouttakinganyofthepadding,borderandmargininconsideration.

Thisapproachhasproventobequitecomplicatedtoworkwith.

Youcanchangethisbehaviorbysettingthe box-sizingproperty.

The box-sizingpropertyisagreathelp.Ithas2values:

border-box

content-box

content-boxisthedefault,theonewehadforagesbefore box-sizingbecameathing.

border-boxisthenewandgreatthingwearelookingfor.Ifyousetthatonanelement:

.my-div{

box-sizing:border-box;

}

widthandheightcalculationincludethepaddingandtheborder.Onlythemarginisleftout,whichisreasonablesinceinourmindwealsotypicallyseethatasaseparatething:marginisoutsideofthebox.

Thispropertyisasmallchangebuthasabigimpact.CSSTricksevendeclaredaninternationalbox-sizingawarenessday,justsaying,andit'srecommendedtoapplyittoeveryelementonthepage,outofthebox,withthis:

*,*:before,*:after{

box-sizing:border-box;

}

BoxSizing

81

Page 82: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

DisplayThe displaypropertyofanobjectdetermineshowitisrenderedbythebrowser.

It'saveryimportantproperty,andprobablytheonewiththehighestnumberofvaluesyoucanuse.

Thosevaluesinclude:

block

inline

none

contents

flow

flow-root

table(andallthe table-*ones)flex

grid

list-item

inline-block

inline-table

inline-flex

inline-grid

inline-list-item

plusothersyouwillnotlikelyuse,like ruby.

Choosinganyofthosewillconsiderablyalterthebehaviorofthebrowserwiththeelementanditschildren.

Inthissectionwe'llanalyzethemostimportantonesnotcoveredelsewhere:

block

inline

inline-block

none

We'llseesomeoftheothersinlaterchapters,includingcoverageof table, flexand grid.

inline

InlineisthedefaultdisplayvalueforeveryelementinCSS.

Display

82

Page 83: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

AlltheHTMLtagsaredisplayedinlineoutoftheboxexceptsomeelementslike div, pandsection,whicharesetas blockbytheuseragent(thebrowser).

Inlineelementsdon'thaveanymarginorpaddingapplied.

Sameforheightandwidth.

Youcanaddthem,buttheappearanceinthepagewon'tchange-theyarecalculatedandappliedautomaticallybythebrowser.

inline-block

Similarto inline,butwith inline-block widthand heightareappliedasyouspecified.

block

Asmentioned,normallyelementsaredisplayedinline,withtheexceptionofsomeelements,including

div

p

section

ul

whicharesetas blockbythebrowser.

With display:block,elementsarestackedoneaftereachother,vertically,andeveryelementtakesup100%ofthepage.

Thevaluesassignedtothe widthand heightpropertiesarerespected,ifyousetthem,alongwith marginand padding.

none

Using display:nonemakesanelementdisappear.It'sstillthereintheHTML,butjustnotvisibleinthebrowser.

Display

83

Page 84: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

PositioningPositioningiswhatmakesusdeterminewhereelementsappearonthescreen,andhowtheyappear.

Youcanmoveelementsaround,andpositionthemexactlywhereyouwant.

Inthissectionwe'llalsoseehowthingschangeonapagebasedonhowelementswithdifferent positioninteractwitheachother.

WehaveonemainCSSproperty: position.

Itcanhavethose5values:

static

relative

absolute

fixed

sticky

StaticpositioningThisisthedefaultvalueforanelement.Staticpositionedelementsaredisplayedinthenormalpageflow.

RelativepositioningIfyouset position:relativeonanelement,youarenowabletopositionitwithanoffset,usingtheproperties

toprightbottomleft

whicharecalledoffsetproperties.Theyacceptalengthvalueorapercentage.

TakethisexampleImadeonCodepen.Icreateaparentcontainer,achildcontainer,andaninnerboxwithsometext:

<divclass="parent">

<divclass="child">

Positioning

84

Page 85: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

<divclass="box">

<p>Test</p>

</div>

</div>

</div>

withsomeCSStogivesomecolorsandpadding,butdoesnotaffectpositioning:

.parent{

background-color:#af47ff;

padding:30px;

width:300px;

}

.child{

background-color:#ff4797;

padding:30px;

}

.box{

background-color:#f3ff47;

padding:30px;

border:2pxsolid#333;

border-style:dotted;

font-family:courier;

text-align:center;

font-size:2rem;

}

here'stheresult:

YoucantryandaddanyofthepropertiesImentionedbefore( top, right, bottom, left)to .box,andnothingwillhappen.Thepositionis static.

Positioning

85

Page 86: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Nowifweset position:relativetothebox,atfirstapparentlynothingchanges.Buttheelementisnowabletomoveusingthe top, right, bottom, leftproperties,andnowyoucanalterthepositionofitrelativelytotheelementcontainingit.

Forexample:

.box{

/*...*/

position:relative;

top:-60px;

}

Anegativevaluefor topwillmaketheboxmoveuprelativelytoitscontainer.

Or

.box{

/*...*/

position:relative;

top:-60px;

left:180px;

}

Positioning

86

Page 87: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Noticehowthespacethatisoccupiedbytheboxremainspreservedinthecontainer,likeitwasstillinitsplace.

Anotherpropertythatwillnowworkis z-indextoalterthez-axisplacement.We'lltalkaboutitlateron.

AbsolutepositioningSetting position:absoluteonanelementwillremoveitfromthedocument'sflow,anditwillnotlonger.

Rememberinrelativepositioningthatwenoticedthespaceoriginallyoccupiedbyanelementwaspreservedevenifitwasmovedaround?

Withabsolutepositioning,assoonasweset position:absoluteon .box,itsoriginalspaceisnowcollapsed,andonlytheorigin(x,ycoordinates)remainthesame.

.box{

/*...*/

position:absolute;

}

Positioning

87

Page 88: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Wecannowmovetheboxaroundasweplease,usingthe top, right, bottom, leftproperties:

.box{

/*...*/

position:absolute;

top:0px;

left:0px;

}

or

.box{

/*...*/

position:absolute;

top:140px;

left:50px;

}

Positioning

88

Page 89: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Thecoordinatesarerelativetotheclosestcontainerthatisnot static.

Thismeansthatifweadd position:relativetothe .childelement,andweset topandleftto0,theboxwillnotbepositionedatthetopleftmarginofthewindow,butratheritwillbepositionedatthe0,0coordinatesof .child:

.child{

/*...*/

position:relative;

}

.box{

/*...*/

position:absolute;

top:0px;

left:0px;

}

Here's(howwealreadysaw)of .childisstatic(thedefault):

Positioning

89

Page 90: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

.child{

/*...*/

position:static;

}

.box{

/*...*/

position:absolute;

top:0px;

left:0px;

}

Likeforrelativepositioning,youcanuse z-indextoalterthez-axisplacement.

FixedpositioningLikewithabsolutepositioning,whenanelementisassigned position:fixedit'sremovedfromtheflowofthepage.

Thedifferencewithabsolutepositioningisthis:elementsarenowalwayspositionedrelativetothewindow,insteadofthefirstnon-staticcontainer.

.box{

/*...*/

position:fixed;

}

Positioning

90

Page 91: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

.box{

/*...*/

position:fixed;

top:0;

left:0;

}

Anotherbigdifferenceisthatelementsarenotaffectedbyscrolling.Onceyouputastickyelementsomewhere,scrollingthepagedoesnotremoveitfromthevisiblepartofthepage.

StickypositioningWhiletheabovevalueshavebeenaroundforaverylongtime,thisonewasintroducedrecentlyandit'sstillrelativelyunsupported(seecaniuse.com)

TheUITableViewiOScomponentisthethingthatcomestomindwhenIthinkabout position:sticky.Youknowwhenyouscrollinthecontactslistandthefirstletterisstickedtothetop,toletyouknowyouareviewingthatparticularletter'scontacts?

WeusedJavaScripttoemulatethat,butthisistheapproachtakenbyCSStoallowitnatively.

Positioning

91

Page 92: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Positioning

92

Page 93: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

FloatingandclearingFloatinghasbeenaveryimportanttopicinthepast.

Itwasusedinlotsofhacksandcreativeusagesbecauseitwasoneofthefewways,alongwithtables,wecouldreallyimplementsomelayouts.Inthepastweusedtofloatthesidebartotheleft,forexample,toshowitontheleftsideofthescreenandaddedsomemargintothemaincontent.

LuckilytimeshavechangedandtodaywehaveFlexboxandGridtohelpuswithlayout,andfloathasgonebacktoitsoriginalscope:placingcontentononesideofthecontainerelement,andmakeitssiblingsshowuparoundit.

The floatpropertysupports3values:

left

right

none(thedefault)

Saywehaveaboxwhichcontainsaparagraphwithsometext,andtheparagraphalsocontainsanimage.

Here'ssomecode:

<divclass="parent">

<divclass="child">

<divclass="box">

<p>Thisissomerandomparagraphandanimage.<imgsrc="https://via.placeholder.com

/100x100"/>Theimageisinthemiddleofthetext.Theimageisinthemiddleofthetex

t.Theimageisinthemiddleofthetext.Theimageisinthemiddleofthetext.Theima

geisinthemiddleofthetext.Theimageisinthemiddleofthetext.Theimageisint

hemiddleofthetext.Theimageisinthemiddleofthetext.Theimageisinthemiddle

ofthetext.

</p>

</div>

</div>

</div>

.parent{

background-color:#af47ff;

padding:30px;

width:500px;

}

.child{

background-color:#ff4797;

padding:30px;

}

Floatingandclearing

93

Page 94: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

.box{

background-color:#f3ff47;

padding:30px;

border:2pxsolid#333;

border-style:dotted;

font-family:courier;

text-align:justify;

font-size:1rem;

}

andthevisualappearance:

Asyoucansee,thenormalflowbydefaultconsiderstheimageinline,andmakesspaceforitinthelineitself.

Ifweadd float:lefttotheimage,andsomepadding:

img{

float:left;

padding:20px20px0px0px;

}

Floatingandclearing

94

Page 95: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

thisistheresult:

andthisiswhatwegetbyapplyingafloat:right,adjustingthepaddingaccordingly:

img{

float:right;

padding:20px0px20px20px;

}

Floatingandclearing

95

Page 96: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Afloatedelementisremovedfromthenormalflowofthepage,andtheothercontentflowsaroundit.

SeetheexampleonCodepen

Youarenotlimitedtofloatingimages,too.Hereweswitchtheimagewitha spanelement:

<divclass="parent">

<divclass="child">

<divclass="box">

<p>Thisissomerandomparagraphandanimage.<span>Sometexttofloat</span>Thei

mageisinthemiddleofthetext.Theimageisinthemiddleofthetext.Theimageisin

themiddleofthetext.Theimageisinthemiddleofthetext.Theimageisinthemiddl

eofthetext.Theimageisinthemiddleofthetext.Theimageisinthemiddleofthet

ext.Theimageisinthemiddleofthetext.Theimageisinthemiddleofthetext.

</p>

</div>

</div>

</div>

span{

float:right;

margin:20px0px20px20px;

padding:10px;

border:1pxsolidblack

Floatingandclearing

96

Page 97: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

}

andthisistheresult:

ClearingWhathappenswhenyoufloatmorethanoneelement?

Ifwhenfloatedtheyfindanotherfloatedimage,bydefaulttheyarestackeduponenexttotheother,horizontally.Untilthereisnoroom,andtheywillstartbeingstackedonanewline.

Saywehad3inlineimagesinsidea ptag:

Floatingandclearing

97

Page 98: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Ifweadd float:lefttothoseimages:

img{

float:left;

padding:20px20px0px0px;

}

thisiswhatwe'llhave:

Floatingandclearing

98

Page 99: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

ifyouadd clear:lefttoimages,thosearegoingtobestackedverticallyratherthanhorizontally:

Floatingandclearing

99

Page 100: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Iusedthe leftvaluefor clear.Itallows

lefttoclearleftfloatsrighttoclearrightfloatsbothtoclearbothleftandrightfloatsnone(default)disablesclearing

Floatingandclearing

100

Page 101: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

z-indexWhenwetalkedaboutpositioning,Imentionedthatyoucanusethe z-indexpropertytocontroltheZaxispositioningofelements.

It'sveryusefulwhenyouhavemultipleelementsthatoverlapeachother,andyouneedtodecidewhichoneisvisible,asnearertotheuser,andwhichone(s)shouldbehiddenbehindit.

Thispropertytakesanumber(withoutdecimals)andusesthatnumbertocalculatewhichelementsappearnearertotheuser,intheZaxis.

Thehigherthez-indexvalue,themoreanelementispositionednearertotheuser.

Whendecidingwhichelementshouldbevisibleandwhichoneshouldbepositionedbehindit,thebrowserdoesacalculationonthez-indexvalue.

Thedefaultvalueis auto,aspecialkeyword.Using auto,theZaxisorderisdeterminedbythepositionoftheHTMLelementinthepage-thelastsiblingappearsfirst,asit'sdefinedlast.

Bydefaultelementshavethe staticvalueforthe positionproperty.Inthiscase,the z-indexpropertydoesnotmakeanydifference-itmustbesetto absolute, relativeorfixedtowork.

Example:

.my-first-div{

position:absolute;

top:0;

left:0;

width:600px;

height:600px;

z-index:10;

}

.my-second-div{

position:absolute;

top:0;

left:0;

width:500px;

height:500px;

z-index:20;

}

Theelementwithclass .my-second-divwillbedisplayed,andbehindit .my-first-div.

z-index

101

Page 102: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Hereweused10and20,butyoucanuseanynumber.Negativenumberstoo.It'scommontopicknon-consecutivenumbers,soyoucanpositionelementsinthemiddle.Ifyouuseconsecutivenumbersinstead,youwouldneedtore-calculatethez-indexofeachelementinvolvedinthepositioning.

z-index

102

Page 103: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

CSSGridCSSGridisthenewkidintheCSStown,andwhilenotyetfullysupportedbyallbrowsers,it'sgoingtobethefuturesystemforlayouts.

CSSGridisafundamentallynewapproachtobuildinglayoutsusingCSS.

KeepaneyeontheCSSGridLayoutpageoncaniuse.com(https://caniuse.com/#feat=css-grid)tofindoutwhichbrowserscurrentlysupportit.Atthetimeofwriting,April2019,allmajorbrowsers(exceptIE,whichwillneverhavesupportforit)arealreadysupportingthistechnology,covering92%ofallusers.

CSSGridisnotacompetitortoFlexbox.Theyinteroperateandcollaborateoncomplexlayouts,becauseCSSGridworkson2dimensions(rowsANDcolumns)whileFlexboxworksonasingledimension(rowsORcolumns).

Buildinglayoutsforthewebhastraditionallybeenacomplicatedtopic.

Iwon'tdigintothereasonsforthiscomplexity,whichisacomplextopiconitsown,butyoucanthinkyourselfasaveryluckyhumanbecausenowadaysyouhave2verypowerfulandwellsupportedtoolsatyourdisposal:

CSSFlexboxCSSGrid

These2arethetoolstobuildtheWeblayoutsofthefuture.

UnlessyouneedtosupportoldbrowserslikeIE8andIE9,thereisnoreasontobemessingwiththingslike:

TablelayoutsFloatsclearfixhacksdisplay:tablehacks

Inthisguidethere'sallyouneedtoknowaboutgoingfromazeroknowledgeofCSSGridtobeingaproficientuser.

ThebasicsTheCSSGridlayoutisactivatedonacontainerelement(whichcanbea divoranyothertag)bysetting display:grid.

CSSGrid

103

Page 104: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Aswithflexbox,youcandefinesomepropertiesonthecontainer,andsomepropertiesoneachindividualiteminthegrid.

Thesepropertiescombinedwilldeterminethefinallookofthegrid.

Themostbasiccontainerpropertiesare grid-template-columnsand grid-template-rows.

grid-template-columnsandgrid-template-rows

Thosepropertiesdefinethenumberofcolumnsandrowsinthegrid,andtheyalsosetthewidthofeachcolumn/row.

Thefollowingsnippetdefinesagridwith4columnseach200pxwide,and2rowswitha300pxheighteach.

.container{

display:grid;

grid-template-columns:200px200px200px200px;

grid-template-rows:300px300px;

}

CSSGrid

104

Page 105: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Here'sanotherexampleofagridwith2columnsand2rows:

.container{

display:grid;

grid-template-columns:200px200px;

grid-template-rows:100px100px;

}

CSSGrid

105

Page 106: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Automaticdimensions

Manytimesyoumighthaveafixedheadersize,afixedfootersize,andthemaincontentthatisflexibleinheight,dependingonitslength.Inthiscaseyoucanusethe autokeyword:

.container{

display:grid;

grid-template-rows:100pxauto100px;

}

Differentcolumnsandrowsdimensions

Intheaboveexampleswemaderegulargridsbyusingthesamevaluesforrowsandthesamevaluesforcolumns.

Youcanspecifyanyvalueforeachrow/column,tocreatealotofdifferentdesigns:

.container{

display:grid;

grid-template-columns:100px200px;

grid-template-rows:100px50px;

}

CSSGrid

106

Page 107: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Anotherexample:

.container{

display:grid;

grid-template-columns:10px100px;

grid-template-rows:100px10px;

}

CSSGrid

107

Page 108: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Addingspacebetweenthecells

Unlessspecified,thereisnospacebetweenthecells.

Youcanaddspacingbyusingthoseproperties:

grid-column-gap

grid-row-gap

ortheshorthandsyntax grid-gap.

Example:

.container{

display:grid;

grid-template-columns:100px200px;

grid-template-rows:100px50px;

CSSGrid

108

Page 109: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

grid-column-gap:25px;

grid-row-gap:25px;

}

Thesamelayoutusingtheshorthand:

.container{

display:grid;

grid-template-columns:100px200px;

grid-template-rows:100px50px;

grid-gap:25px;

}

Spawningitemsonmultiplecolumnsand/orrows

Everycellitemhastheoptiontooccupymorethanjustoneboxintherow,andexpandhorizontallyorverticallytogetmorespace,whilerespectingthegridproportionssetinthecontainer.

Thosearethepropertieswe'lluseforthat:

grid-column-start

grid-column-end

grid-row-start

grid-row-end

CSSGrid

109

Page 110: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Example:

.container{

display:grid;

grid-template-columns:200px200px200px200px;

grid-template-rows:300px300px;

}

.item1{

grid-column-start:2;

grid-column-end:4;

}

.item6{

grid-column-start:3;

grid-column-end:5;

}

Thenumberscorrespondtotheverticallinethatseparateseachcolumn,startingfrom1:

CSSGrid

110

Page 111: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Thesameprincipleappliesto grid-row-startand grid-row-end,exceptthistimeinsteadoftakingmorecolumns,acelltakesmorerows.

Shorthandsyntax

Thosepropertieshaveashorthandsyntaxprovidedby:

grid-column

grid-row

Theusageissimple,here'showtoreplicatetheabovelayout:

.container{

display:grid;

grid-template-columns:200px200px200px200px;

grid-template-rows:300px300px;

}

.item1{

CSSGrid

111

Page 112: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

grid-column:2/4;

}

.item6{

grid-column:3/5;

}

Anotherapproachistosetthestartingcolumn/row,andsethowmanyitshouldoccupyusingspan:

.container{

display:grid;

grid-template-columns:200px200px200px200px;

grid-template-rows:300px300px;

}

.item1{

grid-column:2/span2;

}

.item6{

grid-column:3/span2;

}

Moregridconfiguration

Usingfractions

Specifyingtheexactwidthofeachcolumnorrowisnotidealineverycase.

Afractionisaunitofspace.

Thefollowingexampledividesagridinto3columnswiththesamewidth,1/3oftheavailablespaceeach.

.container{

grid-template-columns:1fr1fr1fr;

}

Usingpercentagesandrem

Youcanalsousepercentages,andmixandmatchfractions,pixels,remandpercentages:

.container{

grid-template-columns:3rem15%1fr2fr

}

Using repeat()

CSSGrid

112

Page 113: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

repeat()isaspecialfunctionthattakesanumberthatindicatesthenumberoftimesarow/columnwillberepeated,andthelengthofeachone.

Ifeverycolumnhasthesamewidthyoucanspecifythelayoutusingthissyntax:

.container{

grid-template-columns:repeat(4,100px);

}

Thiscreates4columnswiththesamewidth.

Orusingfractions:

.container{

grid-template-columns:repeat(4,1fr);

}

Specifyaminimumwidthforarow

Commonusecase:Haveasidebarthatnevercollapsesmorethanacertainamountofpixelswhenyouresizethewindow.

Here'sanexamplewherethesidebartakes1/4ofthescreenandnevertakeslessthan200px:

.container{

grid-template-columns:minmax(200px,3fr)9fr;

}

Youcanalsosetjustamaximumvalueusingthe autokeyword:

.container{

grid-template-columns:minmax(auto,50%)9fr;

}

orjustaminimumvalue:

.container{

grid-template-columns:minmax(100px,auto)9fr;

}

Positioningelementsusing grid-template-areas

BydefaultelementsarepositionedinthegridusingtheirorderintheHTMLstructure.

CSSGrid

113

Page 114: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Using grid-template-areasYoucandefinetemplateareastomovethemaroundinthegrid,andalsotospawnanitemonmultiplerows/columnsinsteadofusing grid-column.

Here'sanexample:

<divclass="container">

<main>

...

</main>

<aside>

...

</aside>

<header>

...

</header>

<footer>

...

</footer>

</div>

.container{

display:grid;

grid-template-columns:200px200px200px200px;

grid-template-rows:300px300px;

grid-template-areas:

"headerheaderheaderheader"

"sidebarmainmainmain"

"footerfooterfooterfooter";

}

main{

grid-area:main;

}

aside{

grid-area:sidebar;

}

header{

grid-area:header;

}

footer{

grid-area:footer;

}

Despitetheiroriginalorder,itemsareplacedwhere grid-template-areasdefine,dependingonthe grid-areapropertyassociatedtothem.

Addingemptycellsintemplateareas

Youcansetanemptycellusingthedot .insteadofanareanamein grid-template-areas:

.container{

CSSGrid

114

Page 115: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

display:grid;

grid-template-columns:200px200px200px200px;

grid-template-rows:300px300px;

grid-template-areas:

".headerheader."

"sidebar.mainmain"

".footerfooter.";

}

FillapagewithagridYoucanmakeagridextendtofillthepageusing fr:

.container{

display:grid;

height:100vh;

grid-template-columns:1fr1fr1fr1fr;

grid-template-rows:1fr1fr;

}

Anexample:header,sidebar,contentandfooterHereisasimpleexampleofusingCSSGridtocreateasitelayoutthatprovidesaheaderoptop,amainpartwithsidebarontheleftandcontentontheright,andafooterafterwards.

Here'sthemarkup:

<divclass="wrapper">

<header>Header</header>

<article>

<h1>Welcome</h1>

<p>Hi!</p>

</article>

CSSGrid

115

Page 116: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

<aside><ul><li>Sidebar</li></ul></aside>

<footer>Footer</footer>

</div>

andhere'stheCSS:

header{

grid-area:header;

background-color:#fed330;

padding:20px;

}

article{

grid-area:content;

background-color:#20bf6b;

padding:20px;

}

aside{

grid-area:sidebar;

background-color:#45aaf2;

}

footer{

padding:20px;

grid-area:footer;

background-color:#fd9644;

}

.wrapper{

display:grid;

grid-gap:20px;

grid-template-columns:1fr3fr;

grid-template-areas:

"headerheader"

"sidebarcontent"

"footerfooter";

}

Iaddedsomecolorstomakeitprettier,butbasicallyitassignstoeverydifferenttaga grid-areaname,whichisusedinthe grid-template-areaspropertyin .wrapper.

Whenthelayoutissmallerwecanputthesidebarbelowthecontentusingamediaquery:

@media(max-width:500px){

.wrapper{

grid-template-columns:4fr;

grid-template-areas:

"header"

"content"

"sidebar"

"footer";

}

}

SeeonCodePen

CSSGrid

116

Page 117: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

WrappingupThesearethebasicsofCSSGrid.TherearemanythingsIdidn'tincludeinthisintroductionbutIwantedtomakeitverysimple,tostartusingthisnewlayoutsystemwithoutmakingitfeeloverwhelming.

CSSGrid

117

Page 118: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

FlexboxFlexbox,alsocalledFlexibleBoxModule,isoneofthetwomodernlayoutssystems,alongwithCSSGrid.

ComparedtoCSSGrid(whichisbi-dimensional),flexboxisaone-dimensionallayoutmodel.Itwillcontrolthelayoutbasedonaroworonacolumn,butnottogetheratthesametime.

Themaingoalofflexboxistoallowitemstofillthewholespaceofferedbytheircontainer,dependingonsomerulesyouset.

UnlessyouneedtosupportoldbrowserslikeIE8andIE9,Flexboxisthetoolthatletsyouforgetaboutusing

TablelayoutsFloatsclearfixhacksdisplay:tablehacks

Let'sdiveintoflexboxandbecomeamasterofitinaveryshorttime.

BrowsersupportAtthetimeofwriting(Feb2018),it'ssupportedby97.66%oftheusers,allthemostimportantbrowsersimplementitsinceyears,soevenolderbrowsers(includingIE10+)arecovered:

Flexbox

118

Page 119: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

WhilewemustwaitafewyearsforuserstocatchuponCSSGrid,Flexboxisanoldertechnologyandcanbeusedrightnow.

EnableFlexboxAflexboxlayoutisappliedtoacontainer,bysetting

display:flex;

or

display:inline-flex;

thecontentinsidethecontainerwillbealignedusingflexbox.

Containerproperties

Flexbox

119

Page 120: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Someflexboxpropertiesapplytothecontainer,whichsetsthegeneralrulesforitsitems.Theyare

flex-direction

justify-content

align-items

flex-wrap

flex-flow

Alignrowsorcolumns

Thefirstpropertywesee, flex-direction,determinesifthecontainershouldalignitsitemsasrows,orascolumns:

flex-direction:rowplacesitemsasarow,inthetextdirection(left-to-rightforwesterncountries)flex-direction:row-reverseplacesitemsjustlike rowbutintheoppositedirectionflex-direction:columnplacesitemsinacolumn,orderingtoptobottomflex-direction:column-reverseplacesitemsinacolumn,justlike columnbutintheoppositedirection-

Verticalandhorizontalalignment

Bydefaultitemsstartfromtheleftis flex-directionisrow,andfromthetopif flex-directioniscolumn.

Flexbox

120

Page 121: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Youcanchangethisbehaviorusing justify-contenttochangethehorizontalalignment,andalign-itemstochangetheverticalalignment.

Changethehorizontalalignment

justify-contenthas5possiblevalues:

Flexbox

121

Page 122: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

flex-start:aligntotheleftsideofthecontainer.flex-end:aligntotherightsideofthecontainer.center:alignatthecenterofthecontainer.space-between:displaywithequalspacingbetweenthem.space-around:displaywithequalspacingaroundthem

Changetheverticalalignment

align-itemshas5possiblevalues:

Flexbox

122

Page 123: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

flex-start:aligntothetopofthecontainer.flex-end:aligntothebottomofthecontainer.center:alignattheverticalcenterofthecontainer.baseline:displayatthebaselineofthecontainer.stretch:itemsarestretchedtofitthecontainer.

Flexbox

123

Page 124: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Flexbox

124

Page 125: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Anoteon baseline

baselinelookssimilarto flex-startinthisexample,duetomyboxesbeingtoosimple.CheckoutthisCodepentohaveamoreusefulexample,whichIforkedfromaPenoriginallycreatedbyMartinMichálek.Asyoucanseethere,itemsdimensionsarealigned.

Wrap

Bydefaultitemsinaflexboxcontainerarekeptonasingleline,shrinkingthemtofitinthecontainer.

Toforcetheitemstospreadacrossmultiplelines,use flex-wrap:wrap.Thiswilldistributetheitemsaccordingtotheordersetin flex-direction.Use flex-wrap:wrap-reversetoreversethisorder.

Ashorthandpropertycalled flex-flowallowsyoutospecify flex-directionand flex-wrapinasingleline,byaddingthe flex-directionvaluefirst,followedby flex-wrapvalue,forexample: flex-flow:rowwrap.

PropertiesthatapplytoeachsingleitemSincenow,we'veseenthepropertiesyoucanapplytothecontainer.

Singleitemscanhaveacertainamountofindependenceandflexibility,andyoucanaltertheirappearanceusingthoseproperties:

order

align-self

flex-grow

flex-shrink

flex-basis

flex

Let'sseethemindetail.

Movingitemsbefore/afteranotheroneusingorder

Itemsareorderedbasedonaordertheyareassigned.Bydefaulteveryitemhasorder 0andtheappearanceintheHTMLdeterminesthefinalorder.

Flexbox

125

Page 126: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Youcanoverridethispropertyusing orderoneachseparateitem.Thisisapropertyyousetontheitem,notthecontainer.Youcanmakeanitemappearbeforealltheothersbysettinganegativevalue.

Verticalalignmentusingalign-self

Anitemcanchoosetooverridethecontainer align-itemssetting,using align-self,whichhasthesame5possiblevaluesof align-items:

flex-start:aligntothetopofthecontainer.flex-end:aligntothebottomofthecontainer.center:alignattheverticalcenterofthecontainer.baseline:displayatthebaselineofthecontainer.stretch:itemsarestretchedtofitthecontainer.

Flexbox

126

Page 127: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Groworshrinkanitemifnecessary

flex-grow

Thedefautforanyitemis0.

Ifallitemsaredefinedas1andoneisdefinedas2,thebiggerelementwilltakethespaceoftwo"1"items.

flex-shrink

Thedefautforanyitemis1.

Ifallitemsaredefinedas1andoneisdefinedas3,thebiggerelementwillshrink3xtheotherones.Whenlessspaceisavailable,itwilltake3xlessspace.

flex-basis

Ifsetto auto,itsizesanitemaccordingtoitswidthorheight,andaddsextraspacebasedonthe flex-growproperty.

Ifsetto0,itdoesnotaddanyextraspacefortheitemwhencalculatingthelayout.

Ifyouspecifyapixelnumbervalue,itwillusethatasthelengthvalue(widthorheightdependsifit'saroworacolumnitem)

flex

Flexbox

127

Page 128: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Thispropertycombinestheabove3properties:

flex-grow

flex-shrink

flex-basis

andprovidesashorthandsyntax: flex:01auto

Flexbox

128

Page 129: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

TablesTablesinthepastweregreatlyoverusedinCSS,astheywereoneoftheonlywayswecouldcreateafancypagelayout.

TodaywithGridandFlexboxwecanmovetablesbacktothejobtheywereintendedtodo:stylingtables.

Let'sstartfromtheHTML.Thisisabasictable:

<table>

<thead>

<tr>

<thscope="col">Name</th>

<thscope="col">Age</th>

</tr>

</thead>

<tbody>

<tr>

<thscope="row">Flavio</th>

<td>36</td>

</tr>

<tr>

<thscope="row">Roger</th>

<td>7</td>

</tr>

</tbody>

</table>

Bydefaultit'snotveryattractive.Thebrowserprovidessomestandardstyles,andthat'sit:

WecanuseCSStostylealltheelementsofthetable,ofcourse.

Let'sstartwiththeborder.Anicebordercangoalongway.

Tables

129

Page 130: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Wecanapplyitonthe tableelement,andontheinnerelementstoo,like thand td:

table,th,td{

border:1pxsolid#333;

}

Ifwepairitwithsomemargin,wegetaniceresult:

Onecommonthingwithtablesistheabilitytoaddacolortoonerow,andadifferentcolortoanotherrow.Thisispossibleusingthe :nth-child(odd)or :nth-child(even)selector:

tbodytr:nth-child(odd){

background-color:#af47ff;

}

Thisgivesus:

Tables

130

Page 131: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Ifyouadd border-collapse:collapse;tothetableelement,allbordersarecollapsedintoone:

Tables

131

Page 132: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Tables

132

Page 133: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

CenteringCenteringthingsinCSSisataskthatisverydifferentifyouneedtocenterhorizontallyorvertically.

InthispostIexplainthemostcommonscenariosandhowtosolvethem.IfanewsolutionisprovidedbyFlexboxIignoretheoldtechniquesbecauseweneedtomoveforward,andFlexboxissupportedbybrowserssinceyears,IE10included.

Centerhorizontally

Text

Textisverysimpletocenterhorizontallyusingthe text-alignpropertysetto center:

p{

text-align:center;

}

Blocks

ThemodernwaytocenteranythingthatisnottextistouseFlexbox:

#mysection{

display:flex;

justify-content:center;

}

anyelementinside #mysectionwillbehorizontallycentered.

Centering

133

Page 134: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Hereisthealternativeapproachifyoudon'twanttouseFlexbox.

Anythingthatisnottextcanbecenteredbyapplyinganautomaticmargintoleftandright,andsettingthewidthoftheelement:

section{

margin:0auto;

width:50%;

}

theabove margin:0auto;isashorthandfor:

section{

margin-top:0;

margin-bottom:0;

margin-left:auto;

margin-right:auto;

}

Remembertosettheitemto display:blockifit'saninlineelement.

CenterverticallyTraditionallythishasalwaysbeenadifficulttask.Flexboxnowprovidesusagreatwaytodothisinthesimplestpossibleway:

#mysection{

display:flex;

align-items:center;

}

anyelementinside #mysectionwillbeverticallycentered.

Centering

134

Page 135: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

CenterbothverticallyandhorizontallyFlexboxtechniquestocenterverticallyandhorizontallycanbecombinedtocompletelycenteranelementinthepage.

#mysection{

display:flex;

align-items:center;

justify-content:center;

}

ThesamecanbedoneusingCSSGrid:

body{

display:grid;

Centering

135

Page 136: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

place-items:center;

height:100vh;

}

Centering

136

Page 137: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

ListsListsareaveryimportantpartofmanywebpages.

CSScanstylethemusingseveralproperties.

list-style-typeisusedtosetapredefinedmarkertobeusedbythelist:

li{

list-style-type:square;

}

Wehavelotsofpossiblevalues,whichyoucanseeherehttps://developer.mozilla.org/en-US/docs/Web/CSS/list-style-typewithexamplesoftheirappearance.Someofthemostpopularonesare disc, circle, squareand none.

list-style-imageisusedtouseacustommarkerwhenapredefinedmarkerisnotappropriate:

li{

list-style-image:url(list-image.png);

}

list-style-positionletsyouaddthemarker outside(thedefault)or insideofthelistcontent,intheflowofthepageratherthanoutsideofit

li{

list-style-position:inside;

}

The list-styleshorthandpropertyletsusspecifyallthosepropertiesinthesameline:

li{

list-style:url(list-image.png)inside;

}

Lists

137

Page 138: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

MediaqueriesandresponsivedesignInthissectionwe'regoingtofirstintroducemediatypesandmediafeaturedescriptors,thenwe'llexplainmediaqueries.

MediatypesUsedinmediaqueriesand@importdeclarations,mediatypesallowustodetermineonwhichmediaaCSSfile,orapieceofCSS,isloaded.

Wehavethefollowingmediatypes

allmeansallthemediaprintusedwhenprintingscreenusedwhenthepageispresentedonascreenspeechusedforscreenreaders

screenisthedefault.

Inthepastwehadmoreofthem,butmostaredeprecatedastheyproventonotbeaneffectivewayofdeterminingdeviceneeds.

Wecanusethemin@importstatementslikethis:

@importurl(myfile.css)screen;

@importurl(myfile-print.css)print;

WecanloadaCSSfileonmultiplemediatypesseparatingeachwithacomma:

@importurl(myfile.css)screen,print;

Thesameworksforthe linktaginHTML:

<linkrel="stylesheet"type="text/css"href="myfile.css"media="screen"/>

<linkrel="stylesheet"type="text/css"href="another.css"media="screen,print"/>

We'renotlimitedtojustusingmediatypesinthe mediaattributeandinthe @importdeclaration.There'smore

Mediafeaturedescriptors

Mediaqueriesandresponsivedesign

138

Page 139: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

First,let'sintroducemediafeaturedescriptors.Theyareadditionalkeywordsthatwecanaddtothe mediaattributeof linkorthethe @importdeclaration,toexpressmoreconditionalsovertheloadingoftheCSS.

Here'sthelistofthem:

width

height

device-width

device-height

aspect-ratio

device-aspect-ratio

color

color-index

monochrome

resolution

orientation

scan

grid

Eachofthemhaveacorrespondingmin-andmax-,forexample:

min-width, max-widthmin-device-width, max-device-width

andsoon.

Someofthoseacceptalengthvaluewhichcanbeexpressedin pxor remoranylengthvalue.It'sthecaseof width, height, device-width, device-height.

Forexample:

@importurl(myfile.css)screenand(max-width:800px);

Noticethatwewrapeachblockusingmediafeaturedescriptorsinparentheses.

Someacceptafixedvalue. orientation,usedtodetectthedeviceorientation,acceptsportraitor landscape.

Example:

<linkrel="stylesheet"type="text/css"href="myfile.css"media="screenand(orientation:p

ortrait)"/>

Mediaqueriesandresponsivedesign

139

Page 140: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

scan,usedtodeterminethetypeofscreen,accepts progressive(formoderndisplays)orinterlace(forolderCRTdevices)

Someotherswantaninteger.

Like colorwhichinspectsthenumberofbitspercolorcomponentusedbythedevice.Verylow-level,butyoujustneedtoknowit'sthereforyourusage(like grid, color-index,monochrome).

aspect-ratioand device-aspect-ratioacceptaratiovaluerepresentingthewidthtoheightviewportratio,whichisexpressedasafraction.

Example:

@importurl(myfile.css)screenand(aspect-ratio:4/3);

resolutionrepresentsthepixeldensityofthedevice,expressedinaresolutiondatatypelikedpi.

Example:

@importurl(myfile.css)screenand(min-resolution:100dpi);

LogicoperatorsWecancombinerulesusing and:

<linkrel="stylesheet"type="text/css"href="myfile.css"media="screenand(max-width:800

px)"/>

Wecanperforman"or"typeoflogicoperationusingcommas,whichcombinesmultiplemediaqueries:

@importurl(myfile.css)screen,print;

Wecanuse nottonegateamediaquery:

@importurl(myfile.css)notscreen;

Important: notcanonlybeusedtonegateanentiremediaquery,soitmustbeplacedatthebeginningofit(orafteracomma)

Mediaqueriesandresponsivedesign

140

Page 141: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

MediaqueriesAllthoseaboveruleswesawappliedto@importorthethe linkHTMLtagcanbeappliedinsidetheCSS,too.

Youneedtowrapthemina @media(){}structure.

Example:

@mediascreenand(max-width:800px){

/*entersomeCSS*/

}

andthisisthefoundationforresponsivedesign.

Mediaqueriescanbequitecomplex.ThisexampleappliestheCSSonlyifit'sascreendevice,thewidthisbetween600and800pixels,andtheorientationislandscape:

@mediascreenand(max-width:800px)and(min-width:600px)and(orientation:landscape){

/*entersomeCSS*/

}

Mediaqueriesandresponsivedesign

141

Page 142: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

FeatureQueriesFeaturequeriesarearecentandrelativelyunknownabilityofCSS,butawellsupportedone.

Wecanuseittocheckifafeatureissupportedbythebrowserusingthe @supportskeyword.

ForexampleIthinkthisisespeciallyuseful,atthetimeofwriting,forcheckingifabrowsersupportsCSSgrid,forexample,whichcanbedoneusing:

@supports(display:grid){

/*applythisCSS*/

}

Wecheckifthebrowsersupportsthe gridvalueforthe displayproperty.

Wecanuse @supportsforanyCSSproperty,tocheckanyvalue.

Wecanalsousethelogicaloperators and, orand nottobuildcomplexfeaturequeries:

@supports(display:grid)and(display:flex){

/*applythisCSS*/

}

FeatureQueries

142

Page 143: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

FiltersFiltersallowustoperformoperationsonelements.

ThingsyounormallydowithPhotoshoporotherphotoeditingsoftware,likechangingtheopacityorthebrightness,andmore.

Youusethe filterproperty.Here'sanexampleofitappliedonanimage,butthispropertycanbeusedonanyelement:

img{

filter:<something>;

}

Youcanusevariousvalueshere:

blur()

brightness()

contrast()

drop-shadow()

grayscale()

hue-rotate()

invert()

opacity()

sepia()

saturate()

url()

Noticetheparenthesesaftereachoption,becausetheyallrequireaparameter.

Forexample:

img{

filter:opacity(0.5);

}

meanstheimagewillbe50%transparent,because opacity()takesonevaluefrom0to1,orapercentage.

Youcanalsoapplymultiplefiltersatonce:

img{

filter:opacity(0.5)blur(2px);

}

Filters

143

Page 144: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Let'snowtalkabouteachfilterindetails.

blur()

Blursanelementcontent.Youpassitavalue,expressedin pxor emor remthatwillbeusedtodeterminetheblurradius.

Example:

img{

filter:blur(4px);

}

opacity()

opacity()takesonevaluefrom0to1,orapercentage,anddeterminestheimagetransparencybasedonit.

0,or 0%,meanstotallytransparent. 1,or 100%,orhigher,meanstotallyvisible.

Example:

img{

filter:opacity(0.5);

}

CSSalsohasan opacityproperty. filterhowevercanbehardwareaccelerated,dependingontheimplementation,sothisshouldbethepreferredmethod.

drop-shadow()

drop-shadow()showsashadowbehindtheelement,whichfollowsthealphachannel.Thismeansthatifyouhaveatransparentimage,yougetashadowappliedtotheimageshape,nottheimagebox.Iftheimagedoesnothaveanalphachannel,theshadowwillbeappliedtotheentireimagebox.

Itacceptsaminimumof2parameters,upto5:

offset-xsetsthehorizontaloffset.Canbenegative.offset-ysetstheverticaloffset.Canbenegative.blur-radius,optional,setstheblurradiusfortheshadow.Itdefaultsto0,noblur.spread-radius,optional,setsthespreadradius.Expressedin px, remor emcolor,optional,setsthecoloroftheshadow.

Filters

144

Page 145: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Youcansetthecolorwithoutsettingthespreadradiusorblurradius.CSSunderstandsthevalueisacolorandnotalengthvalue.

Example:

img{

filter:drop-shadow(10px10px5pxorange);

}

img{

filter:drop-shadow(10px10pxorange);

}

img{

filter:drop-shadow(10px10px5px5px#333);

}

grayscale()

Maketheelementhaveagraycolor.

Youpassonevaluefrom0to1,orfrom0%to100%,where1and100%meancompletelygray,and0or0%meantheimageisnottouched,andtheoriginalcolorsremain.

Example:

img{

filter:grayscale(50%);

}

sepia()

Maketheelementhaveasepiacolor.

Youpassonevaluefrom0to1,orfrom0%to100%,where1and100%meancompletelysepia,and0or0%meantheimageisnottouched,andtheoriginalcolorsremain.

Example:

img{

filter:sepia(50%);

}

invert()

Filters

145

Page 146: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Invertthecolorsofanelement.InvertingacolormeanslookinguptheoppositeofacolorintheHSLcolorwheel.Justsearch"colorwheel"inGoogleifyouhavenoideawhatdoesthatmeans.Forexample,theoppositeofyellowisblue,theoppositeofrediscyan.Everysinglecolorhasanopposite.

Youpassanumber,from0to1orfrom0%to100%,thatdeterminestheamountofinversion.1or100%meansfullinversion,0or0%meansnoinversion.

0.5or50%willalwaysrendera50%graycolor,becauseyoualwaysendupinthemiddleofthewheel.

Example:

img{

filter:invert(50%);

}

hue-rotate()

TheHSLcolorwheelisrepresentedindegrees.Using hue-rotate()youcanrotatethecolorusingapositiveornegativerotation.

Thefunctionacceptsa degvalue.

Example:

img{

filter:hue-rotate(90deg);

}

brightness()

Altersthebrightnessofanelement.

0or0%givesatotalblackelement.1or100%givesanunchangedimage

Valueshigherthan1or100%maketheimagebrighteruptoreachingatotalwhiteelement.

Example:

img{

filter:brightness(50%);

}

contrast()

Filters

146

Page 147: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Altersthecontrastofanelement.

0or0%givesatotalgrayelement.1or100%givesanunchangedimage

Valueshigherthan1or100%givemorecontrast.

Example:

img{

filter:contrast(150%);

}

saturate()

Altersthesaturationofanelement.

0or0%givesatotalgrayscaleelement(withlesssaturation).1or100%givesanunchangedimage

Valueshigherthan1or100%givemoresaturation.

Example:

img{

filter:saturate();

}

url()

ThisfilterallowstoapplyafilterdefinedinanSVGfile.YoupointtotheSVGfilelocation.

Example:

img{

filter:url(filter.svg);

}

SVGfiltersareoutofthescopeofthisbook,butyoucanreadmoreonthisSmashingMagazinepost:https://www.smashingmagazine.com/2015/05/why-the-svg-filter-is-awesome/

Filters

147

Page 148: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

TransformsTransformsallowyoutotranslate,rotate,scale,andskewelements,inthe2Dor3Dspace.TheyareaverycoolCSSfeature,especiallywhencombinedwithanimations.

2DtransformsThe transformpropertyacceptsthosefunctions:

translate()tomoveelementsaroundrotate()torotateelementsscale()toscaleelementsinsizeskew()totwistorslantanelementmatrix()awaytoperformanyoftheaboveoperationsusingamatrixof6elements,alessuserfriendlysyntaxbutlessverbose

Wealsohaveaxis-specificfunctions:

translateX()tomoveelementsaroundontheXaxistranslateY()tomoveelementsaroundontheYaxisscaleX()toscaleelementsinsizeontheXaxisscaleY()toscaleelementsinsizeontheYaxisskewX()totwistorslantanelementontheXaxisskewY()totwistorslantanelementontheYaxis

Hereisanexampleofatransformwhichchangesthe .boxelementwidthby2(duplicatingit)andtheheightby0.5(reducingittohalf):

.box{

transform:scale(2,0.5);

}

transform-originletsussettheorigin(the (0,0)coordinates)forthetransformation,lettinguschangetherotationcenter.

CombiningmultipletransformsYoucancombinemultipletransformsbyseparatingeachfunctionwithaspace.

Forexample:

Transforms

148

Page 149: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

transform:rotateY(20deg)scaleX(3)translateY(100px);

3DtransformsWecangoonestepfurtherandmoveourelementsina3Dspaceinsteadthanona2Dspace.With3D,weareaddinganotheraxis,Z,whichaddsdepthtooutvisuals.

Usingthe perspectivepropertyyoucanspecifyhowfarthe3Dobjectisfromtheviewer.

Example:

.3Delement{

perspective:100px;

}

perspective-origindeterminestheappearanceofthepositionoftheviewer,howarewelookingatitintheXandYaxis.

NowwecanuseadditionalfunctionsthatcontroltheZaxis,thataddsuptotheotherXandYaxistransforms:

translateZ()

rotateZ()

scaleZ()

andthecorrespondingshorthands translate3d(), rotate3d()and scale3d()asshorthandsforusingthe translateX(), translateY()and translateZ()functionsandsoon.

3Dtransformsareabittooadvancedforthishandbook,butagreattopictoexploreonyourown.

Transforms

149

Page 150: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

TransitionsCSSTransitionsarethemostsimplewaytocreateananimationinCSS.

Inatransition,youchangethevalueofaproperty,andyoutellCSStoslowlychangeitaccordingtosomeparameters,towardsafinalstate.

CSSTransitionsaredefinedbytheseproperties:

Property Descriptiontransition-

property theCSSpropertythatshouldtransition

transition-

duration thedurationofthetransition

transition-timing-

function

thetimingfunctionusedbytheanimation(commonvalues:linear,ease).Default:ease

transition-delay optionalnumberofsecondstowaitbeforestartingtheanimation

The transitionpropertyisahandyshorthand:

.container{

transition:property

duration

timing-function

delay;

}

ExampleofaCSSTransitionThiscodeimplementsaCSSTransition:

.one,

.three{

background:rgba(142,92,205,.75);

transition:background1sease-in;

}

.two,

.four{

background:rgba(236,252,100,.75);

}

.circle:hover{

background:rgba(142,92,205,.25);/*lighter*/

}

Transitions

150

Page 151: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

SeetheexampleonGlitchhttps://flavio-css-transitions-example.glitch.me

Whenhoveringthe .oneand .threeelements,thepurplecircles,thereisatransitionanimationthateasethechangeofbackground,whiletheyellowcirclesdonot,becausetheydonothavethe transitionpropertydefined.

Transitiontimingfunctionvaluestransition-timing-functionallowstospecifytheaccelerationcurveofthetransition.

Therearesomesimplevaluesyoucanuse:

linear

ease

ease-in

ease-out

ease-in-out

ThisGlitchshowshowthoseworkinpractice.

Youcancreateacompletelycustomtimingfunctionusingcubicbeziercurves.Thisisratheradvanced,butbasicallyanyofthosefunctionsaboveisbuiltusingbeziercurves.Wehavehandynamesastheyarecommonones.

CSSTransitionsinBrowserDevToolsTheBrowserDevToolsofferagreatwaytovisualizetransitions.

ThisisChrome:

Transitions

151

Page 152: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

ThisisFirefox:

Transitions

152

Page 153: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Fromthosepanelsyoucanliveeditthetransitionandexperimentinthepagedirectlywithoutreloadingyourcode.

WhichPropertiesyoucanAnimateusingCSSAnimationsAlot!TheyarethesameyoucananimateusingCSSTransitions,too.

Here'sthefulllist:

background

background-color

background-position

background-size

border

border-color

border-width

border-bottom

border-bottom-color

border-bottom-left-radius

Transitions

153

Page 154: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

border-bottom-right-radius

border-bottom-width

border-left

border-left-color

border-left-width

border-radius

border-right

border-right-color

border-right-width

border-spacing

border-top

border-top-color

border-top-left-radius

border-top-right-radius

border-top-width

bottom

box-shadow

caret-color

clip

color

column-count

column-gap

column-rule

column-rule-color

column-rule-width

column-width

columns

content

filter

flex

flex-basis

flex-grow

flex-shrink

font

font-size

font-size-adjust

font-stretch

font-weight

grid-area

grid-auto-columns

Transitions

154

Page 155: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

grid-auto-flow

grid-auto-rows

grid-column-end

grid-column-gap

grid-column-start

grid-column

grid-gap

grid-row-end

grid-row-gap

grid-row-start

grid-row

grid-template-areas

grid-template-columns

grid-template-rows

grid-template

grid

height

left

letter-spacing

line-height

margin

margin-bottom

margin-left

margin-right

margin-top

max-height

max-width

min-height

min-width

opacity

order

outline

outline-color

outline-offset

outline-width

padding

padding-bottom

padding-left

padding-right

padding-top

Transitions

155

Page 156: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

perspective

perspective-origin

quotes

right

tab-size

text-decoration

text-decoration-color

text-indent

text-shadow

top

transform.

vertical-align

visibility

width

word-spacing

z-index

Transitions

156

Page 157: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

AnimationsCSSAnimationsareagreatwaytocreatevisualanimations,notlimitedtoasinglemovementlikeCSSTransitions,butmuchmorearticulated.

Ananimationisappliedtoanelementusingthe animationproperty.

.container{

animation:spin10slinearinfinite;

}

spinisthenameoftheanimation,whichweneedtodefineseparately.WealsotellCSStomaketheanimationlast10seconds,performitinalinearway(noaccelerationoranydifferenceinitsspeed)andtorepeatitinfinitely.

Youmustdefinehowyouranimationworksusingkeyframes.Exampleofananimationthatrotatesanitem:

@keyframesspin{

0%{

transform:rotateZ(0);

}

100%{

transform:rotateZ(360deg);

}

}

Insidethe @keyframesdefinitionyoucanhaveasmanyintermediatewaypointsasyouwant.

InthiscaseweinstructCSStomakethetransformpropertytorotatetheZaxisfrom0to360grades,completingthefullloop.

YoucanuseanyCSStransformhere.

Noticehowthisdoesnotdictateanythingaboutthetemporalintervaltheanimationshouldtake.Thisisdefinedwhenyouuseitvia animation.

ACSSAnimationsExampleIwanttodrawfourcircles,allwithastartingpointincommon,all90degreesdistantfromeachother.

<divclass="container">

<divclass="circleone"></div>

Animations

157

Page 158: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

<divclass="circletwo"></div>

<divclass="circlethree"></div>

<divclass="circlefour"></div>

</div>

body{

display:grid;

place-items:center;

height:100vh;

}

.circle{

border-radius:50%;

left:calc(50%-6.25em);

top:calc(50%-12.5em);

transform-origin:50%12.5em;

width:12.5em;

height:12.5em;

position:absolute;

box-shadow:01em2emrgba(0,0,0,.5);

}

.one,

.three{

background:rgba(142,92,205,.75);

}

.two,

.four{

background:rgba(236,252,100,.75);

}

.one{

transform:rotateZ(0);

}

.two{

transform:rotateZ(90deg);

}

.three{

transform:rotateZ(180deg);

}

.four{

transform:rotateZ(-90deg);

}

YoucanseetheminthisGlitch:https://flavio-css-circles.glitch.me

Let'smakethisstructure(allthecirclestogether)rotate.Todothis,weapplyananimationonthecontainer,andwedefinethatanimationasa360degreesrotation:

Animations

158

Page 159: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

@keyframesspin{

0%{

transform:rotateZ(0);

}

100%{

transform:rotateZ(360deg);

}

}

.container{

animation:spin10slinearinfinite;

}

Seeitonhttps://flavio-css-animations-tutorial.glitch.me

Youcanaddmorekeyframestohavefunnieranimations:

@keyframesspin{

0%{

transform:rotateZ(0);

}

25%{

transform:rotateZ(30deg);

}

50%{

transform:rotateZ(270deg);

}

75%{

transform:rotateZ(180deg);

}

100%{

transform:rotateZ(360deg);

}

}

Seetheexampleonhttps://flavio-css-animations-four-steps.glitch.me

TheCSSanimationpropertiesCSSanimationsoffersalotofdifferentparametersyoucantweak:

Property Description

animation-

namethenameoftheanimation,itreferencesananimationcreatedusing@keyframes

animation-

duration howlongtheanimationshouldlast,inseconds

animation-

timing-

function

thetimingfunctionusedbytheanimation(commonvalues: linear,ease).Default: ease

Animations

159

Page 160: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

animation-

delayoptionalnumberofsecondstowaitbeforestartingtheanimation

animation-

iteration-

count

howmanytimestheanimationshouldbeperformed.Expectsanumber,orinfinite.Default:1

animation-

direction

thedirectionoftheanimation.Canbe normal, reverse, alternateoralternate-reverse.Inthelast2,italternatesgoingforwardandthenbackwards

animation-

fill-mode

defineshowtostyletheelementwhentheanimationends,afteritfinishesitsiterationcountnumber. noneor backwardsgobacktothefirstkeyframestyles. forwardsand bothusethestylethat'ssetinthelastkeyframe

animation-

play-state ifsetto paused,itpausestheanimation.Defaultis running

The animationpropertyisashorthandforalltheseproperties,inthisorder:

.container{

animation:name

duration

timing-function

delay

iteration-count

direction

fill-mode

play-state;

}

Thisistheexampleweusedabove:

.container{

animation:spin10slinearinfinite;

}

JavaScripteventsforCSSAnimationsUsingJavaScriptyoucanlistenforthefollowingevents:

animationstart

animationend

animationiteration

Becarefulwith animationstart,becauseiftheanimationstartsonpageload,yourJavaScriptcodeisalwaysexecutedaftertheCSShasbeenprocessed,sotheanimationisalreadystartedandyoucannotintercepttheevent.

constcontainer=document.querySelector('.container')

Animations

160

Page 161: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

container.addEventListener('animationstart',(e)=>{

//dosomething

},false)

container.addEventListener('animationend',(e)=>{

//dosomething

},false)

container.addEventListener('animationiteration',(e)=>{

//dosomething

},false)

WhichPropertiesYouCanAnimateusingCSSAnimationsAlot!TheyarethesameyoucananimateusingCSSTransitions,too.

Here'sthefulllist:

background

background-color

background-position

background-size

border

border-color

border-width

border-bottom

border-bottom-color

border-bottom-left-radius

border-bottom-right-radius

border-bottom-width

border-left

border-left-color

border-left-width

border-radius

border-right

border-right-color

border-right-width

border-spacing

border-top

border-top-color

border-top-left-radius

Animations

161

Page 162: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

border-top-right-radius

border-top-width

bottom

box-shadow

caret-color

clip

color

column-count

column-gap

column-rule

column-rule-color

column-rule-width

column-width

columns

content

filter

flex

flex-basis

flex-grow

flex-shrink

font

font-size

font-size-adjust

font-stretch

font-weight

grid-area

grid-auto-columns

grid-auto-flow

grid-auto-rows

grid-column-end

grid-column-gap

grid-column-start

grid-column

grid-gap

grid-row-end

grid-row-gap

grid-row-start

grid-row

grid-template-areas

grid-template-columns

Animations

162

Page 163: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

grid-template-rows

grid-template

grid

height

left

letter-spacing

line-height

margin

margin-bottom

margin-left

margin-right

margin-top

max-height

max-width

min-height

min-width

opacity

order

outline

outline-color

outline-offset

outline-width

padding

padding-bottom

padding-left

padding-right

padding-top

perspective

perspective-origin

quotes

right

tab-size

text-decoration

text-decoration-color

text-indent

text-shadow

top

transform.

vertical-align

visibility

Animations

163

Page 164: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

width

word-spacing

z-index

Animations

164

Page 165: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

NormalizingCSSThedefaultbrowserstylesheetisthesetofrulesthatbrowserhavetoapplysomeminimumstyletoelements.

Mostofthetimesthosestylesareveryuseful.

Sinceeverybrowserhasitsownset,it'scommonfindingacommonground.

Ratherthanremovingalldefaults,likeoneoftheCSSresetapproachesdo,thenormalizingprocessremovesbrowserinconsistencies,whilekeepingabasicsetofrulesyoucanrelyon.

Normalize.csshttp://necolas.github.io/normalize.cssisthemostcommonlyusedsolutionforthisproblem.

YoumustloadthenormalizingCSSfilebeforeanyotherCSS.

NormalizingCSS

165

Page 166: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

ErrorhandlingCSSisresilient.Whenitfindsanerror,itdoesnotactlikeJavaScriptwhichpacksupallitsthingsandgoesawayaltogether,terminatingallthescriptexecutionaftertheerrorisfound.

CSStriesveryhardtodowhatyouwant.

Ifalinehasanerror,itskipsitandjumpstothenextlinewithoutanyerror.

Ifyouforgetthesemicolonononeline:

p{

font-size:20px

color:black;

border:1pxsolidblack;

}

thelinewiththeerrorANDthenextonewillnotbeapplied,butthethirdrulewillbesuccessfullyappliedonthepage.Basically,itscansalluntilitfindsasemicolon,butwhenitreachesit,theruleisnow font-size:20pxcolor:black;,whichisinvalid,soitskipsit.

Sometimesit'strickytorealizethereisanerrorsomewhere,andwherethaterroris,becausethebrowserwon'ttellus.

ThisiswhytoolslikeCSSLintexist.

Errorhandling

166

Page 167: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

VendorprefixesVendorprefixesareonewaybrowsersusetogiveusCSSdevelopersaccesstonewerfeaturesnotyetconsideredstable.

Beforegoingonkeepinmindthisapproachisdeclininginpopularitythough,infavourofusingexperimentalflags,whichmustbeenabledexplicitlyintheuser'sbrowser.

Why?Becausedevelopersinsteadofconsideringvendorprefixesasawaytopreviewfeatures,theyshippedtheminproduction-somethingconsideredharmfulbytheCSSWorkingGroup.

Mostlybecauseonceyouaddaflaganddevelopersstartusingitinproduction,browsersareinabadpositioniftheyrealisesomethingmustchange.Withflags,youcan'tshipafeatureunlessyoucanpushallyourvisitorstoenablethatflagintheirbrowser(justjoking,don'ttry).

Thatsaid,let'sseewhatvendorprefixesare.

IspecificallyrememberthemforworkingwithCSSTransitionsinthepast.Insteadofjustusingthe transitionproperty,youhadtodothis:

.myClass{

-webkit-transition:all1slinear;

-moz-transition:all1slinear;

-ms-transition:all1slinear;

-o-transition:all1slinear;

transition:all1slinear;

}

Nowyoujustuse

.myClass{

transition:all1slinear;

}

sincethepropertyisnowwellsupportedbyallmodernbrowsers.

Theprefixesusedare:

-webkit-(Chrome,Safari,iOSSafari/iOSWebView,Android)-moz-(Safari)-ms-(Edge,InternetExplorer)-o-(Opera,OperaMini)

Vendorprefixes

167

Page 168: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

SinceOperaisChromium-basedandEdgewillsoonbetoo, -o-and -ms-willprobablygosoonoutoffashion.Butaswesaid,vendorprefixesasawholearegoingoutoffashion,too.

Writingprefixesishard,mostlybecauseofuncertainty.Doyouactuallyneedaprefixforoneproperty?Severalonlineresourcesareoutdated,too,whichmakesitevenhardertodoright.ProjectslikeAutoprefixercanautomatetheprocessinitsentiretywithoutusneedingtofindoutifaprefixisneededanymore,orthefeatureisnowstableandtheprefixshouldbedropped.Itusesdatafromcaniuse.com,averygoodreferencesiteforallthingsrelatedtobrowsersupport.

IfyouuseReactorVue,projectslike create-react-appandVueCLI,twocommonwaystostartbuildinganapplication,use autoprefixeroutofthebox,soyoudon'tevenhavetoworryaboutit.

Vendorprefixes

168

Page 169: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

CSSforprintEventhoughweincreasinglystareatourscreens,printingisstillathing.

Evenwithblogposts.Irememberonetimebackin2009ImetapersonthattoldmehemadehispersonalassistantprinteveryblogpostIpublished(yes,Istaredblanklyforalittlebit).Definitelyunexpected.

MymainusecaseforlookingintoprintingusuallyisprintingtoaPDF.Imightcreatesomethinginsidethebrowser,andIwanttomakeitavailableasPDF.

Browsersmakethisveryeasy,withChromedefaultingto"Save"whentryingtoprintadocumentandaprinterisnotavailable,andSafarihasadedicatedbuttoninthemenubar:

PrintCSSSomecommonthingsyoumightwanttodowhenprintingistohidesomepartsofthedocument,maybethefooter,somethingintheheader,thesidebar.

Maybeyouwanttouseadifferentfontforprinting,whichistotallylegit.

IfyouhavealargeCSSforprint,you'dbetteruseaseparatefileforit.Browserswillonlydownloaditwhenprinting:

<linkrel="stylesheet"

CSSforprint

169

Page 170: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

src="print.css"

type="text/css"

media="print"/>

CSS@mediaprintAnalternativetothepreviousapproachismediaqueries.Anythingyouaddinsidethisblock:

@mediaprint{

/*...*/

}

isgoingtobeappliedonlytoprinteddocuments.

LinksHTMLisgreatbecauseoflinks.It'scalledHyperTextforagoodreason.Whenprintingwemightlosealotofinformation,dependingonthecontent.

CSSoffersagreatwaytosolvethisproblembyeditingthecontent,appendingthelinkafterthe <a>tagtext,using:

@mediaprint{

a[href*='//']:after{

content:"("attr(href)")";

color:$primary;

}

}

Itarget a[href*='//']toonlydothisforexternallinks.Imighthaveinternallinksfornavigationandinternalindexingpurposes,whichwouldbeuselessinmostofmyusecases.Ifyoualsowantinternallinkstobeprinted,justdo:

@mediaprint{

a:after{

content:"("attr(href)")";

color:$primary;

}

}

Pagemargins

CSSforprint

170

Page 171: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

Youcanaddmarginstoeverysinglepage. cmor inisagoodunitforpaperprinting.

@page{

margin-top:2cm;

margin-bottom:2cm;

margin-left:2cm;

margin-right:2cm;

}

@pagecanalsobeusedtoonlytargetthefirstpage,using @page:first,oronlytheleftandrightpagesusing @page:leftand @page:right.

PagebreaksYoumightwanttoaddapagebreakaftersomeelements,orbeforethem.Use page-break-afterand page-break-before:

.book-date{

page-break-after:always;

}

.post-content{

page-break-before:always;

}

Thosepropertiesacceptawidevarietyofvalues.

AvoidbreakingimagesinthemiddleIexperiencedthiswithFirefox:imagesbydefaultarecutinthemiddle,andcontinueonthenextpage.Itmightalsohappentotext.

Use

p{

page-break-inside:avoid;

}

andwrapyourimagesina ptag.Targeting imgdirectlydidn'tworkinmytests.

Thisappliestoothercontentaswell,notjustimages.Ifyounoticesomethingiscutwhenyoudon'twant,usethisproperty.

CSSforprint

171

Page 172: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

DebugtheprintingpresentationTheChromeDevToolsofferwaystoemulatetheprintlayout:

Oncethepanelopens,changetherenderingemulationto print:

CSSforprint

172

Page 173: Table of Contents · Table of Contents Preface Introduction to CSS A brief history of CSS Adding CSS to an HTML page Selectors Cascade Specificity Inheritance ... features like CSS

CSSforprint

173