Less (which stands for Leaner Style Sheets) is a backwards-compatible language extension for CSS. This is the official documentation for Less, the language ...
It'sCSS,withjustalittlemore.
UsewithNode.js:
npminstall-gless
>lesscstyles.lessstyles.css
Orthebrowser:
ViewtheLess.jschangelog
Overview
Variables
Mixins
NestingNestedAt-RulesandBubbling
Operationscalc()exception
Escaping
Functions
NamespacesandAccessors
Maps
Scope
Comments
Importing
Overview
Less(whichstandsforLeanerStyleSheets)isabackwards-compatiblelanguageextensionforCSS.ThisistheofficialdocumentationforLess,thelanguageandLess.js,theJavaScripttoolthatconvertsyourLessstylestoCSSstyles.
BecauseLesslooksjustlikeCSS,learningitisabreeze.LessonlymakesafewconvenientadditionstotheCSSlanguage,whichisoneofthereasonsitcanbelearnedsoquickly.
FordetaileddocumentationonLesslanguagefeatures,seeFeatures
ForalistofLessBuilt-infunctions,seeFunctions
Fordetailedusageinstructions,seeUsingLess.js
Forthird-partytoolsforLess,seeTools
WhatdoesLessaddtoCSS?Here'saquickoverviewoffeatures.
Variables
Theseareprettyself-explanatory:
@width:10px;
@height:@width+10px;
#header{
width:@width;
height:@height;
}
Outputs:
#header{
width:10px;
height:20px;
}
LearnMoreAboutVariables
Mixins
Mixinsareawayofincluding("mixingin")abunchofpropertiesfromonerule-setintoanotherrule-set.Sosaywehavethefollowingclass:
.bordered{
border-top:dotted1pxblack;
border-bottom:solid2pxblack;
}
Andwewanttousethesepropertiesinsideotherrule-sets.Well,wejusthavetodropinthenameoftheclasswherewewanttheproperties,likeso:
#menua{
color:#111;
.bordered();
}
.posta{
color:red;
.bordered();
}
Thepropertiesofthe.borderedclasswillnowappearinboth#menuaand.posta.(Notethatyoucanalsouse#idsasmixins.)
LearnMoreAboutMixins
Nesting
Lessgivesyoutheabilitytousenestinginsteadof,orincombinationwithcascading.Let'ssaywehavethefollowingCSS:
#header{
color:black;
}
#header.navigation{
font-size:12px;
}
#header.logo{
width:300px;
}
InLess,wecanalsowriteitthisway:
#header{
color:black;
.navigation{
font-size:12px;
}
.logo{
width:300px;
}
}
Theresultingcodeismoreconcise,andmimicsthestructureofyourHTML.
Youcanalsobundlepseudo-selectorswithyourmixinsusingthismethod.Here'stheclassicclearfixhack,rewrittenasamixin(&representsthecurrentselectorparent):
.clearfix{
display:block;
zoom:1;
&:after{
content:"";
display:block;
font-size:0;
height:0;
clear:both;
visibility:hidden;
}
}
LearnMoreAboutParentSelectors
NestedAt-RulesandBubbling
At-rulessuchas@mediaor@supportscanbenestedinthesamewayasselectors.Theat-ruleisplacedontopandrelativeorderagainstotherelementsinsidethesamerulesetremainsunchanged.Thisiscalledbubbling.
.component{
width:300px;
@media(min-width:768px){
width:600px;
@media(min-resolution:192dpi){
background-image:url(/img/retina2x.png);
}
}
@media(min-width:1280px){
width:800px;
}
}
outputs:
.component{
width:300px;
}
@media(min-width:768px){
.component{
width:600px;
}
}
@media(min-width:768px)and(min-resolution:192dpi){
.component{
background-image:url(/img/retina2x.png);
}
}
@media(min-width:1280px){
.component{
width:800px;
}
}
Operations
Arithmeticaloperations+,-,*,/canoperateonanynumber,colororvariable.Ifitispossible,mathematicaloperationstakeunitsintoaccountandconvertnumbersbeforeadding,subtractingorcomparingthem.Theresulthasleftmostexplicitlystatedunittype.Iftheconversionisimpossibleornotmeaningful,unitsareignored.Exampleofimpossibleconversion:pxtocmorradto%.
//numbersareconvertedintothesameunits
@conversion-1:5cm+10mm;//resultis6cm
@conversion-2:2-3cm-5mm;//resultis-1.5cm
//conversionisimpossible
@incompatible-units:2+5px-3cm;//resultis4px
//examplewithvariables
@base:5%;
@filler:@base*2;//resultis10%
@other:@base+@filler;//resultis15%
Multiplicationanddivisiondonotconvertnumbers.Itwouldnotbemeaningfulinmostcases-alengthmultipliedbyalengthgivesanareaandcssdoesnotsupportspecifyingareas.Lesswilloperateonnumbersastheyareandassignexplicitlystatedunittypetotheresult.
@base:2cm*3mm;//resultis6cm
Youcanalsodoarithmeticoncolors:
@color:(#224488/2);//resultis#112244
background-color:#112244+#111;//resultis#223355
However,youmayfindLess'sColorFunctionsmoreuseful.
From4.0,Nodivisionisperformedoutsideofparensusing/operator.
@color:#222/2;//resultsin`#222/2`,not#111
background-color:(#FFFFFF/16);//resultsis#101010
YoucanchangeMathsetting,ifyouwanttomakeitalwayswork,butnotrecommended.
calc()exception
Releasedv3.0.0
ForCSScompatibility,calc()doesnotevaluatemathexpressions,butwillevaluatevariables
andmathinnestedfunctions.
@var:50vh/2;
width:calc(50%+(@var-20px));//resultiscalc(50%+(25vh-20px))
Escaping
Escapingallowsyoutouseanyarbitrarystringaspropertyorvariablevalue.Anythinginside~"anything"or~'anything'isusedasiswithnochangesexceptinterpolation.
@min768:~"(min-width:768px)";
.element{
@media@min768{
font-size:1.2rem;
}
}
resultsin:
@media(min-width:768px){
.element{
font-size:1.2rem;
}
}
Note,asofLess3.5,youcansimplywrite:
@min768:(min-width:768px);
.element{
@media@min768{
font-size:1.2rem;
}
}
In3.5+,manycasespreviouslyrequiring"quote-escaping"arenotneeded.
Functions
Lessprovidesavarietyoffunctionswhichtransformcolors,manipulatestringsanddomaths.Theyaredocumentedfullyinthefunctionreference.
Usingthemisprettystraightforward.Thefollowingexampleusespercentagetoconvert0.5to50%,increasesthesaturationofabasecolorby5%andthensetsthebackgroundcolortoonethatislightenedby25%andspunby8degrees:
@base:#f04615;
@width:0.5;
.class{
width:percentage(@width);//returns`50%`
color:saturate(@base,5%);
background-color:spin(lighten(@base,25%),8);
}
See:FunctionReference
NamespacesandAccessors
(NottobeconfusedwithCSS@namespaceornamespaceselectors).
Sometimes,youmaywanttogroupyourmixins,fororganizationalpurposes,orjusttooffersomeencapsulation.YoucandothisprettyintuitivelyinLess.Sayyouwanttobundlesomemixinsandvariablesunder#bundle,forlaterreuseordistributing:
#bundle(){
.button{
display:block;
border:1pxsolidblack;
background-color:grey;
&:hover{
background-color:white;
}
}
.tab{...}
.citation{...}
}
Nowifwewanttomixinthe.buttonclassinour#headera,wecando:
#headera{
color:orange;
#bundle.button();//canalsobewrittenas#bundle>.button
}
Note:append()toyournamespace(e.g.#bundle())ifyoudon'twantittoappearinyourCSSoutputi.e.#bundle.tab.
Maps
AsofLess3.5,youcanalsousemixinsandrulesetsasmapsofvalues.
#colors(){
primary:blue;
secondary:green;
}
.button{
color:#colors[primary];
border:1pxsolid#colors[secondary];
}
Thisoutputs,asexpected:
.button{
color:blue;
border:1pxsolidgreen;
}
Seealso:Maps
Scope
ScopeinLessisverysimilartothatofCSS.Variablesandmixinsarefirstlookedforlocally,andiftheyaren'tfound,it'sinheritedfromthe"parent"scope.
@var:red;
#page{
@var:white;
#header{
color:@var;//white
}
}
LikeCSScustomproperties,mixinandvariabledefinitionsdonothavetobeplacedbeforealinewheretheyarereferenced.SothefollowingLesscodeisidenticaltothepreviousexample:
@var:red;
#page{
#header{
color:@var;//white
}
@var:white;
}
Seealso:LazyLoading
Comments
Bothblock-styleandinlinecommentsmaybeused:
/*Oneheckofablock
*stylecomment!*/
@var:red;
//Getinline!
@var:white;
Importing
Importingworksprettymuchasexpected.Youcanimporta.lessfile,andallthevariablesinitwillbeavailable.Theextensionisoptionallyspecifiedfor.lessfiles.
@import"library";//library.less
@import"typo.css";
LearnMoreAboutImports