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
CSSGrid
Flexbox
Tables
Centering
Lists
Mediaqueriesandresponsivedesign
FeatureQueries
Filters
Transforms
Transitions
Animations
NormalizingCSS
Errorhandling
Vendorprefixes
CSSforprint
3
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
Preface
5
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
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
IntroductiontoCSS
8
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
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
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
Example:
<divstyle="background-color:yellow">...</div>
AddingCSStoanHTMLpage
12
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
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
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
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
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
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
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
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
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
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
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
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
Youcanusethe revertkeywordtorevertit.Inthiscase,thevalueisrevertedtotheoriginalvaluethebrowsergaveitinitsdefaultstylesheet.
Inpracticethisisrarelyused,andmostofthetimesyou'lljustsetanothervalueforthepropertytooverwritethatinheritedvalue.
OtherspecialvaluesInadditiontothe inheritand revertspecialkeywordswejustsaw,youcanalsosetanypropertyto:
initial:usethedefaultbrowserstylesheetifavailable.Ifnot,andifthepropertyinheritsbydefault,inheritthevalue.Otherwisedonothing.unset:ifthepropertyinheritsbydefault,inherit.Otherwisedonothing.
Inheritance
25
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
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
~=checksifthepartialiscontainedintheattribute,butseparatedbyspacesfromtherest
Allthecheckswementionedarecasesensitive.
Ifyouaddan ijustbeforetheclosingbracket,thecheckwillbecaseinsensitive.It'ssupportedinmanybrowsersbutnotinall,checkhttps://caniuse.com/#feat=css-case-insensitive.
Attributeselectors
28
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
: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
Pseudo-classes
31
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
.myElement::before{
content:"HeyHey!";
}
Pseudo-elements
33
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
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
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
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
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
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
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
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
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
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
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
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
}
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
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
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
: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
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
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
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
CustomProperties
53
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Typography
68
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
BoxModel
70
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
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
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
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
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
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
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
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
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
marginistheonlypropertyrelatedtosizingthatcanhaveanegativevalue.It'sextremelyuseful,too.Settinganegativetopmarginmakesanelementmoveoverelementsbeforeit,andgivenenoughnegativevalueitwillmoveoutofthepage.
Anegativebottommarginmovesuptheelementsafterit.
Anegativerightmarginmakesthecontentoftheelementexpandbeyonditsallowedcontentsize.
Anegativeleftmarginmovestheelementleftovertheelementsthatprecedeit,andgivenenoughnegativevalueitwillmoveoutofthepage.
Margin
80
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
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
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
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
<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
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
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
Wecannowmovetheboxaroundasweplease,usingthe top, right, bottom, leftproperties:
.box{
/*...*/
position:absolute;
top:0px;
left:0px;
}
or
.box{
/*...*/
position:absolute;
top:140px;
left:50px;
}
Positioning
88
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
.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
.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
Positioning
92
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
.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
thisistheresult:
andthisiswhatwegetbyapplyingafloat:right,adjustingthepaddingaccordingly:
img{
float:right;
padding:20px0px20px20px;
}
Floatingandclearing
95
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
}
andthisistheresult:
ClearingWhathappenswhenyoufloatmorethanoneelement?
Ifwhenfloatedtheyfindanotherfloatedimage,bydefaulttheyarestackeduponenexttotheother,horizontally.Untilthereisnoroom,andtheywillstartbeingstackedonanewline.
Saywehad3inlineimagesinsidea ptag:
Floatingandclearing
97
Ifweadd float:lefttothoseimages:
img{
float:left;
padding:20px20px0px0px;
}
thisiswhatwe'llhave:
Floatingandclearing
98
ifyouadd clear:lefttoimages,thosearegoingtobestackedverticallyratherthanhorizontally:
Floatingandclearing
99
Iusedthe leftvaluefor clear.Itallows
lefttoclearleftfloatsrighttoclearrightfloatsbothtoclearbothleftandrightfloatsnone(default)disablesclearing
Floatingandclearing
100
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
Hereweused10and20,butyoucanuseanynumber.Negativenumberstoo.It'scommontopicknon-consecutivenumbers,soyoucanpositionelementsinthemiddle.Ifyouuseconsecutivenumbersinstead,youwouldneedtore-calculatethez-indexofeachelementinvolvedinthepositioning.
z-index
102
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
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
Here'sanotherexampleofagridwith2columnsand2rows:
.container{
display:grid;
grid-template-columns:200px200px;
grid-template-rows:100px100px;
}
CSSGrid
105
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
Anotherexample:
.container{
display:grid;
grid-template-columns:10px100px;
grid-template-rows:100px10px;
}
CSSGrid
107
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
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
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
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
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
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
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
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
<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
WrappingupThesearethebasicsofCSSGrid.TherearemanythingsIdidn'tincludeinthisintroductionbutIwantedtomakeitverysimple,tostartusingthisnewlayoutsystemwithoutmakingitfeeloverwhelming.
CSSGrid
117
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
WhilewemustwaitafewyearsforuserstocatchuponCSSGrid,Flexboxisanoldertechnologyandcanbeusedrightnow.
EnableFlexboxAflexboxlayoutisappliedtoacontainer,bysetting
display:flex;
or
display:inline-flex;
thecontentinsidethecontainerwillbealignedusingflexbox.
Containerproperties
Flexbox
119
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
Youcanchangethisbehaviorusing justify-contenttochangethehorizontalalignment,andalign-itemstochangetheverticalalignment.
Changethehorizontalalignment
justify-contenthas5possiblevalues:
Flexbox
121
flex-start:aligntotheleftsideofthecontainer.flex-end:aligntotherightsideofthecontainer.center:alignatthecenterofthecontainer.space-between:displaywithequalspacingbetweenthem.space-around:displaywithequalspacingaroundthem
Changetheverticalalignment
align-itemshas5possiblevalues:
Flexbox
122
flex-start:aligntothetopofthecontainer.flex-end:aligntothebottomofthecontainer.center:alignattheverticalcenterofthecontainer.baseline:displayatthebaselineofthecontainer.stretch:itemsarestretchedtofitthecontainer.
Flexbox
123
Flexbox
124
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
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
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
Thispropertycombinestheabove3properties:
flex-grow
flex-shrink
flex-basis
andprovidesashorthandsyntax: flex:01auto
Flexbox
128
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
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
Ifyouadd border-collapse:collapse;tothetableelement,allbordersarecollapsedintoone:
Tables
131
Tables
132
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
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
CenterbothverticallyandhorizontallyFlexboxtechniquestocenterverticallyandhorizontallycanbecombinedtocompletelycenteranelementinthepage.
#mysection{
display:flex;
align-items:center;
justify-content:center;
}
ThesamecanbedoneusingCSSGrid:
body{
display:grid;
Centering
135
place-items:center;
height:100vh;
}
Centering
136
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
ThisisFirefox:
Transitions
152
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
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
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
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
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
<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
@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
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
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
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
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
width
word-spacing
z-index
Animations
164
NormalizingCSSThedefaultbrowserstylesheetisthesetofrulesthatbrowserhavetoapplysomeminimumstyletoelements.
Mostofthetimesthosestylesareveryuseful.
Sinceeverybrowserhasitsownset,it'scommonfindingacommonground.
Ratherthanremovingalldefaults,likeoneoftheCSSresetapproachesdo,thenormalizingprocessremovesbrowserinconsistencies,whilekeepingabasicsetofrulesyoucanrelyon.
Normalize.csshttp://necolas.github.io/normalize.cssisthemostcommonlyusedsolutionforthisproblem.
YoumustloadthenormalizingCSSfilebeforeanyotherCSS.
NormalizingCSS
165
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
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
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
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
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
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
DebugtheprintingpresentationTheChromeDevToolsofferwaystoemulatetheprintlayout:
Oncethepanelopens,changetherenderingemulationto print:
CSSforprint
172
CSSforprint
173