带有百分比宽度的自适应CSS三角形

下面的代码将在<a>元素下方创建一个箭头:

.btn {

    position: relative;

    display: inline-block;

    width: 100px;

    height: 50px;

    text-align: center;

    color: white;

    background: gray;

    line-height: 50px;

    text-decoration: none;

}

.btn:after {

    content: "";

    position: absolute;

    bottom: -10px;

    left: 0;

    width: 0;

    height: 0;

    border-width: 10px 50px 0 50px;

    border-style: solid;

    border-color: gray transparent transparent transparent;   

}

<a href="#" class="btn">Hello!</a>

问题在于,我们必须指示链接宽度才能获得适当大小的箭头,因为我们无法以像素为单位指示边框宽度。

如何使响应三角形百分比为基础?


慕桂英3389331
浏览 1092回答 3
3回答

慕尼黑的夜晚无繁华

对此的另一种解决方案是使用CSS剪切路径将三角形从彩色块中剪切出来。不支持IE,但是可以用于内部工具等。为方便起见,与SCSS一起编写。.outer {&nbsp; background: orange;&nbsp; width: 25%;&nbsp; position: absolute;&nbsp; top: 50%;&nbsp; left: 50%;&nbsp; transform: translate(-50%, -50%);&nbsp; padding: 1em;&nbsp; p {&nbsp; &nbsp; margin: 0;&nbsp; &nbsp; text-align: center;&nbsp; &nbsp; color: #fff;&nbsp; }&nbsp; &:after {&nbsp; &nbsp; content: '';&nbsp; &nbsp; position: absolute;&nbsp; &nbsp; top: 100%;&nbsp; &nbsp; left: 0;&nbsp;&nbsp; &nbsp; right: 0;&nbsp; &nbsp; padding-bottom: 10%;&nbsp; &nbsp; background: orange;&nbsp; &nbsp; -webkit-clip-path: polygon(0% 0%, 100% 0%, 50% 100%);&nbsp; &nbsp; clip-path: polygon(0% 0%, 100% 0%, 50% 100%);&nbsp; }}

慕姐8265434

我找到了适用于任何宽度/高度的解决方案。您可以在linear-gradient背景中使用两个伪元素,例如(fiddle):.btn {&nbsp; &nbsp; position: relative;&nbsp; &nbsp; display: inline-block;&nbsp; &nbsp; width: 100px;&nbsp; &nbsp; height: 50px;&nbsp; &nbsp; text-align: center;&nbsp; &nbsp; color: white;&nbsp; &nbsp; background: gray;&nbsp; &nbsp; line-height: 50px;&nbsp; &nbsp; text-decoration: none;}.btn:before {&nbsp; &nbsp; content: "";&nbsp; &nbsp; position: absolute;&nbsp; &nbsp; top: 100%;&nbsp; &nbsp; right: 0;&nbsp; &nbsp; width: 50%;&nbsp; &nbsp; height: 10px;&nbsp; &nbsp; background: linear-gradient(to right bottom, gray 50%, transparent 50%)}.btn:after {&nbsp; &nbsp; content: "";&nbsp; &nbsp; position: absolute;&nbsp; &nbsp; top: 100%;&nbsp; &nbsp; left: 0;&nbsp; &nbsp; width: 50%;&nbsp; &nbsp; height: 10px;&nbsp; &nbsp; background: linear-gradient(to left bottom, gray 50%, transparent 50%)}
打开App,查看更多内容
随时随地看视频慕课网APP