ITコンサルの日常

ITコンサル会社に勤務する普通のITエンジニアの日常です。

Sass Tutorial - 6: Mixins

概要

原文

Mixins are one of the most powerful Sass features. They allow re-use of styles properties or even selectors without having to copy and paste them or move them into a non-semantic class.


Mixins are defined using the “@mixin” directive, which takes a block of styles that can then be included in another selector using the “@include” directive.

超意訳

Mixinsは、Sassの特徴の中でも最も強力なものの一つです。プロパティやセレクタの再利用を、コピー&ペーストしたり、非セマンティッククラスに移動することなしに可能にします。


Mixinsは@mixin命令を用いることで定義され、@include命令を使って他のセレクタを含めることができる、ブロックを伴います。

サンプル

scssファイル
/* style.scss */

@mixin rounded-top {
  $side: top;
  $radius: 10px;

  border-#{$side}-radius: $radius;
  -moz-border-radius-#{$side}: $radius;
  -webkit-border-#{$side}-radius: $radius;
}

#navbar li { @include rounded-top; }
#footer { @include rounded-top; }
cssファイル (sassコマンドにより自動生成)
/* style.scss */
#navbar li {
  border-top-radius: 10px;
  -moz-border-radius-top: 10px;
  -webkit-border-top-radius: 10px; }

#footer {
  border-top-radius: 10px;
  -moz-border-radius-top: 10px;
  -webkit-border-top-radius: 10px; }

イメージとしては、ブロック丸ごと変数みたいな感じ?

非セマンティッククラスってなんぞ?

たぶん、クラス名なしの要素に対するスタイル指定のことだと理解。(いや、違うかも知れないけど)

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
    <title>index</title>
    <style type = "text/css">
        .a {
            font-size: 14pt;
            color: red;
        }
        .b {
            font-size: 14pt;
            color: blue;
        }
    </style>
</head>
<body>
    <div class = "a">Google</div>
    <div class = "b">Yahoo</div>
</body>
</html>
font-sizeを非セマンティッククラスに移すことも出来る
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
    <title>index</title>
    <style type = "text/css">
        div {
            font-size: 14pt;
        }
        .a {
            color: red;
        }
        .b {
            color: blue;
        }
    </style>
</head>
<body>
    <div class = "a">Google</div>
    <div class = "b">Yahoo</div>
</body>
</html>

これだと、他にdiv要素を追加したときに、font-sizeが14ptになってしまう。

mixinsを使ったらこう。
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
    <title>index</title>
    <link rel="stylesheet" href="Mixins2.css" type="text/css"/>
</head>
<body>
    <div class = "a">Google</div>
    <div class = "b">Yahoo</div>
</body>
</html>
scssファイル
/* style.scss */

@mixin elems {
  $fontSize: 14pt;

  font-size: $fontSize;
}

.a {color: red; @include elems;}
.b {color: blue; @include elems;}
cssファイル (sassコマンドにより自動生成)
/* style.scss */
.a {
  color: red;
  font-size: 14pt; }

.b {
  color: blue;
  font-size: 14pt; }

これだと、他にdiv要素を追加しても、font-sizeが14ptになることはない。
まあ、div要素にスタイル指定とか、現実的にはありえなさそうですが。。



< Sass Tutorial - 5: Interpolation | Sassの記事一覧 | Sass Tutorial - 7: Arguments >