Search code examples
csscss-variables

Assign unit of css variable


Is it possible to assign type of unit to a CSS variable inside of the CSS property?

:root {
    --width: 400;
}

.class {
    width: var(--width); //assign 'px' as unit?
}

Solution

  • You can do that by using the calc() function by multiplying your var which don't have px value by 1px as in example:

    As this will transform the value to px at the end.
    I searched a lot but I think there is no way to just add px to the var without calc().

    :root {
        --width: 200;
    }
    
    div.a {
        width: calc(var(--width) * 1px);
        border: 1px solid black; 
    }
    <body>
    <h1>Test</h1>
    
    <div class="a">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut. Maecenas imperdiet felis nisi, fringilla luctus felis hendrerit sit amet. Pellentesque interdum, nisl nec interdum maximus, augue diam porttitor lorem, et sollicitudin felis neque sit amet erat.</div>
    
    </body>