如何使用HTML与CSS实现带搜索图标的绿色六边形样式

实现带搜索图标的绿色六边形CSS方案
以下提供两种常用的实现方式,可根据兼容性需求选择:
方案1:clip-path 实现(推荐,代码最简)
通过CSS内置的裁剪属性直接生成六边形,代码量少、调整灵活,适配所有主流现代浏览器。
HTML 代码
<div class="hex-search"> <!-- 可替换为字体图标、img图片等任意搜索图标资源 --> <svg width="24" height="24" viewBox="0 0 24 24" fill="white"> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/> </svg> </div>
CSS 代码
.hex-search { /* 可自行调整六边形尺寸 */ width: 80px; height: 80px; /* 可自定义绿色背景色值 */ background: #2ecc71; /* 正六边形裁剪路径 */ clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%); /* 居中内部搜索图标 */ display: flex; align-items: center; justify-content: center; }
如果需要给六边形加阴影,可搭配filter: drop-shadow()属性实现。
方案2:伪元素实现(兼容旧版浏览器)
通过主矩形+上下两个三角形拼接生成六边形,兼容IE11等低版本浏览器。
HTML 代码
和方案1完全一致,无需修改。
CSS 代码
.hex-search { /* 正六边形宽高比为1:√3/2≈0.866,和高度对应调整即可 */ width: 69.28px; height: 80px; background: #2ecc71; position: relative; display: flex; align-items: center; justify-content: center; } /* 上下两个三角形伪元素 */ .hex-search::before, .hex-search::after { content: ""; position: absolute; width: 0; height: 0; border-left: 34.64px solid transparent; border-right: 34.64px solid transparent; } .hex-search::before { bottom: 100%; border-bottom: 20px solid #2ecc71; } .hex-search::after { top: 100%; border-top: 20px solid #2ecc71; }
内容的提问来源于stack exchange,提问作者Manjunath Bhat
相关产品推荐
相关产品推荐

