1

我想制作一个 HTML 表格。假设它有 3 列。我希望第一列的宽度是固定的,其他两列根据可用空间和它们之间的比例进行扩展/收缩。

这一切都可以通过为第一列设置固定大小的宽度并为其他两列使用百分比来完成。但我想要更难的东西。

我希望浏览器自己找出宽度。

我希望它获得列的理想宽度,然后使其成为列的固定宽度。浏览器无需查看文本并找到宽度,只需获取文本的自然宽度并将其设置为列宽。

这是在 GUI 布局网格中相当常见的事情,您可以让某些列具有固定大小。大小由列内容的大小自动确定。布置固定大小的列后剩余的空间将用于非固定大小的列。

有没有办法在 HTML/CSS 中做到这一点?

请注意,JavaScript 在这里不是一个选项(它在一个 wiki 中,我不想在那里介绍 JavaScript)。

4

1 回答 1

-1

这并不太难,但除非您定义它,否则它没有内容的确切大小。有了这个table,你会看到中间的列是最宽的:

<table width="100%" cellpadding="0" cellspacing="0" style="border:none;">
    <tr>
        <td width="150" valign="top">This is a fixed width column, it's only 50 pixels wide</td>
        <td valign="top">This is a variable width column that has a lot of content</td>
        <td valign="top">This is also a variable width column as well</td>
    </tr> 
</table>

如果交换中间单元格和最后一个单元格的内容,您会看到内容宽度随内容而变化。

<table width="100%" cellpadding="0" cellspacing="0" style="border:none;">
    <tr>
        <td width="150" valign="top">This is a fixed width column, it's only 50 pixels wide</td>
        <td valign="top">This is also a variable width column as well</td>
        <td valign="top">This is a variable width column that has a lot of content</td>
    </tr> 
</table>

现在,您还可以通过将表格嵌套在具有固定宽度的单元格中来解决此问题。在下一个示例中,它是中心列。这样,您可以让最后一列的宽度增加并占用空间。

<table width="100%" cellpadding="0" cellspacing="0" style="border:none;">
    <tr>
        <td width="150" valign="top">This is a fixed width column, it's only 50 pixels wide</td>
        <td valign="top">
            <table width="130" cellpadding="0" cellspacing="0" style="border:none;">
                <tr>
                    <td>This is a fixed width table's content inside of a nested table</td>
                </tr>
            </table>
        </td>
        <td valign="top">This is a variable width column that has a lot of content and should push the boundaries</td>
    </tr> 
</table>

有了这些,您就有了一些策略来处理表格中的流动内容。

* * -- 更新 -- **

也许我读错了,对不起。

表格总是从最宽的单元格中获取列宽。如果您有几行内容的宽度不同,则列都将继承列中最宽的单元格宽度。因此,要使表格的列固定宽度,您要么需要具有固定宽度的内容,要么将内容包装在固定宽度的元素中。

gMail、Google Reader 和许多在线电子邮件客户端使用类似的方法在左侧有一个固定宽度的导航,并让渲染区域随着用户的浏览器而增长。

<table width="100%" cellpadding="0" cellspacing="0" style="border:none;">
    <tr>
        <td valign="top">
            <table width="50" cellpadding="0" cellspacing="0" style="border:none;">
                <tr>
                    <td>This is a fixed width column, it's only 50 pixels wide</td>
                </tr>
            </table>
        </td>
        <td valign="top">
            <table width="130" cellpadding="0" cellspacing="0" style="border:none;">
                <tr>
                    <td>This is a fixed width table's content inside of a nested table</td>
                </tr>
            </table>
        </td>
        <td valign="top">This is a variable width column that has a lot of content and should push the boundaries</td>
    </tr> 
</table>

他们通常在 CSS 中执行此操作,但使用这种方法您无需定义表格单元格的宽度。他们只会从内容中继承他们的宽度。第三列的内容没有固定的宽度,将随着用户的网络浏览器宽度而增长并且是流动的。

于 2013-03-17T13:35:11.477 回答