CSS - 如何为 css 形状添加边框颜色

CSS - How to add a border color to a css shape

我需要为 css 形状添加边框颜色,但我不知道该怎么做。 我已经尝试使用 borderborder-width 但不起作用。

这是我的代码:

.shape
    {
      width: 400px;
      height: 40px;
      background-color: green;
      -webkit-clip-path: polygon(5% 0, 100% 0, 100% 100%, 0 100%, 0 100%);
      clip-path: polygon(5% 0, 100% 0, 100% 100%, 0 100%, 0 100%);
    }
<div class="shape"></div>

谢谢

尝试添加:

{
...
border: 1px black solid;
...
}

解释:

.shape
    {
      border: 1px black solid;
      width: 400px;
      height: 40px;
      background-color: green;
      -webkit-clip-path: polygon(5% 0, 100% 0, 100% 100%, 0 100%, 0 100%);
      clip-path: polygon(5% 0, 100% 0, 100% 100%, 0 100%, 0 100%);
    }
<div class="shape"></div>

伪元素

一个很好的方法是使用像 :before

这样的伪元素

制作完全相同的形状,但稍微小一点,以保持您想要的主要颜色并正确定位它,您就会得到您想要的边框。

.shape {
  width: 400px;
  height: 40px;
  background-color: black;
  -webkit-clip-path: polygon(5% 0, 100% 0, 100% 100%, 0 100%, 0 100%);
  clip-path: polygon(5% 0, 100% 0, 100% 100%, 0 100%, 0 100%);
  position: relative;
}

.shape:before {
  content: '';
  width: 398px;
  height: 38px;
  -webkit-clip-path: polygon(5% 0, 100% 0, 100% 100%, 0 100%, 0 100%);
  clip-path: polygon(5% 0, 100% 0, 100% 100%, 0 100%, 0 100%);
  background: green;
  display: block;
  position: absolute;
  top: 1px;
  left: 1px;
}
  
<div class="shape"></div>

一个简单的解决方法是使用伪 transform: skew()

transform: skew() 也有比 clip-path 更好的浏览器支持。

.shape {
  position: relative;
  width: 380px;
  height: 40px;
  background-color: green;
  border: 2px solid red;
  margin-left: 25px;
}

.shape::before {
  content: '';
  position: absolute;
  left: -20px;
  top: -2px;
  width: 40px;
  height: 100%;
  border: inherit;
  background-color: inherit;
  border-right-width: 0;
  transform: skewX(-30deg);
}
<div class="shape"></div>