CSS-ПРЕПРОЦЕССОРЫ

КАК УСКОРИТЬ ВРЕМЯ РАЗРАБОТКИ

ЧТО ТАКОЕ CSS ПРЕПРОЦЕССОР?

CSS препроцессор - язык, это расширяющий CSS поддержкой переменных, примешиваний (миксинов; mixins), функций и многих других вещей, что позволяет сделать CSS более поддерживаемым, тематизируемым и расширяемым.

ПОЧЕМУ МЫ ДОЛЖНЫ ИСПОЛЬЗОВАТЬ CSS ПРЕПРОЦЕССОРЫ?

  1. Экономят наше время, верстаем со скоростью света +10 Coding Speed
  2. Делают наш CSS более чистым и логичным
  3. Делают наш код более модульным и масштабируемым
  4. Писать CSS код становится более весело =)

CSS ПРЕПРОЦЕССОРЫ

Как выглядит код препроцессора

$link-color: #0982C1;
section {
  margin: 10px;
  nav {
    height: 25px;
    a {
      color: $link-color;
      &:hover {
        text-decoration: underline;
      }
    }
  }
}

SCSS

Отличия синтаксиса Less и SASS/SCSS 

@mixin box{
    display: block;
}
$link-color: #0982C1;
section {
  margin: 10px;
  nav {
    height: 25px;
    a {
      color: $link-color;
      @include box();
      &:hover {
        text-decoration: underline;
      }
    }
  }
}

SCSS

=box()
    display: block

$link-color: #0982C1
section 
  margin: 10px
  nav 
    height: 25px
    a 
      color: $link-color
      +box()
      &:hover 
        text-decoration: underline

SASS

.box(){
    display: block;
}
@link-color: #0982C1;
section {
  margin: 10px;
  nav {
    height: 25px;
    a {
      color: @link-color;
      .box;
      &:hover {
        text-decoration: underline;
      }
    }
  }
}

Less

Как это работает

style.scss > компилятор > style.css

$link-color: #0982C1;
section {
  margin: 10px;
  nav {
    height: 25px;
    a {
      color: $link-color;
      &:hover {
        text-decoration: underline;
      }
    }
  }
}
section {
    margin: 10px;
}
section nav {
    height: 25px;
}
section nav a {
    color: #0982C1;
}
section nav a:hover {
    text-decoration: underline;
}

SCSS

CSS

ЧТОБЫ НАЧАТЬ

style.css > style.scss | style.less

просто поменяй расширение файла

Основные возможности

  • Наследование

  • Переменные

  • Расширение классов

  • Миксины

  • Импорты

  • Операторы

Наследование
(Вложенные структуры)

section {
  margin: 10px;
  nav {
    height: 25px;
    a {
      color: #fff;
      &:hover {
        text-decoration: underline;
      }
    }
  }
}
section {
    margin: 10px;
}
section nav {
    height: 25px;
}
section nav a {
    color: #fff;
}
section nav a:hover {
    text-decoration: underline;
}

Less/SCSS

CSS

Избавляемся от повторений
ПОВТОРЕНИЕ МАТЬ УЧЕНИЯ ЗАИКАНИЯ

Селектор &

a {
  color: #fff;
  &:hover {
    text-decoration: underline;
  }
}
.box {
  width:100px;
  height:100px;
  color:blue;
  &.myBox {  
    color: red;
  }
}
a {
  color: #fff;
}
a:hover {
  text-decoration: underline;
}
.box {
  width: 100px;
  height: 100px;
  color: blue;
}
.box.myBox {
  color: red;
}

Less/SCSS

CSS

.box {
  width:100px;
  height:100px;
  color:blue;
  .firefox & {  
    color: red;
  }
}
.box {
  width: 100px;
  height: 100px;
  color: blue;
}
.firefox .box {
  color: red;
}

Parent selector

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

.container {
 width: 960px;

@media screen and (max-width: 960px) {
   width: 100%
 }
}
.container {
  width: 960px;
}
@media screen and (max-width: 960px) {
  .container {
    width: 100%;
  }
}

Less/SCSS

CSS

& и БЭМ

.menu{
    margin: 0 10px;
    padding:0;
    &__link{
        color: #000;

        &:hover{
           color: #222; 
        }
        &--active{
            color:#333;
        }
    }
}
.menu{
    margin: 0 10px;
    padding: 0;
}
.menu__link{
    color: #000;
}
.menu__link:hover{
    color: #222;
}
.menu__link--active{
    color:#333;
}

Less/SCSS

CSS

Переменные

$font-family: 'Open Sans', sans-serif;
$text-color: #222222;
body {
  font-family: $font-family;
  color: $text-color;
}
.menu{
  a{
    color:$text-color;
  }
}
body {
  font-family: 'Open Sans', sans-serif;
  color: #222222;
}
.menu a {
  color: #222222;
}

SCSS

CSS

@font-family: 'Open Sans', sans-serif;
@text-color: #222222;
body {
  font-family: @font-family;
  color: @text-color;
}
.menu{
  a{
    color:@text-color;
  }
}
body {
  font-family: 'Open Sans', sans-serif;
  color: #222222;
}
.menu a {
  color: #222222;
}

Less

CSS

Комментарии  

// Silent comment

/* CSS-style comment */

/*!
 Theme Name: Twenty Fourteen Child
 Template: twentyfourteen
*/
/* CSS-style comment */

/*!
 Theme Name: Twenty Fourteen Child
 Template: twentyfourteen
*/

Less/SCSS

CSS

Расширение классов (Extending)

//Base Class
.box {
  width:100px;
  height:100px;
  color:blue;
}

//Sub Class
.myBox {
  &:extend(.box);
  color: red;
}
.box, .myBox {
  width: 100px;
  height: 100px;
  color: blue;
}
.myBox {
  color: red;
}

Less

CSS

//Base Class
.box {
  width:100px;
  height:100px;
  color:blue;
}

//Sub Class
.myBox {
  @extend .box;
  color: red;
}

SCSS

.box, .myBox {
  width: 100px;
  height: 100px;
  color: blue;
}
.myBox {
  color: red;
}

Миксины (Mixins)

//Mixin
.rounded7px {
  -webkit-border-radius: 7px;
  border-radius: 7px;
} 

article.post {
  background:#ccc;
  display:block;
  
  .rounded7px; //using the mixin
}
.rounded7px {
  -webkit-border-radius: 7px;
  border-radius: 7px;
}
article.post {
  background: #ccc;
  display: block;
  -webkit-border-radius: 7px;
  border-radius: 7px;
}

Less

CSS

//Mixin
@mixin rounded7px {
  -webkit-border-radius: 7px;
  border-radius: 7px;
} 

article.post {
  background:#ccc;
  display:block;
  
  @include rounded7px; //using the mixin
}

SCSS

article.post {
  background: #ccc;
  display: block;
  -webkit-border-radius: 7px;
  border-radius: 7px;
}

CSS

Не выводить Миксины

(только для Less)

//Mixin
.rounded7px() {
  -webkit-border-radius: 7px;
  border-radius: 7px;
} 

article.post {
  background:#ccc;
  display:block;
  
  .rounded7px; //using the mixin
}
.btn{
  .rounded7px; //using the mixin
}
article.post {
  background: #ccc;
  display: block;
  -webkit-border-radius: 7px;
  border-radius: 7px;
}
.btn{
  -webkit-border-radius: 7px;
  border-radius: 7px;
}

Less

CSS

Миксины: еще пример

@mixin btn() {
  background: #6ee16c:
  color: #ffffff;
  &:hover {
    background: #83e581;
  }
}
input[type="submit"] {
  @include btn();
}
input[type="submit"] {
 background: #6ee16c;
 color: white; }
input[type="submit"]:hover {
 background: #83e581; }

SCSS

CSS

Миксины с параметрами

@mixin btn( $bg-color ) {
  background: $bg-color;
  color: white;
  &:hover {
    background: lighten( $bg-color, 5% );
  }
}
input[type="submit"] {
  @include btn( #6ee16c );
}
input[type="submit"] {
 background: #6ee16c;
 color: white; }
input[type="submit"]:hover {
 background: #83e581; }

SCSS

CSS

Миксины с параметрами

@mixin btn( $bg-color ) {
  background: $bg-color;
  color: white;
  &:hover {
    background: lighten( $bg-color, 5% );
  }
}
.btn-blue {
 @include btn( #6cb1e1 );
}
.btn-green {
 @include btn( #6ee16c );
}
.btn-gray {
 @include btn( #ccc );
}
.btn-blue {
 background: #6cb1e1;
 color: white; 
}
.btn-blue:hover {
 background: #81bce5; 
}
.btn-green {
 background: #6ee16c;
 color: white; 
}
.btn-green:hover {
 background: #83e581; 
}
.btn-gray {
 background: #cccccc;
 color: black; 
}
.btn-gray:hover {
 background: #d9d9d9; 
}

SCSS

CSS

Импорты @import

.sidebar {
 margin: 0;
 padding: 0;
}
@import "normalize.css";
.sidebar {
 margin: 0;
 padding: 0;
}
body {
 background: #fff;
}

SCSS

CSS

@import "normalize.css";
@import "_sidebar";

body {
 background: #fff;
}

style.scss

_sidebar.scss

Импорты @import c ключами

(только для Less)

.sidebar {
  margin: 0;
  padding: 0;
}
.main{
  max-width: 960px;
  margin: 0 auto;
}
.sidebar {
 margin: 0;
 padding: 0;
}
body {
 background: #fff;
}

CSS

@import (less) "main.css";
@import "_sidebar";

body {
  background: #fff;
}

style.less

_sidebar.less

.main{
  max-width: 960px;
  margin: 0 auto;
}

main.css

Импорты @import c ключами

(только для Less)

.sidebar {
  margin: 0;
  padding: 0;
}
@import "main.css";
.sidebar {
 margin: 0;
 padding: 0;
}
body {
 background: #fff;
}

CSS

@import "main.css";
@import "_sidebar";

body {
  background: #fff;
}

style.less

_sidebar.less

.main{
  max-width: 960px;
  margin: 0 auto;
}

main.css

Импорты @import c ключами

(только для Less)

@import (keyword) "filename";

style.less

  • reference: Позволяет использовать .less файлы, но не выводить их содержимого без явного вызова.
  • inline: Задача этой опции сказать компилятору, что разработчик ожидает на выходе подключённый файл, но без обработки компилятором.
  • less: Использование этого параметра даёт возможность подключать файлы не .less расширения. 
  • css: любой файл подключаем стандартным для CSS способом.
  • optional: Эта опция позволяет продолжать компиляцию, если подключаемый файл не найден.

Операторы

@base: 10;
@filler: @base * 2;
@other: @base + @filler;

.container{
  color: #888 / 4;
  background-color: @base + #111;
  height: 100% / 2 + @filler;
}
.container {
  color: #222222;
  background-color: #1b1b1b;
  height: 70%;
}

Less

CSS

$base: 10;
$filler: $base * 2;
$other: $base + $filler;

.container{
  color: #888 / 4;
  background-color: $base + #111;
  height: 100% / 2 + $filler;
}

SCSS

.container {
  color: #222222;
  background-color: #1b1b1b;
  height: 70%;
}

CSS

Работа с цветом

color: lighten(#dd4141, 50%);
color: darken(#dd4141, 30%);
color: saturate(#dd4141, 75%);
color: desaturate(#dd4141, 25%);

SCSS

color: white;
color: #711414;
color: #ff1f1f;
color: #c15d5d;

CSS

@mixin btn( $bg-color ) {
  background: $bg-color;
  color: white;
  &:hover {
    background: lighten( $bg-color, 5% );
  }
}
input[type="submit"] {
  @include btn( #6ee16c );
}
input[type="submit"] {
 background: #6ee16c;
 color: white; }
input[type="submit"]:hover {
 background: #83e581; }

SCSS

CSS

Условные операторы

@if {...} @else {...}

$type: monster;
p {
  @if $type == ocean {
    color: blue;
  } @else if $type == matador {
    color: red;
  } @else if $type == monster {
    color: green;
  } @else {
    color: black;
  }
}

SCSS

p {
  color: green; 
}

CSS

LESS, в отличии от SASS/SCSS не имеет логики. В LESS нет if/then, for и т.п.

Autoprefixer

.example {
    display: flex;
    transition: all .5s;
    user-select: none;
    background: linear-gradient(to bottom, white, black);
}

Less/SCSS

.example {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-transition: all .5s;
    transition: all .5s;
    -webkit-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;
    background: -webkit-linear-gradient(top, white, black);
    background: linear-gradient(to bottom, white, black);
}

CSS

Компиляторы

$link-color: #0982C1;
section {
  margin: 10px;
  nav {
    height: 25px;
    a {
      color: $link-color;
      &:hover {
        text-decoration: underline;
      }
    }
  }
}
section {
    margin: 10px;
}
section nav {
    height: 25px;
}
section nav a {
    color: #0982C1;
}
section nav a:hover {
    text-decoration: underline;
}

style.scss > компилятор > style.css

SCSS

CSS

Компиляторы

  1. Установить на свой ПК и работать через командную строку
    1. для SASS/SCSS - Ruby
    2. для Less - Node.js
  1. Устанавливаем Ruby ( http://rubyinstaller.org/ )
  2. Открываем Command Prompt
  3. Запускаем команду:
gem install sass

На примере SASS

1. Идем в директорию где лежит нужный файл

cd /Users/Username/Desktop/

2. Запускаем команду:

sass --watch style.scss:style.css

Компиляторы

Использовать сборщики проектов с нужными плагинами:
gulp, grunt

Компиляторы

Использовать программы-компиляторы:

1. SCOUT http://mhs.github.io/scout-app

2. Koala http://koala-app.com

3. Prepross App https://prepros.io/

CSS препроцессоры

By Alexey Kalyuzhnyi

CSS препроцессоры

  • 3,197