RickL
RickL

Reputation: 574

Calculating an em value -1px in CSS/SASS without assuming the user's default font size

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?

Upvotes: 2

Views: 665

Answers (1)

cimmanon
cimmanon

Reputation: 68319

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;
    }
}

Upvotes: 1

Related Questions