前端快速熟悉stylus

651 阅读2分钟

文如标题,只是让你快速熟悉stylus的一个样式规范,内容简单基础,并且常用。

样式嵌套

样式遵循嵌套规则,不再需要一长串的选择器

body {
  font: 14px/1.5 Helvetica, arial, sans-serif;
  #logo {
    border-radius: 5px;
  }
}

灵活的语法书写规则

在stylus中,我们可以不再写花括号,分号,冒号,以上述代码为例进化

body 
  font  14px/1.5 Helvetica, arial, sans-serif
  #logo 
    border-radius: 5px

父辈引用

这个用法和Sass的用法基本一致

ul
  li a
    display: block
    color: blue
    padding: 5px
    html.ie &   //这里的&表示的是html.ie ul li a
      padding: 6px
    &:hover     //这里的&表示的是ul li a:hover
      color: red

混入

需要你将要复用的样式定义好,这样可以直接在括号中引用

//定义可复用样式
border-radius(val)
  border-radius: val
//在样式表中引用定义好的样式
button {
  border-radius(5px);
}

透明混入

一种使你方便的完成跨浏览器的样式配置

//下面就是透明混入的书写方式,不需要参数,甚至不需要括号
border-radius()
  -webkit-border-radius: arguments
  -moz-border-radius: arguments
  border-radius: arguments
//可以直接将这些参数传递给以上三个属性
button {
  border-radius: 5px 10px;
}

健壮的混入

我个人认为这不是一个简单方便的样式写法,因为它的写法真真实实的类似写一个函数,用到三元运算等逻辑判断,读者可以自行体会,我能力有限,感受不到它的便捷

-pos(type, args)
  i = 0
  position: unquote(type)
  {args[i]}: args[i + 1] is a 'unit' ? args[i += 1] : 0
  {args[i += 1]}: args[i + 1] is a 'unit' ? args[i += 1] : 0

absolute()
  -pos('absolute', arguments)

fixed()
  -pos('fixed', arguments)

#prompt
  absolute: top 150px left 5px
  width: 200px
  margin-left: -(@width / 2)

#logo
  fixed: top left

基本都是在写逻辑,事实上样式很简单

#prompt {
  position: absolute;
  top: 150px;
  left: 5px;
  width: 200px;
  margin-left: -100px;
}
#logo {
  position: fixed;
  top: 0;
  left: 0;
}

到底哪个更简单呢?

变量

书写方式和你在一些其他语言中的写法一样,可以是“$”变量名,也可以是直接加变量名

#prompt
  position: absolute
  top: 150px
  left: 50%
  width: w = 200px
  margin-left: -(w / 2)

块变量

我们可以直接利用已写样式表块内的属性作为变量,并加以引用

#prompt
  position: absolute
  top: 150px
  left: 50%
  width: 200px
  margin-left: -(@width / 2)

循环样式

函数有循环,我的样式表也得有

table
  for row in 1 2 3 4 5
    tr:nth-child({row})
      height: 10px * row

row是变量,从1-5中依次取数,然后在样式表中以{}的形式导入变量