Unlike regular CSS as we know it, LESS works much more like a programming language. It's dynamic, so expect to find some terminologies like ...
CSSPre-processorhasnowbecomeastapleinwebdevelopment.ItshipsplainCSSwithprogrammingtraitssuchasVariables,FunctionsorMixin,andOperationwhichallowwebdeveloperstobuildmodular,scalable,andmoremanageableCSSstyles.
Inthispost,wearegoingtolookintoLESSwhichhasbeenoneofthemostpopularCSSPre-processorsaround,andhasalsobeenwidelydeployedinnumerousfront-endframeworkslikeBootstrap.Wewillalsowalkthroughthebasicutilities,tools,andsetupstohelpgetyouupandrunningwithLESS.
TheCompiler
Tobeginwith,wewillneedtosetupacompiler.LESSsyntaxisnon-standard,perW3Cspecification.Thebrowserwouldnotbeabletoprocessandrendertheoutput,despiteinheritingtraitssimilartoCSS.
HereisaglimpseatLESScode:
@color-base:#2d5e8b;
.class1{
background-color:@color-base;
.class2{
background-color:#fff;
color:@color-base;
}
}
ThecompilerwillprocessthecodeandturnLESSsyntaxintobrowser-compliantCSSformat:
.class1{
background-color:#2d5e8b;
}
.class1.class2{
background-color:#fff;
color:#2d5e8b;
}
ThereareanumberoftoolsforcompilingCSS:
UsingJavaScript
LESScomeswithaless.jsfilewhichisreallyeasytodeployinyourwebsite.Createastylesheetwith.lessextensionandlinkitinyourdocumentusingtherel="stylesheet/less"attribute.
YoucanobtaintheJSfilehere,downloaditthroughBowerpackagemanager,elsedirectlylinktoCDN,likeso:
Youareallsetandcancomposestyleswithinthe.less.TheLESSsyntaxwillbecompiledontheflyasthepageloads.KeepinmindthatusingJavaScriptisdiscouragedattheproductionstageasitwillbadlyaffectthewebsiteperformance.
YoushouldalwayscompiletheLESSsyntaxbeforehandandonlyserveregularCSSinstead.YoucanuseTerminal,aTaskRunnerlikeGruntorGulp,oragraphicalapplicationtodoso.
UsingCLI
LESSprovidesanativecommandlineinterface(CLI),lessc,whichhandlesseveraltasksbeyondjustcompilingtheLESSsyntax.UsingtheCLIwecanlintthecodes,compressthefiles,andcreateasourcemap.ThecommandisbasedonNode.jsthateffectivelyallowsthecommandtoworkacrossWindows,OSX,andLinux.
MakesurethatNode.jshasbeeninstalled(otherwisegrabtheinstallerhere),theninstallLESSCLIthroughNPM(NodePackageManager)usingthefollowingcommandline.
npminstall-gless
NowyouhavethelessccommandatyourdisposaltocompileLESSintoCSS:
lesscstyle.lessstyle.css
UsingTaskRunner
Taskrunnerisatoolthatautomatesdevelopmenttasksandworkflows.Ratherthanrunthelessccommandeverytimewewouldliketocompileourcodes,wecansetupinstallataskrunner,andsetittowatchchangeswithinourLESSfiles,andimmediatelycompileLESSintoCSS.
TwopopulartoolsinthiscategorytodayareGruntandGulp.Wehaveaseriesofpostthatcoverthesetools.Checkouthepoststolearnhowtodeploythesetoolsinyourworkflow.
HowToUseGruntToAutomateYourWorkflow
GettingStartedWithGulp.js
TheBattleOfBuildScripts:GulpVsGrunt
UsingGraphicalApplication
ForthosewhomightnotbeaccustomedtousingTerminalandcommandlines,theycanoptforagraphicalinterfaceinstead.ThereareanabundanceofapplicationstocompileLESStodayforallplatforms–somefree,somepaid
Hereisthecompletelist:
App
Platform
Cost
Mixture
OSX/Windows
Free
Koala
OSX/Windows/Linux
Free
Prepros
OSX/Windows
Freemium(USD29)
WinLESS
Windows
Free
CodeKit
OSX
USD32
Whichcompileryouoptfor(asidefromJavaScript)doesnotreallymatter,frankly,solongasthetoolworksandcomplementsyourworkflow,goforit.
TheCodeEditor
Youcanuseanycodeeditor.SimplyinstallapluginoranextensiontohighlightLESSsyntaxwithpropercolors,afeaturewhichisnowavailableforalmostallcodeeditorsandIDEsincludingSublimeText,Notepad++,VisualStudio,TextMate,andEclipsetonameafew.
Nowthatwehavethecompilerandthecodeeditorallset,wecanstartwritingCSSstyleswithLESSsyntax.
LESSSyntax
UnlikeregularCSSasweknowit,LESSworksmuchmorelikeaprogramminglanguage.It’sdynamic,soexpecttofindsometerminologieslikeVariables,OperationandScopealongtheway.
Variables
Firstofall,let’stakealookattheVariables.
Ifyou’vebeenworkingquiteawhilewithCSS,youprobablyhavewrittensomethinglikethis,wherewehaverepetitivevaluesassignedindeclarationblocksintheentirestylesheet.
.class1{
background-color:#2d5e8b;
}
.class2{
background-color:#fff;
color:#2d5e8b;
}
.class3{
border:1pxsolid#2d5e8b;
}
Thispracticeisactuallyfine–untilwefindourselveshavingtosiftthroughmorethanathousandormoresimilarsnippetsthroughoutthestylesheet.Thiscouldhappenwhenbuildingalarge-scalewebsite.Workwillbecometedious.
IfweareusingaCSSpre-procesorlikeLESS,theinstanceabovewouldnotbeaproblem–wecanuseVariables.Thevariableswillallowustostoreaconstantvaluethatlatercanbereusedintheentirestylesheet.
@color-base:#2d5e8b;
.class1{
background-color:@color-base;
}
.class2{
background-color:#fff;
color:@color-base;
}
.class3{
border:1pxsolid@color-base;
}
Intheexampleabove,westorethecolor#[email protected],weonlyneedtochangethevalueinthisvariable.
Asidefromcolor,youcanalsoputothervaluesinthevariableslikeforexample:
@font-family:Georgia
@dot-border:dotted
@transition:linear
@opacity:0.5
Mixins
InLESS,wecanuseMixinstoreusewholedeclarationsinaCSSrulesetinanotherruleset.Hereisanexample:
.gradients{
background:#eaeaea;
background:linear-gradient(top,#eaeaea,#cccccc);
background:-o-linear-gradient(top,#eaeaea,#cccccc);
background:-ms-linear-gradient(top,#eaeaea,#cccccc);
background:-moz-linear-gradient(top,#eaeaea,#cccccc);
background:-webkit-linear-gradient(top,#eaeaea,#cccccc);
}
Intheabovesnippet,wehavepresetadefaultgradientcolorinsidethe.gradientsclass.Wheneverwewanttoaddthegradientswesimplyinsertthe.gradientsthisway:
div{
.gradients;
border:1pxsolid#555;
border-radius:3px;
}
The.boxwillinheritallthedeclarationblockinsidethe.gradients.So,theCSSruleaboveisequaltothefollowingplainCSS:
div{
background:#eaeaea;
background:linear-gradient(top,#eaeaea,#cccccc);
background:-o-linear-gradient(top,#eaeaea,#cccccc);
background:-ms-linear-gradient(top,#eaeaea,#cccccc);
background:-moz-linear-gradient(top,#eaeaea,#cccccc);
background:-webkit-linear-gradient(top,#eaeaea,#cccccc);
border:1pxsolid#555;
border-radius:3px;
}
Furthermore,ifyouareusingCSS3alotinyourwebsite,youcanuseLESSElementstomakeyourjobmucheasier.LESSElementsisacollectionofcommonCSS3Mixinsthatwemayuseofteninstylesheets,suchasborder-radius,gradients,drop-shadowandsoon.
TouseLESSElements,simplyaddthe@importruleinyourLESSstylesheet,butdon’tforgettodownloaditfirstandadditintoyourworkingdirectory.
@import"elements.less";
Wecannowreusealltheclassesprovidedfromtheelements.less,forexample,toadd3pxborderradiustoadiv,wecanwrite:
div{
.rounded(3px);
}
Forfurtherusage,pleaserefertotheofficialdocumentation.
NestedRules
WhenyouwritestylesinplainCSS,youmayalsohavecomethroughthesetypicalcodestructures.
nav{
height:40px;
width:100%;
background:#455868;
border-bottom:2pxsolid#283744;
}
navli{
width:600px;
height:40px;
}
navlia{
color:#fff;
line-height:40px;
text-shadow:1px1px0px#283744;
}
InplainCSS,weselectchildelementsbyfirsttargetingtheparentineveryruleset,whichisconsiderablyredundantifwefollowthe“bestpractices”principle.
InLESSCSS,wecansimplifytherulesetsbynestingthechildelementsinsidetheparents,asfollows;
nav{
height:40px;
width:100%;
background:#455868;
border-bottom:2pxsolid#283744;
li{
width:600px;
height:40px;
a{
color:#fff;
line-height:40px;
text-shadow:1px1px0px#283744;
}
}
}
Youcanalsoassignpseudo-classes,like:hover,totheselectorusingtheampersand(&)symbol.
Let’ssaywewanttoadd:hovertotheanchortagabove,wecanwriteitthisway:
a{
color:#fff;
line-height:40px;
text-shadow:1px1px0px#283744;
&:hover{
background-color:#000;
color:#fff;
}
}
Operation
WecanalsoperformoperationsinLESS,suchasaddition,subtraction,multiplicationanddivisiontonumbers,colorsandvariablesinthestylesheet.
Let’ssaywewantelementBtobetwotimeshigherthanelementA.Inthatcase,wecanwriteitthisway:
@height:100px
.element-A{
height:@height;
}
.element-B{
height:@height*2;
}
Asyoucanseeabove,wefirststorethevalueinthe@heightvariable,thenassignthevaluetoelementA.
InelementB,ratherthancalculatetheheightourselves,wecanmultiplytheheightby2usingtheasteriskoperator(*).Now,wheneverwechangethevalueinthe@heightvariable,elementBwillalwayshavetwicetheheight.
Checkoutmoreadvancedoperationexamplesinourprevioustutorial:DesigningASlickMenuNavigationBar.
Scope
LESSappliestheScopeconcept,wherevariableswillbeinheritedfirstfromthelocalscope,andwhenitisnotavailablelocally,itwillsearchthroughawiderscope.
header{
@color:black;
background-color:@color;
nav{
@color:blue;
background-color:@color;
a{
color:@color;
}
}
}
Intheexampleabove,theheaderhasablackbackgroundcolor,butnav‘sbackgroundcolorwillbeblueasithasthe@colorvariableinitslocalscope,whiletheawillalsohavebluethatisinheritedfromitsnearerparent,nav.
FinalThought
Ultimately,wehopethispostcangiveyouabasicunderstandingonhowwecanwriteCSSinabetterwayusingLESS.Youmaybefeelalittleawkwardatfirst,butasyoutryitmoreoften,itwillsurelybecomealoteasier.
HereareacoupleoftutorialsthatIencourageyoutolookintoforfurthertipsandpractices,whichcanhelppushyourLESSskilluptothenextlevel.
LESSCSSTutorial:DesigningASlickMenuNavigationBar
UnderstandingLESSColorFunctions
3NewLESSCSSFeaturesYouShouldKnow
ShowComments
Youmightalsolike
CalculatingPercentageMarginsinCSSKevinYank
CSS3BlendingModeThoriqFirdaus
HowtoCreateaCustomAudioPlayerForYourWebsiteThoriqFirdaus
TheBeginnersGuidetoCSSObjectModel(CSSOM)JakeRocheleau
CSSCouldBeTheHardestLanguageofAll(5ReasonsWhy)ThoriqFirdaus
WebDesign:HowtoConvertCSStoSass&SCSSThoriqFirdaus
ALookIntoCSSUnits:Pixels,EM,andPercentageThoriqFirdaus
30CoolCSSAnimationsForYourInspirationAgus
CloseSearch
SearchHongkiat
WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail