如何在<input type="image"/>元素上放置文本?多次尝试仍未成功
解决
<input type="image">上添加底部文本的问题 踩过这个坑的人来给你支招!你说得没错,<input type="image">和普通<img>完全不一样——它是表单提交控件,本质上是个自闭合元素,根本没法嵌套文本内容,所以你之前的写法肯定行不通。下面给你两种靠谱的解决方案,既能实现文本在图片底部的效果,又不破坏它的表单提交功能:
方案一:用容器包裹图片和文本(最直观)
给<input type="image">和文本套一个相对定位的容器,然后把文本绝对定位到容器底部。这样既清晰又容易调整样式:
CSS 代码
.image-wrapper { position: relative; display: inline-block; /* 让容器只占图片的宽度,不会撑满整行 */ } .bottom-text { position: absolute; bottom: 0; /* 牢牢贴在图片底部 */ left: 50%; transform: translateX(-50%); /* 水平居中 */ color: red; margin: 0; padding: 3px 10px; background: rgba(0,0,0,0.2); /* 可选:加个半透明背景,让文本更醒目 */ }
HTML 代码
<div class="image-wrapper"> <input type="image" id="MY_ID" src="img.png" class="btTxt submit" width="100" height="130" /> <span class="bottom-text">Example</span> </div>
方案二:用<label>绑定表单控件(更贴合表单语义)
因为<input type="image">是表单元素,用<label>绑定它不仅符合语义,还能实现点击文本也触发表单提交的效果:
CSS 代码
.image-wrapper { position: relative; display: inline-block; } .image-wrapper label { position: absolute; bottom: 0; left: 50%; transform: translateX(-50%); color: red; cursor: pointer; /* 鼠标悬停时显示手型,提示可点击 */ }
HTML 代码
<div class="image-wrapper"> <input type="image" id="MY_ID" src="img.png" class="btTxt submit" width="100" height="130" /> <label for="MY_ID">Example</label> </div>
补充说明
你之前的代码失败还有个原因:父div没有设置position: relative,导致文本的绝对定位是相对于整个页面,而不是图片所在的容器,所以位置会跑偏~上面两个方案都给容器加了position: relative,就能让文本的定位锚定在图片周围啦!
内容的提问来源于stack exchange,提问作者the flash two
相关产品推荐
相关产品推荐

