在CSS中创建三角形是一种常见的技巧,通常用于创建箭头、工具提示等UI元素。以下是几种创建CSS三角形的方法:
这是最常用的方法,通过设置元素的宽高为0,然后利用边框相交处的斜边效果来创建三角形。
.triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid #f00;
}
/* 向上三角形 */
.triangle-up {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid #f00;
}
/* 向下三角形 */
.triangle-down {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-top: 100px solid #f00;
}
/* 向左三角形 */
.triangle-left {
width: 0;
height: 0;
border-top: 50px solid transparent;
border-right: 100px solid #f00;
border-bottom: 50px solid transparent;
}
/* 向右三角形 */
.triangle-right {
width: 0;
height: 0;
border-top: 50px solid transparent;
border-left: 100px solid #f00;
border-bottom: 50px solid transparent;
}
CSS3的clip-path属性提供了更灵活的裁剪方式:
.triangle-clip {
width: 100px;
height: 100px;
background-color: #f00;
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}
/* 向上 */
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
/* 向下 */
clip-path: polygon(0% 0%, 100% 0%, 50% 100%);
/* 向左 */
clip-path: polygon(100% 0%, 100% 100%, 0% 50%);
/* 向右 */
clip-path: polygon(0% 0%, 0% 100%, 100% 50%);
.triangle-transform {
width: 100px;
height: 100px;
background-color: #f00;
transform: rotate(45deg);
position: relative;
overflow: hidden;
}
.triangle-transform::before {
content: '';
position: absolute;
width: 141%; /* 100% * √2 ≈ 141% */
height: 141%;
background-color: white;
transform: rotate(45deg) translate(-71%, 0);
}
.triangle-gradient {
width: 100px;
height: 100px;
background: linear-gradient(to bottom right, #f00 0%, #f00 50%, transparent 50%, transparent 100%);
}
选择哪种方法取决于你的具体需求和浏览器兼容性要求。