在搜索栏内添加搜索图标:步骤3和4存疑求助
搜索栏添加放大镜图标:步骤3、4详解
步骤3:下载搜索图标
你可以选两种方式获取放大镜图标:
- 直接用SVG代码(推荐):SVG体积小、适配各种屏幕,不用额外下载文件。直接复制下面的SVG代码就能用,无需存本地:
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <circle cx="11" cy="11" r="8"></circle> <line x1="21" y1="21" x2="16.65" y2="16.65"></line> </svg> - 下载本地图标文件:找免费的PNG/SVG图标资源,保存到你的项目文件夹里,记好文件路径即可。
步骤4:添加包含图标的div(实现图标嵌入搜索栏)
要让图标看起来在搜索栏内部,需要用父容器把输入框和图标包起来,再用CSS定位调整位置。具体操作如下:
- 修改HTML结构,添加父容器和图标容器:
<div class="search-container"> <input id="search" type="search" placeholder="search your products here"> <div class="search-icon"> <!-- 这里放上面的SVG代码,或者用img标签引用下载的图标 --> <!-- 例如下载了名为search-icon.png的图标,就写:<img src="search-icon.png" alt="搜索"> --> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <circle cx="11" cy="11" r="8"></circle> <line x1="21" y1="21" x2="16.65" y2="16.65"></line> </svg> </div> </div>
- 添加CSS样式,让图标定位到搜索栏内部:
.search-container { position: relative; width: 300px; /* 可根据需求调整宽度 */ } #search { width: 100%; padding: 8px 30px 8px 10px; /* 右边留足空间放图标,避免输入内容被遮挡 */ box-sizing: border-box; border: 1px solid #ddd; border-radius: 4px; } .search-icon { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); color: #999; /* 调整图标颜色,匹配输入框风格 */ }
设置完成后,放大镜图标会固定在搜索栏右侧,视觉上完全嵌入输入框,输入内容也不会被图标挡住。
内容的提问来源于stack exchange,提问作者Ogugua
相关产品推荐
相关产品推荐

