6

很简单的想法,但我不知道如何做到这一点。我希望能够将它作为一个样式div(如果可能的话)。

如何创建八角形div

4

3 回答 3

15

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).

于 2012-02-17T01:46:41.033 回答
3

只是制作一个正方形,将其旋转 45 度然后剪掉角落怎么样?

.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

于 2013-10-09T10:24:47.183 回答
1

您还可以使用多边形元素获得带有内联 svg的八角形 div 。 这是一个例子:

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>

于 2016-04-13T15:11:40.903 回答