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

如何让内容区块位于flex-direction为column的导航Flex容器右侧?

解决Flex布局中主内容位于导航栏下方的问题

当前布局的核心问题是 .content-body未启用Flex布局,内部的导航容器和主内容区域默认是块级元素,会垂直堆叠,导致主内容出现在导航栏下方。以下是具体的修复方案:


修改后的完整代码

CSS 代码

/* 全局样式重置:消除浏览器默认边距,避免布局错位 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.flex-container-1 {
  display: flex;
  background-color: skyblue;
  color: white;
  width: 100%;
  position: sticky; /* 可选:滚动时固定标题栏在顶部 */
  top: 0;
}

.flex-body-1 {
  padding: 1em;
}

.content-body {
  display: flex; /* 关键:启用Flex布局,让内部元素水平排列 */
  background-color: skyblue;
  color: white;
  padding: max(1em, 2vh);
}

.flex-body-1:hover {
  background-color: white;
  color: skyblue;
}

.nav-container {
  display: flex;
  flex-direction: column;
  width: 10em;
  margin-right: 2em; /* 导航与主内容之间的间距 */
}

.nav-items {
  width: 10em;
  padding: 0.5em 0; /* 增加导航项点击区域 */
}

.nav-items:hover {
  background-color: white;
  color: skyblue;
}

.main-content {
  flex: 1; /* 让主内容占据剩余所有空间 */
}

HTML 代码

<html>
<head>
  <link rel="stylesheet" href="flex-2.css">
</head>
<body>
  <div class="flex-container-1">
    <div class="flex-body-1">Home</div>
    <div class="flex-body-1">About</div>
    <div class="flex-body-1">Contact</div>
  </div>
  <div class="content-body">
    <div class="nav-container">
      <div class="nav-items">Item 1</div>
      <div class="nav-items">Item 2</div>
      <div class="nav-items">Item 3</div>
      <div class="nav-items">Item 4</div>
      <div class="nav-items">Item 5</div>
    </div>
    <div class="main-content">
      <h1>Main content</h1>
      <p>This is the main page of information that I want to display on my page.</p>
      <p>IT should sit to the right of the nav elements which should go along the left side of the page.</p>
    </div>
  </div>
</body>
</html>

关键修改说明

  1. .content-body添加display: flex:直接让导航容器和主内容区域水平排列,解决垂直堆叠问题。
  2. .main-content设置flex: 1:确保主内容自动填充导航栏右侧的所有可用空间,适配不同屏幕宽度。
  3. 全局样式重置:消除浏览器默认的边距和内边距,避免页面出现不必要的空白区域。
  4. 标题栏优化:添加width: 100%和position: sticky,让标题栏占满屏幕顶部,滚动时保持可见(可选功能)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:53:22