我有一个包含 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,因为它是生成的代码。
最佳答案
没有办法(完全动态地——不固定任何宽度——并且使用纯 CSS——没有 JavaScript)让 block 级元素通过 block 级元素继承兄弟 block 级元素的宽度父元素。
解决方法是将 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
的元素。
关于html - 无法使用滚动条使 DIV 宽度为 100%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33904792/