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

嵌套Div无法显示1-200完整数字列表:CSS高度与滚动属性困惑

嵌套Div无法显示1-200完整数字列表:CSS高度与滚动属性困惑

嘿,我来帮你拆解一下这个问题!你遇到的数字从86才开始显示的情况,核心原因是CSS的垂直居中设置和滚动容器的布局冲突了,咱们一步步来解决:

问题根源分析

你的.col2设置了justify-content: space-between,而里面的.nested又加了justify-content: center。当.nested里塞了200个<p>标签时,它的内容高度会远超过自身的可视高度,这时候justify-content: center会把整个内容块垂直居中——这就导致前面的1-85被“顶”到了容器的可视区域上方,超出了范围,所以你只能从中间的86开始看到内容。

另外还有个小细节:你用document.write来生成内容,虽然能工作,但这种方式在现代前端里不太推荐(比如如果页面加载完成后调用会覆盖整个页面),不过这次的核心问题还是布局逻辑。

解决方案

我们只需要调整.nested的布局属性,去掉垂直居中的设置,让内容从顶部开始排列,同时确保滚动容器的高度设置正确:

  1. 把.nested里的justify-content: center删掉,换成align-items: center(如果你需要文字水平居中的话),或者直接保留默认的flex-start(内容从顶部开始)。
  2. 确保.col2的高度设置正确,因为它是flex容器,子元素.nested的height:100%才能正确继承。

修改后的CSS代码如下:

body,
html {
  margin: 0;
  padding: 0;
  height: 100vh;
}

body {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  background-color: yellow;
}

.col1 {
  height: 100%;
  overflow-y: auto;
  width: 20%;
  min-width: 5rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: rgba(0, 255, 242, 0.5);
}

.col2 {
  height: 100%;
  width: 80%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  background-color: rgba(0, 0, 255, 0.5);
}

.nested {
  height: 100%;
  width: 60%;
  overflow-y: scroll;
  display: flex;
  flex-direction: column;
  /* 去掉垂直居中,让内容从顶部开始排列 */
  align-items: center; /* 保留水平居中,不需要的话可以删掉 */
  background-color: rgb(157, 255, 0);
}

另外推荐把document.write换成更安全的DOM操作方式,避免潜在的页面覆盖问题:

<div class="col1" id="col1">
  <!-- Left column div with numbers 1 to 200 -->
</div>
<div class="col2">
  <!-- Right column div with nested div containing numbers 1 to 200 -->
  <div class="nested" id="nested">
  </div>
</div>

<script>
// 生成左侧数字
const col1 = document.getElementById('col1');
for (let i = 1; i <= 200; i++) {
  const p = document.createElement('p');
  p.textContent = i;
  col1.appendChild(p);
}

// 生成右侧嵌套数字
const nested = document.getElementById('nested');
for (let i = 1; i <= 200; i++) {
  const p = document.createElement('p');
  p.textContent = i;
  nested.appendChild(p);
}
</script>

这样修改后,你就能看到嵌套div里从1到200的完整数字,滚动条也能正常工作啦!

备注:内容来源于stack exchange,提问作者Moeen Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 10:04:37