Tahsis Claus
Tahsis Claus

Reputation: 1919

Make math happen inside CSS calc() with LESS

I have the following less code:

.@{namespace}users-row {
     height: calc(100% - (@search-row-height - @vh-antialiasing-number));
}

I have already tried:

.@{namespace}users-row {
     height: calc(100% - (@{search-row-height} - @{vh-antialiasing-number}));
}

but that throws errors during compilation.

Is there a way to make the inner parentheses evaluate to a single number, but not have LESS also evaluate the outer ones? I have StrictMath turned on for compilation, so that the outer ones are not evaluated. I would prefer to not row escape, due to how much it decreases the readability. This is ideally what I would like it to compile too:

.namespace-users-row {
     height: calc(100% - Xpx)
}

where X is the difference of the two variables (both have pixel values).

Upvotes: 4

Views: 2181

Answers (2)

Clément
Clément

Reputation: 12917

The behavior is (unfortunately) on purpose, according to the developers. The issue tracking it is here: https://github.com/less/less.js/issues/3221

The workaround offered in that thread is to use a Less function around the calculation; min works:

@search-row-height: 10px;
@vh-antialiasing-number: 5px;

a {
    height: calc(100% - min(@search-row-height - @vh-antialiasing-number));
}

Here's the output:

$ lessc test.less /dev/stdout
a {
  height: calc(100% - 5px);
}

Upvotes: 0

Luca Detomi
Luca Detomi

Reputation: 5716

You must use "escape" function:

@namespace:namespace;
@search-row-height:100px;
@vh-antialiasing-number:30px;


.@{namespace}-users-row {
      height: calc(~"100% - " (@search-row-height - @vh-antialiasing-number));
}

UPDATE:

After @seven-phases-max's suggestion, you could also write rule limiting use of escape character ~ only to - symbol:

.@{namespace}-users-row {
      height:calc(100% ~"-" (@search-row-height - @vh-antialiasing-number));
}

Both of them will result in the following processed CSS:

.namespace-users-row {
  height: calc(100% - 70px);
}

P.S.: I set @namespace:namespace variable because I thought that you desired to have also selector name variable; for this particular purpose, variable name is equal to its value. If not necessary, obviously you can skip this declaration and remove { } writing directly .namespace-users-row

Upvotes: 4

Related Questions