You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为div容器内的input type="image"按钮居中添加文本?

问题解答

首先明确:你设置的文本根本没有被浏览器渲染出来,不是被图像遮挡。

原因

input type="image"是专门的图像提交按钮,它的value属性仅用于表单提交时传递的参数值,浏览器不会把这个值当成可见文本显示在图像上。所以你写的value="This is my text"不会出现在页面中。

解决办法

要在图像上叠加居中文本,得把图像和文本拆成两个元素,用容器包裹后通过定位实现叠加。示例代码如下:

CSS 代码

.container {
  position: relative;
  width: 100%;
  height: 0;
  padding-top: 56.25%;
}

.button-wrap {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 50%;
  width: 50%;
  position: relative;
  cursor: pointer;
}

.button-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.button-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1;
  color: white;
  font-size: 16px;
  font-weight: bold;
  text-shadow: 0 0 3px rgba(0,0,0,0.8);
}

HTML 代码

<div class="container">
  <div class="button-wrap" onclick="document.forms[0].submit()">
    <img class="button-img" src="https://picsum.photos/200" alt="submit">
    <span class="button-text">This is my text</span>
  </div>
</div>

额外提示

如果需要保留表单提交功能,也可以用<button>元素替代,更符合语义且无需额外点击事件:

<button class="button-wrap" type="submit">
  <img class="button-img" src="https://picsum.photos/200" alt="submit">
  <span class="button-text">This is my text</span>
</button>

内容的提问来源于stack exchange,提问作者Vika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 23:25:25