用响应式的 CSS 创建箭头形状

4
我想制作一个带有向上箭头的容器。我熟悉边框绘制技巧,认为这是可能的解决方案,但我认为只适用于已知大小,因为您必须以em或px指定边框。
我想要制作的形状如下:
          .
         / \
        /   \
       /     \
      | flex  |
      |       |

内容区域可以以父容器的百分比为基础自由调整大小。

下面是 CSS,其中标记了问题区域:

.metric {
    display: inline-block;
    position: relative;
    height: 150px;
    width: 50%;
    background: lawngreen;
}

.metric:after {
    position: absolute;
    top: -25px;
    left: 0;
    content: '';
    background: white;
    width: 100%;
    height: 0;
    border: 75px solid white; /* this fixed width is the problem */
    border-top: none;
    border-bottom: 25px solid lawngreen;
    box-sizing: border-box;
}

这里是 jsfiddle 链接:http://jsfiddle.net/C8XJW/2/

你们知道如何实现这个吗?

4个回答

6

这里有另一种可能性。

这种方法使用渐变背景来实现。您需要两个背景,这样就可以轻松实现对角线效果:

相关的CSS:

.metric:before, .metric:after {
    position: absolute;
    top: -25px;
    content: '';
    width: 50%;
    height: 25px;
}
.metric:before {
    left: 0px;
    background: linear-gradient(to right bottom, transparent 50%, lawngreen 50%);
}
.metric:after {
    right: 0px;
    background: linear-gradient(to left bottom, transparent 50%, lawngreen 50%);
}

更新的Fiddle

与“最简单”的解决方案的不同之处:

优点:透明圆角(如果您有背景时相关)

缺点:浏览器支持较差


哇,那真的很不错。我喜欢那个。 - SimplGy
由于overflow:hidden边框解决方案依赖于box-sizing:border-box,因此我们两个解决方案之间的兼容性可能相似,而linear-gradient则具有更好的降级效果。 - SimplGy
这是我第一次从自问自答的问题中获得了一个被接受的答案。-) - vals

2
这里有一个很好的解决方案。基本上,你让箭头始终居中,并且比你需要的大得多,但是截取溢出部分。
这是JSFiddle: http://jsfiddle.net/nBAK9/4/ 下面是有趣的代码:
.metric:after {
  position: absolute;
  top: 0;
  left: 50%;
  margin-left: -250px;            /* max expected width /2 */
  content: '';
  background: white;
  width: 500px;                   /* max expected width    */
  height: 0;
  border: 250px solid white;      /* max expected width /2 */
  border-top: none;
  border-bottom: 50px solid #cf6; /* This size adjusts the slope of the triangle */
  box-sizing: border-box;
}

1

不确定你能否做到,我尝试过,发现由于em继承自父元素,你可以稍微调整一下。

body{
    font-size: 3em;
}

div {
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 0 3em 4em 7em;
    border-color: transparent transparent #007bff transparent;
    -webkit-transform:rotate(360deg)
}

Fiddle

的内容与编程有关。

一个有趣的方法。旋转360是什么意思? - SimplGy
@SimpleAsCouldBe 这个应该是为了改善 Chrome 中的抗锯齿效果。 - Jonathan

0
.top-arrow:before, .top-arrow:after {
    position: absolute;
    top: -25px;
    content: '';
    width: 50%;
    height: 25px;
}
.top-arrow:before {
    left: 0px;
    background: linear-gradient(to right bottom, transparent 50%, black 50%);
}
.top-arrow:after {
    right: 0px;
    background: linear-gradient(to left bottom, transparent 50%, black 50%);
}


<div class="top-arrow"></div>

我为此制作了一个 JSFiddle,但我没有看到它工作:http://jsfiddle.net/7bun3xw0/1/ - SimplGy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接