CSS - Hexagon
This is sample code to create a hexagon shape using HTML and CSS.
The HTML element has a <div> tag with class name "hexagon" to make it a hexagonal element.
<div class="hexagon"></div>
This code calculates the necessary values to shape a hexagon using custom properties in CSS.
By specifying the reference width "--w", it calculates all the needed values using calc()
.
- Longer diameter: w
- Shorter diameter: w * √3
- Side length: w / 2
Also, the top and bottom parts are separate colors to see the different shapes.
.hexagon {
position: relative;
--w: 300px; /* Base width */
width: var(--w);
height: calc(var(--w) * 0.866);
}
.hexagon::before {
content: "";
width: var(--w);
position: absolute;
top: 1px;
border-bottom: calc(var(--w) * 0.433) solid #00bfff;
border-left: calc(var(--w) * 0.25) solid transparent;
border-right: calc(var(--w) * 0.25) solid transparent;
box-sizing: border-box;
}
.hexagon::after {
content: "";
width: var(--w);
position: absolute;
top: calc(var(--w) * 0.433);
border-top: calc(var(--w) * 0.433) solid #4169e1;
border-left: calc(var(--w) * 0.25) solid transparent;
border-right: calc(var(--w) * 0.25) solid transparent;
box-sizing: border-box;
}