Sassを書き始めるときにいつも引っ張り出してくるmixinをメモ。 よく使うものなので、再利用できるようmixinにしておくとすごく便利です。
要素内のテキストを非表示にする
タイトル要素を画像に置き換えてテキストは表示したくないなど、用意しておくと便利。
@mixin clearText { text-indent: 100%; white-space: nowrap; overflow: hidden; }
メディアクエリをmixinでまとめる
メディアクエリーが必要な部分で$breakpoint(641pxなど)を渡してプロパティーと値を書いてあげると、@contentにロパティーと値を代入して、mixin返してくれます。
@mixin mediaquery($breakpoint){ @media screen and (min-width: $breakpoint) { @content; } }
モバイルデバイス向けに縦横比を維持する画像を配置する
パソコンとモバイルで画像を出し分けはCSSのメディアクエリに頼ることもしばしば。
モバイルの画面幅が可変の場合に対象要素の高さを自動計算。
対称の要素に@include ratio("img-path.png", 680, 2400)
のように、画像のパスとその幅・高さを渡して使用します。
- $im = 画像のパス
- $w = 上記画像の幅
- $h = 上記画像の高さ
@mixin ratio($img, $w, $h){ position: relative; width: 100%; height: 100%; padding-top: $h / $w * 100%; background: image-url($img) no-repeat; background-size: 100%; }
天地左右に中央配置
親要素の幅・高さに対して子要素を天地左右に中央配置するmixin。親要素の高さ指定を忘れずに。
@mixin center{ text-align: center; position: relative; top: 50%; transform: translateY(-50%); }
タイトルなどのテキストを折り返さない
テーブル組のth内のテシストを折り返したくないときなどに使用するmixin。
- $width = 折り返したくない枠の幅
@mixin truncate($width){ width: $width; max-width: 100%; display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
リンクにFont Awesomeのアイコンを付ける
リンクテキストの先頭にFont Awesomeのアイコンを付けるmixin。
対象のa要素に対して@include withFA("\f015", black, red)
のように、アイコン、色を渡して使用します。
- $uni = Font Awesomeアイコンのユニコード
- $col = リンクの色
- $hov = リンクホーバー時の色
@mixin withFA ($uni, $col, $hov){ color: $col; text-decoration: none; &:before{ margin-right: .5em; font-family: "Font Awesome 5 Free"; content: $uni; } &:hover{ color: $hov; transition-duration:.3s; transition-timing-function:ease-in-out; &:before{ transition-duration:.3s; transition-timing-function:ease-in-out; color: $hov; } } }
リンクボタン
CSSだけでリンクボタンを作るmixin。
- $col = リンクボタンの背景色
- $hov = リンクボタンホーバー時の背景色
@mixin boxBtn ($col, $hov){ position: relative; display: inline-block; margin: auto; padding: .5em 1em; text-decoration: none; border-radius: 5px; background: $col; font-size: 21px; color: #fff; &:hover { background: $hov; transition-duration:.3s; transition-timing-function:ease-in-out; } }