Styling tables with CSS: column width is not correct

table, thead, tbody {
    width: 100%;
}

table, th, tr, td {
    border: 1px solid #000;
    border-collapse: collapse;
}

td {
   width: 25% !important;
}
<table>
    <thead>
        <th>
            <td>ID</td>
            <td>Nome da conta</td>
            <td>Titular</td>
            <td>Saldo</td>
        </th>
    </thead>
    <tbody>
     ...
    </tbody>
</table>

I have a table with four columns and I want them all the same width, i.e., each one occupying 25% of the table.

It happens that my columns are not taking 25% of the table width each, as I assumed they would. Even when I apply the !important.

enter image description here

Upvotes: 1

Views: 58

Answers (3)

user9674579
user9674579

Reputation:

table {
  table-layout: fixed;
  width : 100% ;
}
td {
  text-align : center ;
  width: 25%;
}
<table border = "10">
    <tr>
      <td>Some Text</td>
      <td>Another Text</td>
      <td>Some Another Text</td>
      <td>A Very Long Text</td>
    </tr>
</table>

Upvotes: 0

felixmosh
felixmosh

Reputation: 35573

You didn't used the semantic tags in a correct manner. In thead tag you must have tr and th as it's children.

Then you can apply {width: 25%;} on the th

table,
thead,
tbody {
  width: 100%;
}

table,
th,
tr,
td {
  border: 1px solid #000;
  border-collapse: collapse;
}

th {
  width: 25% !important;
}
<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Nome da conta</th>
      <th>Titular</th>
      <th>Saldo</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Upvotes: 2

Paulie_D
Paulie_D

Reputation: 115296

With table-layout: fixed

table {
  table-layout: fixed;
  width: 100%;
}

table,
th,
tr,
td {
  border: 1px solid #000;
  border-collapse: collapse;
}

td {
  width: 25%;
}
<table>

  <tbody>
    <tr>
      <td>ID</td>
      <td>Nome da conta</td>
      <td>Titular</td>
      <td>Saldo</td>
    </tr>
  </tbody>
</table>

Upvotes: 1

Related Questions