Search code examples
htmlcsscss-shapes

How do I give a CSS octagon shape a full border?


I am trying to take this css Octagon and give it a solid red border. However, when i add the border it only works on portion of the shape. Does anyone have a solution for this?

enter image description here

Here is a JS FIDDLE

HTML

<div class='octagonWrap'>
      <div class='octagon'></div>
  </div>

CSS

.octagonWrap{
        width:200px;
        height:200px;
        float: left;
        position: relative;
        }
    .octagon{
        position: absolute;
        top: 0; right: 0; bottom: 0; left: 0;
        overflow: hidden;
        }
    .octagon:before {
        position: absolute;
        top: 0; right: 0; bottom: 0; left: 0;
        transform: rotate(45deg);
        background: #777;
        content: '';
        border: 3px solid red;
        }

Solution

  • You can modify your own code to work with this. Right now, you have rules for .octagon that should be for .octagon-wrapper, and rules for .octagon::before that should be for .octagon. Just shift the CSS rules and have them apply to their parents, while changing the border property of .octagon::before to inherit from .octagon.

    .octagonWrap {
        width:200px;
        height:200px;
        float: left;
        position: relative;
        overflow: hidden;
    }
    .octagon {
        position: absolute;
        top: 0; right: 0; bottom: 0; left: 0;
        overflow: hidden;
        transform: rotate(45deg);
        background: #777;
        border: 3px solid red;
    }
    .octagon:before {
        position: absolute;
        /* There needs to be a negative value here to cancel
         * out the width of the border. It's currently -3px,
         * but if the border were 5px, then it'd be -5px.
         */
        top: -3px; right: -3px; bottom: -3px; left: -3px;
        transform: rotate(45deg);
        content: '';
        border: inherit;
    }
    <div class='octagonWrap'>
        <div class='octagon'></div>
    </div>