l2aelba l2aelba - 6 months ago 101
CSS Question

Calculating width from percent to pixel then minus by pixel in LESS CSS

I will calculate width in some element from percent to pixel so I will minus -10px via using LESS. It´s possible?

div {
width:100%;
height:100px;
> span {
width:calc(100% - 10px);
height:100px;
}
}


I using
calc()
in CSS3 so it doesn't work
calc(100% - 10px)


Ex : if 100% = 500px so width = 490px (500-10);

I made a demo for testing : http://jsfiddle.net/4DujZ/55/

so padding will say: 5 (10px / 2) all the time when I resizing.

Can I do it in LESS ? I know how to do in jQuery and simple CSS like margin padding or else... but i will try to do functional in LESS with
calc()

Answer

You can escape the calc arguments in order to prevent them from being evaluated on compilation.

Using your example, you would simply surround the arguments, like this:

calc(~'100% - 10px')

I find that I use this in one of the following three ways:

Basic Escaping

Everything inside the calc arguments is defined as a string, and is totally static until it's evaluated by the client:

LESS Input

div {width:100%;height:100px;
    > span {

        background:#222;
        width:calc(~'100% - 10px');
        height:100px;
    }
}

CSS Output

div {
  width: 100%;
  height: 100px;
}
div > span {
  background: #222;
  width: calc(100% - 10px);
  height: 100px;
}

Interpolation of Variables

You can insert a LESS variable into the string:

LESS Input

div {width:100%;height:100px;
    > span {
        @pad: 10px;
        background:#222;
        width:calc(~'100% - @{pad}');
        height:100px;
    }
}

CSS Output

div {
  width: 100%;
  height: 100px;
}
div > span {
  background: #222;
  width: calc(100% - 10px);
  height: 100px;
}

Mixing Escaped and Compiled Values

You may want to escape a percentage value, but go ahead and evaluate something on compilation:

LESS Input

@btnWidth: 40px;
div {width:100%;height:100px;
    > span {
        @pad: 10px;
        background:#222;
        width:calc(~'(100% - @{pad})' - (@btnWidth * 2));
        height:100px;
    }
}

CSS Output

div {
  width: 100%;
  height: 100px;
}
div > span {
  background: #222;
  width: calc((100% - 10px) - 80px);
  height: 100px;
}

Source: http://lesscss.org/ and search the page for 'escaping'.