big_smile
big_smile

Reputation: 1523

Can Scss mixins be responsive

In my css I have different font styles* for different devices:

e.g.

@media only screen and (min-width: 480px) and (max-width: 599px) {
t-heading {
font-size:14px;
} 
}

@media only screen and (min-width: 600px) {
t-heading {
font-size:24px;
} 
}

I would like to turn these into a mixin, so I can call these values inside other styles, while still keeping them responsive.

E.g.

SCSS:

.front {
background: red;
@include t-heading; 
}

Outputed CSS:

   .front {
    background:red;
    }

    @media only screen and (min-width: 480px) and (max-width: 599px) {
    .front {
    font-size:14px;
    } 

    }
    @media only screen and (min-width: 600px) {

    .front {
    font-size:24px;
    } 
    }

Is this possible in SCSS? I have tried wrapping mixins in Media queries, but it doesn't seem to work.

*I am just using font-styles as an example.

Upvotes: 3

Views: 539

Answers (1)

cimmanon
cimmanon

Reputation: 68319

You want the mixin to contain the media queries, not the other way around:

@mixin t-heading {
    @media only screen and (min-width: 480px) and (max-width: 599px) {
        font-size:14px;
    }

    @media only screen and (min-width: 600px) {
        font-size:24px;
    } 
}

.front {
    background: red;
    @include t-heading; 
}

Output:

.front {
  background: red;
}
@media only screen and (min-width: 480px) and (max-width: 599px) {
  .front {
    font-size: 14px;
  }
}
@media only screen and (min-width: 600px) {
  .front {
    font-size: 24px;
  }
}

Ideally, you'd want to avoid calling this sort of mixin very often, since that's a lot of extra code to be generating. If the code is something you'll want to repeat, you might want to consider using @extend:

%t-heading {
    @media only screen and (min-width: 480px) and (max-width: 599px) {
        font-size:14px;
    }

    @media only screen and (min-width: 600px) {
        font-size:24px;
    } 
}

.front {
    background: red;
    @extend %t-heading; 
}

.back {
    @extend %t-heading;
}

Output:

@media only screen and (min-width: 480px) and (max-width: 599px) {
  .front, .back {
    font-size: 14px;
  }
}
@media only screen and (min-width: 600px) {
  .front, .back {
    font-size: 24px;
  }
}

.front {
  background: red;
}

Upvotes: 4

Related Questions