DEV Community

Matteo Barbero
Matteo Barbero

Posted on • Edited on

CSS Media queries with math operators

If you work mainly on backend, you may figured the same problem as I did: wtf are all these min-width, max-width instructions inside media queries. And how many pixels is a tablet, or any other mobile device?

For these reasons I made a simple mixin with sass that can help creating media queries.

First things first

If you are already too bored to read till the end, you can try it downloading from Github o NPM

https://github.com/maiobarbero/device_media_query

npm i device_media_query

How it works

The library provides a mixin called device that takes in logical operators and values corresponding to screen widths. You can create complex media queries using operators like >, >=, <, and <= combined with predefined device variables or custom values.
These are the setted variables, that you can override before importing the library in you project

$phone: 480px;
$phone-landscape: 812px;
$tablet: 1024px;
$tablet-landscape: 1366px;
$desktop: 1920px;
$laptop: 1920px;
$screen-4k: 3840px;
Enter fullscreen mode Exit fullscreen mode

You can use the following logical operators with the device mixin:

  • > : greater than
  • >= : greater than or equal to
  • < : less than
  • <= : less than or equal to

Example Usage

Here's an example of how you can use the device mixin:

@include device('>', $tablet, '<=', $desktop) {
  .my-class {
    font-size: 18px;
  }
}
Enter fullscreen mode Exit fullscreen mode

This will generate a media query that applies the specified styles to screens greater than $phone and less than or equal to $tablet. The rendered CSS will look like:

@media (min-width: 1025px) and (max-width: 1920px) {
  .my-class {
    font-size: 18px;
  }
}
Enter fullscreen mode Exit fullscreen mode

Happy coding

Top comments (0)