Saas @mixin for change measures for responsive desing

Working in my last project I needed to change the measure  of some elements to the 60% to adapt them to mobile browsers.

At the beginning I’ve tried to do it with CSS ‘rem’ units but it didn’t seems to work as expected in Android browser :S (it works great in last ios6, firefox mobile, and chrome and firefox desktop. I’ve stop my tests when it fails in Android browser )

The alternative was do it with ‘pixel’ units in plain CSS, but this is a pain in the ass. You have to calculate all the measures “by hand” and declare again the elements in the media queries. The worst part is if you need to change the percentage after completion… because you have to recalculate all the measures and this make impossible (well possible but large) the test / error…

So, I switch to sass and create a mixin to generate the media queries automatically based on the size of every element:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$responsive_resize: 0.6;
$px:1px;

@mixin res($rpx) {
    $px: $rpx;
    @content;
    @media screen and (max-width: 320px) {
        $px: $rpx*$responsive_resize;
        @content;
    }
}

To use it in my elements:

1
2
3
.myclass {
  @include res(400px) { width: $px; }
}

Note that I put the measure of the element between the parentheses and the properties followed by the variable $px between the braces.

This is the result when you compile the scss file into css:

1
2
3
4
5
.myclass {
  width: 400px; }
  @media screen and (max-width: 495px) {
    .myclass {
      width: 240px; } }

The problem with this is that every time you use the mixin it creates a new media query entry in your css:

1
2
3
4
.myclass {
  @include res(400px) { width: $px; }
  @include res(200px) { height: $px; }
}
1
2
3
4
5
6
7
8
9
.myclass {
  width: 400px;
  height: 200px; }
  @media screen and (max-width: 495px) {
    .myclass {
      width: 240px; } }
  @media screen and (max-width: 495px) {
    .myclass {
      height: 120px; } }

I didn’t found a way to resolve this issue, but it works well in all browsers (I didn’t notice any problem of performance but I prefer a clean code and if you use it a lot it’s going to increase also the weight of your css file. If you know a way to solve this issue don’t hesitate to tell me 🙂 ).

Now I can easily change the measures of all my elements for mobiles or tablets at the same time changing the $responsive_resize variable.