Last active
August 29, 2015 14:00
-
-
Save hdemon/6730b119a31cf0e3cc1d to your computer and use it in GitHub Desktop.
retina対応のsprite background
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 使い方 | |
// | |
// ui/button/*.pngをspriteにしたいとして、その中にmain_button-full.pngが存在するとき、.hogeのbackgroundにその画像を指定したい場合は、 | |
// | |
// .hoge { | |
// @include sprite-background("ui/button/*.png", "main_button-full"); | |
// } | |
// | |
// とする。なお、sprite-mapやsprite-urlを自前で定義する必要はない。 | |
// | |
@mixin sprite-background($images-path, $file-name) { | |
$sprite-map: cached-sprite-map($images-path); | |
$y: round(nth(sprite-position($sprite-map, $file-name), 2) / 2); | |
display: block; | |
height: image-height(sprite-file($sprite-map, $file-name)) / 2; | |
width: image-width(sprite-file($sprite-map, $file-name)) / 2; | |
background-size: image-width(sprite-path($sprite-map)) / 2; | |
background-image: cached-sprite-url($images-path); | |
background-repeat: no-repeat; | |
background-position: 0 $y; | |
} | |
$cached-sprite-map-values: () !global; | |
$cached-sprite-url-values: () !global; | |
// @todo cached-sprite-mapとchched-sprite-urlのロジックをDRYに | |
@function cached-sprite-map($images-path) { | |
$key: convert-to-variable-name($images-path); | |
$cached-value: map-get($cached-sprite-map-values, $key); | |
@if $cached-value { | |
@return $cached-value; | |
} @else { | |
$result: sprite-map($images-path); | |
$cached-sprite-map-values: map-merge($cached-sprite-map-values, ($key: $result)) !global; | |
@return $result; | |
} | |
} | |
@function cached-sprite-url($images-path) { | |
$key: convert-to-variable-name($images-path); | |
$cached-sprite-url-value: map-get($cached-sprite-url-values, $key); | |
@if $cached-sprite-url-value { | |
@return $cached-sprite-url-value; | |
} @else { | |
$result: sprite-url(cached-sprite-map($images-path)); | |
$cached-sprite-url-values: map-merge($cached-sprite-url-values, ($key: $result)) !global; | |
@return $result; | |
} | |
} | |
// reference to http://qiita.com/hail2u/items/fffba8d09a21fafaa52d | |
@function str-replace($string, $substr, $newsubstr, $all: 0) { | |
$position-found: str-index($string, $substr); | |
@while ($position-found > 0) { | |
$length-substr: str-length($substr); | |
$string-pre: str-slice($string, 0, $position-found - 1); | |
$string-post: str-slice($string, $position-found + $length-substr); | |
$string: $string-pre + $newsubstr + $string-post; | |
$position-found: 0; | |
@if ($all > 0) { | |
$position-found: str-index($string, $substr); | |
} | |
} | |
@return $string; | |
} | |
@function convert-to-variable-name($path) { | |
@return str-replace($path, '/', '-'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment