The purpose of this site is to build an active community for UIMinds, PHP, HTML, JavaScript, Jquery Developers and UI/UX Designers to Network, Exchange ideas and talk about Code, Architecture, Innovation, and open source in general. Share the Open Source, Examples, Inspirations and best practices.

Wednesday, March 9, 2016

8 important Sass mixins must have in your toolbox

At their core, Sass mixins are blocks of code that you define once and can then re-use anywhere, if you are familiar with any programming language you can think of them as functions. A mixin can take multiple parameters and make calls to functions to in the end output CSS, and they are super useful when you want really clean and DRY code.
Some of the mixins below are already included in the Compass library, but since I prefer not to use Compass in my projects, I decided to write them myself.

So, here are the 8 mixins I think every developer should have in their toolbox.

1. Set a rem font size with pixel fallback

Rem is similar to the em value, but instead of being relative to the parent element it’s relative to the font-size set in the <html>.
It has all the benefits of em but you don’t get issues with e.g (compounding) since rem is only relative to the html element. The bad part is there’s no support for rem units in IE8 and below. But with this mixin we can create a fallback to pixels when rem isn’t supported.

Usage

Output

2. Breakpoints

When Sass 3.2 was released some time ago, they made it possible to define names to our media queries, which makes the usage of them a lot cleaner. Instead of calling them @media (min-width: 600px) we can give them more semantic names like “breakpoint-large” or “breakpoint-a-really-large-computer-machine”.

@mixin bp-large{@media only screen and (max-width: 60em){@content;}}@mixin bp-medium{@media only screen and (max-width: 40em){@content;}}@mixin bp-small{@media only screen and (max-width: 30em){@content;}}

Output

3. SVG background images with PNG and retina fallback

This mixin depends on Modernizr and creates a bit more work for you when creating images for your site, but it’s really worth it in the end.
You need one .svg file, that will serve as the default background image. You’ll also need a regular .png that serves as a fallback for non-svg-supporting browsers. And last you need a twice as large .png as a second fallback to retina screens.
All in all you need this:

Usage

.container-with-floated-children{@extend %clearfix;}

8. Visually hide an element

When you hide an element with display: none, that prevents screen readers from reading it to the user. Sometimes that’s fine, but in other cases this will make the site hard to use for people with screen readers. Thus, we have to use another technique for hiding elements while at the same time make them accessible.
In this example, we are using the Sass placeholder selector since the output will always be the same, which enables us to reduce repetetive code in the output.