0

I have a simple fiddle:

https://jsfiddle.net/1m1rL8ts/

.hex {
  width: 10px;
  height: 10px;
  text-indent: -999px;
  background-color: #000\9;
  background-color: rgba(0, 0, 0, 0);
  border: 1px solid #fff;
}

and there's a rectangular list element. I need to make it into hexagon. What is the easiest way to do it? (I'm aware that even easy way will be still pretty complex).

I need it filled and empty, tried some shapes and it can be done with some tricks when it's filled, but the empty one is harder (it's for carousel gallery).

also it needs to be very small, here's example:

enter image description here

Zbyszek Kisły
  • 2,110
  • 4
  • 26
  • 48

2 Answers2

2

There are several techniques, my favourite is using stacked pseudo-elements

.hex {
  background:chartreuse;
    position: relative;
    width: 4em;
    height: 6.2em;
    border-radius: 10px;
    display: inline-block;
    top: 0;
    &:before,
    &:after {
        position: absolute;
        width: inherit;
        height: inherit;
        border-radius: inherit;
        background: inherit;
        content: "";
    }
    &:before {
        transform: rotate(60deg);
    }
    &:after {
        transform: rotate(-60deg);
    }
}

https://jsfiddle.net/1m1rL8ts/2/

There's even an hexagon generator that uses this approach

Another technique with just 1 pseudo element

.hexagon {
    position: relative;
    overflow: hidden;
    background: transparent;
    width: 10em;
    height: 10em;
    transform: rotate(-30deg) skewX(30deg) scaleY(.866);
}

.hexagon:before {
    position: absolute;
    right: 6.7%;
    bottom: 0;
    left: 6.7%;
    top: 0;
    transform: scaleY(1.155) skewX(-30deg) rotate(30deg);
    background: chartreuse;
    content: '';
}

https://jsfiddle.net/087phqLd/

source for that one

Or you could probably get away with using just 1 element (and no pseudo) by setting multiple, stacking background "gradients".

Facundo Corradini
  • 3,825
  • 9
  • 24
1

I would use clip-path CSS property. You can see It's support here: https://caniuse.com/#search=clip-path

Example:

.hex {
  margin: auto;
  width: 100px;
  height: 100px;
  background: red;
  -webkit-clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
  clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
}
<div class="hex"></div>
Zvezdas1989
  • 1,445
  • 2
  • 16
  • 34
  • while I **love** clip-path, it lacks support on IE, Edge an Safari – Facundo Corradini Jan 09 '18 at 14:14
  • @FacundoCorradini I can understand that. It's just one of possible options. What I don't understand is why am I being downvoted I specifically added current support. – Zvezdas1989 Jan 09 '18 at 14:20
  • well, I'm with you there. Downvoters and the duplicate question police really frustrates me :( Sometimes giving the right answer to a "duplicate question" gets a storm of downvotes. So basically treating beginners well gets you penalised :@ – Facundo Corradini Jan 09 '18 at 14:28