Based on my previous post where I explored methods to generate a pure-CSS hexagon shape, I have developed this into a LESS mixin that allows the hexagon to be included into your project with ease and efficiency.

Examples

HTML

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

LESS

.hexagon {
  .build-hexagon(100px, #ff0000, #ffffff);
}

This will generate a 100px wide hexagon with a red background and white text.

Overrides

If you need multiple coloured hexagons these can be styled efficiently by simply updating the colour options for either the background or text.

LESS

.hexagon {
  .build-hexagon(100px, #ff0000, #ffffff);

  &.blue {
    .hexagon-color(#0000ff);
  }
}

Now adding a hexagon with the class blue will change the colour. This can also apply to text.

LESS

.hexagon {
  .build-hexagon(100px, #ff0000, #ffffff);

  &.blue {
    .hexagon-color(#0000ff);
  }

  &.black-text {
    .hexagon-text-color(#000000);
  }
}

Now adding the class black-text will obviously turn the text black.

You can view the full mixin code below.

Mixin Code (LESS)

.build-hexagon(@size: 32px, @color: #000, @text-color: #fff) {
  @_height: @size / sqrt(3);

  position: relative;
  width: @size;
  height: @_height;
  background-color: @color;
  margin: @_height/2;
  opacity: 0.8;

  .text {
    position: absolute;
    top: 0;
    left: 0;
    font-size: @_height / 1.2;
    color: @text-color;
    width: @size;
    height: @_height;
    text-align: center;
    overflow: hidden;
    line-height: @_height;
  }

  &:before,
  &:after {
    content: "";
    position: absolute;
    width: 0;
    border-left: @size/2 solid transparent;
    border-right: @size/2 solid transparent;
  }

  &:before {
    bottom: 100%;
    border-bottom: @_height/2 solid @color;
  }

  &:after {
    top: 100%;
    left: 0;
    width: 0;
    border-top: @_height/2 solid @color;
  }
}

.hexagon-color(@color) {
  background-color: @color;

  &:before {
    border-bottom-color: @color;
  }

  &:after {
    border-top-color: @color;
  }
}

.hexagon-text-color(@color) {
  .text {
    color: @color;
  }
}