ITコンサルの日常

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

Sass Tutorial - 4: Operations and Functions

概要

原文

In addition to just using variable values as they're defined, you can also modify and combine them using math and useful predefined functions. This allows you to compute element sizing and even coloration dynamically.


The standard math operations (+, -, *, /, and %) are supported for numbers, even those with units. For colors, there are all sorts of useful functions for changing the lightness, hue, saturation, and more.

超意訳

変数の値を定義されたまま使うのに加え、数学関数や、事前定義された有用な関数を使うことで、変数の値を変更したり結合したりできます。これは、動的に要素のサイズや色づけを計算することが可能にします。


標準の算術演算子(+, -, *, /, and %)が数値、および、単位付きの数値に対してサポートされています。色については、明度、色相、彩度、その他の変更のために、あらゆる種類の有用な関数が用意されています。

サンプル

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

#navbar {
  $navbar-width: 800px;
  $items: 5;
  $navbar-color: #ce4dd6;

  width: $navbar-width;
  border-bottom: 2px solid $navbar-color;

  li {
    float: left;
    width: $navbar-width/$items - 10px;

    background-color:
      lighten($navbar-color, 20%);
    &:hover {
      background-color:
        lighten($navbar-color, 10%);
    }
  }
}
cssファイル (sassコマンドにより自動生成)
/* style.scss */
#navbar {
  width: 800px;
  border-bottom: 2px solid #ce4dd6; }
  #navbar li {
    float: left;
    width: 150px;
    background-color: #e5a0e9; }
    #navbar li:hover {
      background-color: #d976e0; }
試しにhtmlファイルから生成されたcssファイルを読んでみる
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
    <title>index</title>
    <link rel="stylesheet" href="style.css" type="text/css"/>
</head>
<body>
    <div id = "navbar">
        <ul>
            <li><a href = "http://www.google.co.jp/">Google</a></li>
            <li><a href = "http://www.yahoo.co.jp/">Yahoo</a></li>
        </ul>
    </div>
</body>
</html>
html表示結果

hoverする(リンクの上にマウスを乗せる)と、色が変わります。

試しに$itemsを5→3に変更してみる

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

#navbar {
  $navbar-width: 800px;
  $items: 3;
  $navbar-color: #ce4dd6;

  width: $navbar-width;
  border-bottom: 2px solid $navbar-color;

  li {
    float: left;
    width: $navbar-width/$items - 10px;

    background-color:
      lighten($navbar-color, 20%);
    &:hover {
      background-color:
        lighten($navbar-color, 10%);
    }
  }
}
cssファイル (sassコマンドにより自動生成)
/* style.scss */
#navbar {
  width: 800px;
  border-bottom: 2px solid #ce4dd6; }
  #navbar li {
    float: left;
    width: 256.667px;
    background-color: #e5a0e9; }
    #navbar li:hover {
      background-color: #d976e0; }

#navbar liのwidthが256.667pxになってますね。

html表示結果

ちゃんと幅が広がってますね!



< Sass Tutorial - 3: Variables | Sassの記事一覧 | Sass Tutorial - 5: Interpolation >