'Bootstrap 5 table equal column width

Is there any way to force all the columns inside a bootstrap table to have the same width ? By default it seems to give a larger size to elements that have more content but I'd like all of them to share the same width. Here's my code:

<table class="table table-hover">
<thead>
<tr>
    <th scope="col">#</th>
    <th scope="col">All</th>
    <th scope="col">Selected</th>
    <th scope="col">1</th>
    <th scope="col">12.5</th>
    <th scope="col">301</th>
    <th scope="col">405.88</th>
    <th scope="col">77</th>
</tr>
</thead>
<tbody id="table-body">
<tr>
    <th scope="row">123456</th>
    <td class="table-danger"></td>
    <td class="table-success"></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
</tr>
</tbody>

The "selected" column ends up being much larger than the rest since it's more text, even though there's enough space to keep all columns using the same width.

I would like to avoid using the "col-x" classes if possible since my columns are generated dynamically and i can easily end up with more than 12 columns.



Solution 1:[1]

Add a class to your "td" and specify their size in css.

Define your table size may also be necessary.

table {
  table-layout: fixed;
  width: your_size px;
}

Solution 2:[2]

No extra CSS is required. You could put all of the Columns inside a single Row and then use the row-cols class. What this does is, instead of dictating a class on each Column for its width, you dictate the width of all Columns using a class in the parent Row.

The code below says whatever happens only put 2 Columns on each Row but you can change 2 to anything between 1 and 12.

<div class="row row-cols-2">
    <div class="col">
      <!-- Content 1 -->
    </div>
    <div class="col">
      <!-- Content 2 -->
    </div>
    <div class="col">
      <!-- Content 3 -->
    </div>    
    <div class="col">
      <!-- Content 4 -->
    </div>

    <!-- Add as many columns as you want -->

</div>

Also, somebody may correct me here but I am fairly certain that adding the row or col class to your table elements is going to make a real struggle when it comes to layout.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SuperRem
Solution 2