CSS预处理器Stylus
Stylus 是一款高效的 CSS 预处理器,它提供了简洁灵活的语法来帮助开发者更高效地编写和管理 CSS 代码。下面是一些基础到进阶的 Stylus 代码教程,涵盖变量、嵌套、混合、继承、运算符等核心特性。
1. 安装 Stylus
在项目中使用 Stylus 前,你需要先安装 Stylus 编译器。如果你使用的是 Node.js,可以通过 npm 安装:
npm install -D stylus
2. 基本使用
变量 (Variables) Stylus 允许你定义变量来存储颜色、字体大小等常用值,提高代码的可维护性。
$primary-color = #3498db
body
background $primary-color
嵌套 (Nesting)
Stylus 支持 CSS 规则的嵌套,使得代码结构更加清晰。
body
font-size 14px
color #333
a
color $primary-color
&:hover
text-decoration underline
3. 混合 (Mixins)
混合允许你定义一组属性,然后像函数一样在任何地方重用。
border-radius()
-webkit-border-radius arguments
-moz-border-radius arguments
border-radius arguments
.button
border-radius 5px
4. 继承 (Inheritance)
Stylus 提供了 extends 关键字来实现选择器的继承。
.base
font-family Arial, sans-serif
font-size 14px
.button
extends .base
background-color $primary-color
padding 10px 20px
5. 运算符 (Operators)
Stylus 支持数学运算,可以直接在属性值中进行计算。
width = 100%
padding = 10px
.box
width width - (padding * 2)
6. 函数与逻辑控制
Stylus 支持自定义函数和条件语句,增加代码的灵活性。
is-mobile($width)
if $width < 600px
return true
false
@media (max-width 600px)
body
if is-mobile(480px)
font-size 12px
7. 导入 (Import)
可以导入其他 Stylus 文件,便于组织和复用代码。
@import 'variables'
@import 'mixins'
8. 插值与字符串拼接
Stylus 提供插值功能,用于动态生成 CSS 代码。
device = 'mobile'
@import 'styles.' + device + '.css'
9. 模块化与命名空间
Stylus 支持模块化编程,可以使用 namespace 关键字创建命名空间,避免全局样式冲突。
namespace 'app'
button
display inline-block
padding 10px 20px
header
background-color #333
color #fff
这将生成:
.app-button {
display: inline-block;
padding: 10px 20px;
}
.app-header {
background-color: #333;
color: #fff;
}
10. 引用 (References)
& 符号可以用来引用父选择器,这对于创建复杂的 CSS 选择器很有用。
.list
li
&.active
background-color #f00
&::before
content '•'
这将生成:
.list li.active {
background-color: #f00;
}
.list li::before {
content: '•';
}
11. 属性集 (Property Sets)
属性集允许你定义一组共享属性,然后在多个选择器中使用。
shared-props
font-size 14px
font-weight bold
button primary
shared-props
background-color blue
button secondary
shared-props
background-color gray
这将生成:
button.primary,
button.secondary {
font-size: 14px;
font-weight: bold;
}
button.primary {
background-color: blue;
}
button.secondary {
background-color: gray;
}
12. 选择器组合 (Selector Combinators)
Stylus 支持 CSS 的所有选择器组合,如 +, ~, >, + > 等。
.parent
color red
child
color blue
& + sibling
color green
这将生成:
.parent {
color: red;
}
.parent child {
color: blue;
}
.parent + sibling {
color: green;
}
13. 条件语句 (Conditional Statements)
Stylus 支持 if、unless 和 when 语句,可以根据条件应用样式。
dark-theme
$color = #333
if $color == #333
body
color $color
else
body
color #fff
14. 循环 (Loops)
Stylus 也支持循环,可以用于创建重复的样式。
for i in 1 2 3 4 5
.item:nth-child(i)
margin-right (i * 10px)
这将生成:
.item:nth-child(1) {
margin-right: 10px;
}
.item:nth-child(2) {
margin-right: 20px;
}
.item:nth-child(3) {
margin-right: 30px;
}
.item:nth-child(4) {
margin-right: 40px;
}
.item:nth-child(5) {
margin-right: 50px;
}
15. 块与块扩展 (Blocks & Block Extending)
Stylus 中的块类似于 CSS 的规则集,可以用于创建更复杂的结构。
.card
display flex
&__content
flex 1
&__actions
margin-left auto
这将生成:
.card {
display: flex;
}
.card__content {
flex: 1;
}
.card__actions {
margin-left: auto;
}
16. 注释 (Comments)
在 Stylus 中,单行注释使用 //,多行注释使用 /* */。
// 单行注释
body
// 这里是另一个单行注释
color #333 /* 这是一个多行
注释 */
17. 自动分号 (Automatic Semicolons)
Stylus 默认自动插入分号,但也可以关闭此功能,以保持更简洁的语法。
no-semicolons
body
color #333
font-size 14px
这将生成:
css
body {
color: #333;
font-size: 14px;
}
18. 解析错误处理
Stylus 在遇到语法错误时会给出明确的错误信息,帮助开发者定位并修复问题。
Error: expected "}", got "}"
line 3, column 1:
...
1: body
2: color #333
3: foobar
...
19. 编译与使用
使用 Stylus 编译器将 .styl 文件转换为 .css 文件:
npx stylus input.styl -o output/
或在 Node.js 应用中编译:
const stylus = require('stylus');
stylus('input.styl')
.set('filename', 'input.styl')
.render((err, css) => {
if (err) throw err;
console.log(css);
});
20. 部署与构建工具集成
Stylus 可以轻松集成到各种构建工具中,如 Gulp、Grunt 或 Webpack,实现自动化编译。
在 Gulp 中:
const gulp = require('gulp');
const stylus = require('gulp-stylus');
gulp.task('stylus', () =>
gulp.src('src/stylus/*.styl')
.pipe(stylus())
.pipe(gulp.dest('dist/css'))
);
在 Grunt 中:
npm install grunt --save-dev
npm install grunt-contrib-stylus --save-dev
然后在你的 Gruntfile.js 中配置 stylus 任务:
module.exports = function(grunt) {
grunt.initConfig({
stylus: {
compile: {
options: {
compress: true // 是否开启压缩
},
files: {
'path/to/output.css': 'path/to/input.styl' // 一个简单的输入输出示例
// 或者可以使用数组映射多对文件
// 'path/to/output.css': ['path/to/input1.styl', 'path/to/input2.styl']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-stylus');
grunt.registerTask('default', ['stylus']);
};
在 Webpack 中:
npm install stylus stylus-loader --save-dev
然后在你的 webpack.config.js 中配置加载器:
const path = require('path');
module.exports = {
module: {
rules: [
{
test: /\.styl$/,
use: [
'style-loader',
'css-loader',
{
loader: 'stylus-loader',
options: {
sourceMap: true, // 是否开启 sourcemaps
},
},
],
},
],
},
};
在 Vite 中:
npm install vite-plugin-stylus stylus --save-dev
创建或更新 vite.config.js 文件,并添加插件配置:
import { defineConfig } from 'vite';
import stylus from 'vite-plugin-stylus';
export default defineConfig({
plugins: [stylus()],
});