如何使用HTML/CSS实现按钮置于文本输入框内部的效果
实现方案
你可以通过给外层容器设置相对定位,按钮设置绝对定位的方式实现需求,修改后的完整代码如下:
SCSS语法代码(适配你原来的嵌套写法)
.pt-site-footer__submit { position: relative; /* 可根据业务需求调整容器宽度,此处为示例值 */ width: 320px; } input { background: #8196aa; border: 0; border-radius: 10px; color: white; /* 加大右侧内边距,预留按钮放置空间,避免输入文字被遮挡 */ padding: 20px 85px 20px 20px; width: 100%; box-sizing: border-box; &:focus { outline: none; } &::placeholder { color: white; } } button { background: #16bdae; border: 0; border-radius: 7px; color: white; padding: 15px; position: absolute; right: 10px; top: 50%; transform: translateY(-50%); cursor: pointer; }
原生CSS语法代码
.pt-site-footer__submit { position: relative; width: 320px; } input { background: #8196aa; border: 0; border-radius: 10px; color: white; padding: 20px 85px 20px 20px; width: 100%; box-sizing: border-box; } input:focus { outline: none; } input::placeholder { color: white; } button { background: #16bdae; border: 0; border-radius: 7px; color: white; padding: 15px; position: absolute; right: 10px; top: 50%; transform: translateY(-50%); cursor: pointer; }
核心逻辑说明
- 外层容器设置相对定位作为子元素的定位上下文
- input设置宽度100%和border-box盒模型,保证撑满容器且内边距不会撑大整体宽度
- 按钮通过绝对定位固定在输入框右侧,配合transform实现垂直居中,不会随页面滚动或输入框状态变化错位
HTML部分无需修改,沿用你原有代码即可。
内容的提问来源于stack exchange,提问作者dmarinus
相关产品推荐
相关产品推荐

