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

如何使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 13:57:48