概述

Less(Leaner Style Sheets 的縮寫)是一種向后兼容的 CSS 語言擴(kuò)展。這是 Less 語言和 Less.js 的官方文檔,Less.js 是將 Less 樣式轉(zhuǎn)換為 CSS 樣式的 JavaScript 工具。

¥Less (which stands for Leaner Style Sheets) is a backwards-compatible language extension for CSS. This is the official documentation for Less, the language and Less.js, the JavaScript tool that converts your Less styles to CSS styles.

因?yàn)?Less 看起來就像 CSS,所以學(xué)習(xí)起來很容易。Less 只對(duì) CSS 語言做了一些方便的補(bǔ)充,這也是它可以學(xué)得這么快的原因之一。

¥Because Less looks just like CSS, learning it is a breeze. Less only makes a few convenient additions to the CSS language, which is one of the reasons it can be learned so quickly.

  • 有關(guān) Less 語言特性的詳細(xì)文檔,請(qǐng)參閱 特性

    For detailed documentation on Less language features, see Features

  • 有關(guān) Less 內(nèi)置函數(shù)的列表,請(qǐng)參閱 函數(shù)

    For a list of Less Built-in functions, see Functions

  • 詳細(xì)使用說明,請(qǐng)參閱 使用 Less.js

    For detailed usage instructions, see Using Less.js

  • Less 的第三方工具,請(qǐng)參閱 工具

    For third-party tools for Less, see Tools

Less 給 CSS 增加了什么?以下是功能的快速概述。

¥What does Less add to CSS? Here's a quick overview of features.

變量

¥Variables

這些都是不言自明的:

¥These are pretty self-explanatory:

@width: 10px;
@height: @width + 10px;

#header {
  width: @width;
  height: @height;
}

輸出:

¥Outputs:

#header {
  width: 10px;
  height: 20px;
}

了解有關(guān)變量的更多信息

Learn More About Variables

混入

¥Mixins

混入是一種將一組屬性從一個(gè)規(guī)則集中包含("混合進(jìn)入")到另一個(gè)規(guī)則集中的方法。所以說我們有以下類:

¥Mixins are a way of including ("mixing in") a bunch of properties from one rule-set into another rule-set. So say we have the following class:

.bordered {
  border-top: dotted 1px black;
  border-bottom: solid 2px black;
}

我們希望在其他規(guī)則集中使用這些屬性。好吧,我們只需要放入我們想要屬性的類的名稱,如下所示:

¥And we want to use these properties inside other rule-sets. Well, we just have to drop in the name of the class where we want the properties, like so:

#menu a {
  color: #111;
  .bordered();
}

.post a {
  color: red;
  .bordered();
}

.bordered 類的屬性現(xiàn)在將出現(xiàn)在 #menu a.post a 中。(請(qǐng)注意,你也可以將 #ids 用作混入。)

¥The properties of the .bordered class will now appear in both #menu a and .post a. (Note that you can also use #ids as mixins.)

了解有關(guān)混合的更多信息

Learn More About Mixins

嵌套

¥Nesting

Less 使你能夠使用嵌套代替級(jí)聯(lián),或與級(jí)聯(lián)結(jié)合使用。假設(shè)我們有以下 CSS:

¥Less gives you the ability to use nesting instead of, or in combination with cascading. Let's say we have the following CSS:

#header {
  color: black;
}
#header .navigation {
  font-size: 12px;
}
#header .logo {
  width: 300px;
}

在 Less 中,我們也可以這樣寫:

¥In Less, we can also write it this way:

#header {
  color: black;
  .navigation {
    font-size: 12px;
  }
  .logo {
    width: 300px;
  }
}

生成的代碼更加簡潔,并且模仿了 HTML 的結(jié)構(gòu)。

¥The resulting code is more concise, and mimics the structure of your HTML.

你還可以使用此方法將偽選擇器與混入打包在一起。這是經(jīng)典的 clearfix hack,重寫為混入(& 代表當(dāng)前選擇器父級(jí)):

¥You can also bundle pseudo-selectors with your mixins using this method. Here's the classic clearfix hack, rewritten as a mixin (& represents the current selector parent):

.clearfix {
  display: block;
  zoom: 1;

  &:after {
    content: " ";
    display: block;
    font-size: 0;
    height: 0;
    clear: both;
    visibility: hidden;
  }
}

了解有關(guān)父選擇器的更多信息

Learn More About Parent Selectors

嵌套的 @ 規(guī)則和冒泡

¥Nested At-Rules and Bubbling

諸如 @media@supports 之類的 @ 規(guī)則可以以與選擇器相同的方式嵌套。@ 規(guī)則放在最前面,與同一規(guī)則集中其他元素的相對(duì)順序保持不變。這稱為冒泡。

¥At-rules such as @media or @supports can be nested in the same way as selectors. The at-rule is placed on top and relative order against other elements inside the same ruleset remains unchanged. This is called bubbling.

.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

算術(shù)運(yùn)算 +-*/ 可以對(duì)任何數(shù)字、顏色或變量進(jìn)行運(yùn)算。如果可能,數(shù)學(xué)運(yùn)算會(huì)考慮單位并在加、減或比較之前轉(zhuǎn)換數(shù)字。結(jié)果在最左邊有明確說明的單位類型。如果轉(zhuǎn)換不可能或沒有意義,則忽略單位。不可能轉(zhuǎn)換的例子:px 到 cm 或 rad 到 %。

¥Arithmetical operations +, -, *, / can operate on any number, color or variable. If it is possible, mathematical operations take units into account and convert numbers before adding, subtracting or comparing them. The result has leftmost explicitly stated unit type. If the conversion is impossible or not meaningful, units are ignored. Example of impossible conversion: px to cm or rad to %.

// numbers are converted into the same units
@conversion-1: 5cm + 10mm; // result is 6cm
@conversion-2: 2 - 3cm - 5mm; // result is -1.5cm

// conversion is impossible
@incompatible-units: 2 + 5px - 3cm; // result is 4px

// example with variables
@base: 5%;
@filler: @base * 2; // result is 10%
@other: @base + @filler; // result is 15%

乘法和除法不轉(zhuǎn)換數(shù)字。大多數(shù)情況下沒有意義 - 長度乘以長度得出面積,而 css 不支持指定面積。Less 將按原樣對(duì)數(shù)字進(jìn)行運(yùn)算,并將明確聲明的單位類型分配給結(jié)果。

¥Multiplication and division do not convert numbers. It would not be meaningful in most cases - a length multiplied by a length gives an area and css does not support specifying areas. Less will operate on numbers as they are and assign explicitly stated unit type to the result.

@base: 2cm * 3mm; // result is 6cm

你還可以對(duì)顏色進(jìn)行算術(shù)運(yùn)算:

¥You can also do arithmetic on colors:

@color: (#224488 / 2); // result is #112244
background-color: #112244 + #111; // result is #223355

但是,你可能會(huì)發(fā)現(xiàn) Less 的 顏色函數(shù) 更有用。

¥However, you may find Less's Color Functions more useful.

從 4.0 開始,不會(huì)使用 / 運(yùn)算符在括號(hào)外執(zhí)行除法。

¥From 4.0, No division is performed outside of parens using / operator.

@color: #222 / 2; // results in `#222 / 2`, not #111
background-color: (#FFFFFF / 16); //results is #101010

你可以改變 數(shù)學(xué) 設(shè)置,如果你想讓它一直有效,但不推薦。

¥You can change Math setting, if you want to make it always work, but not recommended.

calc() 異常

¥calc() exception

發(fā)布于 v3.0.0

Released v3.0.0

為了 CSS 兼容性,calc() 不計(jì)算數(shù)學(xué)表達(dá)式,但會(huì)計(jì)算嵌套函數(shù)中的變量和數(shù)學(xué)。

¥For CSS compatibility, calc() does not evaluate math expressions, but will evaluate variables and math in nested functions.

@var: 50vh/2;
width: calc(50% + (@var - 20px));  // result is calc(50% + (25vh - 20px))

轉(zhuǎn)義

¥Escaping

轉(zhuǎn)義允許你使用任意字符串作為屬性或變量值。~"anything"~'anything' 中的任何內(nèi)容都按原樣使用,除了 插值 之外沒有任何變化。

¥Escaping allows you to use any arbitrary string as property or variable value. Anything inside ~"anything" or ~'anything' is used as is with no changes except interpolation.

@min768: ~"(min-width: 768px)";
.element {
  @media @min768 {
    font-size: 1.2rem;
  }
}

結(jié)果是:

¥results in:

@media (min-width: 768px) {
  .element {
    font-size: 1.2rem;
  }
}

注意,從 Less 3.5 開始,你可以簡單地寫:

¥Note, as of Less 3.5, you can simply write:

@min768: (min-width: 768px);
.element {
  @media @min768 {
    font-size: 1.2rem;
  }
}

在 3.5+ 中,許多以前需要 "引號(hào)轉(zhuǎn)義" 的案例不再需要了。

¥In 3.5+, many cases previously requiring "quote-escaping" are not needed.

函數(shù)

¥Functions

Less 提供了許多函數(shù),可以轉(zhuǎn)換顏色、操作字符串和進(jìn)行數(shù)學(xué)運(yùn)算。它們?cè)?函數(shù)參考手冊(cè) 中有完整的記錄。

¥Less provides a variety of functions which transform colors, manipulate strings and do maths. They are documented fully in the function reference.

使用它們非常簡單。以下示例使用百分比將 0.5 轉(zhuǎn)換為 50%,將基色的飽和度增加 5%,然后將背景顏色設(shè)置為亮 25% 并旋轉(zhuǎn) 8 度的顏色:

¥Using them is pretty straightforward. The following example uses percentage to convert 0.5 to 50%, increases the saturation of a base color by 5% and then sets the background color to one that is lightened by 25% and spun by 8 degrees:

@base: #f04615;
@width: 0.5;

.class {
  width: percentage(@width); // returns `50%`
  color: saturate(@base, 5%);
  background-color: spin(lighten(@base, 25%), 8);
}

查閱:函數(shù)參考

See: Function Reference

命名空間和訪問器

¥Namespaces and Accessors

(不要與 CSS @namespace命名空間選擇器 混淆)。

¥(Not to be confused with CSS @namespace or namespace selectors).

有時(shí),出于組織目的或只是為了提供一些封裝,你可能希望對(duì)混入進(jìn)行分組。你可以在 Less 中非常直觀地做到這一點(diǎn)。假設(shè)你想在 #bundle 下打包一些混入和變量,以供以后重用或分發(fā):

¥Sometimes, you may want to group your mixins, for organizational purposes, or just to offer some encapsulation. You can do this pretty intuitively in Less. Say you want to bundle some mixins and variables under #bundle, for later reuse or distributing:

#bundle() {
  .button {
    display: block;
    border: 1px solid black;
    background-color: grey;
    &:hover {
      background-color: white;
    }
  }
  .tab { ... }
  .citation { ... }
}

現(xiàn)在如果我們想在我們的 #header a 中混合 .button 類,我們可以這樣做:

¥Now if we want to mixin the .button class in our #header a, we can do:

#header a {
  color: orange;
  #bundle.button();  // can also be written as #bundle > .button
}

注意:如果你不希望它出現(xiàn)在你的 CSS 輸出中(即 #bundle .tab),請(qǐng)將 () 附加到你的命名空間(例如 #bundle())。

¥Note: append () to your namespace (e.g. #bundle()) if you don't want it to appear in your CSS output i.e. #bundle .tab.

映射

¥Maps

從 Less 3.5 開始,你還可以使用混入和規(guī)則集作為值映射。

¥As of Less 3.5, you can also use mixins and rulesets as maps of values.

#colors() {
  primary: blue;
  secondary: green;
}

.button {
  color: #colors[primary];
  border: 1px solid #colors[secondary];
}

如預(yù)期的那樣輸出:

¥This outputs, as expected:

.button {
  color: blue;
  border: 1px solid green;
}

也可以看看:映射

See also: Maps

作用域

¥Scope

Less 中的作用域與 CSS 中的作用域非常相似。首先在本地查找變量和混入,如果找不到,則從 "父級(jí)" 作用域繼承。

¥Scope in Less is very similar to that of CSS. Variables and mixins are first looked for locally, and if they aren't found, it's inherited from the "parent" scope.

@var: red;

#page {
  @var: white;
  #header {
    color: @var; // white
  }
}

與 CSS 自定義屬性一樣,混入和變量定義不必放在引用它們的行之前。所以下面的 Less 代碼與前面的例子是一樣的:

¥Like CSS custom properties, mixin and variable definitions do not have to be placed before a line where they are referenced. So the following Less code is identical to the previous example:

@var: red;

#page {
  #header {
    color: @var; // white
  }
  @var: white;
}

也可以看看:延遲加載

See also: Lazy Loading

注釋

¥Comments

塊式注釋和行內(nèi)注釋都可以使用:

¥Both block-style and inline comments may be used:

/* One heck of a block

 * style comment! */
@var: red;

// Get in line!
@var: white;

導(dǎo)入

¥Importing

導(dǎo)入工作與預(yù)期的差不多。你可以導(dǎo)入一個(gè) .less 文件,其中的所有變量都將可用。可選地為 .less 文件指定擴(kuò)展名。

¥Importing works pretty much as expected. You can import a .less file, and all the variables in it will be available. The extension is optionally specified for .less files.

@import "library"; // library.less
@import "typo.css";

了解有關(guān)導(dǎo)入的更多信息

Learn More About Imports