Search code examples
htmlcss

use width inside of calc


I am trying to do something like this:

.my-style {
    width: 50px;
    margin-left: calc(50% - calc(width / 2));
}

Later I am changing the width to 90px and I want the margin grow accordingly.
It doesn't work. Is it possible?


Solution

  • The newest browser's SHOULD support it, I tried the following code.

    This is a webkit example I made, so check it in chrome

    CSS

    p {      
          -webkit-var-a: -webkit-calc(1px + 3px);
          margin-left:-webkit-calc(-webkit-var(a) + 5px);
    }
    

    HTML

    <p>This text should have margin-left, but it doesn't</p>
    

    FIDDLE

    http://jsfiddle.net/uqE8b/

    If you inspect the <p> element you can see that it DOES see the code as valid, it just doesn't do anything... So it seems that for now you have to use javascript, LESS or anything equivelent as it's still a experimental feature.

    EDIT:

    it DOES seem to work when you make the var a plain number:

    p {      
          -webkit-var-a: 3px;
          margin-left:-webkit-calc(-webkit-var(a) + 5px);
    }
    

    http://jsfiddle.net/uqE8b/1/

    So to answer your question, yes this is possible, but I would not recommend it for now.

    CSS

    .my-style {
        height:100px;
        background-color:black;
        -webkit-var-width: 50px;
        margin-left: -webkit-calc(50% - -webkit-var(width) / 2);
    }
    

    FIDDLE

    http://jsfiddle.net/ShsmX/