You need to enable JavaScript to run this app. 如何在侧边栏(sidebar)旁额外新增两列?现有布局代码无法实现求助
优惠活动
大模型
产品
解决方案
定价
更多

如何在侧边栏(sidebar)旁额外新增两列?现有布局代码无法实现求助

你可以通过flex布局实现侧边栏旁加两列的效果,完整修改后的代码如下:

HTML代码

<!-- 外层布局容器 -->
<div class="layout-wrapper">
  <!-- -------------Navigation Bar------------- -->
  <div class="sidebar">
    <a class="active" href="#home">Home</a>
    <a href="#services">Example 1</a>
    <a href="#portfolio">Example 2</a>
    <a href="#about">Example 3</a>
    <a href="#contact">Example 4</a>
  </div>
  <!-- 第一列内容 -->
  <div class="col">
    <div class="content">
      <h2>第一列内容</h2>
      <p>This example use media queries to transform the sidebar to a top navigation bar when the screen size is 700px or less.
      </p>
      <p>We have also added a media query for screens that are 400px or less, which will vertically stack and center the navigation links.</p>
      <h3>Resize the browser window to see the effect.</h3>
    </div>
  </div>
  <!-- 新增的第二列内容 -->
  <div class="col">
    <div class="content">
      <h2>第二列内容</h2>
      <p>这里是额外新增的第二列的内容区域,可根据需求自定义填充内容</p>
    </div>
  </div>
</div>

CSS代码

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* 外层flex容器,实现侧边栏+两列的横向布局 */
.layout-wrapper {
  display: flex;
  width: 100%;
  min-height: 100vh;
}

/* 侧边栏样式 */
.sidebar {
  width: 200px;
  background-color: #f1f1f1;
  height: 100vh;
  position: sticky;
  top: 0;
}

.sidebar a {
  display: block;
  color: black;
  padding: 16px;
  text-decoration: none;
}

.sidebar a.active {
  background-color: #04AA6D;
  color: white;
}

.sidebar a:hover:not(.active) {
  background-color: #555;
  color: white;
}

/* 内容列通用样式,每列占剩余宽度的一半 */
.col {
  flex: 1;
  padding: 20px;
}

.content {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 700px以下响应式:侧边栏变顶部导航,内容列改为纵向排列 */
@media screen and (max-width: 700px) {
  .layout-wrapper {
    flex-direction: column;
  }
  .sidebar {
    width: 100%;
    height: auto;
    position: relative;
  }
  .sidebar a {
    float: left;
  }
  .col {
    width: 100%;
  }
}

/* 400px以下响应式:导航链接纵向堆叠居中 */
@media screen and (max-width: 400px) {
  .sidebar a {
    text-align: center;
    float: none;
  }
}

核心修改说明

  • 新增.layout-wrapper外层容器,通过flex布局实现侧边栏、两个内容列的横向排列
  • 两个内容列设置flex:1,自动平分侧边栏之外的剩余宽度,实现等宽两列效果
  • 完全保留原有响应式逻辑:屏幕宽度小于700px时侧边栏转为顶部导航,内容列纵向堆叠适配移动端;小于400px时导航链接纵向居中排列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 15:54:03