2

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?
}

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

This approach does not seem to work with fr units.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.