如何将图片置于input元素旁?求助解决布局设置无效问题
解决submit.png无法与input元素并排的问题
核心问题分析
你的input元素设置了width: 100%,会完全占据父容器.input-box的宽度,导致后面的submit图片被挤到下一行——这就是你尝试display: inline-block和float: right没生效的根本原因。
解决方案1:使用Flex布局(推荐)
给父容器.input-box添加display: flex和align-items: center,让内部元素自动对齐;同时把input的宽度改为flex: 1,让它自动填充剩余空间,图片就能和input自然并排:
<div class="input-box" style="height: 40px; width: 500px; display: flex; align-items: center; position: relative;"> <img src="img/delete.png" width="25px" height="25px" style="position: absolute; right: 50px;"> <input id="answer" type="text" style="border: none; border-bottom: 2px solid silver; flex: 1; font-size: 17px; background-color: #ffffff00; outline: none; color: white; font-weight: bold; text-align: center;" required readonly oninput="let p=this.selectionStart;this.value=this.value.toUpperCase();this.setSelectionRange(p, p);"> <img src="img/submit.png" width="25px" height="25px" style="margin-left: 10px;"> </div>
解决方案2:调整宽度并使用inline-block
去掉input的width: 100%,用calc()计算出预留图片和间距后的宽度;同时给input和submit图片添加display: inline-block和vertical-align: middle,确保垂直对齐:
<div class="input-box" style="height: 40px; width: 500px; position: relative;"> <img src="img/delete.png" width="25px" height="25px" style="position: absolute; right: 0;"> <input id="answer" type="text" style="border: none; border-bottom: 2px solid silver; height: 100%; width: calc(100% - 60px); font-size: 17px; background-color: #ffffff00; outline: none; color: white; font-weight: bold; text-align: center; display: inline-block; vertical-align: middle;" required readonly oninput="let p=this.selectionStart;this.value=this.value.toUpperCase();this.setSelectionRange(p, p);"> <img src="img/submit.png" width="25px" height="25px" style="display: inline-block; vertical-align: middle; margin-left: 10px;"> </div>
补充提示
- 绝对定位的delete.png需要调整
right值,避免和submit图片重叠; - Flex布局适配性更强,能自动应对不同屏幕尺寸,优先推荐;
- 如果需要input占满图片外的所有空间,方案1的
flex:1是最优选择。
内容的提问来源于stack exchange,提问作者Veri Virgandra
相关产品推荐
相关产品推荐

