Question

I have two media queries. One is for phones while the other is for tablets. They both call for the same exact styling. In this case what would be the best approach for keeping this code DRY?

$mobile-portrait: "only screen and (max-width: 680px)";
$tablet-portrait: "only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait)";

div {
    background: gray; margin: 0 auto; height: 50px; width: 50px;

    @media #{$mobile-portrait} {
        height: 100px; width: 100px;
    }

   @media #{$tablet-portrait} {
       height: 100px; width: 100px;
   }
}
Was it helpful?

Solution

I'm not sure that there's any good way to do this, but you could always just create multiple selectors. (I don't know if that's the best practice, but that's what I would do.)

@media #{$mobile-portrait},
@media #{$tablet-portrait} {
   height: 100px;
   width: 100px;
}

EDIT: The following is also valid.

@media #{$mobile-portrait}, @media #{$tablet-portrait} {
   height: 100px; width: 100px;
}

For aesthetic I prefer putting the selectors on multiple lines. When there are longer selectors, the line break helps differentiate between them.

I also prefer the styles on multiple lines. If you have more than about three or four in a selector, it can get confusing.

EDIT 2: The comma actually acts like a logical or when inside of a media query.

Per this MDN article:

comma-separated lists

Comma-separated lists behave like the logical operator or when used in media queries. When using a comma-separated list of media queries, if any of the media queries returns true, the styles or style sheets get applied. Each media query in a comma-separated list is treated as an individual query, and any operator applied to one media query does not affect the others. This means the comma-separated media queries can target different media features, types, and states.

Which means that the second @media is not necessary:

@media #{$mobile-portrait}, #{$tablet-portrait} {
    height: 100px;
    width: 100px;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top