Search code examples
csscss-variablescss-calc

CSS var : attributes refer to the same variable but measure different


<html>
<body>
<div></div> 
</body>
</html>
:root { 
    --scrollbar-width: calc(100vw - 100%);
}

body, html {
    width: 100%;
    height: 100%;
  margin: 0px;
}

div {
    background-image: url(https://i.sstatic.net/r5CAq.jpg);  
  width: var(--scrollbar-width);
  height: var(--scrollbar-width);
}

The width and height of the div element refer to the same CSS custom variable(--scrollbar-width) but its width and height measure different in the browser. Why is that??


Solution

  • As already mentioned in the first comment. The calculation arn't done inside of the definition but inside of the property.

    This results in the following:

    height: var(--scrollbar-width); is equal to height: calc(100vw - 100%); where 100% is calculated relative to the height of the element. While width: var(--scrollbar-width); or width: calc(100vw - 100%); would result in a calculation where 100% is relative to the elements width.

    That's the reason why even tho you are referencing the same custom property the results for width and height are different.