Single-div perfect CSS hexagons using :before, :after, transform and calc()
Single-div perfect CSS hexagons using :before, :after, transform and calc()
by Adhik Bagul
HTML
<div id="hex1" class="hexagon-wrapper">
<div id="color1" class="hexagon"></div>
</div>
<!-- Prefixfree.js allows you to write prefix-free CSS
This means no -webkit-transform, -moz-transform, ... -->
<script src="//cdn.jsdelivr.net/prefixfree/1.0.7/prefixfree.min.js"></script>
CSS
body {
background: #ecf0f1;
}
#hex1 {
width: 75px;
height: 75px;
}
#hex2 {
width: 150px;
height: 150px;
}
#hex3 {
width: 200px;
height: 200px;
}
#color1 {
background-color: #39D;
}
#color2 {
background-color: #93D;
}
#color3 {
background-color: #D93;
}
.hexagon-wrapper {
text-align: center;
margin: 20px;
position: relative;
display: inline-block;
}
.hexagon {
height: 100%;
width: calc(100% * 0.57735);
display: inline-block;
}
.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);
}