CSS 如何指定表格的高度以显示垂直滚动条?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4457274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to specify table's height such that a vertical scroll bar appears?
提问by Misha Moroshko
I have a table with many rows on my page. I would like to set table's height, say for 500px, such that if the height of the table is bigger than that, a vertical scroll bar will appear. I tried to use CSS height
attribute on the table
, but it doesn't work.
我的页面上有一个包含多行的表格。我想设置表格的高度,比如说500px,这样如果表格的高度大于这个高度,就会出现一个垂直滚动条。我试图在 上使用 CSSheight
属性table
,但它不起作用。
回答by AgentConundrum
Try using the overflow
CSS property. There are also separate properties to define the behaviour of just horizontal overflow (overflow-x
) and vertical overflow (overflow-y
).
尝试使用overflow
CSS 属性。还有单独的属性来定义水平溢出 ( overflow-x
) 和垂直溢出 ( overflow-y
) 的行为。
Since you only want the vertical scroll, try this:
由于您只想要垂直滚动,请尝试以下操作:
table {
height: 500px;
overflow-y: scroll;
}
EDIT:
编辑:
Apparently <table>
elements don't respect the overflow
property. This appears to be because <table>
elements are not rendered as display: block
by default (they actually have their own display type). You can force the overflow
property to work by setting the <table>
element to be a block type:
显然<table>
元素不尊重overflow
属性。这似乎是因为<table>
元素不是display: block
默认呈现的(它们实际上有自己的显示类型)。您可以overflow
通过将<table>
元素设置为块类型来强制该属性工作:
table {
display: block;
height: 500px;
overflow-y: scroll;
}
Note that this will cause the element to have 100% width, so if you don't want it to take up the entire horizontal width of the page, you need to specify an explicit width for the element as well.
请注意,这将导致元素具有 100% 的宽度,因此如果您不希望它占据页面的整个水平宽度,则还需要为元素指定显式宽度。
回答by Dark Falcon
You need to wrap the table inside another element and set the height of that element. Example with inline css:
您需要将表格包裹在另一个元素中并设置该元素的高度。内联 css 示例:
<div style="height: 500px; overflow: auto;">
<table>
</table>
</div>
回答by krupesh Anadkat
to set the height of table, you need to first set css property "display: block" then you can add "width/height" properties. I find this Mozilla Article a very good resource to learn how to style tables : Link
要设置表格的高度,您需要先设置css属性“display:block”,然后您可以添加“width/height”属性。我发现这篇 Mozilla 文章是学习如何设计表格样式的非常好的资源: 链接