よく使うのでmixinにしています。
方針としては、
- image-width、image-heightで大きさを合わせる
- text-indentを-9999pxにしてテキストを飛ばす
- 背景画像を設定する
を行っています。
インライン要素に対してはdisplayをblockにしてやる必要がありますが、そこはmixinにはいれていません。
@mixin replaceImg($imgName) { $root: "/"; $path: "data/img/"; width: image-width(#{$path}#{$imgName}); height: image-height(#{$path}#{$imgName}); background-image: url(#{$root}#{$path}#{$imgName}); background-repeat: no-repeat; text-indent: -9999px; }
また、スプライト画像はこのようにしています。
上下に繋げる形で、上が通常、下がhover時を想定しています。
自動でスプライトをつくるという方針もありますが、個人的には重くなるので好きではありません。
@mixin replaceBtnImg($imgName) { $root: "/"; $path: "data/img/"; $width: image-width(#{$path}#{$imgName}); $height: image-height(#{$path}#{$imgName}); width: $width; height: round($height / 2); background-image: url(#{$root}#{$path}#{$imgName}); background-position: left top; background-repeat: no-repeat; background-size: $width $height; text-indent: -9999px; &:hover { background-position: left bottom; } }
Retinaディスプレイ対応の時はそれぞれこんな感じです。
要素の大きさを画像サイズの半分に設定し、background-sizeをcontainに設定しています。
@mixin replaceRetinaImg($imgName) { $root: "/"; $path: "data/img/"; width: round(image-width(#{$path}#{$imgName}) / 2); height: round(image-height(#{$path}#{$imgName}) / 2); background-image: url(#{$root}#{$path}#{$imgName}); background-repeat: no-repeat; background-size: contain; text-indent: -9999px; }
@mixin replaceBtnRetinaImg($imgName) { $root: "/"; $path: "data/img/"; $width: round(image-width(#{$path}#{$imgName}) / 2); $height: round(image-height(#{$path}#{$imgName}) / 2); width: $width; height: round($height / 2); background-image: url(#{$root}#{$path}#{$imgName}); background-position: left top; background-repeat: no-repeat; background-size: $width $height; text-indent: -9999px; &:hover { background-position: left bottom; } }