stylus是css的预处理框架,是以.styl为后缀的文件,能够建立健壮的,动态的富有表现的css。它用来为css增长一些编程的特性,好比在css中可使用变量,函数等编程语言的特性,从而是css更加的简洁,适应性更强,代码也更加的直观易懂。
在写代码的时候发现stylus有个特色,代码风格有点像python,特别简洁不须要大括号,分号什么的而且也是用空格来规范格式。
安装css
使用stylus首先须要安装,固然这也是一个比较简单的事情,安装stylus只须要一个简单的命令nmp install -g stylus(这是在你安装好了nodejs而且配置好了环境变量状况下,安装和配置nodejs能够去网上查找一下,很简单这里就很少讲)。安装好了后使用stylus --version查看是否安装成功。
首先建立style.styl文件编写一段简单的stylus的代码node
bgc = red $border-radius(arg) -webkit-border-radius: arg -moz-border-radius: arg border-radius: arg * margin 0 padding 0 .box height 100 width 100 background-color bgc border-radius(2px) .content background-color bgc h1 color white &:hover color green
使用命令stylus -w style.styl -o style.css将文件style.styl文件编译成并输出成css文件,编译后生成的css代码以下python
* { margin: 0; padding: 0; } .box { height: 100; width: 100; background-color: #f00; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; } .box .content { background-color: #f00; } .box .content h1 { color: #fff; } .box .content h1:hover { color: #008000; }
是否是感受写css简单了许多,写一个styl文件再编译生成的css文件效率高多了。
下面咱们在来分析一下这段代码web
bgc = red background-color bgc
这段代码声明了变量bgc,而且为变量赋值为red。在须要用到相同颜色的地方能够 直接使用这个变量. 前面有两处背景颜色为red,直接使用变量,当须要改变颜色时不须要一个个的改, 只须要改变变量的值就能够了。
$border-radius(arg) -webkit-border-radius: arg -moz-border-radius: arg border-radius: arg $border-radiius(2px)
这段代码声明了函数,而且接收了参数arg.在使用时只须要像上面的代码那样输入函数名称 和参数就能够设置css属性。参数不必定要传入的,根据代码的状况跟其余语言都差很少。
.box height 100 width 100 background-color bgc border-radius(2px) .content background-color bgc h1 color white &:hover color green
这段代码被编译成
.box { height: 100; width: 100; background-color: #f00; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; } .box .content { background-color: #f00; } .box .content h1 { color: #fff; } .box .content h1:hover { color: #008000; }
在元素里面写样式的时候是使用一个tab键缩进来体现是属于该元素的样式。写.box 的子元素.content的样式不须要在像写css那样从新去写,只须要在.box下使用缩进来体现元素.content是.box的子元素而后在写.content的样式就能够。是否是感受喜欢上了stylus了。编程
在上面的这段stylus的代码使用了一个&符号,这个&符号根据编译出来的代码能够很容易理解,它会指向最近的父级元素而且与他链接。框架
@import导入文件.styl,任何.css扩展文件将做为字面量,stylus样式做为动态导入的。编程语言
@import "reset.css"
@css{} {}里面的不会被编译
@block{} 做为一个块赋值给一个变量
@media 和在css使用的方法相同
@keyframe 编译的时候转换成@-webkit-keyframes,能够通变量来添加前缀函数