Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SASS Math Calculation

Trying to create a responsive grid of videos. Instead of using different %'s for each media query, I was hoping to use a standard SASS formula that calculates based on 100% width, however not sure if SASS can do this. The 40 in the below formula, takes into account 2 x 20px fixed margins (i.e this would be a 3-column grid).

Ideal formula:

ul.videos {   li {      width: ((100% / 3) - 40);   } } 

Any way that CSS/SASS can handle this? Would prefer not to use JS if possible.

like image 602
SeekingCharlie Avatar asked Sep 26 '13 00:09

SeekingCharlie


People also ask

Can you do math in Sass?

SASS allows for mathematical operations such as addition, subtraction, multiplication and division. You cannot use incompatible units such as px * px or while adding number with px and em leads to produce invalid CSS.

Does Calc work with Sass?

Calc() is not compiled by Sass but by the browser itself so it needs to have all values properly written in the function.

How do you divide in Sass?

Division permalinkDivision Unlike other mathematical operations, division in Sass is done with the math. div() function. Although many programming languages use / as a division operator, in CSS / is used as a separator (as in font: 15px/32px or hsl(120 100% 50% / 0.8) ).


2 Answers

This is possible in all major browsers using calc().

Demo: http://jsfiddle.net/gb5HM/

li {     display: inline-block;     width: calc(100% / 3 - 40px); } 

Of course, you can still declare this in a SASS file but it's a pure CSS solution. It's not possible in SASS because SASS doesn't know what 100% is at the time the stylesheet is generated, and the pixel value of 100% can fluctuate as the document is resized.

Spec: http://www.w3.org/TR/css3-values/#calc

like image 161
Tim M. Avatar answered Sep 22 '22 13:09

Tim M.


Unfortunately you can't subtract 40px from 33%. SASS generates a standard CSS file to be interpreted by the browser, and at build time SASS doesn't know the dimensions of the browser.

However, you should be able to achieve the desired effect by using CSS margins, eg

ul.videos {   li {      width: (100% / 3);      div {          margin: 0 20px;      }   } } 
like image 35
Gareth Bowen Avatar answered Sep 23 '22 13:09

Gareth Bowen