如何用 CSS 和 HTML 创建带图片的按钮
使用原生 <button>,用 CSS 添加背景图,并设置左内边距让图标与标签分开。示例将放大镜用作装饰,在 HTML 中保留“搜索”文字。
明确图片与按钮各自的用途
CSS 背景图片没有 alt 属性。用文字给按钮命名,即使图标没有加载也能说明用途。type="submit" 会提交表单。要连接单独操作而不提交时,可用 type="button"。 HTML Standard · button
示例使用本站的 32×32 放大镜 PNG。复制到项目时,请让 url() 指向你的文件。外部 CSS 中的相对 URL 以该样式表的位置为基准。 CSS Values and Units · Relative URLs
创建带文字和图标的按钮
将代码保存为 image-button.html 并打开。远程图片需要联网。background 将 24×24 CSS 像素的图标放在离左侧 8px 的位置并垂直居中。44px 的左内边距为文字留出空间,按钮高度至少为 44px。
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>带图标的搜索按钮</title>
<style>
body { margin: 20px; font: 16px/1.6 system-ui, sans-serif; color: #203348; }
* { box-sizing: border-box; }
form { display: flex; flex-wrap: wrap; gap: 10px; align-items: end; max-width: 520px; }
label { display: grid; gap: 6px; flex: 1 1 200px; }
input { width: 100%; min-height: 44px; padding: 8px; border: 1px solid #66798c; font: inherit; }
.search-button {
min-height: 44px; padding: 8px 16px 8px 44px;
border: 1px solid #66798c; border-radius: 6px;
background: #eef4fa url("https://www.codingfactory.net/wp-content/uploads/button_search.png") no-repeat 8px center / 24px 24px;
color: #203348; font: inherit; cursor: pointer;
}
.search-button:hover { background-color: #dceafa; }
.search-button:focus-visible { outline: 3px solid #146bcc; outline-offset: 3px; }
.search-button:active { background-color: #c7dcf4; }
</style>
</head>
<body>
<h1>为搜索按钮添加样式</h1>
<form method="get" role="search">
<label for="query">搜索词
<input id="query" name="q" type="search" required>
</label>
<button class="search-button" type="submit">搜索</button>
</form>
<p>提交后文字会作为 q 进入 URL。本示例不返回搜索结果。</p>
</body>
</html>
检查键盘操作和表单提交
按 Tab 将焦点移到按钮并查看轮廓线。按 Enter 或空格键激活按钮。:hover 和 :active 分别改变指针悬停与按下时的背景色。保留 :focus-visible 的轮廓线,让键盘用户能找到焦点。 WCAG · Focus Visible
要通过 HTTP 测试,在安装了 Python 3 的环境中进入保存目录并运行 python -m http.server 8000 --bind 127.0.0.1。在 http://127.0.0.1:8000/image-button.html 提交 css,地址会带上 ?q=css。空字段会被 required 阻止提交。搜索结果页面需要另行实现。
处理图片缺失和仅图标按钮
如果图标没显示,先在开发者工具的网络面板检查图片 URL。若请求成功,再查看 background-size 或 background-position 是否被其他样式覆盖。暂时禁用背景图片并确认文字仍在,再恢复样式。
如果按钮只有图标,请用 aria-label="搜索" 等方式提供操作名称。带名称的按钮中若有装饰性的 <img>,可指定 alt="" 避免重复朗读。可见标签还能在图片加载失败时保留操作提示。




