如何使用CSS Flexbox在文本输入框内创建按钮?
实现按钮嵌入输入框内部的解决方案
我明白你想要打造一个按钮嵌入输入框内部的文本输入组件,目前你的Flexbox布局让按钮和输入框处于并排状态,还没达到“嵌入”的视觉效果。这里给你调整代码,实现你想要的样式:
修改后的完整代码
<!DOCTYPE html> <html> <head> <style> .container { position: relative; /* 作为按钮绝对定位的参考容器 */ width: 500px; margin: 0 auto; display: flex; justify-content: center; } input { height: 60px; width: 100%; /* 占满容器宽度 */ padding-right: 110px; /* 给右侧按钮留出空间,避免输入内容被遮挡 */ background-color: #fce6ef; border-radius: 50px; border: 1px solid #ffc5dd; box-sizing: border-box; /* 确保内边距不增加总宽度 */ } button { position: absolute; right: 8px; /* 调整右侧间距,让按钮嵌入输入框内 */ top: 50%; transform: translateY(-50%); /* 垂直居中按钮 */ height: 54px; width: 94px; background-color: #ff0266; color: #ffffff; text-transform: uppercase; border-style: none; border-radius: 50px; cursor: pointer; /* 添加鼠标悬停指针效果 */ } </style> </head> <body> <div class="container"> <input type="text" placeholder="输入内容..."> <button>Submit</button> </div> </body> </html>
关键修改说明
- 容器相对定位:给
.container设置position: relative,这样按钮的绝对定位会相对于这个容器来计算位置 - 输入框内边距:给
input添加padding-right,确保输入的文本不会被右侧的按钮挡住 - 按钮绝对定位:通过
position: absolute将按钮定位到输入框的右侧,配合transform: translateY(-50%)实现垂直居中,让按钮完美嵌入输入框内部 - 盒模型调整:给
input设置box-sizing: border-box,保证内边距不会让输入框的总宽度超出容器
内容的提问来源于stack exchange,提问作者user14338723
相关产品推荐
相关产品推荐

