Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting percentages to work in CSS calc() for Firefox and Safari?

I'm using the following calc() equation to calculate the width of two divs:

CSS

.MyClass {
    width: calc((100% - 800px) / 2);
    width: -moz-calc((100% - 800px) / 2);
    width: -webkit-calc((100% - 800px) / 2);
}

This works fine for Chrome and IE, but not Firefox and Safari. I've noticed that Firefox seems unable to interpret the percentage. For example the following will display fine:

CSS

width: calc((1000px - 800px) / 2);

Any advice?

Thanks.

Update

So out my pre-processor is creating css that looks like this:

SCSS

.MyClass {
    width: calc( ( 100% - #{$WrapperWidth} ) / 2 ) ;
    width: -moz-calc( ( 100% - #{$WrapperWidth} ) / 2 ) ;
    width: -webkit-calc( ( 100% - #{$WrapperWidth} ) / 2 ) ;
}

CSS

.MyClass {
  width: calc( ( 100% - 800px ) / 2);
  width: -moz-calc(100%-800px/2);
  width: -webkit-calc(100%-800px/2);
}

I've tried correcting it but it still doesn't seem to be working. The code from the browser is still:

width: calc((100% - 800px) / 2);

It doesn't seem to be reading the -moz-calc though.

like image 262
user2078938 Avatar asked May 30 '14 15:05

user2078938


People also ask

How do you calculate percentages in CSS?

Syntax. The <percentage> data type consists of a <number> followed by the percentage sign ( % ). Optionally, it may be preceded by a single + or - sign, although negative values are not valid for all properties. As with all CSS dimensions, there is no space between the symbol and the number.

Does Calc work in Safari?

Safari & iOS Safari (both 6 and 7) do not support viewport units (vw, vh, etc) in calc(). So in your case, try not to use viewport units in calc(), since you will have issues in Safari 6 and 7. Usually with calc() you need to also use the -webkit prefix which is required for Safari 6 and Chrome 19-25 per the spec?

How does the CALC () function work on values in CSS?

The calc() function takes a single expression as its parameter, with the expression's result used as the value. The expression can be any simple expression combining the following operators, using standard operator precedence rules: + Addition.


2 Answers

Eureka. I've been struggeling with this for days. Finally found that 100vh instead off 100% would make it work with most browsers.

height: calc(100vh - 100px);

instead of

height: calc(100% - 100px);

Finally, now I can get on with my project.

like image 138
Frode Avatar answered Oct 20 '22 16:10

Frode


The reason for this not working is that the parent element does not have height value defined.

It is strange but it works for Chrome and it does not need defined height, but that is not the case for Firefox

If you have:

<div class="parent">
    <div class="child"></div>
</div>

put:

.parent {
    height: 100%;
}

and it should be ok.

like image 26
onetwo12 Avatar answered Oct 20 '22 17:10

onetwo12