1

以下 HTML 代码在固定宽度的 div 内创建了一个表格。似乎“th,td”宽度是从父 div 继承的(但 W3 文档说它不是继承属性!)。

如何增加表格列的宽度(比如 500 像素)?

您可以看到更改“th, td”选择器中的宽度值对宽度没有任何影响。

请注意:
- 我不想更改 div 的宽度
- 我不想为我的表格设置固定宽度
- 我尝试过“table-layout:fixed;” 内表选择器。它没有使“td,th”宽度属性起作用。

<!DOCTYPE html>
<html>

    <head>
        <style>
            table {
                border-collapse:collapse;
            }
            table, td, th {
                border:1px solid black;
            }
            th, td {
                /* Changing width doesn't make any difference */
                width:500px;
            }
            .myclass {
                width:200px;
                overflow:auto
            }
        </style>
    </head>

    <body>
        <div class="myclass">
            <table>
                <tr>
                    <th>Firstname</th>
                    <th>Lastname</th>
                    <th>Savings</th>
                    <th>Expenditure</th>
                </tr>
                <tr>
                    <td>Peter</td>
                    <td>Griffin</td>
                    <td>$100</td>
                    <td>$50</td>
                </tr>
            </table>
        </div>
    </body>

</html>
4

2 回答 2

2

为什么不使用百分比?

jsfiddle:http: //jsfiddle.net/qCYDq/

您也将自己的宽度限制为 200 像素,如果表格内的文本(字宽)大于您的 200 像素,它将强制其宽度,然后导致您的滚动条出现,因为表格将拉伸以适合文字。

<!DOCTYPE html>
<html>
<head>
<style>
table {
    border-collapse:collapse;
    width: 100%;
    font-size: 9px;
}
td,th { 
    border:1px solid black;
    width: 25%;
}
.myclass
{
    width:200px;
    overflow:auto
}
</style>
</head>
<body>    
<div class="myclass">
    <table>
        <tr>
           <th>Firstname</th>
           <th>Lastname</th>
           <th>Savings</th>
           <th>Expenditure</th>
        </tr>
        <tr>
           <td>Peter</td>
           <td>Griffin</td>
           <td>$100</td>
           <td>$50</td>
        </tr>
    </table>
</div>
</body>
</html>
于 2013-08-28T11:42:21.690 回答
1

最后,让它工作!

"table-layout:fixed; width:100%" 成功了...

<!DOCTYPE html>
<html>

<head>
    <style>
        table {
            border-collapse:collapse;
        }
        table, td, th {
            border:1px solid black;
        }
        th, td {
            /* Changing width doesn't make any difference */
            width:500px;
        }
        .myclass {
            width:200px;
            overflow:auto
        }
    </style>
</head>

<body>
    <div class="myclass">
        <table>
            <tr>
                <th>Firstname</th>
                <th>Lastname</th>
                <th>Savings</th>
                <th>Expenditure</th>
            </tr>
            <tr>
                <td>Peter</td>
                <td>Griffin</td>
                <td>$100</td>
                <td>$50</td>
            </tr>
        </table>
    </div>
</body>

</html>
于 2013-08-29T12:07:36.733 回答