less
Less (Leaner Style Sheets 的缩写) 是一门向后兼容的 CSS 扩展语言。这里呈现的是 Less 的官方文档(中文版),包含了 Less 语言以及利用 JavaScript 开发的用于将 Less 样式转换成 CSS 样式的 Less.js 工具。
因为 Less 和 CSS 非常像,因此很容易学习。
npm install -g less
yarn add less
两者都可以将less下载,安装至依赖中。之后在style中加入 lang='less'
即可。
<style lang="less">
</style>
scoped
在之前很多地方,都会给你默认加上
<style scoped>
</style>
那这是什么意思呢,经过查阅资料:实现组件的私有化, 当前style属性只属于当前模块
基本less用法
接下来跟着官方文档一起学习下less
变量(Variables)
可以定义一些变量进行更改。
@width: 10px;
@height: @width + 10px;
#header {
width: @width;
height: @height;
}
混合(Mixins)
.bordered {
border-top: dotted 1px black;
border-bottom: solid 2px black;
}
#menu a {
color: #111;
.bordered();
}
.post a {
color: red;
.bordered();
}
.bordered
类所包含的属性就将同时出现在 #menu a
和 .post a
中了
嵌套(Nesting)
#header {
color: black;
.navigation {
font-size: 12px;
}
.logo {
width: 300px;
}
}
header
下的navigation
class以及logo
class
你还可以使用此方法将伪选择器(pseudo-selectors)与混合(mixins)一同使用。下面是一个经典的 clearfix 技巧,重写为一个混合(mixin) (&
表示当前选择器的父级)
.clearfix {
display: block;
zoom: 1;
&:after {
content: " ";
display: block;
font-size: 0;
height: 0;
clear: both;
visibility: hidden;
}
}
运算(Operations)
@conversion-1: 5cm + 10mm; // 结果是 6cm
@conversion-2: 2 - 3cm - 5mm; // 结果是 -1.5cm
// conversion is impossible
@incompatible-units: 2 + 5px - 3cm; // 结果是 4px
// example with variables
@base: 5%;
@filler: @base * 2; // 结果是 10%
@other: @base + @filler; // 结果是 15%
calc() 特例
为了与 CSS 保持兼容,calc()
并不对数学表达式进行计算,但是在嵌套函数中会计算变量和数学公式的值。
@var: 50vh/2;
.nav{
width: calc(50% + (@var - 20px));
}
转义(Escaping)
转义(Escaping)允许你使用任意字符串作为属性或变量值。任何 ~"anything"
或 ~'anything'
形式的内容都将按原样输出,除非 interpolation
@min768: ~"(min-width: 768px)";
.element {
@media @min768 {
font-size: 1.2rem;
}
}
函数(Functions)
@base: #f04615;
@width: 0.5;
.class {
width: percentage(@width); // returns `50%`
color: saturate(@base, 5%);
background-color: spin(lighten(@base, 25%), 8);
}
映射(Maps)
从 Less 3.5 版本开始,你还可以将混合(mixins)和规则集(rulesets)作为一组值的映射(map)使用
#colors() {
primary: blue;
secondary: green;
}
.button {
color: #colors[primary];
border: 1px solid #colors[secondary];
}
作用域(Scope)
@var: red;
#page {
@var: white;
#header {
color: @var; // white
}
}
////////////////////////
@var: red;
#page {
#header {
color: @var; // white
}
@var: white;
}
后面还有注释和导入就不记下来了。