Skip to content

Instantly share code, notes, and snippets.

@neretin-trike
Last active March 30, 2024 12:42
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save neretin-trike/214fe69cf632fbd9db04d702b7f303c1 to your computer and use it in GitHub Desktop.
Save neretin-trike/214fe69cf632fbd9db04d702b7f303c1 to your computer and use it in GitHub Desktop.
Туториал по CSS препроцессору Stylus

Препроцессор Stylus

Stylus - это препроцессор CSS, который был написан на JavaScript для Node.js.

Содержание:

  1. Селекторы
  2. Переменные
  3. Интерполяция переменных
  4. Операторы
  5. Миксины
  6. Хэши
  7. Циклы
  8. Импорт и наследование
  9. Медиа-запросы
  10. Блоки

Официальная документация по Stylus

Селекторы

В Stylus не используются скобки и любые символы разделения кроме пробела, вместо этого он использует строгую табуляцию (или отступы) для определения вложености селекторов.

Stylus

white-color = white
body
  color white-color

CSS

body {
  color: #fff;
}

Stylus

textarea
input
  color #A7A7A7
  &:hover
    color #000

CSS

textarea,
input {
  color: #a7a7a7;
}
textarea:hover,
input:hover {
  color: #000;
}

Stylus

textarea
input
  color #A7A7A7
  &:hover,
  /.is-hovered
    color #000

CSS

textarea,
input {
  color: #a7a7a7;
}
textarea:hover,
input:hover,
.is-hovered {
  color: #000;
}

Переменные

Переменные в Stylus обявляются без дополнительных символо перед названием, кроме того можно использовать значение свойства текущего селектора (например @width).

Stylus

 font-size = 14px
 body
   font font-size Arial, sans-serif

CSS

 body {
   font: 14px Arial, sans-serif;
 }

Stylus

position()
  position: arguments
  z-index: 1 unless @z-index

#logo
  z-index: 20
  position: absolute

#logo2
  position: absolute

CSS

#logo {
  z-index: 20;
  position: absolute;
}
#logo2 {
  position: absolute;
  z-index: 1;
}

Интерполяция переменных

Stylus предоставляет различные способы вывода переменных используя символы { и }.

Stylus

mySelectors = '#foo,#bar,.baz'
{mySelectors}
  background: #000

CSS

#foo,
#bar,
.baz {
  background: #000;
}

Операторы

В Stylus присутствуют различные операторы, позволяющие производить вычисления, обращаться к массиву, сравнивать значения и т.д.

Stylus

list = 1 2 3
list[0]
// => 1

list[-1]
// => 3

1..5
// => 1 2 3 4 5

1...5
// => 1 2 3 4

5..1
// => 5 4 3 2 1

nums = 1 2 3
1 in nums
// => true

5 in nums
// => false

color := red
color ?= red
color = color is defined ? color : white   
// => color red

15 is a 'unit'
// => true

#fff is a 'rgba'
// => true

Миксины

Поддержка миксинов позволяет создавать переиспользуемые блоки.

Stylus

stripe(even = #fff, odd = #eee)
 tr
   background-color odd
   &.even
   &:nth-child(even)
     background-color even
body
stripe()

CSS

body tr {
  background-color: #eee;
}
body tr.even,
body tr:nth-child(even) {
  background-color: #456;
}

Stylus

foo()
  .bar
    {block}

+foo()
  width: 10px

CSS

.bar {
   width: 10px;
}

Stylus

sum()
 n = 0
 for num in arguments
   n = n + num

sum(1,2,3,4,5)
// => 15

Stylus

  pad(types = margin padding, n = 5px)
    padding unit(n, px) if padding in types
    margin unit(n, px) if margin in types

  body
    pad()

  body
    pad(margin)

  body
    apply-mixins = true
    pad(padding, 10) if apply-mixins

CSS

  body {
    padding: 5px;
    margin: 5px;
  }
  body {
    margin: 5px;
  }
  body {
    padding: 10px;
  }

Хэши

С помощью Stylus можно создавать ассоциативные массивы, который позволяет хранить пары (ключ, значение) и выполнять три операции: операцию добавления новой пары, операцию поиска и операцию удаления пары по ключу. Вызывать значение хэша нужно в самом конце селектора, иначе возникнет ошибка

Stylus

foo = {
  bar: baz,
  baz: raz
}

foo = {
  bar: baz,
  'baz': raz,
  '0': raz
}

foo[baz]
foo.baz
// => 'raz'

Stylus

foo = {
  width: 10px,
  height: 20px,
  '&:hover': {
    padding: 0

  }
}
.bar
  {foo}

CSS

.bar {
  width: 10px;
  height: 20px;
}
.bar:hover {
  padding: 0;
}

Stylus

foo = { width: 10px, height: 20px }

for key, value in foo
  {key}: value

// => width: 10px;
//    height: 20px;

Stylus

foo = { bar: 'a', baz: 'b' }

keys(foo)
// => 'bar' 'baz'
values(foo)
// => 'a' 'b'

obj = { foo: 1, bar: 2 }
remove(obj, 'foo')
// => {"bar":"(2)"}

obj = {
  foo: 'foo'
  bar: 'bar'
}
obj2 = {
  baz: 'baz'
}

merge(obj, obj2)
// => {"foo":"('foo')","bar":"('bar')","baz":"('baz')"}

Циклы

Stylus

body
  for num in (1..3)
    foo num

CSS

body {
  foo: 1;
  foo: 2;
  foo: 3;
}

Stylus

apply(props)
 props = arguments if length(arguments) > 1
 for prop in props
   {prop[0]} prop[1]
body
 apply(one 1, two 2, three 3)

body
 list = (one 1) (two 2) (three 3)
 apply(list)

CSS

body {
  one: 1;
  two: 2;
  three: 3;
}
body {
  one: 1;
  two: 2;
  three: 3;
}

Импорт и наследование

Stylus позволяет импортировать файлы в свой код с помощью директивы @import, а также наследовать селекторы с помощью @extend.

Stylus

.message
  padding 10px
  border 1px solid #eee

.warning
  @extend .message
  color #E2E21E

CSS

.message,
.warning {
  padding: 10px;
  border: 1px solid #eee;
}
.warning {
  color: #e2e21e;
}

Медиа-запросы

Как и CSS, препроцессор поддерживает медиа-запросы, которые позволяет изменять значения свойств в зависимости от устройства.

Stylus

.widget
  padding 10px
  
  @media screen and (min-width: 600px)
    padding 20px

CSS

.widget {
  padding: 10px;
}

@media screen and (min-width: 600px) {
  .widget {
    padding: 20px;
  }
}

Stylus

@media (max-width: 500px)
  .foo
    color: #000

  @media (min-width: 100px), (min-height: 200px)
    .foo
      color: #100

CSS

@media (max-width: 500px) {
  .foo {
    color: #000;
  }
}
@media (max-width: 500px) and (min-width: 100px), (max-width: 500px) and (min-height: 200px) {
  .foo {
    color: #100;
  }
}

Блоки

Можно назначить любой блок кода в Stylus переменной, а затем вызвать ее, передать в качестве аргумента или повторного использования любым другим способом

Stylus

foo =
  width: 20px
  height: 20px
 
.icon
  {foo}

CSS

.icon {
  width: 20px;
  height: 20px;
}

@ssyrota
Copy link

ssyrota commented Sep 13, 2020

Awesome tutorial!

@duha000750
Copy link

thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment