带边框的CSS自定义形状

时间:2018-07-09 22:26:05

标签: css css3 svg css-shapes

我正在尝试制作带有标签的菜单。标签的样式如下:

enter image description here

我需要背景透明且有边框,将鼠标悬停时,它将用另一种颜色填充背景。

我尝试使用纯CSS来做到这一点,我可以使用:before和:after来获得正确的形状,但是当我使用边框来做到这一点时,我无法在两边都添加边框并以此为最终:

enter image description here

#pointer {
  width: 200px;
  height: 40px;
  position: relative;
  background: red;
  text-align: centre;
  border: 1px solid white;
}

#pointer:after {
  content: "";
  position: absolute;
  left: -20px;
  bottom: 0;
  width: 0;
  margin-bottom: 20px;
  height: 0;
  border-right: 20px solid red;
  border-top: 0px solid red;
  border-bottom: 20px solid transparent;
}

#pointer:before {
  content: "";
  position: absolute;
  right: -20px;
  bottom: 0;
  width: 0;
  height: 0;
  border-left: 20px solid red;
  border-top: 20px solid transparent;
  border-bottom: 20px solid red;
}
<div id="pointer">Tab 1</div>

我也尝试过使用SVG进行此操作,可以使形状和边界正确,但是悬停区域比边界大很多。

    <svg
      class="test"
      xmlns='http://www.w3.org/2000/svg'
      viewBox='0 0 64 64'
      width='150' height='150'
      stroke='white'
      fill='red'>
      <path d='M8 30 L62 30 L62 22 L56 16 L2 16 L8 22 Z' />
    </svg>

如何通过CSS尝试完成边框,或使SVG的悬停区域与边框完全匹配?

2 个答案:

答案 0 :(得分:2)

这是一个考虑偏斜变换的简单想法:

.box {
  width: 200px;
  height: 80px;
  margin: 20px;
  color:#fff;
  z-index:0;
  position: relative;
  --c: black;
  --b: red;
}

.box:hover {
  --b: blue;
  --c:green;
}

.box:before,
.box:after {
  content: "";
  position: absolute;
  z-index: -1;
  left: 0;
  right: 0;
  height: 50%;
  border: 3px solid var(--c);
  background: var(--b);
  box-sizing:border-box;
}

.box:before {
  top: 0;
  transform: skewX(30deg);
  transform-origin: bottom right;
  border-bottom: none;
}

.box:after {
  bottom: 0;
  border-top: none;
}
<div class="box">
  some text
</div>

对于您的SVG形状,您只需要减小viewBox即可仅覆盖您的形状:

svg {
  border:1px solid
}
svg:hover path{
 stroke:red;
 fill:blue;
}
 <svg
      class="test"
      xmlns='http://www.w3.org/2000/svg'
      viewBox='0 14 64 18'
      width="150"
      stroke='blue'
      stroke-width=2
      fill='red'>
      <path d='M8 30 L62 30 L62 22 L56 16 L2 16 L8 22 Z' />
    </svg>

答案 1 :(得分:1)

对于复杂的枪支,最好使用svg

我从您的问题中得到的是,svg区域/悬停区域大于该图。这是真的。但是您可以通过在svg中定位path来使样式变path:hover来解决此问题。

我做了一个小片段,以便您了解它的工作原理。

希望这会有所帮助:>

svg {
  background: red;
}

svg:hover {
  background: orange;
}

path:hover {
  fill: blue;
}
<svg
  class="test"
  xmlns='http://www.w3.org/2000/svg'
  viewBox='0 0 64 64'
  width='150' height='150'
  stroke='white'
  fill='green'>
  <path d='M8 30 L62 30 L62 22 L56 16 L2 16 L8 22 Z' />
</svg>