LoginSignup
76
77

More than 3 years have passed since last update.

Stylus入門

Last updated at Posted at 2016-01-04

自分用メモを兼ねてまとめておきます。
もっと流行ってくれることを祈りつつ・・・
(最近公式ページが新しくなりましたね!)

Stylusとは

  • Node.js製のCSSプリプロセッサ。
  • node.jsのexpressやjadeと同じ人が開発してる。
  • コロン, セミコロン, カンマ, 波括弧を省略して記述できる。
  • 拡張子は.styl もしくは .stylus

※似たようなものにLESSやSass(SCSS)などがあります。

導入

何はなくともまずはNode.jsをインストール
コマンドプロンプトもしくはターミナルで
$ npm i -g stylus
以上

コンパイル

コマンドラインからコンパイルします。

// 同じディレクトリに同じファイル名でコンパイル
$ stylus file.styl

// 出力先を指定してコンパイル
$ stylus file.styl --out path/to/directory
$ stylus file.styl -o path/to/directory

// ファイルを監視して変更があればコンパイル
$ stylus -w file.styl
$ stylus --watch file.styl

gulpでコンパイル

毎回コマンドラインに打つのも大変なのでgulpでタスク化します。
こちらを使ってコンパイルします。

$ npm i --save-dev gulp-stylus
gulptask.js
var gulp        = requier('gulp'),
    gulp-stylus = require('gulp-stylus');

var path = {
    'stylusFile': ['path/to/stylus/**/!(_)*.styl']
};

gulp.task('stylus', function() {
    return gulp.src(path.stylusFile)
        .pipe(stylus({
            compress: true,
            use: [
                // 例
                // koutoSwiss(),
            ]
        }))
        .on('error', function (err) {
            console.error('Error', err.message);
        })
        .pipe(gulp.dest("public/css"));
});

gulp.task('watch-stylus', function(){
    gulp.watch(path.stylusFile, ['stylus']);
});

記述の基本

Stylusの良い所はなんといっても書き方に幅があること。
LESSやSCSSのようなCSS風の書き方でも良いし、Sassのような省略形の記述もできる。
初めのうちはCSS風に書いて、慣れてきたら省略して書いていけばよいかと思います。

sample.styl
.test {
    .hoge {
        color: red;
        &:hover {
            color: blue;
        }
    }
}

もしくは

sample.styl
.test
    .hoge
        color red
        &:hover
            color blue

このように書ける。

コメント

コメントは以下のように書くことができる。
基本的にはcompressするとコメントは残らないが/*!を使用するとcompressしてもコメントを残すことができる。

// 一行のコメント

/*
 * 複数行のコメント
 */

/*!
 * compressしても残るコメント
 */

VARIABLES(変数)

SassやLessと同様、変数に値を代入しておくことができます。
=を使うことによって代入できます。

font-size = 14px
font = font-size "Lucida Grande", Arial

body
    font font, sans-serif

もちろんSass式に書いても大丈夫

$font-size = 14px
body {
    font $font-size sans-serif
}

@をつけるとプロパティを変数のように扱うこともできます。

 #logo
    position absolute
    top 50%
    left 50%
    width w = 150px           // 一旦変数に入れる
    height 80px
    margin-left -(w / 2)
    margin-top -(@height / 2) // @heignt = 80px

OPERATOR

演算を行うことができます。

 .
 []
 ! ~ + -
 is defined
 ** * / %
 + -
 ... ..
 <= >= < >
 in
 == is != is not isnt
 is a
 && and || or
 ?:
 = := ?= += -= *= /= %=
 not
 if unless

@IMPORT AND @REQUIRE

ファイルを読み込む際は@importを使用します。
拡張子が.stylの場合は拡張子を省いて記述することが可能です。
また、特定ディレクトリ以下すべてを読み込む場合は*が使用できます。

commmon.styl
@import "normalize.css"
@require "common"
@import "directory/*"

@require を使った場合は一度だけインポートされます

MIXINS

他CSSプリプロセッサでもお馴染みのMixinももちろんStylusで使うことが出来ます。
同じようなスタイルを何度も書かなくても定義しておくことが出来ます。

mixin.styl
border-radius(n)
  -webkit-border-radius n
  -moz-border-radius n
  border-radius n

form input[type=button]
  border-radius(5px)

compile後

mixin_compile.css
form input[type=button] {
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

FUNCTION

Mixinと同じ要領で関数を作ることができます。

function.styl
add(a, b)
  a + b

予め用意された関数もあります

@EXTEND

一度書いたスタイルを再利用することができます。
例えば今まで以下のように書いていたスタイルがあるとして、

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

.warning {
  color: #E2E21E;
}

@extendを使うと以下のようになります。

example.styl
.message {
  padding: 10px;
  border: 1px solid #eee;
}

.warning {
  @extend .message;
  color: #E2E21E;
}

コンパイル後で比較すると素で書いているスタイルの方が文字数は少ないですが、Stylusで書いている方が読みやすいかと思います。

@block

明示的に使わなくても良いのですが、変数に複数のプロパティを格納することができます。

foo =
  width: 20px
  height: 20px

@blockを使う場合は以下

foo = @block {
  width: 20px
  height: 20px
}

定義したfooを使う

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

URL()

まだ使い方がわかっていませんが、画像パスを指定するとバイナリに変換してくれるっぽいです。

  stylus(str)
    .set('filename', __dirname + '/css/test.styl')
    .define('url', stylus.url())
    .render(function(err, css){

    });

デフォルトで30kbまでのリミットがかけられているみたいですがlimitオプションをfalseにすると解除できるみたい

引き続き使いつつ追記していきたいと思いまーす。

76
77
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
76
77