BEM SCSS Mixin

It shortens the BEM syntax of your SCSS child elements into the directive @include e('elementName') {} making it a lot tidier than you would without these. You can also use @include m('modifierName') {} for the modifier CSS class.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

/// BEM Mixin

/// @link https://css-tricks.com/snippets/sass/bem-mixins/

///

/// Block Element

/// @access public

/// @param {String} $element - Element&#39;s name

@mixin element($element){

&__#{$element} {

@content;

}

}

/// Block Modifier

/// @access public

/// @param {String} $modifier - Modifier&#39;s name

@mixin modifier($modifier){

&--#{$modifier} {

@content;

}

}

/// @alias element

@mixine($element){

@include element($element){

@content;

}

}

/// @alias modifier

@mixinm($modifier){

@include modifier($modifier){

@content;

}

}

PX to REM SCSS Mixin Function

This function mixin converts px to rem. You can then use rem(14px) that will calculate itself later against the $browser-context that you will set in this mixin. A great mixin from Chris Coyier at CSS Tricks. I have modified this slightly to use rem however the original article uses this for em.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

/// PX to REM Function

/// @link https://css-tricks.com/snippets/sass/px-to-em-functions/

$browser-context:16;

@functionrem($pixels,$context:$browser-context){

@if(unitless($pixels)){

$pixels:$pixels *1px;

}

@if(unitless($context)){

$context:$context *1px;

}

@return$pixels/$context *1rem;

}

These two mixins are the most common mixins in modern theme development.

Please feel free to use these with your other mixins. And write down in the comments your mixins that you use!

How to Find Your Mixins File

You will typically find the mixins file in the same directory/level as your style.scss file.

In the Underscores theme used by Automattic — the company behind WordPress — you will find it within the sass/mixins folder as _mixins-master.scss.

Adding the Mixin to your Mixins file

You have to simply copy the mixins for example the ones mentioned in this article, and paste them directly to the bottom of your mixins file.

Why is it called mixins-master.scss

The file was called _mixins-master.scss for the sole reason that you will want to create separate files e.g. sass/mixins/_buttons.scss where you can have your own button mixins. And then you will have to add the line @import 'location-to-your-buttons-mixin' at the top of your _mixins-master.scss file.

However this is purely from an organisational perspective.

It is not required to do so, but if you happen to be having a lot of mixins, then organising them into their separate files will help a lot.