Still using CSS? Let's try the more beautiful and convenient Less

Less preprocessing language

Lessis aDynamic Style Language; In order to improve the flexibility and efficiency of CSS application, LESS endows CSS with dynamic language features, such as variables, inheritance, operations, and functions. LESS can not only run 客户端 on (support IE 6+, Webkit, Firefox), but also run on the server side with the help of Node.js.

Shortcomings of CSS

We chose Less because it makes up for many of the shortcomings of CSS. As front-end learners, we all need to learn some CSS. As one of the three cornerstones of front-end development, it always leads the development trend of the Web. As a markup language, CSS may give beginners the first impression that it is easy to understand, illogical, and not like programming. When the grammar is updated, whenever a new attribute is proposed, the compatibility of the browser will immediately become a stumbling block. It can be said that the shortcomings of CSS cannot be ignored.

The birth of problems is often accompanied by the rise of technology. In the past few years of Web development, in order to make CSS more logical and less serious, some magical preprocessing languages ​​have emerged. They CSS completely turn into a markup language that can use various features such as 变量, 循环, 继承, 自定义方法and so on, and the logic is greatly enhanced.

The Birth of Preprocessing Languages

Among them, there are three languages ​​commonly used: Sass, Less, Stylus.

  1. Sass was born in 2007, written in Ruby, and its syntax functions are very comprehensive. It can be said that it completely turns CSS into a programming language. In addition, it is very popular at home and abroad, and its project team is very strong, it is a very good preprocessing language.
  2. Stylus was born in 2010, from the Node.js community, and its grammatical function is comparable to that of Sass. It is a very unique and innovative language.
  3. Less was born in 2009, an open source project created under the influence of Sass. It expands the CSS language and adds functions such as variables, mixins, and functions, making CSS easier to maintain, easy to make themes, and expand.

Less installation

Using Less in a Node.js environment:

npm install -g less

Using Less in a browser environment:

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/3.11.1/less.min.js" ></script>

Less Notes

There are two types of annotations for less:

//这种注释,在编译后不会出现在CSS文件上
/*这种注释,编译后会出现在CSS文件上*/

Less variable

We often see the same value repeated many times in CSS, which makes the code difficult to maintain. Ideally, it should look like this:

const bgColor="skyblue";
$(".post-content").css("background-color",bgColor);
$("#wrap").css("background-color",bgColor);
$(".arctive").css("background-color",bgColor);

As long as we modify the variable bgColor, the background color of the entire page will change accordingly. The variables in Less are very powerful and can change everything,It is worth mentioning that its variables are constants, so they can only be defined once and cannot be reused

value variable

/* Less */
@color: #999;
@bgColor: skyblue;//不要添加引号
@width: 50%;
#wrap {
      
      
	color: @color;
	background: @bgColor;
	width: @width;
}
/* 生成后的 CSS */
#wrap {
      
      
	color: #999;
	background: skyblue;
	width: 50%;
}

@Variables are defined starting with , and typed directly when used @名称. In normal work, we can encapsulate commonly used variables into a file, which is conducive to code organization and maintenance.

For example:

@lightPrimaryColor: #c5cae9;
@textPrimaryColor: #fff;
@accentColor: rgb(99, 137, 185);
@primaryTextColor: #646464;
@secondaryTextColor: #000;
@dividerColor: #b6b6b6;
@borderColor: #dadada;

selector variable

Make the selector dynamic:

/* Less */
@mySelector: #wrap;
@Wrap: wrap;
@{
    
    mySelector}{
    
     //变量名 必须使用大括号包裹
	color: #999;
	width: 50%;
}
.@{
    
    Wrap}{
    
    
	color:#ccc;
}
#@{
    
    Wrap}{
    
    
	color:#666;
}
/* 生成的 CSS */
#wrap{
      
      
	color: #999;
	width: 50%;
}
.wrap{
    
    
	color:#ccc;
}
#wrap{
      
      
	color:#666;
}

attribute variable

Can reduce the amount of code writing:

/* Less */
@borderStyle: border-style;
@Soild:solid;
#wrap{
      
      
	@{
    
    borderStyle}: @Soild;//变量名 必须使用大括号包裹
}
/* 生成的 CSS */
#wrap{
      
      
	border-style:solid;
}

url variable

When the project structure changes, just modify its variables:

/* Less */
@images: "../img";//需要加引号
body {
    
    
	background: url("@{images}/dog.png");//变量名 必须使用大括号包裹
}
/* 生成的 CSS */
body {
    
    
	background: url("../img/dog.png");
}

Let's summarize:
Variable Interpolation:
That is, when variables are used in selector names, attribute names, URLs, and @import statements, they must be wrapped in curly braces.

declare variable

A bit like the following hybrid approach:

  • structure:@name: { 属性: 值 ;};
  • use:@name();

For example:

/* Less */
@background: {
    
    background:red;};
#main{
      
      
	@background();
}
@Rules:{
    
    
	width: 200px;
	height: 200px;
	border: solid 1px red;
};
#con{
      
      
	@Rules();
}
/* 生成的 CSS */
#main{
      
      
	background:red;
}
#con{
      
      
	width: 200px;
	height: 200px;
	border: solid 1px red;
}

variable operation

It must be mentioned that Less's variable operations are very powerful.

  • Add and subtract based on the unit of the first data
  • When multiplying and dividing, pay attention to the unit must be unified
  • When connecting operations, pay attention to adding spaces to avoid errors that cannot be found for variables
/* Less */
@width:300px;
@color:#222;
#wrap{
      
      
	width:@width - 20;
	height:@width - 20*5;
	margin:(@width - 20)*5;
	color:@color*2;
	background-color:@color + #111;
}
/* 生成的 CSS */
#wrap{
      
      
	width:280px;
	height:200px;
	margin:1400px;
	color:#444;
	background-color:#333;
}

variable scope

One sentence understanding is: the principle of proximity.

/* Less */
@var: @a;
@a: 100%;
#wrap {
      
      
	width: @var;
	@a: 9%;
}
/* 生成的 CSS */
#wrap {
      
      
	width: 9%;
}

use variables to define variables

/* Less */
@fnord: "I am fnord.";
@var: "fnord";
#wrap::after{
      
      
	content: @@var; //将@var替换为其值 content:@fnord;
}
/* 生成的 CSS */
#wrap::after{
      
      
	content: "I am fnord.";
}

Less nesting

The magic of &

& : The name of the upper-level selector represented

This example is the header:

/* Less */
#header{
      
      
	&::after{
    
    
		content:"Less is more!";
	}
	.title{
    
    
		font-weight:bold;
	}
	&_content{
    
    //理解方式:直接把 & 替换成 #header
		margin:20px;
	}
}
/* 生成的 CSS */
#header::after{
      
      
	content:"Less is more!";
}
#header .title{
      
       //嵌套了
	font-weight:bold;
}
#header_content{
      
      //没有嵌套!
	margin:20px;
}

media query

In previous work, we used media queries to write an element separately:

#wrap{
      
      
	width:500px;
}
@media screen and (max-width:768px){
    
    
	#wrap{
      
      
		width:100px;
	}
}

Less provides a very convenient way:

/* Less */
#main{
      
      
	//something...
	@media screen{
    
    
		@media (max-width:768px){
    
    
			width:100px;
		}
	}
	@media tv {
    
    
		width:2000px;
	}
}

/* 生成的 CSS */
@media screen and (maxwidth:768px){
    
    
	#main{
      
      
		width:100px;
	}
}
@media tv{
    
    
	#main{
      
      
		width:2000px;
	}
}

The only downside is that each element will compile its own @media declaration and not be merged.

Practical skills

You can use Less to define your own private styles in elements.

/* Less */
#main{
      
      
	// something..
	&.show{
    
    
		display:block;
	}
}
.show{
    
    
	display:none;
}
const main = document.getElementById("main");
main.classList.add("show");

result:

#main.show{
      
      
	display:block;
}
.show{
    
    
	display:none; //会被覆盖。
}

mixed approach

Mixin (Mixin) is a way to include (or mix in) a set of attributes from one rule set to another, which can be understood as copy and paste.

No parameter method

A method is like a collection of declarations, just type in the name when using it:

/* Less */
.card {
    
     // 等价于 .card()
	background: #f6f6f6;
	-webkit-box-shadow: 0 1px 2px rgba(151, 151, 151, .58);
	box-shadow: 0 1px 2px rgba(151, 151, 151, .58);
}
#wrap{
      
      
	.card;//等价于.card();
}
/* 生成的 CSS */
#wrap{
      
      
	background: #f6f6f6;
	-webkit-box-shadow: 0 1px 2px rgba(151, 151, 151, .58);
	box-shadow: 0 1px 2px rgba(151, 151, 151, .58);
}

where .cardand .card()are equivalent. It is suggested that, in order to avoid code confusion, it should be written as:

.card(){
    
    
	//something...
}
#wrap{
      
      
	.card();
}

Main points:

  • . Both and #can be used as method prefixes.
  • Whether to write after the method depends on ()personal habits.

default parameter method

  • Less can use default parameters, if no parameters are passed, then default parameters will be used.
  • @argumentsJust like in JS argumentsrefers to all parameters.
  • The passed parameter must have a unit.
/* Less */
.border(@a:10px,@b:50px,@c:30px,@color:#000){
    
    
	border:solid 1px @color;
	box-shadow: @arguments;//指代的是 全部参数
}
#main{
      
      
	.border(0px,5px,30px,red);//必须带着单位
}
#wrap{
      
      
	.border(0px);
}
#content{
      
      
	.border;//等价于 .border()
}
/* 生成的 CSS */
#main{
      
      
	border:solid 1px red;
	box-shadow:0px,5px,30px,red;
}
#wrap{
      
      
	border:solid 1px #000;
	box-shadow: 0px 50px 30px #000;
}
#content{
      
      
	border:solid 1px #000;
	box-shadow: 10px 50px 30px #000;
}

method matching pattern

Very similar to polymorphism in object-oriented:

/* Less */
.triangle(top,@width:20px,@color:#000){
    
    
	border-color:transparent transparent @color transparent ;
}
.triangle(right,@width:20px,@color:#000){
    
    
	border-color:transparent @color transparent transparent ;
}
.triangle(bottom,@width:20px,@color:#000){
    
    
	border-color:@color transparent transparent transparent ;
}
.triangle(left,@width:20px,@color:#000){
    
    
	border-color:transparent transparent transparent @color;
}
.triangle(@_,@width:20px,@color:#000){
    
    
	border-style: solid;
	border-width: @width;
}
#main{
      
      
	.triangle(left, 50px, #999)
}
/* 生成的 CSS */
#main{
      
      
	border-color:transparent transparent transparent #999;
	border-style: solid;
	border-width: 50px;
}

main points:

  • The first leftparameter will find the method with the highest matching degree. If the matching degree is the same, all will be selected, and there will be a style override replacement.
  • Will match if the matched argument is a variable, eg @_.

method namespace

Make the method more standardized

/* Less */
#card(){
      
      
	background: #723232;
	.d(@w:300px){
    
    
		width: @w;
		#a(@h:300px){
      
      
			height: @h;//可以使用上一层传进来的方法
		}
	}
}

#wrap{
      
      
	#card > .d > #a(100px); // 父元素不能加 括号
}

#main{
      
      
	#card .d();
}

#con{
      
      
	//不得单独使用命名空间的方法
	//.d() 如果前面没有引入命名空间 #card ,将会报错
	
	#card; // 等价于 #card();
	.d(20px); //必须先引入 #card
}
/* 生成的 CSS */
#wrap{
      
      
	height:100px;
}
#main{
      
      
	width:300px;
}
#con{
      
      
	width:20px;
}

main points:

  • In CSS, the >selector selects the child element, that is, the element that must have a direct blood source with the parent element.
  • When introducing a command space, such as using a >selector , the parent element cannot be parenthesized.
  • A method that cannot use a namespace alone must first introduce a namespace before using its methods.
  • The sub-method can use the method passed in from the previous layer

Conditional filter of the method

Less doesn't have if else, but it has when:

/* Less */
#card{
      
      
// and 运算符 ,相当于 与运算 &&,必须条件全部符合才会执行
	.border(@width,@color,@style) when (@width>100px) and(@color=#999){
    
    
	border:@style @color @width;
	}
// not 运算符,相当于 非运算 !,条件为 不符合才会执行
	.background(@color) when not (@color>=#222){
    
    
		background:@color;
	}
// , 逗号分隔符:相当于 或运算 ||,只要有一个符合条件就会执行
	.font(@size:20px) when (@size>50px) , (@size<100px){
    
    
		font-size: @size;
	}
}

#main{
      
      
	#card>.border(200px,#999,solid);
	#card .background(#111);
	#card > .font(40px);
}

/* 生成后的 CSS */
#main{
      
      
	border:solid #999 200px;
	background:#111;
	font-size:40px;
}

main points

  • Comparison operations are: > >= = =< <.
  • = stands for equal to
  • Values ​​other than the keyword true are considered false:

variable number of parameters

If you want your method to accept a variable number of arguments, you can use ..., like ES6, the spread operator.

/* Less */
.boxShadow(...){
    
    
	box-shadow: @arguments;
}
.textShadow(@a,...){
    
    
	text-shadow: @arguments;
}

#main{
      
      
	.boxShadow(1px,4px,30px,red);
	.textShadow(1px,4px,30px,red);
}
/* 生成后的 CSS */
#main{
      
      
	box-shadow: 1px 4px 30px red;
	text-shadow: 1px 4px 30px red;
}

The method uses the important!

The method of use is very simple, just add keywords after the method name.

/* Less */
.border{
    
    
	border: solid 1px red;
	margin: 50px;
}
#main{
      
      
	.border() !important;
}
/* 生成后的 CSS */
#main {
      
      
	border: solid 1px red !important;
	margin: 50px !important;
}

loop method

Less does not provide a for loop function, but it is not difficult for smart programmers to use recursion to achieve it. The following is a demo on the official website, which simulates the generated grid system.

/* Less */
.generate-columns(4);
.generate-columns(@n, @i: 1) when (@i =< @n) {
    
    
	.column-@{
    
    i} {
    
    
		width: (@i * 100% / @n);
	}
	.generate-columns(@n, (@i + 1));
}
/* 生成后的 CSS */
.column-1 {
    
    
	width: 25%;
}
.column-2 {
    
    
	width: 50%;
}
.column-3 {
    
    
	width: 75%;
}
.column-4 {
    
    
	width: 100%;
}

Attribute splicing method

  • +_ represents a space;
  • +Represents a comma.

comma:

/* Less */
.boxShadow() {
    
    
	box-shadow+: inset 0 0 10px #555;
}
.main {
    
    
	.boxShadow();
	box-shadow+: 0 0 20px black;
}
	
/* 生成后的 CSS */
.main {
    
    
	box-shadow: inset 0 0 10px #555, 0 0 20px black;
}

space:

/* Less */
.Animation() {
    
    
	transform+_: scale(2);
}
.main {
    
    
	.Animation();
	transform+_: rotate(15deg);
}
/* 生成的 CSS */
.main {
    
    
	transform: scale(2) rotate(15deg);
}

Practical skills

/* Less */
.average(@x, @y) {
    
    
	@average: ((@x + @y) / 2);
}
div {
    
    
	.average(16px, 50px); // 调用 方法
	padding: @average; // 使用返回值
}

/* 生成的 CSS */
div {
    
    
	padding: 33px;
}

It can be said that Less is an elegant programming language.

Guess you like

Origin blog.csdn.net/zyb18507175502/article/details/127394312