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

CSS+HTML布局中侧边栏与主内容无法并排显示问题求助

问题根源

  • 你给.sidenav设置的是position: relative,该属性下元素仍会占据正常文档流的整块宽度,后续的.main元素会被挤到侧边栏下方,你设置的margin-left: 160px只会让主内容整体向右偏移160px,并不会和上方的侧边栏并列。

解决方案

方案1:固定侧边栏(滚动页面时侧边栏常驻左侧)

直接修改.sidenav的定位属性即可,修改后的对应CSS代码:

.sidenav{
height: 100%;
width: 160px;
position: fixed; /* 仅把原来的relative改成fixed即可 */
z-index: 1;
top: 0;
left: 0;
background-color: rgba(0,0,0,0.5);
overflow-x: hidden;
padding-top: 20px;
}

方案2:弹性布局(侧边栏跟随页面滚动,适配性更强)

第一步:修改HTML结构,在外层新增父容器

<!-- 新增外层父容器 -->
<div class="page-container">
  <div class="sidenav">
    <a href="">Latest Blog Posts</a>
    <a href="">Why You are more successful than you think</a>
  </div>
  <div class="main">
    <div class="content">
      <div class="card">
        <h1 style="font-size: 50px;">Submit!</h1>
        <p style="font-size: 20px">Thank you for considering working with 
DaddyChill and submitting!<br>Submitting your notes will mean that 
you've helped someone with their highschool test!<br> If you want to 
submit just click the link below!<br>
      </div> 
    </div>
  </div>
</div>

第二步:新增对应CSS规则

.page-container {
  display: flex;
  width: 100%;
}
/* 删掉原有.main里的margin-left:160px属性,替换为flex:1 */
.main{
  flex: 1;
  font-size: 28px;
  padding: 1px 10px;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:15:08