CSS中怎样通过样式实现空心三角写法呢?
方法一:利用边框和伪元素
- 原理:通过设置元素的宽度和高度为0,利用边框来创建三角形,再使用伪元素覆盖部分边框形成空心效果。
- 代码示例:
css复制.triangle{ width:0; height:0; border-left:50pxsolidtransparent; border-right:50pxsolidtransparent; border-bottom:100pxsolidblack; position:relative; } .triangle::before{ content:""; position:absolute; top:5px; left:-45px; border-left:45pxsolidtransparent; border-right:45pxsolidtransparent; border-bottom:90pxsolidwhite; }
- HTML结构:
html复制<divclass="triangle"></div>
方法二:SVG实现
- 原理:使用SVG的
<polygon>
元素绘制三角形,通过设置stroke
和fill
属性实现空心效果。 - 代码示例:
html复制<svgwidth="100"height="100"> <polygonpoints="50,00,100100,100"stroke="black"stroke-width="5"fill="none"/> </svg>
对比表格
实现方式 | 优点 | 缺点 |
---|---|---|
边框和伪元素 | 纯CSS实现,兼容性好 | 代码相对复杂,调整样式较麻烦 |
SVG实现 | 代码简洁,易于调整样式 | 对于不支持SVG的旧浏览器可能有兼容性问题 |