Learn LESS in 10 Minutes (or Less) - TutorialZine

文章推薦指數: 80 %
投票人數:10人

In this quick lesson we are going to cover the basics of Less. It is one of the most widely used CSS pre-processor at the moment and is a ... LearnLESSin10Minutes(orLess) July23rd2015 QuickLearn WeallknowCSScanbeabitfrustratingtowrite,especiallywhenitcomestomoreseriousprojectswiththousandsoflinesofcode.Youendupduplicatingthesamerulesallovertheplaceandusingyoureditor'ssearchandreplaceforeverycolorchange.IttakesalotofeffortanddisciplinetokeepyourCSSmaintainable.Butitdoesn'thavetobethisway. Luckily,thewebdevelopmentcommunityhassolvedthisproblem.WenowhaveCSSpre-processorssuchasLess,SassandStylus.TheygiveusanumberofbenefitsoverplainCSS: Variables,sothatyoucandefineandeasilychangevaluesthroughoutyourstylesheet.(ThisisactuallycomingtoCSSsomeday.) Dynamicallycalculatedvalues.(InCSSwerecentlygotcalc,butitisonlyforlengthunits.) Mixins,whichenableyoutoreuseandcombinestyles.Theyevensupportpassingarguments. Functions,whichgiveyouanumberofhandyutilitiesformanipulatingcolor,convertingimagestodata-urisandmore. Thenegativeaspectisthatifyouuseoneofthesepre-processors,youwillneedtocompileyourstylesheetsdowntoregularCSSsothatitworksinbrowsers. 1.GettingStarted LessiswritteninJavaScript,andneedseitherNode.jsorawebbrowsertorun.Youcanincludeless.jsinyourwebsiteanditcancompileallthelinked.lessstylesheetsinrealtime,butthisisslowandisnotrecommended.TherecommendedwayistocompileyourlessstylesheetsaheadoftimeanddeployaregularCSSfileonline.Therearealsoanumberoffreegraphicalprogramsthatcancompile.lessfilesforyou,butinthisarticlewewillcovernode.js. Ifyouhavenodeinstalled,andyouknowwhataterminalis,goaheadandopenone.TheninstalllessusingNPM: npminstall-gless Thiswillgiveyouaccesstothelessccommandfromanyopenterminal,enablingyoutocompileyour.lessfilesintovanillaCSSlikethis: lesscstyles.less>styles.css Let'ssaywe'vewrittenallourstylesheetruleswithLESSinstyles.less.Withtheaboveline,ourcodewillbetransformedtoplainCSSinstyles.css.AllthatisleftistolinkthiscssfileourHTML.Iftherewasacompilationmistake,itwillshowupinyourterminal. 2.Variables OneofthemainfeaturesofLessistheabilitytocreatevariablesjustlikeyouwouldinastandardprogramminglanguage.Theycanstoreanytypeofvalueyoufindyourselfusingfrequently:colors,dimensions,selectors,fontnames,URLsandsoon.ThephilosophyoflessistoreusetheCSSsyntaxwherepossible. Here,wedefinetwovariables,oneforbackgroundcolorandonefortextcolor,bothcontaininghexadecimalcodes.SwitchbetweenthetabstoseethetranslatedtoCSSversionofthecode: @background-color:#ffffff; @text-color:#1A237E; p{ background-color:@background-color; color:@text-color; padding:15px; } ul{ background-color:@background-color; } li{ color:@text-color; } p{ background-color:#ffffff; color:#1A237E; padding:15px; } ul{ background-color:#ffffff; } li{ color:#1A237E; } Intheexampleabove,thebackgroundcoloriswhite,whilethetextisdark.If,let'ssay,wewanttoswitchthemaroundandhavedarkelementswithwhitetext,wecansimplychangethevaluesofthevariables,insteadofmanuallyreplacingeveryoccurrence. FormoreaboutvariablesinLessreadhere. 3.Mixins LESSenablesustouseanexistingclassoridsandapplyallit'sstylesdirectlytoanotherselector.Thefollowingexamplewillclearthingsup: #circle{ background-color:#4CAF50; border-radius:100%; } #small-circle{ width:50px; height:50px; #circle } #big-circle{ width:100px; height:100px; #circle } #circle{ background-color:#4CAF50; border-radius:100%; } #small-circle{ width:50px; height:50px; background-color:#4CAF50; border-radius:100%; } #big-circle{ width:100px; height:100px; background-color:#4CAF50; border-radius:100%; } Ifyoudon'twantthemixintoappearasaruleintheCSSyoucanplaceparenthesesafterit: #circle(){ background-color:#4CAF50; border-radius:100%; } #small-circle{ width:50px; height:50px; #circle } #big-circle{ width:100px; height:100px; #circle } #small-circle{ width:50px; height:50px; background-color:#4CAF50; border-radius:100%; } #big-circle{ width:100px; height:100px; background-color:#4CAF50; border-radius:100%; } Anothercoolthingmixinscandoisreceiveparameters.Inthefollowingexampleweaddanargumentforthewidthandheightofourcircles,withadefaultvalueof25pixels.Thiswillcreateasmallcircle25x25andabigone100x100pixels. #circle(@size:25px){ background-color:#4CAF50; border-radius:100%; width:@size; height:@size; } #small-circle{ #circle } #big-circle{ #circle(100px) } #small-circle{ background-color:#4CAF50; border-radius:100%; width:25px; height:25px; } #big-circle{ background-color:#4CAF50; border-radius:100%; width:100px; height:100px; } ReadmoreaboutLessmixinsintheirofficialdocumentation. 4.NestingandScope NestingcanbeusedtostructureyourstylesheetinawaythatmatchestheHTMLstructureofthepage,whilereducingthechanceofconflicts.Hereisanexampleofanunorderedlistanditschildren: ul{ background-color:#03A9F4; padding:10px; list-style:none; li{ background-color:#fff; border-radius:3px; margin:10px0; } } ul{ background-color:#03A9F4; padding:10px; list-style:none; } ulli{ background-color:#fff; border-radius:3px; margin:10px0; } Justlikeinprogramminglanguages,inLessvariablesreceivetheirvaluesdependingonthescope.Ifthevalueisn'tspecifiedinthespecificscope,LESSwilllookforitinupperblocksuntilitfindsthenearestdeclaration. TranslatedtoCSS,ourliwillhavewhitecoloredtext,sincewe'vepredefinedstrong>@text-colorintheulrules. @text-color:#000000; ul{ @text-color:#fff; background-color:#03A9F4; padding:10px; list-style:none; li{ color:@text-color; border-radius:3px; margin:10px0; } } ul{ background-color:#03A9F4; padding:10px; list-style:none; } ulli{ color:#ffffff; border-radius:3px; margin:10px0; } Learnmoreaboutscopehere. 5.Operations Youcandobasicmathoperationstonumericalvaluesandcolors.Letssaywewanttohavetwodivsplacednexttoeachother,thesecondonebeingtwiceaswideandwithadifferentbackground.LESSknowswhatthemeasuringunitsareandwon'tmessthemup. @div-width:100px; @color:#03A9F4; div{ height:50px; display:inline-block; } #left{ width:@div-width; background-color:@color-100; } #right{ width:@div-width*2; background-color:@color; } div{ height:50px; display:inline-block; } #left{ width:100px; background-color:#004590; } #right{ width:200px; background-color:#03a9f4; } 6.Functions LESShasfunctionstoo!It'sstartingtolookmoreandmorelikeaprogramminglanguage,isn'tit? Let'stakealookatfadeout,afunctionthatdecreasestheopacityofacolor. @var:#004590; div{ height:50px; width:50px; background-color:@var; &:hover{ background-color:fadeout(@var,50%) } } div{ height:50px; width:50px; background-color:#004590; } div:hover{ background-color:rgba(0,69,144,0.5); } Withthecodeabove,whenourdivishovereditwillturnhalfwaytransparentmakingmouseovertransitionseasierthanever.Therearealotofotherusefulfunctionsformanipulatingcolors,detectingthesizeofimagesandevenembeddingassetsasdata-uriinthestylesheet.Seethefulllistoffunctionshere. Furtherreading YounowknowenoughofLesstogetstarted!EveryCSSfileisavalidLessstylesheet,soyoucanstartcleaningupthatoldandunwieldy.cssrightaway.Asyoulearnmore,youwillbeabletomakethecodeevenbetter.Hereiswhatwerecommendthatyoureadnext: Allthelanguagefeatures-link LESSfunctionreference-link Editorandcompilerinthebrowser-link BootstrapStudio Therevolutionarywebdesigntoolforcreatingresponsivewebsitesandapps. Learnmore RelatedArticles LearnHandlebarsin10MinutesorLess JavaScript | QuickLearn LearnSassIn15Minutes CSS | QuickLearn LearnWebpackin15Minutes JavaScript | QuickLearn LearnSQLIn20Minutes MySQL | QuickLearn LearnGitin30Minutes QuickLearn LearntheBootstrapGridin15Minutes Bootstrap | QuickLearn wizston 4yearsago Wow,Nicetutorial. Neverreallyconsideredusingit...Cool! Thanksforsharing. Peeyush 4yearsago ReallyGoodOne. sina 4yearsago reallyuseful! Iamconvincedtolearnanduseit! SrinivasReddy 4yearsago NicetutorialforstartLess.Thanksalot. Tobmai 4yearsago Awesome,easyanduseful!!! MertKahyaoğlu 4yearsago Niceone!Thankyou.Iwonderwhichsyntaxhighlightingthemeyouareusing?Iwouldliketouseittoo. DannyMarkov 4yearsago ThanksforthecommentMert! Forthesyntaxhighlightingweusedhighlight.jswiththeTomorrowtheme:) MertKahyaoğlu 4yearsago Thankyouverymuch! Jagadish 4yearsago NiceTutorial SrikanthReddy 4yearsago SimplyAwesome! NanduHulsure 4yearsago AwesometutorialDanny,reallyitgoeswithtitle. Maha 4yearsago Veryusefultutorialforbeginners,ithelpsmeunderstandLessalot, thankyousomuch:) Nomy 4yearsago Veryhelpfulandeasytounderstand.Thanks Vasil 4yearsago IamusingLESSanditisinsanelyhelpful-itcanhelpyouwithinyourworkalot printo 4yearsago ReallyGood,Thankyouverymuch swetha 3yearsago Nicework! Dave 3yearsago Reallygoodjobsummingupthebasics.Veryhelpfulforbeginnerslikeme.Thankssomuch. AniketAshokMaratkar 3yearsago Veryhelpfultutorialforbeginners,ithelpsmeunderstandLessalot,thankyousomuch Asim 3yearsago Nicesimpleandcleanwithgreatexplanation.Thanksforthis. AshishBhalerao 3yearsago Greatlesstutorialforbeginner. ReallyThankYouforthis Gourab 3yearsago BestLESStutorial.Thanks. Will 2yearsago Thankyouforsharing.Greattutorial! DannyMarkov DannyisTutorialzine'sEditorinChief.Whenheisnotintheoffice,youcanusuallyfindhimridinghisbikeandcodingonhislaptopinthepark. LatestArticles SeeAll TheSimplestWaytoAddGoogleMapstoYourSite TheEasiestWayToAddInputMasksToYourForms ConvertingfromSpeechtoTextwithJavaScript 12TerminalCommandsEveryWebDeveloperShouldKnowAbout JavaScriptAsync/AwaitExplainedin10Minutes Freebies SeeAll TheEasiestWayToAddInputMasksToYourForms Freebie:BeautifulCVTemplatewithBootstrap Freebie:3AmazingBootstrap4GalleryTemplates Freebie:BeautifulPricingTablewithBootstrap4 Freebie:2BeautifulCheckoutFormswithBootstrap4 VideoTutorials Subscribe CreatingaWebsitewithBootstrapStudio CreatingTesla'sWebsitewithBootstrap4 × BootstrapStudioExclusive ThissnippetisavailableonlyinBootstrapStudio,themostpowerfuldraganddropwebsitebuilderever. GetBootstrapStudio × Oops!Somethingwentwrong:(Tryagain... OK



請為這篇文章評分?