Search code examples
cssbordercss-shapes

Giving hexagon div a border


Is there any way I can give this hexagonal shape a border?

The hexagon is made up of three parts top(triangle) middle(rectangle) and bottom(triangle).

I am having trouble because in order to make the top and bottom triangles of the hexagon, I have to use "border: transparent".

CSS:

.hex-mid {
    width: 208px;
    height: 120px;
    background-color: #64C7CC;
}
.hex-top {
    width: 0;
    border-bottom: 60px solid #64C7CC;
    border-left: 104px solid transparent;
    border-right: 104px solid transparent;
}
.hex-bot {
    width: 0;
    border-top: 60px solid #64C7CC;
    border-left: 104px solid transparent;
    border-right: 104px solid transparent;
}

HTML:

<ul class="hexagon">
  <li class="hex-top"></li>
  <li class="hex-mid"></li>
  <li class="hex-bot"></li>
</ul>

Solution

  • svg solution:

    You can do this easily if you use svg:

    <svg width="240" height="300" viewBox="-1 -1 240 300">
      <path d="M104,0 L208,60 L208,180 L104,240 L0,180 L0,60z" stroke="black" stroke-width="1" fill="#64C7CC" />
    </svg>

    CSS solution:

    You can add :before :pseudo-elements and position them behind the main elements.

    .hex-mid {
      width: 208px;
      height: 120px;
      background-color: #64C7CC;
      position: relative;
    }
    .hex-mid:before {
      content: '';
      position: absolute;
      z-index: -1;
      width: 210px;
      height: 122px;
      background-color: black;
      margin-left: -1px;
      margin-top: -1px;
    }
    .hex-top {
      width: 0;
      border-bottom: 60px solid #64C7CC;
      border-left: 104px solid transparent;
      border-right: 104px solid transparent;
      position: relative;
    }
    .hex-top:before {
      width: 0;
      content: '';
      position: absolute;
      border-bottom: 60px solid black;
      border-left: 104px solid transparent;
      border-right: 104px solid transparent;
      margin-left: -104px;
      margin-top: -1px;
      z-index: -1;
    }
    .hex-bot {
      width: 0;
      border-top: 60px solid #64C7CC;
      border-left: 104px solid transparent;
      border-right: 104px solid transparent;
    }
    .hex-bot:before {
      content: '';
      position: absolute;
      width: 0;
      border-top: 60px solid black;
      border-left: 104px solid transparent;
      border-right: 104px solid transparent;
      margin-left: -104px;
      margin-top: -59px;
      z-index: -1;
    }
    li {
      list-style: none;
    }
    <ul class="hexagon">
      <li class="hex-top"></li>
      <li class="hex-mid"></li>
      <li class="hex-bot"></li>
    </ul>