TD column width value not working with fixed table

2020-04-02 09:21发布

I have following table structure:

<table class="tableStyle">
<tr>
    <td width="20px">col1</td>
    <td width="50px">col2</td>
    <td width="50px">col3</td>
    <td width="15px">col4</td>
    <td width="25px">col5</td>
    <td width="20px">col6</td>
    <td width="20px">col7</td>
    <td width="20px">col8</td>
</tr>
</table>

CSS class definition is:

.tableStyle{
table-layout:fixed;
margin: 0 auto; width: 960px;
}

The problem is that all columns are displaying with equal width despite the fact that i am explicitly defining each column width.

Why are above width values are not working? Any suggestion to make it work with fixed table layout?

标签: html css
7条回答
Melony?
2楼-- · 2020-04-02 09:51

Instead of putting the width on the td, try adding it to the th using css.

For example,

HTML

<table>
    <tr>
        <th class="column-1">Heading 1</th>
        <th class="column-2">Heading 2</th>
        <th class="column-3">Heading 3</th>
    </tr>
    <tr>
        <td>TD 1</td>
        <td>TD 2</td>
        <td>TD 3</td>
    </tr>
</table>

CSS

.column-1 {
    width: 50%;
}
.column-2 {
    width: 25%;
}
.column-3 {
    width: 25%;
}

I had the exact same problem and found this resource helpful:

https://css-tricks.com/fixing-tables-long-strings/

查看更多
登录 后发表回答