A medly of marvelous mixins

When starting a new project, I begin by importing boilerplate code - stuff that I’ve written and improved upon over time. Here are a few of my favourite Sass mixin snippets which I use constantly to help speed up my workflow. I’ve created a gist for each of them so you can copy, paste and comment on to your heart’s content. On with the round-up

Style highlighted text

Because you can’t comma-separate the declarations for selection (or at least you couldn’t at one point), it’s easier to create a mixin that can accept foreground and background colours. I also find it makes highlighted text easier to read if any text-shadow is removed.

@mixin selection($background, $foreground:#fff) {
    ::-moz-selection { 
		background: $background; 
		color: $foreground; 
		text-shadow: none; 
	}
    ::selection { 
		background: $background; 
		color: $foreground; 
		text-shadow: none; 
	}
}

Gist: mixin-selection.scss

Background Image Replacement

This mixin takes advantage of the image-width() and image-height() functions in Compass that returns the dimensions of an image.

@mixin background-image-dimensions($image) {
    width:image-width($image);
    height:image-height($image);
    background-image:url($image);
}

Gist: mixin-background-image-dimensions.scss

Text Replacement

An old-school but still reliable way of doing image replacement. Keeping the screen-reader-text placeholder separate means it can be used elsewhere in the codebase without image replacement.

%screen-reader-text {
    text-align:left;
    text-indent:-9999px;
}
@mixin image-replacement($image) {
    @include background-image-dimensions($image);
    @extend %screen-reader-text;
}

Gist: mixin-image-replacement.scss

Respond to breakpoint: simple media queries

I get bored of typing out media query syntax so this nice little wrapper comes in handy. If you work Mobile First you can set the default property to “min-width”.

@mixin respond-to($breakpoint, $property:max-width) {
    @media screen and ($property:$breakpoint) {
        @content;
    }
}

Gist mixin-respond-to.scss

Placeholder

Style the placeholder text in form inputs.

@mixin placeholder() {
    ::-webkit-input-placeholder {
        @content;
    }
    ::-moz-placeholder {
        @content;
    }
    :-moz-placeholder {
        @content;
    }
    :-ms-input-placeholder {
        @content;
    }
}

Gist mixin-placeholder.scss

Bonus - turn px into em

Not a mixin but a function and it’s really useful for calculating a size in ems based on a known pixel size and context.

@function calc-em($target-px, $context) {
    @return ($target-px / $context) * 1em;
}

Gist function-calc-em.scss


If you found any of these mixins useful or if you have any of your own that you can’t live without, I’d love to hear about them. Drop me a tweet @guyroutledge or leave a comment below.

If you hate email but still want to keep in touch, follow me on Twitter.

Guy Routledge avatar
Currently available hire me