Search code examples
cssshapescss-shapes

How to center a CSS Hexagon


Not sure how to center this hexagon, setting margin: auto; doesn't effect the whole shape. Grateful if anyone could help, thanks in advance.

.hexagon {
    position: absolute;
    width: 300px; 
    height: 173.21px;
    background-color: #fff;
}

.hexagon:before,
.hexagon:after {

    content: "";
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    border-left: 150px solid transparent;
    border-right: 150px solid transparent;
}

.hexagon:before {
      bottom: 100%;
      border-bottom: 86.60px solid #fff;
      position: absolute;
      margin-left: auto;
      margin-right: auto;
}

.hexagon:after {
      position: absolute;
      top: 100%;
      width: 0;
      border-top: 86.60px solid #fff;
}

Solution

  • margin:auto won't work if you have absolutely positioned divs so to center the hexagon, you have to add top:50%, left:50% and margin: -86.6px 0 0 -150px. The -86.6px is half the height of your hexagon and -150px is the half of the width. Also you have to make its parent position relative with a height of 100%.

    HTML

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

    CSS

    html,body{
        background-color:#333;
        height: 100%;
        width: 100%;
        position:relative;
    }
    
    .hexagon {
        top: 50%;
        left: 50%;
        margin: -86.6px 0 0 -150px ;
    }
    

    Fiddle