Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Media queries issue when using sass @mixin and @content

Tags:

Can someone please advise me on whats going wrong with the following. I'm getting multiple media queries using @content in @Mixin...

I have created @mixin for media queries:

@mixin tablet {
@media only screen and (max-width:1024px){
    @content;
}
}

and then implemented like so:

.container{
width:1080px; 
margin: 0 auto;

@include tablet{width:940px;}
}

#slider{
width:800px; height:500px;

@include tablet{width:470px; height:470px;}
}

However, when compiling it creates a new media query for each of my css style:

@media only screen and (max-width: 1024px) {
div#slider {
width: 470px;
height: 470px; } 
}

@media only screen and (max-width: 1024px) {
.container {
width: 940px; } }

I'm wanting all the css styles to be in just one of the media queries... and not a new media query created for each... bloated my code.

Can someone please advise what I'm doing wrong here.

Many thanks

like image 894
user2538833 Avatar asked Feb 10 '17 13:02

user2538833


1 Answers

That's the expected behaviour from Sass. I suggest you take a look at this post if you worry about bloat: https://benfrain.com/inline-or-combined-media-queries-in-sass-fight/ It basically suggests that the bloat is negligible in the end, even for large projects.

I have two suggestions:

1) From this post:

https://medium.com/front-end-developers/the-solution-to-media-queries-in-sass-5493ebe16844#.z9osb8t01

Step 1. Make a media-queries.scss file which holds all media queries in only one Sass file

// small screen size (sm)

@media (min-width: 801px) {

}

// medium screen size (md)

@media (min-width: 992px) {

}

Step 2. Create a responsive mixin for each component to be called inside the break points defined in your media-queries.scss file.

.banner {
  text-align: center;
  font-size: 14px;
}

// called in media-queries.scss

@mixin banner--sm() {
  .banner {
    font-size: 20px;
  }
}

@mixin banner--md() {
  .banner {
    text-align: left;
    font-size: 25px;
  }
}

Step 3. Call the mixins in your media-queries.scss

// small screen size (sm)

@media (min-width: 801px) {
  @include banner--sm();
}

// medium screen size (md)

@media (min-width: 992px) {
  @include banner--md()
}

2) Use a media queries combiner

  • Grunt: grunt-combine-media-queries

  • Gulp: gulp-combine-media-queries

  • Webpack: postcss-move-media

like image 103
Nelson Yeung Avatar answered Sep 21 '22 10:09

Nelson Yeung