HTML table: column width percentage

前端 未结 2 2081
时光取名叫无心
时光取名叫无心 2021-02-02 08:36

I have a table with 7 columns. I want the columns to be of the following widths:

  • 3 columns x width=20%
  • 4 columns x width=10%
相关标签:
2条回答
  • 2021-02-02 09:01

    To fixe width, you can use table-layout:fixed; .

    You may also want to use the colgroup and col tags to assign at once width and bg to your columns.

    table {
      width: 100%;
      table-layout: fixed;
    }
    .ten {
      width: 10%;
      background: tomato;
    }
    .twenty {
      width: 20%;
      background: turquoise
    }
    /* see me */
    td {
      border: solid;
    }
    /* play with bg cells and cols ? */
    
    tr:nth-child(even) :nth-child(odd) {
      background:rgba(100,255,50,0.3);
      }
    tr:nth-child(odd) :nth-child(even) {
      background:rgba(255,255,255,0.3);
      }
    <table>
      <colgroup>
        <col class="ten" />
        <col class="ten" />
        <col class="ten" />
        <col class="twenty" />
        <col class="twenty" />
        <col class="twenty" />
        <col class="ten" />
      </colgroup>
      <tr>
        <th>H1</th>
        <th>H2</th>
        <th>H3</th>
        <th>H4</th>
        <th>H5</th>
        <th>H6</th>
        <th>H7</th>
      </tr>
    
      <tr>
        <td>A1</td>
        <td>A2</td>
        <td>A3</td>
        <td>A4</td>
        <td>A5</td>
        <td>A6</td>
        <td>A7</td>
      </tr>
    
      <tr>
        <td>B1</td>
        <td>B2</td>
        <td>B3</td>
        <td>B4</td>
        <td>B5</td>
        <td>B6</td>
        <td>B7</td>
      </tr>
     <tr>
        <td>A1</td>
        <td>A2</td>
        <td>A3</td>
        <td>A4</td>
        <td>A5</td>
        <td>A6</td>
        <td>A7</td>
      </tr>
    
      <tr>
        <td>B1</td>
        <td>B2</td>
        <td>B3</td>
        <td>B4</td>
        <td>B5</td>
        <td>B6</td>
        <td>B7</td>
      </tr>
    
    </table>

    0 讨论(0)
  • 2021-02-02 09:20

    Your CSS works as expected, in a way that the widths of the table heads and cells are correct. However:

    th by default have text-align: center applied, while the td element has not.

    So you should add either to the td or th the same text alignment. E.g.:

    th {
        text-align: left;
    }
    
    0 讨论(0)
提交回复
热议问题