How to use CSS calc () with element height

I studied ways to create a hexagon with CSS only, and found a solution that gives me the correct width-based hexagons:

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

However, the code works by creating new rectangles based on the width of the parent element. I was looking for a way to calculate width based on parent height.

Is it possible to use element height property instead of width for calc() ? (I do not look at using vh , since the closest parent is not always a viewport). I googled around and could not find the answer.

+11
html css3
source share
3 answers

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

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

If you find a solution, let me know. This will help a lot.

Hooray!!

+25
source share

As @YAMAN said, this is not possible, but I have a trick that I can share with you in case it works and helps you.

 top: calc(50% - 0.59em); 

To test this, using a div with size and text inside, you can increase the font size, manually get the height and divide it by 2, replace 0.59em with this value, and you will probably see that they stay at the same level. garrison shop

Please note that I already know that this is not 100% accurate, but it works pretty well for several scenarios, check this out for you, may be suitable for your case or not.

+1
source share

You can get around the problem by using a mediator: CSS variables , which are the only data that is “outside” the curly braces.

If the parent width is also dynamic or dependent on a different value, use a different variable for this. As an example, so you can see the syntax, it will 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 scope: global and local. Local variables will only work logically in the same selector, but global variables are the same in all of your CSS. Declaring one or more variables globally is done through the root block, as shown in the code example.

Getting the value of a variable, as you can see, is as simple as using the CSS var () function, which, if you don’t know, has a very good backup function .

For example, if you needed --hex-parent-height set --hex-parent-height and something went wrong, and --hex-parent-height , you can insert a default value to minimize damage, for example : var(--hex-parent-height, 10px)

0
source share

All Articles