Lawrence William Trigg Lawrence William Trigg - 5 months ago 28
CSS Question

Hexagon CSS Width & Height %

Is there anyway of creating an Hexagon with the property's set to % instead of px's?
So i could create a div container within my website with a width and height of 100px's, the hexagon set to 100% width and height would take up the entire div?
Thank you for any reply! :)



.hexagon {
position: relative;
width: 70px;
height: 40.41px;
background-color: #64C7CC;
margin: 20.21px 0;
}

.hexagon:before,
.hexagon:after {
content: "";
position: absolute;
width: 0;
border-left: 35px solid transparent;
border-right: 35px solid transparent;
}

.hexagon:before {
bottom: 100%;
border-bottom: 20.21px solid #64C7CC;
}

.hexagon:after {
top: 100%;
width: 0;
border-top: 20.21px solid #64C7CC;
}

<div class="hexagon"></div>





edit
In case someone wants it made a kind of really sloppy solution where you can change the pixels of the container to change the hexagon



.container {
width: 90px;
height: 90px;
}
.hexagon1 {
position: relative;
height: 30%;
width: 30%;
top: 15%;
left: 10%;
background: #76B4FF;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-o-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.hexagon2 {
position: relative;
height: 30%;
width: 30%;
top: 0%;
left: 16%;
background: #76B4FF;
}
.hexagon3 {
position: relative;
height: 30%;
width: 30%;
top: -15%;
left: 10%;
background: #76B4FF;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-o-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.hexagon4 {
position: relative;
height: 30%;
width: 30%;
top: -60%;
left: 4%;
background: #76B4FF;
}

<div class="container">
<div class="hexagon1">
</div>
<div class="hexagon2">
</div>
<div class="hexagon3">
</div>
<div class="hexagon4">
</div>
</div>




Answer

You can use em units since border can't do percents. This way you only have to specify the hexagon size in one place, with font-size:

#container {
    border: 1px solid black;
    width: 400px;
    height: 400px;
}
.hexagon {
    font-size: 400px;
    position: relative;
    width: 0.86602540378em;
    height: 0.5em;
    background-color: #64C7CC;
    margin: 0.25em 0.0669872981em;
}
.hexagon:before,
.hexagon:after {
    content: "";
    position: absolute;
    width: 0;
    border-left: 0.43301270189em solid transparent;
    border-right: 0.43301270189em solid transparent;
}
.hexagon:before {
    bottom: 100%;
    border-bottom: 0.25em solid #64C7CC;
}
.hexagon:after {
    top: 100%;
    border-top: 0.25em solid #64C7CC;
}
<div id="container">
    <div class="hexagon"></div>
</div>

It is not the most ideal solution however, since it's not relative to the container size.