Подборка полезных утилит SCSS

от автора

Для успешной реализации проекта разработчикам фронтенда не обойтись без проверенного арсенала расширения SCSS. Ниже представлены утилиты, которые могут пригодиться в работе.

Triangle

Примесь triangle (которую дизайнеры Sagi предпочитают называть «chupchick»), добавляет к всплывающей подсказке треугольник. И tooltips становится похожим на диалоговое окно. Но triangle также может использоваться в качестве автономного элемента.

/*  * @include triangle within a pseudo element and add positioning properties (ie. top, left) * $direction: up, down, left, right */ @mixin triangle($direction, $size: 6px, $color: #222){   content: '';   display: block;   position: absolute;   height: 0; width: 0;   @if ($direction == 'up'){     border-bottom: $size solid $color;     border-left: 1/2*$size solid transparent;     border-right: 1/2*$size solid transparent;   }   @else if ($direction == 'down'){     border-top: $size solid $color;     border-left: 1/2*$size solid transparent;     border-right: 1/2*$size solid transparent;   }   @else if ($direction == 'left'){     border-top: 1/2*$size solid transparent;     border-bottom: 1/2*$size solid transparent;     border-right: $size solid $color;   }   @else if ($direction == 'right'){     border-top: 1/2*$size solid transparent;     border-bottom: 1/2*$size solid transparent;     border-left: $size solid $color;   } } 

Вот еще вариант готового tooltips:

span.tooltip:after {       content: "";       position: absolute;       width: 0;       height: 0;       border-width: 10px;       border-style: solid;       border-color: transparent #FFFFFF transparent transparent;       top: 11px;       left: -24px; } 

Currency

Утилита отображает текущие курсы валют. Используя описанный метод можно задать элементы, показывающие цену или валютные символы, выбрать базовую валюту, добавить несколько дополнительных в избранные. Таким образом на сайте будут динамично переключаться разные валюты в соответствии с местоположением пользователя.

%currency {   position: relative;   &:before {     content: '$';     position: relative;     left: 0;   } } .USD %currency:before { content: '$'; } .EUR %currency:before { content: '\20AC'; } // must escape the html entities for each currency symbol .ILS %currency:before { content: '\20AA'; } .GBP %currency:before { content: '\00A3'; } 

Пример использования:

<body class="USD">         <span class="price">45</span> </body>  .price {     @extend %currency; } 

Clear Fix

Есть много различных способов размещения «плавающих» блоков внутри контейнера без внесения изменений в исходный код разметки страницы. Один из наиболее популярных — micro clearfix nicolasgallagher.com/micro-clearfix-hack Николаса Галлахера (Nicolas Gallagher). Ниже представлен вариант модифицированной версии с использованием псевдоэлемента :after.

%clearfix {   *zoom: 1;   &:after {     content: '';     display: table;     line-height: 0;     clear: both;   } } 

Respond To

Для реализации медиа запросов хорошо подходит примесь Sass content. В результате директива позволяет управлять размерами в соответствии со стилем.

// Breakpoints for each query $smartphone: 480px; $tabletPortrait: 767px; $tabletLandscape: 1024px; $desktop: 1174px; $largeScreen: 1400px; @mixin respondTo($media) {   @if $media == smartphone {     @media (max-width: $smartphone) { @content; }   }   @else if $media == tablet {     @media (min-width: $tabletPortrait) and (max-width: $tabletLandscape) { @content; }   }   @else if $media == smallScreen {     @media (max-width: $desktop) { @content; }   }   @else if $media == desktop {     @media (min-width: $desktop) { @content; }   } } 

Пример использования:

div {     // regular styles here     @include respondTo(desktop) {         &:hover { background: blue; } // only add the hover effect on desktop browsers     } } 

Вертикальное выравнивание

Несколько модифицированная версия метода CSS-Tricks css-tricks.com/centering-in-the-unknown для вертикального центрирования элементов с динамическими размерами. Работает красиво и не требует дополнительных не-семантических элементов HTML.

@mixin ghostVerticalAlign(){   &:before {     content: '';     display: inline-block;     vertical-align: middle;     height: 100%; width: .1px;   } } 

Кроссбраузерный text-overflow

Метод, который поможет предотвратить переполнение у блочных элементов, а также убедиться, что текстовый элемент аккуратно размещается и не вылезает за переделы блока.

@mixin truncateText($overflow: ellipsis){   overflow: hidden;   white-space: nowrap;   text-overflow: $overflow; // values are: clip, ellipsis, or a string } 

Анимация

Вариант примеси для анимации в CSS3 на основе фреймворка Compass.

@mixin animation($name, $duration: 1000ms, $iterations: infinite, $timing-function: ease, $delay: 0ms) {   // There is a FF bug that requires all time values to have units, even 0 !!!!!!   -webkit-animation: $name $duration $iterations $timing-function $delay;   -moz-animation: $name $duration $iterations $timing-function $delay;   -o-animation: $name $duration $iterations $timing-function $delay;   animation: $name $duration $iterations $timing-function $delay; } 

Alerted

Примесь Аlerted — неплохое решение для демонстрации уведомлений, напоминающих пользователю о необходимости принять те или иные меры.

@mixin alerted() {   &:before {     content: '';     position: absolute;     top: 6px; right: 6px;     height: 8px; width: 8px;     @include border-radius(10px);     background-color: gold;   }   &:after {     content: '';     position: absolute;     top: 0; right: 0;     height: 20px; width: 20px;     @include border-radius(20px);     background-color: transparent;     border: solid gold;     border-width: 2px; // animates     @include box-sizing(border-box);     @include animation($name: alertMe);   } }  @keyframes alertMe {   // -vendor prefixes omitted for brevity, but should be used in production   from {     border-width: 3px;     border-color: gold;   }   to {     border-width: 0;     border-color: rgba(gold, .1);   } } 

Изменение размера Спрайтов

Примесь от Даррена Вуда (Darren Wood), которая позволяет создавать и загружать файловые изображения и затем уменьшать их, используя CSS. Замечательно подходит для работы с 2X изображениями.

@mixin resize-sprite($map, $sprite, $percent) {   $spritePath:    sprite-path($map);   $spriteWidth:   image-width($spritePath);   $spriteHeight:  image-height($spritePath);   $width: image-width(sprite-file($map, $sprite));   $height: image-height(sprite-file($map, $sprite));   @include background-size(ceil($spriteWidth * ($percent/100)) ceil($spriteHeight * ($percent/100)));   width: ceil($width*($percent/100));   height: ceil($height*($percent/100));   background-position: 0 floor(nth(sprite-position($map, $sprite), 2)  * ($percent/100) ); } 

Tooltips

Пустые всплывающие подсказки, позволяющие размещать контент в HTML и при этом получать удивительно хорошую поддержку браузера.

@mixin hui_tooltip($content: attr(data-tooltip), $direction: top) {   position: relative;   &:before, &:after {     display: none;     z-index: 98;   }   &:hover {     &:after { // for text bubble       content: $content;       display: block;       position: absolute;       height: 12px; // (makes total height including padding 22px)       padding: 6px;       font-size: 12px;       white-space: nowrap;       color: #fff;       @include text-shadow(1px 1px #000);       background-color: #222;     }     @if ($direction == 'top'){       &:before {         @include triangle(down, 6px, #222);         top: -6px; margin-top: 0;         left: 47%;       }       &:after {         top: -28px;         left: 47%; margin-left: -20px;       }     }     @else if ($direction == 'bottom'){       &:before {         @include triangle(up, 6px, #222);         top: auto; margin-top: 0;         bottom: -6px;         left: 47%;       }       &:after {         bottom: -28px;         left: 47%; margin-left: -20px;       }     }   } } 

Список можно продолжать и продолжать. У каждого разработчика свои любимые методы и наборы инструментов для реализации проектов.

ссылка на оригинал статьи https://habrahabr.ru/post/276509/


Комментарии

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *