Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

CSS CSS to Sass Refactoring with Sass Defining Media Queries

Shaheer Mir
Shaheer Mir
11,599 Points

Why did we have to use interpolation for the media queries ?

Hi, Could someone please explain why we had to use interpolation in the following manner for media queries. I thought we needed interpolation ${} when we wanted to insert a variable inside a string.

@media #{$brk-narrow}{
    font-size: 1rem;
  }

Why will the following code not work ?

@media $brk-narrow {
    font-size: 1rem;
  }

How is this different than working with any other variable ?

Thank you in advance!

2 Answers

Hi,

When using the @media rule in Sass if you use a variable without interpolation it simply prints out the variable name not the value of the variable.

I do not know the exact reason behind this but that is the info provided when I tried your code snippet in sassmiester.

To try and help you in the future this is the way I use media queries in Sass...

// Media Breakpoints
$break-xs : 420px;
$break-sm : 768px;
$break-md : 992px;
$break-lg :   1200px;

// Media Query Mixin
@mixin mq($break-point) {
    @media (min-width: #{$break-point}) { 
        @content; 
    }
}

// Using The Mixin
.selector {

  // Usual Styles
  property: value;
  property: value;

  // Include The Mixin
  @include mq($break-sm) {
    property: value;
    property: value;
  } 
}

I thought I would give you that mixin as it will become a much better way to use your media queries in the future.

Craig

Kirsty Pollock
Kirsty Pollock
14,260 Points

That's a useful method, thanks. I have been puzzling myself, over what the over-arching principle is, for when interpolation is required - and I think interpolation is necessary when it has been necessary to declare the variable within quotes - which is the case for all but simple single values.

(following Kirsty thought).........which brings us to the conclusion that entire css is a string. It's funny because css rules look alike an object. I agree with Mr Mir this needs clarification. Or we have to accept at the face value. I just realized something. You are replacing entire parenthesis which include prop value pair not only value. Also they are a parameter in the function. We should follow this path I think.