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

如何在Tailwind CSS中实现导航栏搜索栏的响应式宽度适配?

导航栏搜索栏响应式宽度问题解决

问题描述

我有一个包含logo、搜索栏、登出按钮和头像的导航栏,已实现logo居左、登出按钮与头像居右、搜索栏居中的布局。现需让搜索栏在屏幕从移动端到平板再到桌面端时逐步变宽。

我尝试在移动端使用grid-cols-3,在640px及以上使用sm:grid-cols-4,并给logo设置sm:col-span-1、搜索栏设置sm:col-span-2、登出按钮与头像设置sm:col-span-1。搜索框(input)已添加w-full类,但搜索栏并未如预期变宽,完整代码如下:

<body>
  <nav class="bg-gray-700">
    <div class="grid grid-cols-3 sm:grid-cols-4">
      <div class="pt-3 pb-2.5 ml-5 sm:col-span-1">
        <a href="#"><img src="images/logo.svg" alt="logo" class="w-50 h-7"></a>
      </div>

      <div class="flex mt-[2px] sm:col-span-2">
        <form class="flex h-9">
          <div class="">
            <input type="text" placeholder="Search.." class="text-base mt-2 p-1.5 rounded-l h-7 bg-white w-full">
          </div>
          <button type="submit" class="text-sm cursor-pointer rounded-r mt-2 px-2 bg-blue-600">
            <i class="fa fa-search relative top-[0.75px]"></i>
          </button>
        </form>
      </div>

      <div class="mt-1 flex flex-row-reverse sm:col-span-1">
        <div class="mt-2 mr-5 ml-2 relative bottom-[2px]">
          <a href="logout.php" class="text-sm underline text-white">Logout</a>
        </div>
        <img src="https://api.lorem.space/image/face?w=150&h=150" alt="profile picture" class="w-10 h-10 rounded-full mt-[1px]">
      </div>
    </div>
  </nav>
</body>

解决方案

核心问题是搜索栏的外层容器和表单没有占满所在网格列的宽度,导致输入框的w-full无法发挥作用。修改点如下:

  • 给搜索栏的外层div添加w-full,让它撑满网格分配的空间
  • 给表单form添加w-full,确保表单宽度继承父容器的100%
  • 给网格添加gap-2控制元素间距,让布局更合理
  • 给右侧元素容器添加items-center,让头像和登出按钮垂直居中

修改后的完整代码:

<body>
  <nav class="bg-gray-700">
    <div class="grid grid-cols-3 sm:grid-cols-4 gap-2">
      <div class="pt-3 pb-2.5 ml-5 sm:col-span-1">
        <a href="#"><img src="images/logo.svg" alt="logo" class="w-50 h-7"></a>
      </div>

      <div class="flex mt-[2px] sm:col-span-2 w-full">
        <form class="flex h-9 w-full">
          <div class="flex-1">
            <input type="text" placeholder="Search.." class="text-base mt-2 p-1.5 rounded-l h-7 bg-white w-full">
          </div>
          <button type="submit" class="text-sm cursor-pointer rounded-r mt-2 px-2 bg-blue-600">
            <i class="fa fa-search relative top-[0.75px]"></i>
          </button>
        </form>
      </div>

      <div class="mt-1 flex flex-row-reverse sm:col-span-1 items-center">
        <div class="mr-5 ml-2">
          <a href="logout.php" class="text-sm underline text-white">Logout</a>
        </div>
        <img src="https://api.lorem.space/image/face?w=150&h=150" alt="profile picture" class="w-10 h-10 rounded-full">
      </div>
    </div>
  </nav>
</body>

额外优化:给输入框的外层div添加flex-1,确保它能占满表单的剩余空间,和提交按钮完美衔接。

内容的提问来源于stack exchange,提问作者Tibo Mertens

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:07:16