Fancy Media Queries with some LESS Magic

Here is what I've done in my projects:

@desktop:   ~"only screen and (min-width: 960px) and (max-width: 1199px)";
@tablet:    ~"only screen and (min-width: 720px) and (max-width: 959px)";

@media @desktop {
  footer {
    width: 940px;
  }
}

@media @tablet {
  footer {
    width: 768px;
  }
}

This allows you to only define your media queries once and you can use it throughout your less files. Also a little easier to read. :)


I completely agree with Hai Nguyen's answer (which has been accepted) but you can clean it up a bit more by doing something like this:

@desktop:   ~"only screen and (min-width: 960px) and (max-width: 1199px)";
@tablet:    ~"only screen and (min-width: 720px) and (max-width: 959px)";

footer{
  width: 100%;
  @media @tablet {
    width: 768px;
  }
  @media @desktop {
    width: 940px;
  }
}

It's essentially the same thing but lets you nest your media queries inside of the original selector. It keeps all css for a specific element together and makes your styles much more modular (vs the split breakpoint approach).


+1 for Nguyen and Yancey - and one more addition.

If you want explicit definition of the widths, you can accomplish that with string interpolation and variables for your breakpoints. Here for example with those of bootstrap - the strict rules are to prevent definition overlapping.

@screen-xs-min:     480px;
@screen-sm-min:     768px;
@screen-md-min:     992px;
@screen-lg-min:     1200px;

@screen-xs-max:     (@screen-sm-min - 1);
@screen-sm-max:     (@screen-md-min - 1);
@screen-md-max:     (@screen-lg-min - 1);

@phone:             ~"only screen and (max-width: @{screen-xs-min})";
@phone-strict:      ~"only screen and (min-width: @{screen-xs-min}) and (max-width: @{screen-xs-max})";
@tablet:            ~"only screen and (min-width: @{screen-sm-min})";
@tablet-strict:     ~"only screen and (min-width: @{screen-sm-min}) and (max-width: @{screen-sm-max})";
@desktop:           ~"only screen and (min-width: @{screen-md-min})";
@desktop-strict:    ~"only screen and (min-width: @{screen-md-min}) and (max-width: @{screen-md-max})";
@large:             ~"only screen and (min-width: @{screen-lg-min})";

footer{
    width: 100%;
    @media @tablet {
        width: 768px;
    }
    @media @desktop {
        width: 940px;
    }
}