65

I was studying ways to make a hexagon with just CSS, and found a solution that gives me regular hexagons based on the width:

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

However, the code works by generating new rectangles based on the parent element's width. I was searching for a way to calculate the width based on the parent's height.

Is there a way to use an element's height property instead of width for calc()? (I'm not looking into using vh since the nearest parent won't always be the viewport). I googled around and could not find an answer.

10
  • Have you though about using Sass or Less? Nov 18, 2015 at 9:30
  • @RafaRomero: If he or she did, what solution would you suggest? How would it help with the question?
    – dakab
    Nov 18, 2015 at 9:31
  • 1
    @RafaRomero I'd like to know if there's a simple way to do it without SASS or LESS, but write your answer, might be helpful.
    – Luciano
    Nov 18, 2015 at 9:31
  • 3
    calc() doesn't use the width of anything, it just do the simple operation between the left-hand side and the right-hand side by the operator. . So in the case of relative values (like here 100%) it first converts this value to an absolute one. You can't pass another element's relative value nor an other preoperties btw...
    – Kaiido
    Nov 18, 2015 at 9:33
  • @dakab I was asking it because first of all I wanted to know if he/she want to user other technologies Nov 18, 2015 at 9:34

5 Answers 5

89

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.

3
  • 7
    What is the alternative to doing this?
    – Halo
    Oct 27, 2021 at 20:44
  • 1
    the alternative is javascript. or in react, use useEffect to find the height of an element and do the calculations based on that. Create a function to do that so you can use it for window.resize event too Mar 28, 2022 at 11:40
  • many of the problems involving calcs can be resolved using flexbox or gridlayout.
    – danilo
    Mar 3 at 16:30
30

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 dependent on another value, use another var for that. Just as an example so you can see the syntax, 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 scope: global and local. Local vars will only work logically within the same selector, but global vars are the same throughout 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 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)

3
  • 7
    yes, but these still depend on the fixed value set at the :root. Unfortunately it's not possible to use dynamic values, so I moved away from that... Maybe one day we'll have it!
    – Luciano
    Sep 18, 2019 at 15:25
  • 1
    Unless you can update the css variable from js css-tricks.com/updating-a-css-variable-with-javascript Aug 24, 2020 at 20:39
  • 1
    I originally didn't like this answer (if we're using JS, why not just do everything in JS?), but I've changed my mind - using JS to set a CSS variable allows us to do all of the "other" calculations in CSS, thus simplifying the rest of the layout/animation.
    – rinogo
    Aug 30, 2021 at 23:14
6

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.

1
2

I suggest to define a css rule which depends on a css var (as proposed by Carles Alcolea) and implement a javascript code which updates the value of the css var.

  1. Define css which uses var()
.hexagon.parent {
  /* ... */
  width: var(--hex-parent-height);
}
  1. Create a placeholder within the html to hold var(s) definition
<style id="my-dyn-css">
/* dynamically define css vars here */
</style>
  1. Define a function to set and update the values of the vars (for example on window resize)
function updateDynCss() {
  var parentHeight = computeHeight();
  var style = ":root{--hex-parent-height:" + parentHeight + "px;}";
  $("#my-dyn-css").empty().html(style);
}
2
  • 1
    why make it so complex? might as well update the style directly with the js
    – Luciano
    May 29, 2020 at 7:33
  • You are right, Luciano, it is not strictly necessary. But it helps code readability and reusability (you can reuse var in other css declarations). For example I use this approach to define vars which hold variations of a main color. May 30, 2020 at 9:25
2

As noted many times by many people, it is not possible to set a width based on 100% height using pure CSS.

If you know or can figure out the aspect ratio, then you technically know the width, and you can calculate it fairly easily.

.wrapper {
    position: relative;
    width: 100%;
    padding-top: 56.25%; /* 16:9 or widescreen aspect ratio */
}
.hexagon {
    top: 0;
    position: absolute;
    width: calc(100% * 9 / 16); /* or simply 56.25%; */
}

If the aspect ratio is unknown, then the only viable solutions using CSS is to set the height (or min-height) of the parent element using px or em values. These can also be set using CSS variables, although CSS variables are not fully supported by some older browsers.

.wrapper {
    min-height: 400px;
}
.hexagon {
    width: calc(400px * 0.57735);
}

Finally, if the height is completely dynamic, for instance it changes based on the number of lines of text, then the width will need to be calculated using javascript.

// Example using jQuery, but the principles should be the same.
jQuery(function($){
    var hexagon = $('.hexagon');
    // Resizing the document may change the height of the parent element.
    $(window).on('resize', function() {
        hexagon.each(function(){
            // We'll remove the existing width before calling parent.height()
            $(this).css({width:''}).css({width:$(this).parent().height()});
        });
    }).trigger('resize');
});

Please note that the javascript solution may not provide the exact results you are looking for if the size of the parent element changes when the child element changes. This is also part of the challenge with using height values with CSS and why almost everything is based on width instead.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.