Bhojendra Nepal Bhojendra Nepal - 2 months ago 22
CSS Question

using calc with auto margin

I wanted to use margin-right to auto + some pixels by using css3 calc() but seems the statement is wrong.

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


So, how can use so that it can take auto margin and plus fixed pixels margin?




Something like this!

enter image description here

Answer

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;
}
Comments