Skip to content

Instantly share code, notes, and snippets.

@ian-pvd
Last active August 29, 2015 14:26
Show Gist options
  • Save ian-pvd/6d20f55f9fa750e1419f to your computer and use it in GitHub Desktop.
Save ian-pvd/6d20f55f9fa750e1419f to your computer and use it in GitHub Desktop.
Image Replacement Mixin
/* Generated CSS */
.replace-image {
text-indent: 101%;
white-space: nowrap;
overflow: hidden;
display: block;
width: 12.5em;
height: 3.125em;
background-image: url('../images/image-name.png');
background-image: url('../images/image-name-2x.png');
background-image: url('../images/image-name.svg');
background-position: center;
background-size: contain;
background-repeat: no-repeat;
}
/* Dependencies */
// calc-em($px)
// Calculates an em value based on a supplied px value and base font size.
//
// $px - The intended px value to be converted.
// $base: 16 - The base font size to calculate the em value from.
@function calc-em($px, $base: 16) {
@return ($px / $base) * 1em;
}
// @extend $hide-text;
// Extend to hide text by indenting it all the way outside of a block.
%hide-text {
text-indent: 101%;
white-space: nowrap;
overflow: hidden;
}
/* Image Replace Mixin */
// @include image-replace($width, $height, $images);
// Mixin which hides text in a block and replaces it with a list of background images.
//
// $width - Block width in pixels.
// $height - Block height in pixels.
// $images - List of at least one image to use for background image replacement.
// $font-size: 16 - Base font size for calculating em values with calc-em($px)
// $position: center - Replaced background image positioning in block.
// $size: contain - Replace background image size.
// $repeat: no-repeat - Background image repeat.
@mixin image-replace($width, $height, $images, $font-size: 16, $position: center, $size: contain, $repeat: no-repeat) {
@extend %hide-text;
display: block;
width: calc-em($width,$font-size);
height: calc-em($height,$font-size);
@each $url in $images {
background-image: url(#{$url});
}
background-position: $position;
background-size: $size;
background-repeat: $repeat;
}
/* Usage */
.replace-image {
$images: (
'../images/image-name.png',
'../images/image-name-2x.png',
'../images/image-name.svg'
);
@include image-replace(200,50,$images);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment