Search code examples
csssassscss-mixins

how to change media query based on if a class exists or not using scss


I have this html element :

<div class="parent">
  <div class="content">
     <p>Content of the component</p>
  </div>
</div>

and i'm using this sass mixin:

@mixin screen-is($size) {
  $media-query: "";
  $media-query2: "";
  @if $size == tablet {
    $media-query: '(min-width: 1000px) and (max-width: 1200px)';
    $media-query2: '(min-width: 1000px) and (max-width: 1400px)';
  } @else {
    @error 'Unknown size #{$size}';
  }

  @if $media-query2 {
    .parent {
      @media #{$media-query2} {
        @content;
      }
    }
  }

  @media #{$media-query} {
    @content;
  }
}

.content {
  @include screen-is(tablet) {
    background-color: lightblue;
  }
}

My goal is this:

  • if class parent exists on DOM, use $media-query2, means apply background-color as lightblue when screen is between 1000px and 1400px.
  • if class parent doesnt exist on DOM, use $media-query, means apply background-color as lightblue when screen is between 1000px and 1200px. But the problem is that the style is never applied above 1201px, so i think there is something wrong in the usage of media-query2.

Can be tested here: https://codepen.io/abasse/pen/qBgNEYo?editors=1111


Solution

  • If you look at the compiled css code in your codepen, you can see that the generated selector is .content .parent, which means, in order for this selector to work .parent is supposed to be a child of .content.

    But as per your goal, what you need is .parent .content. So you need to edit the .content block in your sass code.

    Just move .content selector one line down and that should generate the correct css code:

    @include screen-is(tablet) {
      .content {
        background-color: lightblue;
      }
    }