无法使用滚动条使 DIV 宽度为 100%

2023-11-23

我有一个带有 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%?理想情况下,我不想更改表,因为它是生成的代码。


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

解决方法是把display: inline-block在父元素上,因为内联块会计算其width来自其最宽子代的财产。

就你而言,don't put display: inline-block on the body元素。我建议包裹你的100% div and table另一个包装元素中的元素,因此:

<!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在较大的屏幕尺寸上。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法使用滚动条使 DIV 宽度为 100% 的相关文章