带搜索框的CSS响应式导航栏图标位置调整及搜索表单改造问题
解决方案
核心修改说明
- 将原独立搜索input替换为标准form表单结构,新增type为submit的按钮,按钮内置Font Awesome搜索图标作为提交触发控件
- 修复小屏断点下汉堡菜单图标位置错误问题:将原小屏下的左浮动改为右浮动,适配导航栏右侧布局
- 补充搜索表单、提交按钮的配套样式,保证和原有导航风格统一,大小、交互效果和周边元素对齐
修改后完整HTML代码
<header id="logo"></header> <div class="navbar" id="nav"> <a href="https://klia2.co" class="active">Home</a> <a href="../facilities/index.htm">Facilities</a> <a href="../airlines/index.htm">Airlines Offices</a> <!-- 替换为form结构的搜索框 --> <form class="search-form" action="" method="get"> <input type="text" placeholder="Search.." name="search"> <button type="submit" class="search-btn"><i class="fa fa-search"></i></button> </form> <a href="javascript:void(0);" class="icon" onclick="myFunction()"> <i class="fa fa-bars"></i> </a> </div> <script> function myFunction() { var x = document.getElementById("nav"); if (x.className === "navbar") { x.className += " responsive"; } else { x.className = "navbar"; } } </script>
修改后完整CSS代码
.navbar { overflow: hidden; background-color: #0000ff; } .navbar a { float: left; display: block; color: white; text-align: center; padding: 14px 14px; text-decoration: none; font-size: 17px; height: 18px; } .active { background-color: #0033CC; color: white; } .navbar .icon { display: none; } .navbar a:hover, .search-btn:hover { background-color: #dddddd; color: black; } /* 搜索表单配套样式 */ .search-form { float: right; margin-top: 3px; margin-right: 5px; } .navbar input[type=text] { padding: 12px; border: none; float: left; } .search-btn { float: left; padding: 12px 15px; background: #0000ff; color: white; border: none; cursor: pointer; font-size: 17px; } .search-btn:hover { background: #dddddd; color: black; } @media screen and (max-width: 600px) { .navbar a, .navbar .search-form { display: none; } /* 汉堡图标改为右浮动,显示在右侧 */ .navbar a.icon { float: right; display: block; } } @media screen and (max-width: 600px) { .navbar.responsive {position: relative;} .navbar.responsive .icon { position: absolute; right: 0; top: 0; } .navbar.responsive a { float: none; display: block; text-align: left; } .navbar.responsive .search-form { float: none; display: block; width: 90%; margin: 0 auto; } .navbar.responsive input[type=text] { width: 75%; border: 2px solid black; } .navbar.responsive .search-btn { width: 20%; } }
效果验证
- 桌面端:搜索框和搜索按钮组合显示在导航栏右侧,交互悬停效果和导航其他元素统一
- 移动端(宽度小于600px):汉堡菜单图标显示在导航栏最右侧,点击展开后菜单列表、搜索表单依次垂直排列,搜索功能可正常提交
内容的提问来源于stack exchange,提问作者sexy18
相关产品推荐
相关产品推荐

