【问题标题】:CSS - How to add a border color to a css shape [duplicate]CSS - 如何为css形状添加边框颜色[重复]
【发布时间】:2017-09-29 10:16:44
【问题描述】:

我需要为 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>

谢谢

【问题讨论】:

  • 边框:2px 实心 #000;
  • 您可以添加边框,但它会隐藏在您剪裁了 div 的位置。您的问题是关于简单地添加边框还是在剪辑上添加边框?
  • 是的,我需要将边框也放在裁剪区域中。 @CalT
  • 如果重复的答案没有帮助,您可以尝试这样的方法:codepen.io/bennettfeely/pen/azJWWX
  • 你想让它在 Safari、IE 和 Edge 中工作吗?

标签: css css-shapes


【解决方案1】:

伪元素

一个很好的方法是使用像: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>

【讨论】:

  • 嗨@Stewartside,此代码适用于引导菜单。现在我有一个问题。子菜单不显示,因为我们定义了固定高度。我怎样才能用这个形状解决这个问题?谢谢
  • 如果你能得到一个演示设置,请好好看看它,但实现可以用 100 种不同的方式完成,我不知道你是用什么方式完成的。
  • 我创建一个问题!如果您想查看我的问题,请查看此链接。谢谢你。 @Stewartside stackoverflow.com/questions/44456733/…
【解决方案2】:

一个简单的解决方法是使用伪和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>

【讨论】:

    【解决方案3】:

    尝试添加这个:

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

    【讨论】:

    • “我已经尝试过使用边框或边框宽度,但不起作用。”
    • 好的。但我想把边框也放在左边。 @NikitaGoncharov
    • 然后使用边框:border-left
    • @NikitaGoncharov border 表示所有方向的边界,包括左侧。那是行不通的..
    • 我猜为什么边框不以这种方式添加 - 因为左侧是隐藏的,如果我们检查元素,我们可以看到这一点,所以我找到了解决问题的方法 - 具有必要颜色的父元素,左填充等于到你预期的边框大小,看看:codepen.io/bennettfeely/pen/azJWWX
    猜你喜欢
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 2013-11-20
    • 2017-01-23
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多