制作带有边框,圆角和透明背景的六边形

时间:2016-04-24 20:52:09

标签: css css3 svg css-shapes

我想在CSS3中制作一个六边形的边框,圆角和透明背景,如下图所示:

rounded hexagon with border

我不能用圆角和边框来制作它。

我的代码在这里:



#hexagon-circle {
  position: relative;
  margin: 1em auto;
  width: 10em;
  height: 17.32em;
  border-radius: 1em/.5em;
  background: red;
  transition: opacity .5s;
  cursor: pointer;
}
#hexagon-circle:before {
  position: absolute;
  width: inherit;
  height: inherit;
  border-radius: inherit;
  background: inherit;
  content: '';
  -webkit-transform: rotate(60deg);  /* Chrome, Opera 15+, Safari 3.1+ */
  -ms-transform: rotate(60deg);  /* IE 9 */
  transform: rotate(60deg); /* Firefox 16+, IE 10+, Opera */
}

#hexagon-circle:after {
  position: absolute;
  width: inherit;
  height: inherit;
  border-radius: inherit;
  background: inherit;
  content: '';
  -webkit-transform: rotate(-60deg);  /* Chrome, Opera 15+, Safari 3.1+ */
  -ms-transform: rotate(-60deg);  /* IE 9 */
  transform: rotate(-60deg); /* Firefox 16+, IE 10+, Opera */
}

<div id="hexagon-circle"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:5)

带圆角的六边形是复杂的形状,我通常建议使用SVG来创建它们。对透明背景的需求使其更适合SVG。使用SVG,您可以更好地控制形状,曲线等,并且您不必在标记中添加许多额外的(不必要的)元素。

使用SVG创建此形状所需的全部内容是使用单个path元素以及一些L(行)和A(弧)命令。 L(line)命令基本上从第1点到第2点绘制一条线,而A(弧)命令绘制指定半径的弧(紧跟在{{1}之后的前两个值) }命令)。

您可以在this MDN tutorial中详细了解SVG A元素及其命令。

path
svg {
  height: 200px;
  width: 240px;
}
path {
  stroke: #777;
  fill: none;
}

body {
  background: black;
}

如果您仍想使用CSS,则可以按照jbutler483this fiddle使用的方法。 (我已将该小提琴中的代码附加到此答案中以避免链接腐烂问题

<svg viewBox='0 0 120 100'>
  <path d='M38,2 
           L82,2 
           A12,12 0 0,1 94,10 
           L112,44 
           A12,12 0 0,1 112,56
           L94,90       
           A12,12 0 0,1 82,98
           L38,98
           A12,12 0 0,1 26,90
           L8,56
           A12,12 0 0,1 8,44
           L26,10
           A12,12 0 0,1 38,2' />
</svg>
.roundHex {
  position: relative;
  margin: 0 auto;
  background: transparent;
  border-radius: 10px;
  height: 300px;
  width: 180px;
  box-sizing: border-box;
  transition: all 1s;
  border: 10px solid transparent;
  border-top-color: black;
  border-bottom-color: black;
}
.roundHex:before,
.roundHex:after {
  content: "";
  border: inherit;
  position: absolute;
  top: -10px;
  left: -10px;
  background: inherit;
  border-radius: inherit;
  height: 100%;
  width: 100%;
}
.roundHex:before {
  transform: rotate(60deg);
}
.roundHex:after {
  transform: rotate(-60deg);
}