less 基本使用

xiaoxiao2021-03-01  37

Less 基本使用

说明

Less 是一门 CSS 预处理语言,它扩展了 CSS 语言,增加了变量、Mixin、函数等特性,使 CSS 更易维护和扩展,Less 是基于 JavaScript 的,使用 Less 编写样式最简单的方式可以在 页面中引入 less.min.js 即可,样式会在客户端处理

不同于 Sass, Sass 是一种动态样式语言,基于 ruby 运行,样式必须在到达浏览器前处理完成

1. 声明及使用变量

@br: 1px solid red; .box{ border: @br; } // 变量作为类名,或者作为属性值得一部分使用 变量值会代替 @{变量名} 得部分 @path: image; @property: color; .@{path}{ width: 100%; height: 100%; } #box{ background-image: url("/@{path}/icon.png"); @{property}: red; }

2. 生明及使用混合 Mixins

// 会输出到最终编译后的 css 中的 Mixin,与一般 class 写法一致 .border-red { border: 1px solid red; } #box{ .border-red; } // 不会存放到输出的css 中的 Mixin, 要加括号。可以在其中写参数 .flexv (@jc: center, @ai: center) { display: flex; flex-direction: column; justify-content: @jc; align-items: @ai; } #box{ .flexv() !important; // 得到的所有 mixin 属性值都会加上 !important }

3. 使用继承 extend

继承同一个类的,共同继承的部分会被提取出共有样式

.fv { display: flex; flex-direction: column; justify-content: center; align-items: center; p{ color: red; } } // extend(.fv) 只继承 .fv 的样式 .fv p 的样式不被继承 #box { &:extend(.fv); width: 100%; } // extend(.fv all) .fv p 的样式也被继承 #box { &:extend(.fv all); width: 100%; } #box:extend(.fv) { width: 100%; // 与上边结果一致 }; // 输出的共有样式被提取

4. 嵌套规则

#box{ width: 100%; p { width: 50%; &:last-child{ width: 70%; }; } }

5. 可加减乘除运算,包括 数值、颜色、变量

6. Scope 作用域,变量就近获取

@var: red; #box{ color: @var; // white @var: white; }

7. 通过 @import 引用外部样式文件

@import "_common"; // _common.less @import "_common.css"; // CSS 文件 @import (reference) '_common'; // 引入的文件不输出到最终的 css 中 // ...
转载请注明原文地址: https://www.6miu.com/read-3200351.html

最新回复(0)