skip to Main Content

I would like to make th and td both 100% width by only manupulating css.
It seems like th stretches out far but never fully to push out the td.
What’s wrong with this code?

.custom-table {
  display: grid;
  width: 100%;
  table-layout:fixed;
}

.custom-table th,
.custom-table td {
  width: 100%;
  border: 1px solid black; /* Just for visualization */
  text-align: center; /* Center the content */
  padding: 5px;
}
<table class="custom-table">
<tbody>
  <tr>
    <th>name</th>
    <td>Alex</td>
  </tr>
  </tbody>
  
  <tbody>
  <tr>
    <th>Age</th>
    <td>30</td>
  </tr>
  </tbody>
</table>

2

Answers


  1. To achieve your goal of having both <th> and <td> elements take up 100% of the width, you might need to rethink your approach. Instead of using a percentage-based width, you could try something like this:

    .custom-table {
      width: 100%;
      border-collapse: collapse; /* Merge cell borders */
    }
    
    .custom-table th,
    .custom-table td {
      border: 1px solid black; /* Just for visualization */
      text-align: center; /* Center the content */
      padding: 5px;
    }
    
    /* Distribute available width evenly among table cells */
    .custom-table th {
      width: 50%;
    }
    
    .custom-table td {
      width: 50%;
    }
    <table class="custom-table">
      <tbody>
        <tr>
          <th>name</th>
          <td>Alex</td>
        </tr>
        <tr>
          <th>Age</th>
          <td>30</td>
        </tr>
      </tbody>
    </table>
    Login or Signup to reply.
  2. if you want both "th" and "td" elements take up 100% just give display: flex; and flex-direction: column; on "tr" then it will take 100% width.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search