2

I am setting my RWD breakpoints as variables in SASS, e.g. $bp-medium: 48em; (equivalent to 768px when 1em = 16px). I would also like to be able to set a variable that is 1px less than that, and have that variable's value be set in ems so that the breakpoint continues to respect the user's base size preferences.

SASS provides calculation tools, certainly, but every way I've tried relies on me having to make an assumption regarding how many pixels the user has their browser's default font size set to. For example:

$bp-medium-1: ($bp-medium/1em)*16px-1px;

…gives $bp-medium-1 a value of 767px (worst of all options as the result is in px), or

$bp-medium-1: $bp-medium - (1em/16);

…which gives $bp-medium-1 a value of 47.9375em — better, since at least the result is in ems now, but I've had to use that assumed '16' in the calculation again.

To recap then: I want to work out 48em - 1px, with the end result being in ems and without having to assume a 16px/em base size.

Can this be done?

RickL
  • 524
  • 1
  • 5
  • 15
  • It's advisable to use pxs, rather than ems for media queries so text size zoom is separate from everything (including layout) zoom. – bjb568 Aug 01 '15 at 16:11
  • 1
    Well, opinion is divided on that score I would say. I'm quite swayed by this argument: http://blog.cloudfour.com/the-ems-have-it-proportional-media-queries-ftw/ – RickL Aug 01 '15 at 16:15
  • em does make sense for when you're directly dealing with text width, like in the menu example. But for most layout things, px makes sense since most people zoom everything at once. – bjb568 Aug 01 '15 at 16:33
  • I had this same question, it may not help much but I did find this: https://github.com/sass-mq/sass-mq. For my purposes I just manually set the variables and calculated them at http://pxtoem.com - I don't think either addresses the 16px base issue though. – Stu Furlong Aug 31 '15 at 00:46

1 Answers1

1

No, you cannot. The only way you can perform arithmetic operations with incompatible units like em and px is via calc() in CSS (not Sass), and that is not allowed in media queries.

You can use the largest possible decimal (based on your precision settings) that is smaller than a specific value.

// default precision in Sass is 5 decimal places
// go any bigger and Sass will round up
@media (max-width: 34.99999em) {
    body {
        background: red;
    }
}

@media (min-width: 35em) {
    body {
        background: green;
    }
}
Community
  • 1
  • 1
cimmanon
  • 67,211
  • 17
  • 165
  • 171
  • What I suspected, but thanks for confirming. So, yes, I could use $bp-medium-1 : $bp-medium - 0.00001em; Except that it might fall foul of browser rounding differences. – RickL Aug 01 '15 at 16:13