【问题标题】:Cannot make DIV width 100% with scrollbar无法使用滚动条使 DIV 宽度为 100%
【发布时间】:2026-01-01 09:25:02
【问题描述】:

我有一个包含 DIV 和 TABLE 的页面。 DIV 是我的标题,即使显示水平滚动条,我也希望它是 100% 宽度。由于某种原因,它只占用了可见窗口的 100%。

我的 HTML 代码是:

<!DOCTYPE html>
<html lang="en">
<body>

    <div style="background-color:yellow;">100% DIV</div>

    <table style="width:100%; background-color:orange;">
        <thead>
            <tr>
                <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_1</th>
                <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_2</th>
                <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_3</th>
            </tr>
        </thead>
    </table>

</body>
</html>

当我向右滚动时,DIV 不会使用所有宽度:

如何使 DIV 占据页面宽度的 100%?理想情况下,我不想更改 TABLE,因为它是生成的代码。

【问题讨论】:

  • 您是在 IE 中进行测试,还是只是您喜欢的浏览器?
  • @HunterTurner - 它也发生在 Chrome 中
  • 不适用于 IE、Chrome、FF 和 Apple Safari。

标签: html css


【解决方案1】:

没有办法(完全动态地——不固定任何宽度——并且使用纯 CSS——没有 JavaScript)让块级元素通过块级继承兄弟块级元素的宽度父元素。

解决方法是将display: inline-block 放在父元素上,因为内联块从其最宽的子元素计算其width 属性。

在您的情况下,不要display: inline-block 放在body 元素上。我建议将您的 100% divtable 元素包装在另一个包装器元素中,因此:

<!DOCTYPE html>
<html lang="en">
<body>
  <div class="wrapper" style="display: inline-block; min-width: 100%;">
    <div style="background-color:yellow;">100% DIV</div>
    <table style="width:100%; background-color:orange;">
      <thead>
        <tr>
          <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_1</th>
          <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_2</th>
          <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_3</th>
        </tr>
      </thead>
    </table>
  </div>
</body>
</html>

此外,将min-width: 100% 放在包装元素上会使其在更大的屏幕尺寸上模仿带有display: block 的元素。

【讨论】:

    【解决方案2】:

    实际上table 标记已溢出,因此请尝试将100% 赋予其父级以及div。 如果它不起作用,请给我一个 jsfiddle url

    【讨论】: