Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an octogonal div?

Pretty simple idea, but I'm not sure how to do this. I'd like to be able to style it as one div (if possible).

How can I create an octagonal div?

like image 497
fancy Avatar asked Feb 17 '12 01:02

fancy


3 Answers

The CSS used in this link is this:

#octagon {
    width: 100px;
    height: 100px;
    background: red;
    position: relative;
}

#octagon:before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;    
    border-bottom: 29px solid red;
    border-left: 29px solid #eee;
    border-right: 29px solid #eee;
        width: 42px;
    height: 0;
}

#octagon:after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;    
    border-top: 29px solid red;
    border-left: 29px solid #eee;
    border-right: 29px solid #eee;
    width: 42px;
    height: 0;
}

It is constructed from the div element itself which is given a rectangular shape. Using the :before and :after pseudo classes, content is added to create two trapeziums that complete the octagon. Cleverly this keeps the actual tag count at just one by using the funkier bits of CSS.

The origins of this technique can be found here.


Here is a quick demo. The blue part is the :before CSS and the green the :after CSS. And even better, here is a demo that allows transparent backgrounds! (thank you @GGG).

like image 191
Bojangles Avatar answered Nov 20 '22 21:11

Bojangles


How about just making a square, rotate it 45 degrees and then clip the corners?

.octagon {
    height: 10em;
    position: relative;
    overflow: hidden;
    width: 10em;
}

.octagon:after {
    background: red;
    content: " ";
    height: 100%;
    position: absolute;
    width: 100%;


  -webkit-transform: rotate(45deg); 
     -moz-transform: rotate(45deg); 
      -ms-transform: rotate(45deg); 
       -o-transform: rotate(45deg); 
          transform: rotate(45deg); 

}

jsFiddle

like image 32
Stephan Muller Avatar answered Nov 20 '22 23:11

Stephan Muller


You can also achive an octogonal div with inline svg using the polygon element.
Here is an example :

svg{width:30%;}
<svg viewbox="0 0 10 10">
  <polygon points="3 0, 7 0, 10 3, 10 7, 7 10, 3 10, 0 7, 0 3" />
</svg>
like image 1
web-tiki Avatar answered Nov 20 '22 21:11

web-tiki