CSS preprocessor

Guanhui
Release: 2020-06-15 09:08:07
forward
2775 people have browsed it

CSS preprocessor

What is a CSS preprocessor? Generally speaking, they have extended a set of their own DSL (Domain Specific Language) based on CSS to solve problems that are difficult for us to solve when writing CSS:

  • The syntax is not powerful enough, such as the inability to nest writing This leads to the need to write many repeated selectors in modular development;
  • There is no variable and reasonable style reuse mechanism, so logically related attribute values ​​​​must be repeatedly output in the form of literals, making it difficult to maintain.

It boils down to abstract ability. So this determines the main goal of the CSS preprocessor: to provide the style layer reuse mechanism missing in CSS, reduce redundant code, and improve the maintainability of style code. This is not the icing on the cake, but a timely help.

However, the CSS preprocessor is not a panacea. The advantage of CSS is that it is easy to use and debug anytime and anywhere. The addition of the pre-compiled CSS step adds another link to our development workflow and makes debugging more troublesome. The bigger problem is that precompilation can easily lead to the abuse of descendant selectors. So when using CSS preprocessors, be careful to avoid such problems.

Sass variables beginning with $ are less likely to conflict with CSS standard syntax. Variables in Less start with @. Although it is easy to conflict with the new syntax of subsequent specification updates, in theory, as long as the CSS specification does not introduce rules such as @a: b, the problem is not big. Moreover, many existing implementations will be referred to when formulating the specifications.

The variable mechanisms of Sass and Less are very different. Sass is similar to the block-level scope of JS. Values ​​can be reassigned within the scope without affecting the outside world. Less is based on the last global assignment. . SASS and SCSS are just two syntax styles. SCSS is closer to CSS syntax and is more comfortable to write on the front end. There is no obvious difference between the most commonly used parts of Less and Sass, so don’t worry too much about which one to use, just pick one. As for which one the company uses, just stick with it. If there are no major problems, don’t consider changing.

File splitting

The pages are becoming more and more complex, and the CSS files that need to be loaded are getting larger and larger. It is necessary for us to split the large files. , otherwise it will be difficult to maintain. Traditional CSS file splitting solutions are basically CSS native @import directives, or loading multiple CSS files in HTML. These solutions usually cannot meet performance requirements.

The CSS preprocessor extends the ability of the @import directive to re-merge the split files into one large file through the compilation process. On the one hand, this solves the problem of inconvenient maintenance of large files, and on the other hand, it also solves the performance problem when loading a bunch of small files.

Modularization

Taking the idea of ​​file segmentation one step further is "modularization". After a large CSS file is reasonably split, the relationship between the resulting small files should be a tree structure.

The root node of the tree is generally called the "entry file", and the other nodes of the tree are generally called "module files". Entry files usually depend on multiple module files, and each module file may also depend on other terminal modules, thus forming the entire tree.

The following is a simple example:

entry.less
 ├─ base.less
 │   ├─ normalize.less
 │   └─ reset.less
 ├─ layout.less
 │   ├─ header.less
 │   │   └─ nav.less
 │   └─ footer.less
 ├─ section-foo.less
 ├─ section-bar.less
 └─ ...复制代码
Copy after login

Entry fileentry.less When compiling, the required modules will be introduced, entry.css will be generated, and then referenced by the page .

If you have used other programming languages ​​​​with a module mechanism, you should already have a deep understanding that modularization is a very good way of organizing code and an important means for developers to design code structure. Modules can clearly implement code layering, reuse and dependency management, allowing the CSS development process to enjoy the convenience of modern program development.

Selector nesting

Selector nesting is a code organization method within a file, which allows a series of related rules to present a hierarchical relationship.

Variables

Before the change occurs, all property values ​​in CSS are "magic numbers". You don't know where this value comes from or what its meaning is. After we have variables, we can give these "magic numbers" names to facilitate memory, reading and understanding.

Next we will find that when a specific value is used in multiple places, variables are a simple and effective abstraction method that can eliminate such duplication and make your code more DRY. .

Variables make it easier for developers to unify the visual style of the website, and also make requirements such as "skin change" easier.

Operation

It is not enough to have variables, we also need operations. If variables make values ​​meaningful, operations can associate values ​​with values. The values ​​of some attributes are actually closely related to the values ​​of other attributes. CSS syntax cannot express this relationship; in the preprocessing language, we can use variables and expressions to present this relationship.

For example, we need to make a container display only three lines of text at most. In the past, we usually wrote like this:

.wrapper {	overflow-y: hidden;	line-height: 1.5;	max-height: 4.5em;  /* = 1.5 x 3 */}复制代码
Copy after login

大家可以发现,我们只能用注释来表达 max-height 的值是怎么来的,而且注释中 3 这样的值也是幻数,还需要进一步解释。未来当行高或行数发生变化的时候,max-height 的值和注释中的算式也需要同步更新,维护起来很不方便。

接下来我们用预处理语言来改良一下:

.wrapper
	$max-lines = 3
	$line-height = 1.5

	overflow-y: hidden
	line-height: $line-height
	max-height: unit($line-height * $max-lines, 'em')复制代码
Copy after login

乍一看,代码行数似乎变多了,但代码的意图却更加清楚了——不需要任何注释就把整件事情说清楚了。在后期维护时,只要修改那两个变量就可以了。

值得一提的是,这种写法还带来另一个好处。$line-height 这个变量可以是 .wrapper 自己定义的局部变量(比如上面那段代码),也可以从更上层的作用域获取:

$line-height = 1.5  // 全局统一行高

body
	line-height: $line-height

.wrapper
	$max-lines = 3

	max-height: unit($line-height * $max-lines, 'em')
	overflow-y: hidden复制代码
Copy after login

这意味着 .wrapper 可以向祖先继承行高,而不需要为这个“只显示三行”的需求把自己的行高写死。有了运算,我们就有能力表达属性与属性之间的关联,它令我们的代码更加灵活、更加 DRY。

函数

把常用的运算操作抽象出来,我们就得到了函数。

开发者可以自定义函数,预处理器自己也内置了大量的函数。最常用的内置函数应该就是颜色的运算函数了吧!有了它们,我们甚至都不需要打开 Photoshop 来调色,就可以得到某个颜色的同色系变种了。

举个例子,我们要给一个按钮添加鼠标悬停效果,而最简单的悬停效果就是让按钮的颜色加深一些。我们写出的 CSS 代码可能是这样的:

.button {	background-color: #ff4466;
}.button:hover {	background-color: #f57900;
}复制代码
Copy after login

我相信即使是最资深的视觉设计师,也很难分清 #ff4466#f57900 这两种颜色到底有什么关联。而如果我们的代码是用预处理语言来写的,那事情就直观多了:

.button
	$color = #ff9833

	background-color: $color
	&:hover
		background-color: darken($color, 20%)复制代码
Copy after login

此外,预处理器的函数往往还支持默认参数、具名实参、arguments 对象等高级功能,内部还可以设置条件分支,可以满足复杂的逻辑需求。

Mixin

Mixin 是 CSS 预处理器提供的又一项实用功能。Mixin 的形态和用法跟函数十分类似——先定义,然后在需要的地方调用,在调用时可以接受参数。它与函数的不同之处在于,函数用于产生一个值,而 Mixin 的作用是产生一段 CSS 代码。

Mixin 可以产生多条 CSS 规则,也可以只产生一些 CSS 声明。

一般来说,Mixin 可以把 CSS 文件中类似的代码块抽象出来,并给它一个直观的名字。比如 CSS 框架可以把一些常用的代码片断包装为 mixin 备用,在内部按需调用,或暴露给使用者在业务层调用。

举个例子,我们经常会用到 clearfix 来闭合浮动。在原生 CSS 中,如果要避免 clearfix 代码的重复,往往只能先定义好一个 .clearfix 类,然后在 HTML 中挂载到需要的元素身上:

/* 为 clearfix 定义一个类 */
.clearfix {...}
.clearfix::after {...}复制代码
Copy after login
<!-- 挂载到这两个元素身上 --><p class="info clearfix">...</p>...<footer class="clearfix">...</footer>复制代码
Copy after login

把表现层的实现暴露到了结构层,是不是很不爽?而在预处理器中,我们还可以选择另一种重用方式:

// 为 clearfix 定义一个 mixin
clearfix()
    ...
    &::after
        ...

// 在需要的元素身上调用
.info
    clearfix()

footer
    clearfix()复制代码
Copy after login

工程化

CSS 预处理语言无法直接运行于浏览器环境,这意味着我们编写的源码需要编译为 CSS 代码之后才能用于网页。这似乎是一个门槛,需要我们付出“额外”的成本。

但在目前的大环境下,大多数项目的前端开发流程已经包含了构建环节,比如选择任何一个脚本模块化方案都是需要在部署时走一道打包程序的。所以对大多数团队来说,这个门槛其实已经跨过去一大半了。

而一旦接受了这种设定,我们还可以享受到“额外”的福利。在给 CSS 的开发加入编译环节的同时,还可以顺道加入其它构建环节,比如代码校验、代码压缩、代码后处理等等。

“代码后处理”是指 PostCSS 平台上各类插件所提供的功能,光是 Autoprefixer 这一项就已经值回票价了。我们再也不需要在 CSS 代码中手工添加浏览器前缀了,直接使用标准写法,剩下的事情让工具搞定吧!

推荐教程:《CSS教程

The above is the detailed content of CSS preprocessor. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template