如何让同一div内的输入框与带图标按钮高度一致?
解决输入框与带图标按钮高度一致的问题
核心问题分析
当前导致高度不一致的几个关键点:
- 父容器
.names_input_feature设置了align-items: flex-start,导致按钮和输入框仅顶部对齐,未拉伸至相同高度 - 输入框有
2px边框,按钮无边框,且两者盒模型计算方式未统一 - 输入框的
margin-bottom:40px影响横向布局,按钮内边距与输入框未匹配
具体修改方案
调整flex容器对齐方式
将.names_input_feature的align-items改为stretch,让子元素自动拉伸至容器高度;移除不必要的align-content: center统一盒模型与边框
给按钮#name_submit_btn添加box-sizing: border-box,确保内边距和边框不额外增加元素高度;同时添加和输入框一致的2px solid rgb(255, 0, 0)边框,保证视觉高度匹配修正间距与内边距
移除flex容器内输入框的margin-bottom(避免影响横向布局),给按钮添加和输入框一致的背景色,保证视觉统一优化交互样式
hover时同步修改按钮边框和图标颜色,提升交互一致性
修改后的完整代码
CSS部分
.wrapper { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 75vh; display: grid; grid-template-columns: 1fr 1fr; column-gap: 30px; } .form_section { display: flex; flex-direction: column; justify-content: center; align-items: center; border: 2px solid rgb(255, 255, 255); border-radius: 4px; padding: 20px 20px; margin-top: 70px; margin-bottom: 20px; min-width: 400px; } #team_form { display: flex; flex-direction: column; justify-content: center; align-items: start; } .team_form_label { color: white; font-size: 26px; } input[type="number"], input[type="text"], select { padding: 10px 15px; margin-bottom: 40px; box-sizing: border-box; border: 2px solid rgb(255, 0, 0); border-radius: 4px; background-color: rgb(255, 255, 255); color: black; font-size: 18px; width: 100%; } .names_input_feature { width: 100%; display: flex; align-items: stretch; } /* 移除flex容器内输入框的底部间距 */ .names_input_feature input[type="text"] { margin-bottom: 0; } /*The player names adding button*/ #name_submit_btn { padding: 10px 20px; margin-left: 10px; display: flex; justify-content: center; align-items: center; border: 2px solid rgb(255, 0, 0); box-sizing: border-box; border-radius: 4px; color: black; font-size: 22px; cursor: pointer; transition: 0.4s ease; background-color: rgb(255, 255, 255); } #name_submit_btn:hover { color: #fff; background-color: #3da736; border-color: #3da736; } #name_submit_btn i { transition: 0.4s ease; } #name_submit_btn:hover i { color: #fff; }
HTML部分
<label class="team_form_label" for="team_players"> Enter the name of the players: </label> <div class="names_input_feature"> <input type="text" id="team_players" class="team_form_input" name="team_players" placeholder="Must match the total"/> <button id="name_submit_btn"> <i class="fa-solid fa-plus" style="color: #000000"></i> </button> </div>
额外说明
box-sizing: border-box是核心,它让元素的内边距和边框都包含在设定的尺寸内,避免布局偏移align-items: stretch会让flex子元素自动填充容器高度,确保输入框和按钮高度完全一致- 统一边框、背景色以及hover状态样式,能让组件视觉更协调
内容的提问来源于stack exchange,提问作者Ashim Shrestha
相关产品推荐
相关产品推荐

