如何使用可缩放到父 div 高度的 CSS 创建三角形?

Ant*_*ish 5 html css css-shapes

我目前正在创建一个内容块,它的高度取决于它的内容。块的一端需要有一个箭头,可以缩放到块的高度。

如果可能的话,我理想地想要一个纯 CSS 解决方案。我目前正在使用边界三角形方法:https : //css-tricks.com/snippets/css/css-triangle/

这很好用,如下面我的小提琴所示,但是如果你增加 div 的高度,那么它不会将三角形重新缩放到新的高度。

https://jsfiddle.net/xq5wwf3h/10/

<div id="triangle-container">
    Some interesting content goes in here!
</div>

body * {
    box-sizing: border-box;
}

#triangle-container {
    position: relative;
    height: 100px;
    width: 100%;
    background: grey;
    margin-left:50px;
    color: #fff;
    padding: 15px;
}

#triangle-container:before {
    content: '';
    position: absolute;
    left: -50px;
    top: 0;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 50px 50px 50px 0;
    border-color: transparent #007bff transparent transparent;
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*ish 7

我找到了一个解决方案(尽管 IE 不支持),所以根据具体情况,它可能不是最好的方法。

解决方案使用背景剪辑属性:

https://jsfiddle.net/xq5wwf3h/32/

body * {
    box-sizing: border-box;
}

#triangle-container {
    position: relative;
    height: 100px;
    width: 100%;
    background: grey;
    margin-left:50px;
    color: #fff;
    padding: 15px;
}

#triangle-container:before {
    content: '';
    position: absolute;
    display: block;
    left: -25px;
    top: 0;
    bottom: 0;
    width: 25px;
    height: 100%;
    background: #007bff;
    -webkit-clip-path: polygon(100% 0, 100% 100%, 0 50%);
    clip-path: polygon(100% 0, 100% 100%, 0 50%);
}
Run Code Online (Sandbox Code Playgroud)