





In this tutorial I will how you how to create perfect CSS hexagons in any size using transform and calc(). This method doesn’t make use of borders and dynamically calculates the essential values like the width and positioning based on some trigonometry calculations.

The demo below features 3 differently sized hexagons. that can be made with a single div (and a wrapper div to define width and height of the hexagon).

The HTML markup

Our aim is to keep the markup simple.

<div id="hex1" class="hexagon-wrapper"> <div id="color1" class="hexagon"></div> </div>

The important classes here are hexagon-wrapper and hexagon. The hexagon-wrapper‘s most important role will be to serve as a point to position the other elements. The hexagon class will take care of the rest!

In this particular example I have added two IDs to the divs. One for size and one for color. Though in practice if you want all your hexagons to be the same color and size, or if you only want one hexagon, these can be omitted.

Creating the CSS hexagon

To create a hexagon we will need to define a width and height. The hexagon class gets centered by hexagon-wrapper‘s text-align:center property. The height will be 100% of the parent div.

But how do we calculate the width? We can easily do this by using calc().







.hexagon-wrapper { text-align: center; margin: 20px; position: relative; display: inline-block; } .hexagon { height: 100%; width: calc(100% * 0.57735); display: inline-block; }

Without going into too much detail about the mathemathics, we can define the width of a hexagon’s side by multiplying the height with approximately 0.57735.

This still doesn’t give us a hexagon of course, so we will use :after and :before to rotate the div by 60 degrees and -60 degrees.

.hexagon:before { position: absolute; top: 0; right: calc((100% / 2) - ((100% * 0.57735) / 2)); background-color: inherit; height: inherit; width: inherit; content: ''; transform: rotateZ(60deg); } .hexagon:after { position: absolute; top: 0; right: calc((100% / 2) - ((100% * 0.57735) / 2)); background-color: inherit; height: inherit; width: inherit; content: ''; transform: rotateZ(-60deg); }

In addition to rotating. We also need to position the :before and :after pseudo-element. Luckily this can also be calculated relative to the size!

The formula for this is (x / 2) – ((x * 0.57735) / 2)). Of course in our CSS we replace x with 100%. It is also important to set content to an empty value or the element won’t appear.

That’s it!

You now have created a hexagon using pure CSS that can be made in any size and have calc() do everything else for you!