使用Flexbox实现标题与搜索框并排显示失败问题排查
问题分析与解决方案
嘿,我来帮你揪出问题根源!你现在的核心问题是没给nav元素本身设置Flex布局——你只给搜索区域的容器flex-display加了display: flex,但nav的子元素(标题header和搜索容器flex-display)默认是块级元素,会自动上下堆叠,再加上nav固定了70px高度,直接把搜索区域挤到容器外面去啦。
具体修正步骤
1. 把nav改成Flex容器
将nav的display: inline-block替换成display: flex,这样它的两个子元素就能并排显示。同时添加align-items: center,让所有子元素垂直居中,甚至可以去掉标题的line-height:70px,用Flex布局来实现更灵活的垂直对齐。
2. 分配剩余空间给搜索区域
给flex-display添加flex: 1,让它占据nav中除标题外的所有剩余空间,这样搜索栏就能自适应可用宽度,不会溢出容器。
3. 清理冗余样式
去掉搜索栏和图标上的vertical-align: super,因为Flex的align-items:center已经能实现完美的垂直居中了。
修改后的完整代码
CSS 代码
* { margin: 0; padding: 0; font-family: 'Dosis', sans-serif; } a { text-decoration: none; } nav { height: 70px; width: 100%; background-color: #5DA0E8; display: flex; /* 关键修改:将nav设为flex容器 */ align-items: center; /* 垂直居中所有子元素 */ gap: 20px; /* 标题与搜索区域的间距 */ padding: 0 20px; /* 左右内边距,避免内容贴边 */ } nav .header { font-size: 30px; color: white; /* 移除line-height,靠flex的align-items实现垂直居中 */ } nav .searchbar { background-color: #4170A3; font-size: 18px; padding: 8px 12px; /* 增加内边距,提升输入体验 */ border: none; border-radius: 5px 0 0 5px; color: white; flex: 1; /* 让搜索栏占满父容器剩余空间 */ } input:focus { outline: none; } #search-icon { width: 18px; height: 18px; padding: 8px; background-color: #4170A3; border-radius: 0 5px 5px 0; cursor: pointer; } nav .flex-display { display: flex; flex: 1; /* 让搜索容器占据nav剩余空间 */ align-items: center; }
HTML 代码
<nav> <span class="header">PLANS DU BAC</span> <div class="flex-display"> <input type="search" class="searchbar" placeholder="搜索内容..." /> <img src="./ressources/media/search-icon.svg" alt="搜索图标" id="search-icon" /> </div> </nav>
额外优化说明
- 用
gap属性控制元素间距,比手动加margin更简洁直观。 - 给搜索栏添加
placeholder提示文字,提升用户体验。 - 把
font-family统一放到全局样式里,避免重复设置。
内容的提问来源于stack exchange,提问作者Miloertas
相关产品推荐
相关产品推荐

