无法使带有滚动条的DIV宽度100%

10
我有一个包含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占据整个页面宽度?理想情况下,我不想改变表格,因为它是生成的代码。

你是在IE浏览器中测试还是那只是你偏好的浏览器? - Hunter Turner
@HunterTurner - 这也发生在Chrome浏览器中。 - j08691
在IE、Chrome、FF和Apple Safari中都无法工作。 - Vad
2个回答

12
没有办法(完全动态-不修复任何宽度-使用纯CSS-没有JavaScript)通过块级父元素来继承同级块级元素的宽度。
解决方法是在父元素上放置"display: inline-block",因为inline-block从其最宽的子元素计算其"width"属性。
在您的情况下,不要将"display: inline-block"放在"body"元素上。我建议将您的"100% div"和"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 的元素。


1

实际上 table 标签溢出了,所以尝试给其父元素和 div 设置 100%。 如果不起作用,请提供 jsfiddle 的 URL。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接