Search code examples
csscss-variables

Calculate and Concatenate in CSS variables


Assume there is a --size variable and my purpose is to do something like this:

  .myElement {
    --size: 100;

    pading: var(--size / 2)px;
    margin: var(--size * 2)%;
    [anything]: var(--size) // calculate with --size and unit is px or % ...
  }

The code above is just assumed so how can I implement it?


Solution

  • You can use calc() in your CSS properties to calculate pixel and percentage units of measurement with variables.

    box model

    :root {
      --size: 100;
    }
    
    .myElement {
      background-color: lightgreen;
      margin: calc(var(--size) * .2%);
      padding: calc(var(--size) / 2 * 1px);
    }
    
    .myElement>span {
      background: limegreen;
    }
    <div class="myElement">
      <span>text</span>
    </div>