Sass calculate percent minus px

2020-01-25 04:46发布

I want to be able to do the following:

height: 25% - 5px;

Obviously when I do that I get the error:

Incompatible units: 'px' and '%'.

标签: sass
6条回答
你好瞎i
2楼-- · 2020-01-25 05:03

Sass cannot perform arithmetic on values that cannot be converted from one unit to the next. Sass has no way of knowing exactly how wide "100%" is in terms of pixels or any other unit. That's something only the browser knows.

You need to use calc() instead. Check browser compatibility on Can I use...

.foo {
    height: calc(25% - 5px);
}

If your values are in variables, you may need to use interpolation turn them into strings (otherwise Sass just tries to perform arithmetic):

$a: 25%;
$b: 5px;

.foo {
  width: calc(#{$a} - #{$b});
}
查看更多
够拽才男人
3楼-- · 2020-01-25 05:04

Just add the percentage value into a variable and use #{$variable} for example

$twentyFivePercent:25%;
.selector {
    height: calc(#{$twentyFivePercent} - 5px);
}
查看更多
何必那么认真
4楼-- · 2020-01-25 05:08

IF you know the width of the container, you could do like this:

#container
  width: #{200}px
  #element
    width: #{(0.25 * 200) - 5}px

I'm aware that in many cases #container could have a relative width. Then this wouldn't work.

查看更多
▲ chillily
5楼-- · 2020-01-25 05:09

There is a calc function in both SCSS [compile-time] and CSS [run-time]. You're likely invoking the former instead of the latter.

For obvious reasons mixing units won't work compile-time, but will at run-time.

You can force the latter by using unquote, a SCSS function.

.selector { height: unquote("-webkit-calc(100% - 40px)"); }
查看更多
做个烂人
6楼-- · 2020-01-25 05:13
$var:25%;
$foo:5px;
.selector {
    height:unquote("calc( #{$var} - #{$foo} )");
}
查看更多
叛逆
7楼-- · 2020-01-25 05:24

Sorry for reviving old thread - Compass' stretch with an :after pseudo-selector might suit your purpose - eg. if you want a div to fill width from left to (50% + 10px) of screen you could use (in SASS indented syntax):

.example
    background: red
    +stretch(0, -10px, 0, 0)
    &:after
        +stretch(0, 0, 0, 50%)
        content: ' '
        background: blue

The :after element fills 50% to the right of .example (leaving 50% available for .example's width), then .example is stretched to that width plus 10px.

查看更多
登录 后发表回答