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

如何在不使用绝对定位的情况下调整导航栏搜索框与汉堡按钮的左右布局?

解决方案:Flex布局实现搜索栏左对齐、汉堡按钮右对齐(无absolute/float)

针对需求,我们可以通过调整Flex布局属性实现效果,无需使用absolute或float,具体修改如下:

核心修改思路

  1. 在移动端(max-width:768px)默认状态下,将导航栏flex-direction从column改回row,通过justify-content: space-between让搜索栏和汉堡按钮分别靠左右两侧排列
  2. 修正导航链接的隐藏规则,确保仅保留搜索栏与汉堡按钮
  3. 在导航展开的.nav.responsive状态下,恢复flex-direction:column让链接垂直排列,同时用align-self:flex-end让汉堡按钮保持靠右对齐
  4. 微调搜索栏的内边距与宽度,适配移动端显示

修改后的完整CSS代码

.nav {
  background-color: #FFC000;
  text-align: center;
  display: flex;
  padding: 10px;
}

.nav a {
  flex: 1;
  display: block;
  color: white;
  text-decoration: none;
  font-size: 18px;
  margin: auto;
  border-radius: 4px;
  padding: 5px;
}

.nav form {
  flex: 5;
  line-height: 0px;
  margin: auto;
}

.nav form input {
  font-size: 15px;
  border: 1px solid grey;
  width: 80%;
  background: #f1f1f1;
  margin: auto;
  border-radius: 8px;
  padding: 5px;
}

.nav form button {
  width: 15%;
  background: #2196F3;
  color: white;
  font-size: 15px;
  border: 1px solid grey;
  border-left: none;
  cursor: pointer;
  margin: auto;
  border-radius: 8px;
  padding: 5px;
}

.nav form button:hover {
  background: #0b7dda;
}

.nav a:hover {
  background-color: #FAD5A5;
}

.nav .icon {
  display: none;
}

/* 媒体查询修改部分 */
@media (max-width: 768px) {
  .main {
    flex-direction: column;
  }
  .header {
    flex-direction: column;
  }
  /* 修改默认导航布局为横向,两端对齐 */
  .nav {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
  /* 隐藏除汉堡按钮外的所有导航链接 */
  .nav a:not(.icon) {
    display: none;
  }
  .nav a.icon {
    display: block;
  }
  /* 展开后的导航恢复垂直布局 */
  .nav.responsive {
    flex-direction: column;
    align-items: flex-start;
  }
  /* 让汉堡按钮在展开状态下靠右对齐 */
  .nav.responsive .icon {
    align-self: flex-end;
    margin-top: 10px;
  }
  .nav.responsive a {
    display: block;
    text-align: left;
    width: 100%;
    margin: 5px 0;
  }
  /* 调整搜索栏在移动端的宽度 */
  .nav form {
    flex: 0 1 70%;
  }
  .nav form input {
    width: 75%;
  }
}

代码说明

  • justify-content: space-between:让flex容器内的元素自动分布在两端,实现搜索栏左、汉堡按钮右的效果
  • align-self:flex-end:在垂直布局的容器中,让汉堡按钮单独靠右对齐,替代原来的absolute定位
  • 调整.nav form的flex属性:限制搜索栏在移动端的宽度,避免挤压汉堡按钮
  • 修正链接隐藏选择器:确保仅保留汉堡按钮,避免错误隐藏元素

内容的提问来源于stack exchange,提问作者Brian Serrano

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:35:18