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

心已入冬 提交于 2019-12-20 03:21:28

问题


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?


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


来源:https://stackoverflow.com/questions/31763225/calculating-an-em-value-1px-in-css-sass-without-assuming-the-users-default-fon

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!