flexbox导航栏中动画搜索框定位异常,需无margin实现居中
错位的根本原因
- 直接造成搜索框偏移的代码是
.search-box上的transform: translate(0%, -50%),这段代码是原YouTube教程中给绝对定位元素做居中的遗留逻辑,并不适配当前的flex导航布局,会直接把搜索框向上偏移自身高度的50%,完全打乱flex的对齐规则。 - 布局层面的潜在隐患:
.search-box默认的内容盒模型计算规则,会让自带的10px内边距超出设置的40px固定高度,导致元素实际高度和预期不符,进一步干扰垂直居中效果。
零margin约束下的修正逻辑
- 直接删除
.search-box上的错误transform代码 - 全局统一启用
border-box盒模型,让内边距、边框都纳入元素自身尺寸计算范围,和flex的对齐规则完全匹配 - 仅通过flex容器的属性调整搜索框位置:需要水平居中就把
.container的justify-content设为center;如果后续导航栏要加左右两侧的其他元素,只需要给左右两侧元素设置flex: 1占满剩余空间,就能自动把搜索框挤到水平居中位置,全程不需要给搜索框添加任何margin属性。
修正后可直接运行的代码
<!DOCTYPE html> <html lang="zh-CN"> <head> <script src="https://kit.fontawesome.com/20c0c25f7c.js" crossorigin="anonymous"></script> <title>导航栏动画搜索框实现</title> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> * { box-sizing: border-box; } body{ font-family: Helvetica, sans-serif; background: black; margin: 0; padding: 0; } .container{ display: flex; /* 设置为center即可实现搜索框水平完全居中,无任何margin参与 */ justify-content: center; align-items: center; flex-direction: row; width: 100%; min-height: 60px; } .search-box{ display:inline-block; /* 移除导致错位的transform属性 */ background: #2f3640; height: 40px; border-radius: 40px; padding: 10px; } .search-box:hover > .search-txt { width: 240px; padding: 0 6px; } .search-btn{ color: #53e3f8; float: left; width: 40px; height: 40px; border-radius: 50%; background: #2f3640; display: flex; justify-content: center; align-items: center; text-decoration: none; } .search-txt{ border: none; background: none; outline: none; float: right; padding: 0; color: white; font-size: 16px; transition: 0.4s; line-height: 40px; width: 0px; } </style> </head> <body> <nav class="container"> <div class="search-box"> <input class="search-txt" type="text" name="" placeholder="Search..."> <a class="search-btn" href="#"><i class="fas fa-search"></i></a> </div> </nav> </body> </html>
注意:如果导航栏后续需要恢复
space-between布局适配左右两侧元素,只需要保证搜索框两侧的占位元素设置flex: 1,即可自动让搜索框停在容器水平居中位置,依然不需要给搜索框加任何margin。
内容的提问来源于stack exchange,提问作者Vidit Aggarwal
相关产品推荐
相关产品推荐

