Skip to content

Instantly share code, notes, and snippets.

@seriema
Last active August 16, 2023 12:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save seriema/e7605bbcdfc9eaf67ac3 to your computer and use it in GitHub Desktop.
Save seriema/e7605bbcdfc9eaf67ac3 to your computer and use it in GitHub Desktop.
Media query variables in LESS (for Bootstrap, but could be used anywhere)

I got the idea from the Trello CSS guide.

Why do it like this?

Here are some real world examples of where it helped me. Note: The comments in the code were actually there and not added now.

Simple query.

Before:

// Tablet only
@media (min-width: @screen-xs-min) and (max-width: @screen-sm-max) {

After:

@media @tablet {

Combining queries.

Before:

@media (min-width: @screen-sm-min) {

After:

@media @tablet, @desktop {

Why not have a @tablet-and-up or @not-mobile? I tried it, but it didn't expose these situations as good as having to write @tablet, @desktop:

Before:

@media (min-width: @screen-sm-min) {
  ...
}
// Tablet only
@media (min-width: @screen-xs-min) and (max-width: @screen-sm-max) {
  ...
}

After #1:

@media @tablet-and-up {
  ...
}

@media @tablet {
    ...
}

After #2 (I prefer it like this):

@media @tablet, @desktop {
  ...
}

@media @tablet {
    ...
}

Inconsistent and incorrect combinations of min-width: and max-width: properties with screen-xx-min and screen-xx-max values.

This:

@media (min-width: @screen-sm-max) {

Should be:

@media (min-width: @screen-md-min) {

Which is solved by this:

@media @desktop {
// Media query variables. Usage: @media @sm-and-up { ... } or @media @tablet, @desktop { ... }
// Media query names like Bootstrap
@xs-and-up: ~"only screen"; // xs is the smallest size, so "xs and up" is basically "everything on a screen"
@xs-only: ~"only screen and (max-width: @{screen-xs-max})";
@sm-and-up: ~"only screen and (min-width: @{screen-sm-min})";
@sm-only: ~"only screen and (min-width: @{screen-sm-min}) and (max-width: @{screen-sm-max})";
@md-and-up: ~"only screen and (min-width: @{screen-md-min})";
@md-only: ~"only screen and (min-width: @{screen-md-min}) and (max-width: @{screen-md-max})";
@lg-and-up: ~"only screen and (min-width: @{screen-lg-min})";
@lg-only: @lg-and-up;
// Media query names like how we talk in the project (although "true" responsive webdesign shouldn't use these terms)
@print: ~"print";
@mobile: @xs-only; // Don't use this if you're using other sizes too, because Mobile First should be the default.
@tablet: @sm-only;
@desktop: @md-and-up;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment