How to use CSS calc() with an element's height

I think you are trying to run script in a css syntax, which is NOT POSSIBLE.

calc() can do basic math operation with absolute values, it cannot find the height of an element and then perform math on it.


You can circumvent the problem using an intermediary: CSS variables, which is the only data "outside" the curly brackets, as it were.

If the parent's width is also dynamic or dependant on other value, use another var for that. Just as an example so you can see the syntaxis, it'd look something like this:

:root {
  --hex-parent-height: 10px;
}

.hexagon.parent {
  /* ... */
  width: var(--hex-parent-height);
}

.hexagon {
  height: 100%;
  width: calc(100% * var(--hex-parent-height));
  display: inline-block;
}

CSS Variables have two types of scopes: global and local. Local vars will only work logically within the same selector, but global vars are the same through all your CSS. Declaring one or more variables globally is done through the root block, as shown in the code example.

Retrieving a var value as you can see is as easy as using the var() CSS function, which in case you don't know, has a very nice fallback feature.

For example, if you were to set --hex-parent-height dynamically and something goes wrong and the var is left unset, you may insert a default value to minimize the damages, like so: var(--hex-parent-height, 10px)


It is not possible as @YAMAN said but I have a trick to share with you just in case it works and help you.

top: calc(50% - 0.59em);

To test it, given a div with a size and a text inside, you can increase the font size, get manually the height and divide it by 2, replace the 0.59em by that value and you will probably see that they stays in the same px.

Notice that I already know that this is not 100% precise, but it does work quite decent for few scenarios, check it out for you, might suit your case or might not.