Search code examples
javascripthtmlcssreactjsreactstrap

Setting fixed th widths in Reactstrap table


I am creating a table using the Table attribute in Reactstrap. When I create the table and enter values for my th columns, the width of each column is different, with some being very wide and others way too narrow. Can I adjust the table headers so that the column widths are adjustable or all the same width?

<Table hover className="text-sm">
   <thead>
      <tr>
         <th>Features</th>
         <th>HDHP</th>
         <th>PPO 15</th>
         <th>PPO 20</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <th scope="row">Plan Design</th>
         <td>
            Deductible-based plan. 100% covered (excluding
            prescription Drug copays) once deductible is
            met.
         </td>
         <td>Copay-based plan without a deductible.</td>
         <td>
            Copay-based plan without a deductible, with
            lower premiums than the PPO 15 but higher
            out-of-network costs.
         </td>
      </tr>
      <tr>
         <th scope="row">Premium (Bi-Weekly)</th>
         <td>
            Employee: $31.99
            <br />
            Employee + One: $75.66
            <br />
            Employee + Family: $95.02
         </td>
         <td>
            Employee: $71.98
            <br />
            Employee + One: $163.36
            <br />
            Employee + Family: $205.15
         </td>
         <td>
            Employee: $53.32
            <br />
            Employee + One: $122.83
            <br />
            Employee + Family: $154.25
         </td>
      </tr>
   </tbody>
</Table>

Solution

  • Depending on how messy you're ok with it getting, there are a few options.

    First, let me point out that it's natural for tables to have columns of varying sizes and you rarely get a better look out of them by equalizing their widths. With that said, here is how to accomplish what you want.

    1. Bootstrap/Reactstap has classes for popular width percents (e.g. 25% 50% etc). So if you know that your table will always have 4 columns for example, you can give your ths the appropriate classes:
    <tr>
       <th className={"w-25"}>Features</th>
       <th className={"w-25"}>HDHP</th>
       <th className={"w-25"}>PPO 15</th>
       <th className={"w-25"}>PPO 20</th>
    </tr>
    
    1. You could simply use JSX's inline styling for an arbitrary number of columns. So here is how to equalize the width of 3 columns:
    <tr>
        <th style={{width: "33%"}}>Features</th>
        <th style={{width: "33%"}}>HDHP</th>
        <th style={{width: "33%"}}>PPO 15</th>
    </tr>
    

    I never recommend inline styling, but if you're bent on getting this done, you could go that route.