neelmeg
neelmeg

Reputation: 2509

sass code style with media queries

I'm doing a code review for sass code and came across using media queries inside the code. Is it a good practice? Are there better alternatives to writing this code?

.col-md-push-8 {
    padding-top: 1.5em;
    .btn {
        &.btn-block {
            border: none;
            background-color: $footer-button;
            margin: 1em 0 .5em;
            width: 100%;
            padding: 7px 10px;
            border-radius: 8px;
            &:hover {
                background-color: $footer-button-hover;
            }
            @media (min-width: $screen-md-min) {
                color: #025191;
                &:hover .media span p.media-heading {
                    color: #0070ca;
                }
            }
        }
    }
}

Note: The code is for illustration purpose only and is not completely shown here.

Upvotes: 1

Views: 741

Answers (3)

Preview
Preview

Reputation: 35796

I think that what your way to do it is perfectly fine if you're using SASS >= 3.2 (was buggy before).

Just one thing that you could do to define your media queries breakpoints more globally is to create a mixin for that purpose that you will re-use on each element you need responsive.

This way when you have to change let's say your min breakpoint, add another or change your media min-width to max-width, you don't have to do it everywhere.

Some little example assuming you have already defined $screen-md-min and $screen-md-mid :

@mixin custom-media($size) {

    @if ($size == $small) {
         @media (min-width: $screen-md-min) { @content; }
    }
    @else if ($size == $middle) {
         @media (min-width: $screen-md-mid) { @content; }
    }
}

And call it like so :

.btn {
    &.btn-block {
        ...
        @include custom-media($small) {
            color: #025191;
            &:hover .media span p.media-heading {
                color: #0070ca;
            }
        }
    }
}

Upvotes: 1

coreyward
coreyward

Reputation: 80041

Sass handles this fine, but that code is going to produce overly qualified selectors and is hardly concise.

There are a number of patterns for writing “better” CSS and Sass, such as BEM, OOCSS, OOCSS + Sass, and SMACSS.

There's also a bunch of great information on Media Queries in Sass that is probably worth a read.

Upvotes: 0

h0n24
h0n24

Reputation: 89

There is no difference if you put Media Query inside or outside. It just depends on your preffered style.

Style 1

.some-class {
  @media (min-width: 700px) {
    background: red;
  }
}

Style 2

@media (min-width: 700px) {
  .some-class {
    background: red;
  }
}

Both will compile as:

@media (min-width: 700px) {
  .some-class {
    background: red;
  }
}

Upvotes: 0

Related Questions