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

React布局:如何让主内容Div宽度填充页面剩余空间?

解决React侧边栏与主内容重叠问题

问题根源是当前LeftSidebar、RightSidebar和主内容Main为同级元素,没有被布局容器约束,导致主内容默认占满视口宽度,覆盖在侧边栏下方。以下是两种常用的解决方法:

方法一:Flexbox布局(推荐)

通过Flex容器控制三个元素的排列,让主内容自动填充剩余空间。

1. 修改App组件结构,添加布局容器

import React from 'react'
import LeftSidebar from './components/sidebar/LeftSidebar'
import Main from './Pages/Main'
import RightSidebar from './components/sidebar/RightSidebar'

import { BrowserRouter, Route, Routes } from 'react-router-dom'

import "../src/styles/global.css"
const App = () => {
  return (
    <BrowserRouter>
      {/* 新增布局容器,包裹侧边栏和主内容 */}
      <div className="app-container">
        <LeftSidebar />
        <Routes>
            <Route path='/' element={<Main />}/>
        </Routes>
        <RightSidebar />
      </div>
    </BrowserRouter>
  )
}

export default App

2. 在global.css中添加容器和侧边栏样式

/* 全局布局容器 */
.app-container {
  display: flex;
  width: 100vw;
  height: 100vh;
}

/* 左侧侧边栏样式(替换为你实际的类名) */
.left-sidebar {
  width: 200px; /* 自定义侧边栏宽度 */
  flex-shrink: 0; /* 防止侧边栏被压缩 */
}

/* 右侧侧边栏样式(替换为你实际的类名) */
.right-sidebar {
  width: 180px; /* 自定义侧边栏宽度 */
  flex-shrink: 0; /* 防止侧边栏被压缩 */
}

3. 调整主内容样式(Main.module.css)

.mainSection {
  flex: 1; /* 占据容器剩余所有空间 */
  background-color: #1e1e1e;
  height: 100vh;
  overflow-x: hidden;
  overflow-y: auto; /* 内容过长时允许纵向滚动 */
}

方法二:Grid布局

利用Grid的列分配特性,直接指定各区域宽度。

1. 修改global.css中的容器样式

.app-container {
  display: grid;
  /* 左侧宽度、中间自适应、右侧宽度 */
  grid-template-columns: 200px 1fr 180px;
  width: 100vw;
  height: 100vh;
}

2. 主内容样式无需额外修改

保持原Main.module.css即可,Grid会自动为中间列分配剩余空间。

注意事项

  • 确保侧边栏的类名与你组件中根元素的类名完全匹配。
  • 若侧边栏需动态调整宽度,可将固定宽度改为flex-basis(Flex方案)或调整grid-template-columns的参数(Grid方案)。
  • 不要给主内容设置固定宽度,依赖flex:1或1fr实现自适应填充。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:10:43