Can I use the auto value with the calc() property?

Bhojendra Rauniyar picture Bhojendra Rauniyar · Jan 22, 2014 · Viewed 38.6k times · Source

I wanted to set margin to auto plus some pixel amount using calc(), but my code doesn't seem to work.

selector {
    margin: calc(auto + 5px);
}

Can I set calc() to an automatic margin plus a fixed value? Something like this:

enter image description here

Answer

Mr. Alien picture Mr. Alien · Jan 22, 2014

From MDN :

The calc() CSS function can be used anywhere a <length>, <frequency>, <angle>, <time>, <number>, or <integer> is required. With calc(), you can perform calculations to determine CSS property values.

You cannot use auto there, as it's not a valid value for calc().

Grammar for calc()

term
  : unary_operator?
    [ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* |
      TIME S* | FREQ S* ]
  | STRING S* | IDENT S* | URI S* | hexcolor | function | math
  ;

For more information, refer the Docs


As you commented that you want to center the div but you also want a 5px margin on the right than you can achieve it by using text-align: center; on the parent element and make the child div elements to display: inline-block;

Demo

Output

enter image description here

div.wrap {
    text-align: center;
}

div.wrap div {
    display: inline-block;
    height: 100px;
    width: 100px;
    color: #fff;
}

div.wrap div.with_margin {

    margin-right: 5px;
    background: #f00;
}

div.wrap div.without_margin { 
    background: #000;
}