Sass @mixin to change sizes for responsive design
Working on my last project I needed to change the size of some elements to 60% to adapt them to mobile browsers.
At the beginning I tried to do it with CSS ‘rem’ units but it didn’t seem to work as expected in Android browser :S (it works great in the latest iOS 6, Firefox Mobile, and Chrome and Firefox desktop. I stopped my tests when it fails in Android browser )
The alternative was to do it with ‘pixel’ units in plain CSS, but this is a pain in the ass. You have to calculate all the sizes “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 sizes and this makes trial and error impossible (well, possible but long)…
So, I switched to Sass and created a mixin to generate the media queries automatically based on the size of every element:
1$responsive_resize: 0.6;
2$px:1px;
3
4@mixin res($rpx) {
5 $px: $rpx;
6 @content;
7 @media screen and (max-width: 320px) {
8 $px: $rpx*$responsive_resize;
9 @content;
10 }
11}To use it in my elements:
1.myclass {
2 @include res(400px) { width: $px; }
3}Note that I put the size 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.myclass {
2 width: 400px; }
3 @media screen and (max-width: 495px) {
4 .myclass {
5 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.myclass {
2 @include res(400px) { width: $px; }
3 @include res(200px) { height: $px; }
4}1.myclass {
2 width: 400px;
3 height: 200px; }
4 @media screen and (max-width: 495px) {
5 .myclass {
6 width: 240px; } }
7 @media screen and (max-width: 495px) {
8 .myclass {
9 height: 120px; } }I didn’t find a way to resolve this issue, but it works well in all browsers (I didn’t notice any performance problems 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 sizes of all my elements for mobiles or tablets at the same time by changing the $responsive_resize variable.