CSS Book Manual PDF

Title CSS Book Manual
Author andres villanueva
Course Informática
Institution Instituto Politécnico Nacional
Pages 173
File Size 5.2 MB
File Type PDF
Total Downloads 8
Total Views 184

Summary

Apuntes de css ...


Description

TableofContents Preface IntroductiontoCSS AbriefhistoryofCSS AddingCSStoanHTMLpage Selectors Cascade Specificity Inheritance Import Attributeselectors Pseudo-classes Pseudo-elements Colors Units url calc Backgrounds Comments CustomProperties Fonts Typography BoxModel Border Padding Margin BoxSizing Display Positioning Floatingandclearing z-index

2

CSSGrid Flexbox Tables Centering Lists Mediaqueriesandresponsivedesign FeatureQueries Filters Transforms Transitions Animations NormalizingCSS Errorhandling Vendorprefixes CSSforprint

3

Preface

Preface Welcome! IwrotethisbooktohelpyouquicklylearnCSSandgetfamiliarwiththeadvancedCSStopics. CSS,ashorthandforCascadingStyleSheets,isoneofthemainbuildingblocksoftheWeb. Itshistorygoesbacktothe90'sandalongwithHTMLithaschangedalotsinceitshumble beginnings. HavingcreatedwebsitessincebeforeCSSexisted,Ihaveseenitsevolution. CSSisanamazingtool,andinthelastfewyearsithasgrownalot,introducingmanyfantastic featureslikeCSSGrid,FlexboxandCSSCustomProperties. Thishandbookisaimedatavastaudience. First,thebeginner.IexplainCSSfromzeroinasuccinctbutcomprehensiveway,soyoucan usethisbooktolearnCSSfromthebasics. Then,theprofessional.CSSisoftenconsideredlikeasecondarythingtolearn,especiallyby JavaScriptdevelopers.TheyknowCSSisnotarealprogramminglanguage,theyare programmersandthereforetheyshouldnotbotherlearningCSStherightway.Iwrotethis bookforyou,too. Next,thepersonthatknowsCSSfromafewyearsbuthasn'thadtheopportunitytolearnthe newthingsinit.We'lltalkextensivelyaboutthenewfeaturesofCSS,theonesthataregoing tobuildthewebofthenextdecade. CSShasimprovedalotinthepastfewyearsandit'sevolvingfast. Evenifyoudon'twriteCSSforaliving,knowinghowCSSworkscanhelpsaveyousome headacheswhenyouneedtounderstanditfromtimetotime,forexamplewhiletweakinga webpage. Thankyouforgettingthisebook.Mygoalwithitistogiveyouaquickyetcomprehensive overviewofCSS. Flavio Youcanreachmeviaemailat[email protected],onTwitter@flaviocopes. Mywebsiteisflaviocopes.com.

4

Preface

5

IntroductiontoCSS

IntroductiontoCSS CSS(anabbreviationofCascadingStyleSheets)isthelanguagethatweusetostylean HTMLfile,andtellthebrowserhowshoulditrendertheelementsonthepage. InthisbookItalkexclusivelyaboutstylingHTMLdocuments,althoughCSScanbeused tostyleotherthingstoo. ACSSfilecontainsseveralCSSrules. Eachruleiscomposedby2parts: theselector thedeclarationblock Theselectorisastringthatidentifiesoneormoreelementsonthepage,followingaspecial syntaxthatwe'llsoontalkaboutextensively. Thedeclarationblockcontainsoneormoredeclarations,inturncomposedbyaproperty andvaluepair. ThoseareallthethingswehaveinCSS. Carefullyorganisingproperties,associatingthemvalues,andattachingthosetospecific elementsofthepageusingaselectoristhewholeargumentofthisebook.

HowdoesCSSlooklike ACSSrulesethasonepartcalledselector,andtheotherpartcalleddeclaration.The declarationcontainsvariousrules,eachcomposedbyaproperty,andavalue. Inthisexample, pistheselector,andappliesonerulewhichsetsthevalue 20pxtothe font-sizeproperty:

p{ font-size:20px; }

Multiplerulesarestackedoneaftertheother: p{ font-size:20px; } a{

6

IntroductiontoCSS

color:blue; }

Aselectorcantargetoneormoreitems: p,a{ font-size:20px; }

anditcantargetHTMLtags,likeabove,orHTMLelementsthatcontainacertainclass attributewith .my-class,orHTMLelementsthathaveaspecific idattributewith #my-id. Moreadvancedselectorsallowyoutochooseitemswhoseattributematchesaspecificvalue, oralsoitemswhichrespondtopseudo-classes(moreonthatlater)

Semicolons EveryCSSruleterminateswithasemicolon.Semicolonsarenotoptional,exceptafterthelast rule,butIsuggesttoalwaysusethemforconsistencyandtoavoiderrorsifyouaddanother propertyandforgettoaddthesemicolononthepreviousline.

Formattingandindentation Thereisnofixedruleforformatting.ThisCSSisvalid: p { font-size:20px; } a{color:blue;}

butapaintosee.Sticktosomeconventions,liketheonesyouseeintheexamplesabove: stickselectorsandtheclosingbracketstotheleft,indent2spacesforeachrule,havethe openingbracketonthesamelineoftheselector,separatedbyonespace. Correctandconsistentuseofspacingandindentationisavisualaidinunderstandingyour code.

7

IntroductiontoCSS

8

AbriefhistoryofCSS

AbriefhistoryofCSS Beforemovingon,IwanttogiveyouabriefrecapofthehistoryofCSS. CSSwasgrownoutofthenecessityofstylingwebpages.BeforeCSSwasintroduced,people wantedawaytostyletheirwebpages,whichlookedallverysimilarand"academic"backin theday.Youcouldn'tdomuchintermsofpersonalisation. HTML3.2introducedtheoptionofdefiningcolorsinlineasHTMLelementattributes,and presentationaltagslike centerand font,butthatescalatedquicklyintoafarfromideal situation. CSSletusmoveeverythingpresentation-relatedfromtheHTMLtotheCSS,sothatHTML couldgetbackbeingtheformatthatdefinesthestructureofthedocument,ratherthanhow thingsshouldlookinthebrowser. CSSiscontinuouslyevolving,andCSSyouused5yearsagomightjustbeoutdated,asnew idiomaticCSStechniquesemergedandbrowserschanged. It'shardtoimaginethetimeswhenCSSwasbornandhowdifferentthewebwas. Atthetime,wehadseveralcompetingbrowsers,themainonesbeingInternetExploreror NetscapeNavigator. PageswerestyledbyusingHTML,withspecialpresentationaltagslike boldandspecial attributes,mostofwhicharenowdeprecated. Thismeantyouhadalimitedamountofcustomisationopportunities. Thebulkofthestylingdecisionswerelefttothebrowser. Also,youbuiltasitespecificallyforoneofthem,becauseeachoneintroduceddifferentnonstandardtagstogivemorepowerandopportunities. Soonpeoplerealisedtheneedforawaytostylepages,inawaythatwouldworkacrossall browsers. Aftertheinitialideaproposedin1994,CSSgotitsfirstreleasein1996,whentheCSSLevel1 ("CSS1")recommendationwaspublished. CSSLevel2("CSS2")gotpublishedin1998. Sincethen,workbeganonCSSLevel3.TheCSSWorkingGroupdecidedtosplitevery featureandworkonitseparately,inmodules.

9

AbriefhistoryofCSS

Browsersweren'tespeciallyfastatimplementingCSS.Wehadtowaituntil2002tohavethe firstbrowserimplementthefullCSSspecification:IEforMac,asnicelydescribedinthisCSS Trickspost:https://css-tricks.com/look-back-history-css/ InternetExplorerimplementedtheboxmodelincorrectlyrightfromthestart,whichledtoyears ofpaintryingtohavethesamestyleappliedconsistentlyacrossbrowsers.Wehadtouse varioustricksandhackstomakebrowsersrenderthingsaswewanted. Todaythingsaremuch,muchbetter.WecanjustusetheCSSstandardswithoutthinking aboutquirks,mostofthetime,andCSShasneverbeenmorepowerful. Wedon'thaveofficialreleasenumbersforCSSanymorenow,buttheCSSWorkingGroup releasesa"snapshot"ofthemodulesthatarecurrentlyconsideredstableandreadytobe includedinbrowsers.Thisisthelatestsnapshot,from2018:https://www.w3.org/TR/css-2018/ CSSLevel2isstillthebasefortheCSSwewritetoday,andwehavemanymorefeatures builtontopofit.

10

AddingCSStoanHTMLpage

AddingCSStoanHTMLpage CSSisattachedtoanHTMLpageindifferentways.

1:Usingthe linktag The linktagisthewaytoincludeaCSSfile.ThisisthepreferredwaytouseCSSasit's intendedtobeused:oneCSSfileisincludedbyallthepagesofyoursite,andchangingone lineonthatfileaffectsthepresentationofallthepagesinthesite. Tousethismethod,youadda linktagwiththe hrefattributepointingtotheCSSfileyou wanttoinclude.Youadditinsidethe headtagofthesite(notinsidethe bodytag):

The reland typeattributesarerequiredtoo,astheytellthebrowserwhichkindoffilewe arelinkingto.

2:usingthe styletag Insteadofusingthe linktagtopointtoseparatestylesheetcontainingourCSS,wecanadd theCSSdirectlyinsidea styletag.Thisisthesyntax:

UsingthismethodwecanavoidcreatingaseparateCSSfile.Ifindthisisagoodwayto experimentbefore"formalising"CSStoaseparatefile,ortoaddaspeciallineofCSSjusttoa file.

3:inlinestyles InlinestylesarethethirdwaytoaddCSStoapage.Wecanadda styleattributetoany HTMLtag,andaddCSSintoit. ...

11

AddingCSStoanHTMLpage

Example: ...

12

Selectors

Selectors Aselectorallowsustoassociateoneormoredeclarationstooneormoreelementsonthe page.

Basicselectors Supposewehavea pelementonthepage,andwewanttodisplaythewordsintoitusing theyellowcolor. Wecantargetthatelementusingthisselector p,whichtargetsalltheelementusingthe p taginthepage.AsimpleCSSruletoachievewhatwewantis: p{ color:yellow; }

EveryHTMLtaghasacorrespondingselector,forexample: div, span, img. Ifaselectormatchesmultipleelements,alltheelementsinthepagewillbeaffectedbythe change. HTMLelementshave2attributeswhichareverycommonlyusedwithinCSStoassociate stylingtoaspecificelementonthepage: classand id. Thereisonebigdifferencebetweenthosetwo:insideanHTMLdocumentyoucanrepeatthe same classvalueacrossmultipleelements,butyoucanonlyusean idonce.Asa corollary,usingclassesyoucanselectanelementwith2ormorespecificclassnames, somethingnotpossibleusingids. Classesareidentifiedusingthe .symbol,whileidsusingthe #symbol. Exampleusingaclass:

Roger

.dog-name{ color:yellow; }

13

Selectors

Exampleusinganid:

Roger

#dog-name{ color:yellow; }

Combiningselectors Sofarwe'veseenhowtotargetanelement,aclassoranid.Let'sintroducemorepowerful selectors.

Targetinganelementwithaclassorid Youcantargetaspecificelementthathasaclass,orid,attached. Exampleusingaclass:

Roger

p.dog-name{ color:yellow; }

Exampleusinganid:

Roger

p#dog-name{ color:yellow; }

Whywouldyouwanttodothat,iftheclassoridalreadyprovidesawaytotargetthat element?Youmighthavetodothattohavemorespecificity.We'llseewhatthatmeanslater.

14

Selectors

Targetingmultipleclasses Youcantargetanelementwithaspecificclassusing .class-name,asyousawpreviously. Youcantargetanelementwith2(ormore)classesbycombiningtheclassnamesseparated withadot,withoutspaces. Example:

Roger

.dog-name.roger{ color:yellow; }

Combiningclassesandids Inthesameway,youcancombineaclassandanid. Example:

Roger

.dog-name#roger{ color:yellow; }

Groupingselectors Youcancombineselectorstoapplythesamedeclarationstomultipleselectors.Todoso,you separatethemwithacomma. Example: Mydognameis:

Roger

15

Selectors

p,.dog-name{ color:yellow; }

Youcanaddspacesinthosedeclarationstomakethemmoreclear: p, .dog-name{ color:yellow; }

Followthedocumenttreewithselectors We'veseenhowtotargetanelementinthepagebyusingatagname,aclassoranid. Youcancreateamorespecificselectorbycombiningmultipleitemstofollowthedocument treestructure.Forexample,ifyouhavea spantagnestedinsidea ptag,youcantarget thatonewithoutapplyingthestyletoa spantagnotincludedina ptag: Hello! Mydognameis:  Roger 

pspan{ color:yellow; }

Seehowweusedaspacebetweenthetwotokens pand span. Thisworkseveniftheelementontherightismultiplelevelsdeep. Tomakethedependencystrictonthefirstlevel,youcanusethe >symbolbetweenthetwo tokens: p>span{ color:yellow; }

16

Selectors

Inthiscase,ifa spanisnotafirstchildrenofthe pelement,it'snotgoingtohavethenew colorapplied. Directchildrenwillhavethestyleapplied:  Thisisyellow    Thisisnotyellow  

Adjacentsiblingselectorsletusstyleanelementonlyifprecededbyaspecificelement.We dosousingthe +operator: Example: p+span{ color:yellow; }

Thiswillassignthecoloryellowtoallspanelementsprecededbya pelement: Thisisaparagraph Thisisayellowspan

Wehavealotmoreselectorswecanuse: attributeselectors pseudoclassselectors pseudoelementselectors We'llfindallabouttheminthenextsections.

17

Cascade

Cascade CascadeisafundamentalconceptofCSS.Afterall,it'sinthenameitself,thefirstCofCSSCascadingStyleSheets-itmustbeanimportantthing. Whatdoesitmean? Cascadeistheprocess,oralgorithm,thatdeterminesthepropertiesappliedtoeachelement onthepage.TryingtoconvergefromalistofCSSrulesthataredefinedinvariousplaces. Itdoessotakinginconsideration: specificity importance inheritance orderinthefile Italsotakescareofresolvingconflicts. TwoormorecompetingCSSrulesforthesamepropertyappliedtothesameelementneedto beelaboratedaccordingtotheCSSspec,todeterminewhichoneneedstobeapplied. EvenifyoujusthaveoneCSSfileloadedbyyourpage,thereisotherCSSthatisgoingtobe partoftheprocess.Wehavethebrowser(useragent)CSS.Browserscomewithadefaultset ofrules,alldifferentbetweenbrowsers. ThenyourCSScomeintoplay. Thenthebrowserappliesanyuserstylesheet,whichmightalsobeappliedbybrowser extensions. Allthoserulescomeintoplaywhilerenderingthepage. We'llnowseetheconceptsofspecificityandinheritance.

18

Specificity

Specificity Whathappenswhenanelementistargetedbymultiplerules,withdifferentselectors,that affectthesameproperty? Forexample,let'stalkaboutthiselement:

Roger

Wecanhave .dog-name{ color:yellow; }

andanotherrulethattargets p,whichsetsthecolortoanothervalue: p{ color:red; }

Andanotherrulethattargets p.dog-name.Whichruleisgoingtotakeprecedenceoverthe others,andwhy? Enterspecificity.Themorespecificrulewillwin.Iftwoormoreruleshavethesame specificity,theonethatappearslastwins. Sometimeswhatismorespecificinpracticeisabitconfusingtobeginners.Iwouldsayit's alsoconfusingtoexpertsthatdonotlookatthoserulesthatfrequently,orsimplyoverlook them.

Howtocalculatespecificity Specificityiscalculatedusingaconvention. Wehave4slots,andeachoneofthemstartsat0: 00000.Theslotattheleftisthemost important,andtherightmostoneistheleastimportant. Likeitworksfornumbersinthedecimalsystem: 1000ishigherthan 0100.

19

Specificity

Slot1 Thefirstslot,therightmostone,istheleastimportant. Weincreasethisvaluewhenwehaveanelementselector.Anelementisatagname.Ifyou havemorethanoneelementselectorintherule,youincrementaccordinglythevaluestoredin thisslot. Examples: p{}/*0001*/ span{}/*0001*/ pspan{}/*0002*/ p>span{}/*0002*/ divp>span{}/*0003*/

Slot2 Thesecondslotisincrementedby3things: classselectors pseudo-classselectors attributeselectors Everytimearulemeetsoneofthose,weincrementthevalueofthesecondcolumnfromthe right. Examples: .name{}/*0010*/ .users.name{}/*0020*/ [href$='.pdf']{}/*0010*/ :hover{}/*0010*/

Ofcourseslot2selectorscanbecombinedwithslot1selectors: div.name{}/*0011*/ a[href$='.pdf']{}/*0011*/ .picturesimg:hover{}/*0021*/

Onenicetrickwithclassesisthatyoucanrepeatthesameclassandincreasethespecificity. Forexample: .name{}/*0010*/ .name.name{}/*0020*/ .name.name.name{}/*0030*/

20

Specificity

Slot3 Slot3holdsthemostimportantthingthatcanaffectyourCSSspecificityinaCSSfile:the id.

Everyelementcanhavean idattributeassigned,andwecanusethatinourstylesheetto targettheelement. Examples: #name{}/*0100*/ .user#name{}/*0110*/ #namespan{}/*0101*/

Slot4 Slot4isaffectedbyinlinestyles.Anyinlinestylewillhaveprecedenceoveranyruledefinedin anexternalCSSfile,orinsidethe styletaginthepageheader. Example: Test/*1000*/

EvenifanyotherruleintheCSSdefinesthecolor,thisinlinestyleruleisgoingtobeapplied. Exceptforonecase-if !importantisused,whichfillstheslot5.

Importance Specificitydoesnotmatterifaruleendswith !important: p{ font-size:20px!important; }

Thatrulewilltakeprecedenceoveranyrulewithmorespecificity Adding !importantinaCSSruleisgoingtomakethatrulebemoreimportantthananyother rule,accordingtothespecificityrules.Theonlywayanotherrulecantakeprecedenceisto have !importantaswell,andhavehigherspecificityintheotherlessimportantslots.

Tips

21

Specificity

Ingeneralyoushouldusetheamountofspecificityyouneed,butnotmore.Inthisway,you cancraftotherselectorstooverwritetherulessetbyprecedingruleswithoutgoingmad. !importantisahighlydebatedtoolthatCSSoffersus.ManyCSSexpertsadvocateagainst

usingit.IfindmyselfusingitespeciallywhentryingoutsomestyleandaCSSrulehasso muchspecificitythatIneedtouse !importanttomakethebrowserapplymynewCSS. Butgenerally, !importantshouldhavenoplaceinyourCSSfiles. Usingthe idattributetostyleCSSisalsodebatedalot,sinceithasaveryhighspecificity.A goodalternativeistouseclassesinstead,whichhavelessspecificity,andsotheyareeasier toworkwith,andtheyaremorepowerful(youcanhavemultipleclassesforanelement,anda classcanbereusedmultipletimes).

Toolstocalculatethespecificity Youcanusethesitehttps://specificity.keegan.st/toperformthespecificitycalculationforyou automatically. It'susefulespeciallyifyouaretryingtofigurethingsout,asitcanbeanicefeedbacktool.

22

Inherit...


Similar Free PDFs