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条回答
我命由我不由天
2楼-- · 2020-04-02 09:36

You should the attribute width without the unit px. Probably there are some modern browsers that accept the attribute with the units, but is not the correct way!

You have a similar issue in this another Stackoverflow case:

查看更多
迷人小祖宗
3楼-- · 2020-04-02 09:40

Seems like works as intended for me. please check the below fiddle.

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

http://jsfiddle.net/9x56E/

查看更多
劫难
4楼-- · 2020-04-02 09:45

The width property does not support px for td, if you want to write the width in px, you need to provide css as below

<td style="width: 20px">
查看更多
forever°为你锁心
5楼-- · 2020-04-02 09:49

The "archaic" width attribute does not take a unit, it expects something like width="20".

However, the "most correct" way to define a table is like so:

<table>
    <colgroup>
        <col style="width:20px" />
        <col style="width:50px" span="2" />
        <col style="width:15px" />
        <col style="width:25px" />
        <col style="width:20px" span="3" />
    </colgroup>
    <tbody>
        <tr>
            <td>col1</td>
            <td>col2</td>
            <td>col3</td>
            <td>col4</td>
            <td>col5</td>
            <td>col6</td>
            <td>col7</td>
            <td>col8</td>
        </tr>
    </tbody>
</table>

This works especially well for large tables, because the browser only needs to read the <colgroup> element to know exactly how the entire table should be laid out, without needing to calculate widths based on individual cell styles.

查看更多
时光不老,我们不散
6楼-- · 2020-04-02 09:50

suggest such an option

HTML

<table class="tableStyle">
<tr>
    <td>col1</td>
    <td>col2</td>
    <td>col3</td>
    <td>col4</td>
    <td>col5</td>
    <td>col6</td>
    <td>col7</td>
    <td>col8</td>
</tr>
</table>

CSS

.tableStyle{
table-layout:fixed;
margin: 0 auto; width: 960px;
  background: #ddd;
}
td:nth-child(1n) {
  width: 20px;
  background: #876342;
}
td:nth-child(3n+1) {
  width: 100px;
}

demo

查看更多
家丑人穷心不美
7楼-- · 2020-04-02 09:51

You have to use:

<td width="20">

or

<td style="width: 20px">
查看更多
登录 后发表回答