Skip to content

Instantly share code, notes, and snippets.

@manabuyasuda
Created July 15, 2015 12:38
Show Gist options
  • Save manabuyasuda/44ddd64d898a1f612f7c to your computer and use it in GitHub Desktop.
Save manabuyasuda/44ddd64d898a1f612f7c to your computer and use it in GitHub Desktop.
単位のある数値から単位だけを削除する@functionです。
// ==========================================================================
// Function remove-unit
// ==========================================================================
//
// 16pxや1remなど単位のある数値から単位だけを削除する@functionです。
// 単位のない数値を使用すると、値はそのまま返されます。
// TODO: 登録している単位と単位なしのいずれかに当てはまらない場合はエラーになります。
//
// e.g.
// remove-unit(16px) => 16
// remove-unit(1.8rem) => 1.8
// remove-unit(50%) => 50
//
@function remove-unit($number){
// 引数に単位がない場合は引数がそのまま返されます。
@if unitless($number) {
@warn "Unit is not attached.";
@return $number;
}
// 引数の値の単位を文字列として取得する。
$unit: unit($number);
// 配列に比較する単位を文字列で準備する。
$compare-list:
// percentage
"%",
// length
"px", "em", "rem", "vw", "vh", "vmin", "vmax", "ch", "ex",
"cm", "mm", "q", "in", "pt", "pc", "mozmm",
// resolution
"dpi", "dpcm", "dppx",
// angle
"deg", "grad", "rad", "turn",
// time
"s", "ms",
// frequency
"Hz", "kHz";
// 配列に比較する単位を数値で準備する。
$compare-item:
// percentage
1%,
// length
1px, 1em, 1rem, 1vw, 1vh, 1vmin, 1vmax, 1ch, 1ex,
1cm, 1mm, 1q, 1in, 1pt, 1pc, 1mozmm,
// resolution
1dpi, 1dpcm, 1dppx,
// angle
1deg, 1grad, 1rad, 1turn,
// time
1s, 1ms,
// frequency
1Hz, 1kHz;
// $compare-listの配列番号を取得する。
$compare-length: length($compare-list);
// $compare-listの配列の数だけ繰り返し処理をする。
@for $i from 1 through $compare-length {
// 配列を1番目から取得して単位を比較する。
@if $unit == nth($compare-list, $i) {
$value: $number / nth($compare-item, $i);
@return $value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment