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

ReactJS实现搜索框紧邻Logo无大间距并居中导航栏的方法

问题描述

我尝试将搜索框设置在Logo图片旁,使其位于导航栏样式区域的中央,但不明原因导致搜索框出现在页面右上角。

React代码

const Home = () => {
  return (
    <>
      <header>
            <div className='container-fluid'>
                <div className='row'>
                   <div className='sm2'>
                      <img src={logo} alt=''/>
                   </div>
                   <div className='search-box'>
                      <i><Fas.FaSearch/></i>
                      <input type='text' placeholder='Hit Enter'/>
                   </div>
                </div>
            </div>
      </header>
    </>
  )
}

export default Home

问题CSS代码

header{
    width: 100%;
    height: 80px;
}

header .row {
    width: 100%;
    display:flex;
    align-items: center;
    justify-content: space-between;
    background-color: #E6E6FA;
    
}

img{
    width: 20%;
}

.search-box{
  width: 100%;
  text-align: center;
}

问题效果:搜索框位于页面右上角,与Logo之间存在较大间距。


解决建议

核心问题分析

.row的justify-content: space-between会将子元素分别推到容器两端,这是搜索框跑到右上角的直接原因;同时.search-box设置width:100%会占满剩余空间,进一步加剧布局异常。

具体调整方案

  1. 修正Flex布局对齐规则
    把.row的justify-content从space-between改为center,同时添加gap控制Logo和搜索框的间距:

    header .row {
        width: 100%;
        display:flex;
        align-items: center;
        justify-content: center; /* 替换原space-between */
        gap: 1rem; /* 自定义Logo与搜索框的间距 */
        background-color: #E6E6FA;
        height: 80px; /* 继承header的高度,避免内容溢出 */
    }
    
  2. 调整搜索框宽度与布局
    移除.search-box的width:100%,设置合适的宽度,并优化内部元素对齐:

    .search-box{
      width: 50%; /* 按需调整,比如占容器宽度的一半 */
      display: flex;
      align-items: center;
      border: 1px solid #ddd;
      border-radius: 4px;
      padding: 0.4rem 0.8rem;
      background-color: #fff;
    }
    .search-box input {
      flex: 1;
      border: none;
      outline: none;
      background: transparent;
      margin-left: 0.5rem;
    }
    
  3. 优化Logo容器与尺寸
    避免Logo因百分比宽度过大,固定其尺寸并确保容器不被压缩:

    .sm2 {
        flex-shrink: 0; /* 防止Logo容器被压缩 */
    }
    img{
        width: 80px; /* 固定Logo宽度,按需调整 */
        height: auto;
    }
    

调整后,Logo与搜索框会在导航栏中央并排显示,布局符合预期。


内容的提问来源于stack exchange,提问作者Ismael Sanchez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 17:20:56