SASSの使い方【1】
SASS https://www.sassmeister.com/
SASSでの記述
$link-color-active: #da1e32; //変数が使える
$link-color-base: #333;
$link-font-size: 16px;
.button {
color: #333;
font-size: 16px;
display: inline-block;
margin-top: 20px;
padding: 8px 16px;
border: 1px solid #333;
text-decoration: none;
}
.lists {
list-style: none;
padding: 0;
margin: 0;
display: flex;
li {
width: 25%;
text-align: center;
a {
color: $link-color-base;
font-size: $link-font-size; //何階層にも入れ子にできる
@extend .button; //スタイルの使いまわし
&:hover{
font-size: $link-font-size * 3; //四則演算可(ホバー時フォントサイズを3倍に)
color: #da1e32;
}
&:active {
font-size:$link-font-size + 10px; //四則演算可
color: $link-color-active; //変数を代入することで、値を一括変換できる
}
}
}
}
CSSの結果
.button, .lists li a {
color: #333;
font-size: 16px;
display: inline-block;
margin-top: 20px;
padding: 8px 16px;
border: 1px solid #333;
text-decoration: none;
}
.lists {
list-style: none;
padding: 0;
margin: 0;
display: flex;
}
.lists li {
width: 25%;
text-align: center;
}
.lists li a {
color: #333;
font-size: 16px;
}
.lists li a:hover {
font-size: 48px;
color: #da1e32;
}
.lists li a:active {
font-size: 26px;
color: #da1e32;
}
@mixin(引数が使える)
@mixin button( $font-size ) {
color: #333;
font-size: $font-size;
display: inline-block;
margin-top: 20px;
padding: 8px 16px;
border: 1px solid #333;
text-decoration: none;
}
・・・
li {
width: 25%;
text-align: center;
a {
@include button( 14px ) ; 引数を代入
CSSの結果
.lists li a {
color: #333;
font-size: 14px; 代入された値に変更されている
display: inline-block;
margin-top: 20px;
padding: 8px 16px;
border: 1px solid #333;
text-decoration: none;
}
メディアクエリでの利用
//マップ型変数breakpointsを定義
$breakpoints: (
//キー 値
'xs': 'screen and (max-width: 350px)',
'sp': 'screen and (max-width: 767px)', //767px以下(スマホ)用の表示
'pc': 'screen and (min-width: 768px)' //768px以上(タブレット・PC)用の表示
) !default;
//メディアクエリ用のmixinを定義。デフォ値はsp
@mixin mq($breakpoint: sp) {
//map-get(マップ型変数, キー)で値を取得
@media #{map-get($breakpoints, $breakpoint)} {
//この中をカスタムできる
@content;
}
}
//使用例
.header {
height: 100px; //PC用の表示
@include mq { //引数を何も定義していない場合はスマホの値になる
height: 60px;
}
@include mq('xs') {
height: 30px;
}
}
CSSの結果
@charset "UTF-8";
.header {
height: 100px;
}
@media screen and (max-width: 767px) {
.header {
height: 60px;
}
}
@media screen and (max-width: 350px) {
.header {
height: 30px;
}
}
/*このように @media screen and (width: 767px) { } を書かなくても、
PC用のcssを書きながらスマホ用の表示を書き足すことができます! */
@function 関数
SASS
@function activeFontsize($base-size){
@return $base-size + 2px;
}
$link-font-size: 16px;
・・・
&.active{
font-size: activeFontsize($link-font-size) ;
color: #da1e32;
}
CSSの結果
・・・
li a.active {
font-size: 18px; //変数で設定した値16pxに、2px足された値が入る
color: #da1e32;
}

