SCSS語法 - comment、function directives、Nesting、Nested Properties、Parent Selectors

 

以下要點不打算多做說明,只列出scss語法與結果

一、Comments: /* */ and //

scss也支援單行註解,不過並不會主動轉換到css裡

scss輸入

/* This comment is
 * several lines long.
 * since it uses the CSS comment syntax,
 * it will appear in the CSS output. */
body { color: black; }

// These comments are only one line long each.
// They won't appear in the CSS output,
// since they use the single-line comment syntax.
a { color: green; }

 

輸出css

/* This comment is
 * several lines long.
 * since it uses the CSS comment syntax,
 * it will appear in the CSS output. */
body {
    color: black;
}

a {
color: green;
}

 

另外註解也可放變數

scss輸入

$version: "1.2.3";
/* This CSS is generated by My Snazzy Framework version #{$version}. */

輸出css

/* This CSS is generated by My Snazzy Framework version 1.2.3. */

 

二、function directives

scss輸入

@function grid-width($n) {
    @return $n * 10px;
}

#sidebar {
width: grid-width(5);
}

輸出css

#sidebar {
  width: 50px;
}

/*# sourceMappingURL=output.css.map */

說明:

a、function內可以接受function外的全域變數。

b、function名稱的命名建議其前置詞使用連字號,如

@function -grid-width($n)

以便用來跟@mixin的名稱命名有所區別。

 

三、Nesting

scss輸入

div {
    background-color: #333;

<span style="color: #1e90ff; font-weight: bold">p</span> {
    <span style="color: #1e90ff">color</span>: <span style="color: #009999">#fff</span>;
}

}

輸出css

div {
  background-color: #333;
}
div p {
  color: #fff;
}

 

四、Nested Properties

scss輸入

li {
    font: {
        family: serif;
        weight: bold;
        size: 1.3em;
    }
}

輸出css

li {
    font-family: serif;
    font-weight: bold;
    font-size: 1.3em;
}

 

五、Referencing Parent Selectors: &

scss輸入

a {
    font-weight: bold;
    text-decoration: none;
    &:hover {
        text-decoration: underline;
    }
    body.firefox & {
        font-weight: normal;
    }
}

輸出css

a {
  font-weight: bold;
  text-decoration: none;
}
a:hover {
  text-decoration: underline;
}
body.firefox a {
  font-weight: normal;
}

/*# sourceMappingURL=output.css.map */

上例中,「&」符號是指parent selector,也就是元素 a。

 

參考資料:

Sass/SCSS 簡明入門教學

30天掌握Sass語法 系列