CSS 使表格列占用尽可能多的空间,而其他列占用尽可能少的空间
我需要用 CSS 布局 html 数据表。
表的实际内容可能有所不同,但始终有一个主列和 2 个或更多其他列。 我想让主列占用尽可能多的宽度,无论其内容如何,而其他列占用尽可能小的宽度。 我无法指定任何列的确切宽度,因为它们的内容可能会发生变化。
如何仅使用简单的语义有效的 html 表和 css 来做到这一点?
例如:
| Main column | Col 2 | Column 3 | <------------------ fixed width in px -------------------> <------- as wide as possible ---------> Thin as possible depending on contents: <-----> <-------->
I need to layout a html datatable with CSS.
The actual content of the table can differ, but there is always one main column and 2 or more other columns. I'd like to make the main column take up as MUCH width as possible, regardless of its contents, while the other columns take up as little width as possible. I can't specify exact widths for any of the columns because their contents can change.
How can I do this using a simple semantically valid html table and css only?
For example:
| Main column | Col 2 | Column 3 | <------------------ fixed width in px -------------------> <------- as wide as possible ---------> Thin as possible depending on contents: <-----> <-------->
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我远不是 CSS 专家,但这对我有用(在 IE、FF、Safari 和 Chrome 中):
然后在 HTML 中:
I'm far from being a CSS expert but this works for me (in IE, FF, Safari and Chrome):
Then in your HTML:
我没有成功使用
width: 100%;
,因为似乎没有具有固定宽度的容器 div,这将无法获得预期的结果。 相反,我使用类似下面的东西,它似乎给了我最好的结果。这样,如果需要,它可以变得更大,而且浏览器似乎会将所有额外的空间分配给以这种方式设置的任何列。 不确定它是否适用于每个人,但在 chrome 中对我有用(没有尝试过其他)......值得一试。
I've not had success with
width: 100%;
as it seems that without a container div that has a fixed width this will not get the intended results. Instead I use something like the following and it seems to give me my best results.This way it can get larger if it needs to, and it seems that the browser will give all the extra space to whichever column is set this way. Not sure if it works for everyone but did for me in chrome (haven't tried others)... worth a shot.
与 Alexk 的解决方案类似,但根据您的情况可能更容易实现:
如果您想避免换行,您可能还需要对单元格应用
white-space:nowrap
。Similar to Alexk's solution, but possibly a little easier to implement depending on your situation:
You might also want to apply
white-space:nowrap
to the cells if you want to avoid wrapping.