Title | CSS Book Manual |
---|---|
Author | andres villanueva |
Course | Informática |
Institution | Instituto Politécnico Nacional |
Pages | 173 |
File Size | 5.2 MB |
File Type | |
Total Downloads | 8 |
Total Views | 184 |
Apuntes de css ...
TableofContents Preface 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
Preface Welcome! IwrotethisbooktohelpyouquicklylearnCSSandgetfamiliarwiththeadvancedCSStopics. CSS,ashorthandforCascadingStyleSheets,isoneofthemainbuildingblocksoftheWeb. Itshistorygoesbacktothe90'sandalongwithHTMLithaschangedalotsinceitshumble beginnings. HavingcreatedwebsitessincebeforeCSSexisted,Ihaveseenitsevolution. CSSisanamazingtool,andinthelastfewyearsithasgrownalot,introducingmanyfantastic featureslikeCSSGrid,FlexboxandCSSCustomProperties. Thishandbookisaimedatavastaudience. First,thebeginner.IexplainCSSfromzeroinasuccinctbutcomprehensiveway,soyoucan usethisbooktolearnCSSfromthebasics. Then,theprofessional.CSSisoftenconsideredlikeasecondarythingtolearn,especiallyby JavaScriptdevelopers.TheyknowCSSisnotarealprogramminglanguage,theyare programmersandthereforetheyshouldnotbotherlearningCSStherightway.Iwrotethis bookforyou,too. Next,thepersonthatknowsCSSfromafewyearsbuthasn'thadtheopportunitytolearnthe newthingsinit.We'lltalkextensivelyaboutthenewfeaturesofCSS,theonesthataregoing tobuildthewebofthenextdecade. CSShasimprovedalotinthepastfewyearsandit'sevolvingfast. Evenifyoudon'twriteCSSforaliving,knowinghowCSSworkscanhelpsaveyousome headacheswhenyouneedtounderstanditfromtimetotime,forexamplewhiletweakinga webpage. Thankyouforgettingthisebook.Mygoalwithitistogiveyouaquickyetcomprehensive overviewofCSS. Flavio Youcanreachmeviaemailat[email protected],onTwitter@flaviocopes. Mywebsiteisflaviocopes.com.
4
Preface
5
IntroductiontoCSS
IntroductiontoCSS CSS(anabbreviationofCascadingStyleSheets)isthelanguagethatweusetostylean HTMLfile,andtellthebrowserhowshoulditrendertheelementsonthepage. InthisbookItalkexclusivelyaboutstylingHTMLdocuments,althoughCSScanbeused tostyleotherthingstoo. ACSSfilecontainsseveralCSSrules. Eachruleiscomposedby2parts: theselector thedeclarationblock Theselectorisastringthatidentifiesoneormoreelementsonthepage,followingaspecial syntaxthatwe'llsoontalkaboutextensively. Thedeclarationblockcontainsoneormoredeclarations,inturncomposedbyaproperty andvaluepair. ThoseareallthethingswehaveinCSS. Carefullyorganisingproperties,associatingthemvalues,andattachingthosetospecific elementsofthepageusingaselectoristhewholeargumentofthisebook.
HowdoesCSSlooklike ACSSrulesethasonepartcalledselector,andtheotherpartcalleddeclaration.The declarationcontainsvariousrules,eachcomposedbyaproperty,andavalue. Inthisexample, pistheselector,andappliesonerulewhichsetsthevalue 20pxtothe font-sizeproperty:
p{ font-size:20px; }
Multiplerulesarestackedoneaftertheother: p{ font-size:20px; } a{
6
IntroductiontoCSS
color:blue; }
Aselectorcantargetoneormoreitems: p,a{ font-size:20px; }
anditcantargetHTMLtags,likeabove,orHTMLelementsthatcontainacertainclass attributewith .my-class,orHTMLelementsthathaveaspecific idattributewith #my-id. Moreadvancedselectorsallowyoutochooseitemswhoseattributematchesaspecificvalue, oralsoitemswhichrespondtopseudo-classes(moreonthatlater)
Semicolons EveryCSSruleterminateswithasemicolon.Semicolonsarenotoptional,exceptafterthelast rule,butIsuggesttoalwaysusethemforconsistencyandtoavoiderrorsifyouaddanother propertyandforgettoaddthesemicolononthepreviousline.
Formattingandindentation Thereisnofixedruleforformatting.ThisCSSisvalid: p { font-size:20px; } a{color:blue;}
butapaintosee.Sticktosomeconventions,liketheonesyouseeintheexamplesabove: stickselectorsandtheclosingbracketstotheleft,indent2spacesforeachrule,havethe openingbracketonthesamelineoftheselector,separatedbyonespace. Correctandconsistentuseofspacingandindentationisavisualaidinunderstandingyour code.
7
IntroductiontoCSS
8
AbriefhistoryofCSS
AbriefhistoryofCSS Beforemovingon,IwanttogiveyouabriefrecapofthehistoryofCSS. CSSwasgrownoutofthenecessityofstylingwebpages.BeforeCSSwasintroduced,people wantedawaytostyletheirwebpages,whichlookedallverysimilarand"academic"backin theday.Youcouldn'tdomuchintermsofpersonalisation. HTML3.2introducedtheoptionofdefiningcolorsinlineasHTMLelementattributes,and presentationaltagslike centerand font,butthatescalatedquicklyintoafarfromideal situation. CSSletusmoveeverythingpresentation-relatedfromtheHTMLtotheCSS,sothatHTML couldgetbackbeingtheformatthatdefinesthestructureofthedocument,ratherthanhow thingsshouldlookinthebrowser. CSSiscontinuouslyevolving,andCSSyouused5yearsagomightjustbeoutdated,asnew idiomaticCSStechniquesemergedandbrowserschanged. It'shardtoimaginethetimeswhenCSSwasbornandhowdifferentthewebwas. Atthetime,wehadseveralcompetingbrowsers,themainonesbeingInternetExploreror NetscapeNavigator. PageswerestyledbyusingHTML,withspecialpresentationaltagslike boldandspecial attributes,mostofwhicharenowdeprecated. Thismeantyouhadalimitedamountofcustomisationopportunities. Thebulkofthestylingdecisionswerelefttothebrowser. Also,youbuiltasitespecificallyforoneofthem,becauseeachoneintroduceddifferentnonstandardtagstogivemorepowerandopportunities. Soonpeoplerealisedtheneedforawaytostylepages,inawaythatwouldworkacrossall browsers. Aftertheinitialideaproposedin1994,CSSgotitsfirstreleasein1996,whentheCSSLevel1 ("CSS1")recommendationwaspublished. CSSLevel2("CSS2")gotpublishedin1998. Sincethen,workbeganonCSSLevel3.TheCSSWorkingGroupdecidedtosplitevery featureandworkonitseparately,inmodules.
9
AbriefhistoryofCSS
Browsersweren'tespeciallyfastatimplementingCSS.Wehadtowaituntil2002tohavethe firstbrowserimplementthefullCSSspecification:IEforMac,asnicelydescribedinthisCSS Trickspost:https://css-tricks.com/look-back-history-css/ InternetExplorerimplementedtheboxmodelincorrectlyrightfromthestart,whichledtoyears ofpaintryingtohavethesamestyleappliedconsistentlyacrossbrowsers.Wehadtouse varioustricksandhackstomakebrowsersrenderthingsaswewanted. Todaythingsaremuch,muchbetter.WecanjustusetheCSSstandardswithoutthinking aboutquirks,mostofthetime,andCSShasneverbeenmorepowerful. Wedon'thaveofficialreleasenumbersforCSSanymorenow,buttheCSSWorkingGroup releasesa"snapshot"ofthemodulesthatarecurrentlyconsideredstableandreadytobe includedinbrowsers.Thisisthelatestsnapshot,from2018:https://www.w3.org/TR/css-2018/ CSSLevel2isstillthebasefortheCSSwewritetoday,andwehavemanymorefeatures builtontopofit.
10
AddingCSStoanHTMLpage
AddingCSStoanHTMLpage CSSisattachedtoanHTMLpageindifferentways.
1:Usingthe linktag The linktagisthewaytoincludeaCSSfile.ThisisthepreferredwaytouseCSSasit's intendedtobeused:oneCSSfileisincludedbyallthepagesofyoursite,andchangingone lineonthatfileaffectsthepresentationofallthepagesinthesite. Tousethismethod,youadda linktagwiththe hrefattributepointingtotheCSSfileyou wanttoinclude.Youadditinsidethe headtagofthesite(notinsidethe bodytag):
The reland typeattributesarerequiredtoo,astheytellthebrowserwhichkindoffilewe arelinkingto.
2:usingthe styletag Insteadofusingthe linktagtopointtoseparatestylesheetcontainingourCSS,wecanadd theCSSdirectlyinsidea styletag.Thisisthesyntax:
UsingthismethodwecanavoidcreatingaseparateCSSfile.Ifindthisisagoodwayto experimentbefore"formalising"CSStoaseparatefile,ortoaddaspeciallineofCSSjusttoa file.
3:inlinestyles InlinestylesarethethirdwaytoaddCSStoapage.Wecanadda styleattributetoany HTMLtag,andaddCSSintoit. ...
11
AddingCSStoanHTMLpage
Example: ...
12
Selectors
Selectors Aselectorallowsustoassociateoneormoredeclarationstooneormoreelementsonthe page.
Basicselectors Supposewehavea pelementonthepage,andwewanttodisplaythewordsintoitusing theyellowcolor. Wecantargetthatelementusingthisselector p,whichtargetsalltheelementusingthe p taginthepage.AsimpleCSSruletoachievewhatwewantis: p{ color:yellow; }
EveryHTMLtaghasacorrespondingselector,forexample: div, span, img. Ifaselectormatchesmultipleelements,alltheelementsinthepagewillbeaffectedbythe change. HTMLelementshave2attributeswhichareverycommonlyusedwithinCSStoassociate stylingtoaspecificelementonthepage: classand id. Thereisonebigdifferencebetweenthosetwo:insideanHTMLdocumentyoucanrepeatthe same classvalueacrossmultipleelements,butyoucanonlyusean idonce.Asa corollary,usingclassesyoucanselectanelementwith2ormorespecificclassnames, somethingnotpossibleusingids. Classesareidentifiedusingthe .symbol,whileidsusingthe #symbol. Exampleusingaclass:
Roger
.dog-name{ color:yellow; }
13
Selectors
Exampleusinganid:
Roger
#dog-name{ color:yellow; }
Combiningselectors Sofarwe'veseenhowtotargetanelement,aclassoranid.Let'sintroducemorepowerful selectors.
Targetinganelementwithaclassorid Youcantargetaspecificelementthathasaclass,orid,attached. Exampleusingaclass:
Roger
p.dog-name{ color:yellow; }
Exampleusinganid:
Roger
p#dog-name{ color:yellow; }
Whywouldyouwanttodothat,iftheclassoridalreadyprovidesawaytotargetthat element?Youmighthavetodothattohavemorespecificity.We'llseewhatthatmeanslater.
14
Selectors
Targetingmultipleclasses Youcantargetanelementwithaspecificclassusing .class-name,asyousawpreviously. Youcantargetanelementwith2(ormore)classesbycombiningtheclassnamesseparated withadot,withoutspaces. Example:
Roger
.dog-name.roger{ color:yellow; }
Combiningclassesandids Inthesameway,youcancombineaclassandanid. Example:
Roger
.dog-name#roger{ color:yellow; }
Groupingselectors Youcancombineselectorstoapplythesamedeclarationstomultipleselectors.Todoso,you separatethemwithacomma. Example: Mydognameis:
Roger
15
Selectors
p,.dog-name{ color:yellow; }
Youcanaddspacesinthosedeclarationstomakethemmoreclear: p, .dog-name{ color:yellow; }
Followthedocumenttreewithselectors We'veseenhowtotargetanelementinthepagebyusingatagname,aclassoranid. Youcancreateamorespecificselectorbycombiningmultipleitemstofollowthedocument treestructure.Forexample,ifyouhavea spantagnestedinsidea ptag,youcantarget thatonewithoutapplyingthestyletoa spantagnotincludedina ptag: Hello! Mydognameis: Roger
pspan{ color:yellow; }
Seehowweusedaspacebetweenthetwotokens pand span. Thisworkseveniftheelementontherightismultiplelevelsdeep. Tomakethedependencystrictonthefirstlevel,youcanusethe >symbolbetweenthetwo tokens: p>span{ color:yellow; }
16
Selectors
Inthiscase,ifa spanisnotafirstchildrenofthe pelement,it'snotgoingtohavethenew colorapplied. Directchildrenwillhavethestyleapplied: Thisisyellow Thisisnotyellow
Adjacentsiblingselectorsletusstyleanelementonlyifprecededbyaspecificelement.We dosousingthe +operator: Example: p+span{ color:yellow; }
Thiswillassignthecoloryellowtoallspanelementsprecededbya pelement: Thisisaparagraph Thisisayellowspan
Wehavealotmoreselectorswecanuse: attributeselectors pseudoclassselectors pseudoelementselectors We'llfindallabouttheminthenextsections.
17
Cascade
Cascade CascadeisafundamentalconceptofCSS.Afterall,it'sinthenameitself,thefirstCofCSSCascadingStyleSheets-itmustbeanimportantthing. Whatdoesitmean? Cascadeistheprocess,oralgorithm,thatdeterminesthepropertiesappliedtoeachelement onthepage.TryingtoconvergefromalistofCSSrulesthataredefinedinvariousplaces. Itdoessotakinginconsideration: specificity importance inheritance orderinthefile Italsotakescareofresolvingconflicts. TwoormorecompetingCSSrulesforthesamepropertyappliedtothesameelementneedto beelaboratedaccordingtotheCSSspec,todeterminewhichoneneedstobeapplied. EvenifyoujusthaveoneCSSfileloadedbyyourpage,thereisotherCSSthatisgoingtobe partoftheprocess.Wehavethebrowser(useragent)CSS.Browserscomewithadefaultset ofrules,alldifferentbetweenbrowsers. ThenyourCSScomeintoplay. Thenthebrowserappliesanyuserstylesheet,whichmightalsobeappliedbybrowser extensions. Allthoserulescomeintoplaywhilerenderingthepage. We'llnowseetheconceptsofspecificityandinheritance.
18
Specificity
Specificity Whathappenswhenanelementistargetedbymultiplerules,withdifferentselectors,that affectthesameproperty? Forexample,let'stalkaboutthiselement:
Roger
Wecanhave .dog-name{ color:yellow; }
andanotherrulethattargets p,whichsetsthecolortoanothervalue: p{ color:red; }
Andanotherrulethattargets p.dog-name.Whichruleisgoingtotakeprecedenceoverthe others,andwhy? Enterspecificity.Themorespecificrulewillwin.Iftwoormoreruleshavethesame specificity,theonethatappearslastwins. Sometimeswhatismorespecificinpracticeisabitconfusingtobeginners.Iwouldsayit's alsoconfusingtoexpertsthatdonotlookatthoserulesthatfrequently,orsimplyoverlook them.
Howtocalculatespecificity Specificityiscalculatedusingaconvention. Wehave4slots,andeachoneofthemstartsat0: 00000.Theslotattheleftisthemost important,andtherightmostoneistheleastimportant. Likeitworksfornumbersinthedecimalsystem: 1000ishigherthan 0100.
19
Specificity
Slot1 Thefirstslot,therightmostone,istheleastimportant. Weincreasethisvaluewhenwehaveanelementselector.Anelementisatagname.Ifyou havemorethanoneelementselectorintherule,youincrementaccordinglythevaluestoredin thisslot. Examples: p{}/*0001*/ span{}/*0001*/ pspan{}/*0002*/ p>span{}/*0002*/ divp>span{}/*0003*/
Slot2 Thesecondslotisincrementedby3things: classselectors pseudo-classselectors attributeselectors Everytimearulemeetsoneofthose,weincrementthevalueofthesecondcolumnfromthe right. 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*/
20
Specificity
Slot3 Slot3holdsthemostimportantthingthatcanaffectyourCSSspecificityinaCSSfile:the id.
Everyelementcanhavean idattributeassigned,andwecanusethatinourstylesheetto targettheelement. Examples: #name{}/*0100*/ .user#name{}/*0110*/ #namespan{}/*0101*/
Slot4 Slot4isaffectedbyinlinestyles.Anyinlinestylewillhaveprecedenceoveranyruledefinedin anexternalCSSfile,orinsidethe styletaginthepageheader. Example: Test/*1000*/
EvenifanyotherruleintheCSSdefinesthecolor,thisinlinestyleruleisgoingtobeapplied. Exceptforonecase-if !importantisused,whichfillstheslot5.
Importance Specificitydoesnotmatterifaruleendswith !important: p{ font-size:20px!important; }
Thatrulewilltakeprecedenceoveranyrulewithmorespecificity Adding !importantinaCSSruleisgoingtomakethatrulebemoreimportantthananyother rule,accordingtothespecificityrules.Theonlywayanotherrulecantakeprecedenceisto have !importantaswell,andhavehigherspecificityintheotherlessimportantslots.
Tips
21
Specificity
Ingeneralyoushouldusetheamountofspecificityyouneed,butnotmore.Inthisway,you cancraftotherselectorstooverwritetherulessetbyprecedingruleswithoutgoingmad. !importantisahighlydebatedtoolthatCSSoffersus.ManyCSSexpertsadvocateagainst
usingit.IfindmyselfusingitespeciallywhentryingoutsomestyleandaCSSrulehasso muchspecificitythatIneedtouse !importanttomakethebrowserapplymynewCSS. Butgenerally, !importantshouldhavenoplaceinyourCSSfiles. Usingthe idattributetostyleCSSisalsodebatedalot,sinceithasaveryhighspecificity.A goodalternativeistouseclassesinstead,whichhavelessspecificity,andsotheyareeasier toworkwith,andtheyaremorepowerful(youcanhavemultipleclassesforanelement,anda classcanbereusedmultipletimes).
Toolstocalculatethespecificity Youcanusethesitehttps://specificity.keegan.st/toperformthespecificitycalculationforyou automatically. It'susefulespeciallyifyouaretryingtofigurethingsout,asitcanbeanicefeedbacktool.
22
Inherit...