Less(LeanerStyleSheets的缩写)是一种向后兼容的CSS语言扩展。这是Less语言和Less.js的官方文档,Less.js是将Less样式转换为CSS样式的JavaScript工具。
¥Less(whichstandsforLeanerStyleSheets)isabackwards-compatiblelanguageextensionforCSS.ThisistheofficialdocumentationforLess,thelanguageandLess.js,theJavaScripttoolthatconvertsyourLessstylestoCSSstyles.
因为Less看起来就像CSS,所以学习起来很容易。Less只对CSS语言做了一些方便的补充,这也是它可以学得这么快的原因之一。
¥BecauseLesslooksjustlikeCSS,learningitisabreeze.LessonlymakesafewconvenientadditionstotheCSSlanguage,whichisoneofthereasonsitcanbelearnedsoquickly.
Less给CSS增加了什么?以下是功能的快速概述。
¥WhatdoesLessaddtoCSSHere'saquickoverviewoffeatures.
¥Variables
这些都是不言自明的:
¥Theseareprettyself-explanatory:
@width:10px;@height:@width+10px;#header{width:@width;height:@height;}输出:
¥Outputs:
¥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();}.bordered类的属性现在将出现在#menua和.posta中。(请注意,你也可以将#ids用作混入。)
¥Thepropertiesofthe.borderedclasswillnowappearinboth#menuaand.posta.(Notethatyoucanalsouse#idsasmixins.)
¥Nesting
Less使你能够使用嵌套代替级联,或与级联结合使用。假设我们有以下CSS:
¥Lessgivesyoutheabilitytousenestinginsteadof,orincombinationwithcascading.Let'ssaywehavethefollowingCSS:
#header{color:black;}#header.navigation{font-size:12px;}#header.logo{width:300px;}在Less中,我们也可以这样写:
¥InLess,wecanalsowriteitthisway:
#header{color:black;.navigation{font-size:12px;}.logo{width:300px;}}生成的代码更加简洁,并且模仿了HTML的结构。
¥Theresultingcodeismoreconcise,andmimicsthestructureofyourHTML.
你还可以使用此方法将伪选择器与混入打包在一起。这是经典的clearfixhack,重写为混入(&代表当前选择器父级):
¥Youcanalsobundlepseudo-selectorswithyourmixinsusingthismethod.Here'stheclassicclearfixhack,rewrittenasamixin(&representsthecurrentselectorparent):
¥NestedAt-RulesandBubbling
诸如@media或@supports之类的@规则可以以与选择器相同的方式嵌套。@规则放在最前面,与同一规则集中其他元素的相对顺序保持不变。这称为冒泡。
¥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
算术运算+、-、*、/可以对任何数字、颜色或变量进行运算。如果可能,数学运算会考虑单位并在加、减或比较之前转换数字。结果在最左边有明确说明的单位类型。如果转换不可能或没有意义,则忽略单位。不可能转换的例子:px到cm或rad到%。
¥Arithmeticaloperations+,-,*,/canoperateonanynumber,colororvariable.Ifitispossible,mathematicaloperationstakeunitsintoaccountandconvertnumbersbeforeadding,subtractingorcomparingthem.Theresulthasleftmostexplicitlystatedunittype.Iftheconversionisimpossibleornotmeaningful,unitsareignored.Exampleofimpossibleconversion:pxtocmorradto%.
¥Multiplicationanddivisiondonotconvertnumbers.Itwouldnotbemeaningfulinmostcases-alengthmultipliedbyalengthgivesanareaandcssdoesnotsupportspecifyingareas.Lesswilloperateonnumbersastheyareandassignexplicitlystatedunittypetotheresult.
@base:2cm*3mm;//resultis6cm你还可以对颜色进行算术运算:
¥Youcanalsodoarithmeticoncolors:
从4.0开始,不会使用/运算符在括号外执行除法。
¥From4.0,Nodivisionisperformedoutsideofparensusing/operator.
¥calc()exception
为了CSS兼容性,calc()不计算数学表达式,但会计算嵌套函数中的变量和数学。
¥ForCSScompatibility,calc()doesnotevaluatemathexpressions,butwillevaluatevariablesandmathinnestedfunctions.
@var:50vh/2;width:calc(50%+(@var-20px));//resultiscalc(50%+(25vh-20px))
¥Escaping
@min768:~"(min-width:768px)";.element{@media@min768{font-size:1.2rem;}}结果是:
¥resultsin:
@media(min-width:768px){.element{font-size:1.2rem;}}注意,从Less3.5开始,你可以简单地写:
¥Note,asofLess3.5,youcansimplywrite:
@min768:(min-width:768px);.element{@media@min768{font-size:1.2rem;}}在3.5+中,许多以前需要"引号转义"的案例不再需要了。
¥In3.5+,manycasespreviouslyrequiring"quote-escaping"arenotneeded.
¥Functions
使用它们非常简单。以下示例使用百分比将0.5转换为50%,将基色的饱和度增加5%,然后将背景颜色设置为亮25%并旋转8度的颜色:
¥Usingthemisprettystraightforward.Thefollowingexampleusespercentagetoconvert0.5to50%,increasesthesaturationofabasecolorby5%andthensetsthebackgroundcolortoonethatislightenedby25%andspunby8degrees:
¥NamespacesandAccessors
有时,出于组织目的或只是为了提供一些封装,你可能希望对混入进行分组。你可以在Less中非常直观地做到这一点。假设你想在#bundle下打包一些混入和变量,以供以后重用或分发:
¥Sometimes,youmaywanttogroupyourmixins,fororganizationalpurposes,orjusttooffersomeencapsulation.YoucandothisprettyintuitivelyinLess.Sayyouwanttobundlesomemixinsandvariablesunder#bundle,forlaterreuseordistributing:
#bundle(){.button{display:block;border:1pxsolidblack;background-color:grey;&:hover{background-color:white;}}.tab{...}.citation{...}}现在如果我们想在我们的#headera中混合.button类,我们可以这样做:
¥Nowifwewanttomixinthe.buttonclassinour#headera,wecando:
#headera{color:orange;#bundle.button();//canalsobewrittenas#bundle>.button}注意:如果你不希望它出现在你的CSS输出中(即#bundle.tab),请将()附加到你的命名空间(例如#bundle())。
¥Note:append()toyournamespace(e.g.#bundle())ifyoudon'twantittoappearinyourCSSoutputi.e.#bundle.tab.
¥Maps
从Less3.5开始,你还可以使用混入和规则集作为值映射。
¥AsofLess3.5,youcanalsousemixinsandrulesetsasmapsofvalues.
#colors(){primary:blue;secondary:green;}.button{color:#colors[primary];border:1pxsolid#colors[secondary];}如预期的那样输出:
¥Thisoutputs,asexpected:
¥Scope
Less中的作用域与CSS中的作用域非常相似。首先在本地查找变量和混入,如果找不到,则从"父级"作用域继承。
¥ScopeinLessisverysimilartothatofCSS.Variablesandmixinsarefirstlookedforlocally,andiftheyaren'tfound,it'sinheritedfromthe"parent"scope.
@var:red;#page{@var:white;#header{color:@var;//white}}与CSS自定义属性一样,混入和变量定义不必放在引用它们的行之前。所以下面的Less代码与前面的例子是一样的:
¥LikeCSScustomproperties,mixinandvariabledefinitionsdonothavetobeplacedbeforealinewheretheyarereferenced.SothefollowingLesscodeisidenticaltothepreviousexample:
¥Comments
块式注释和行内注释都可以使用:
¥Bothblock-styleandinlinecommentsmaybeused:
/*Oneheckofablock*stylecomment!*/@var:red;//Getinline!@var:white;
¥Importing
导入工作与预期的差不多。你可以导入一个.less文件,其中的所有变量都将可用。可选地为.less文件指定扩展名。
¥Importingworksprettymuchasexpected.Youcanimporta.lessfile,andallthevariablesinitwillbeavailable.Theextensionisoptionallyspecifiedfor.lessfiles.