Reputation: 4988
In the following table I require in th tags to see their content in the opposite ends
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
text-align: left;
padding: 10px;
border: 1px solid #ddd;
}
<table>
<thead>
<tr>
<th><span>Col 1</span>^</th>
<th><span>Col 2</span>^</th>
<th><span>Col 3</span>^</th>
<th><span>Col 4</span>^</th>
</tr>
</thead>
<tbody>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
</tbody>
</table>
When trying to do it using flex I get unexpected behavior
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
text-align: left;
padding: 10px;
border: 1px solid #ddd;
}
/* here is the change */
th {
display: flex;
justify-content: space-between;
}
<table>
<thead>
<tr>
<th><span>Column 1</span>^</th>
<th><span>Column 2</span>^</th>
<th><span>Column 3</span>^</th>
<th><span>Column 4</span>^</th>
</tr>
</thead>
<tbody>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
</tbody>
</table>
The expected result is obtained but the headers lose their position
What is the correct way to use flex in table headers?
Upvotes: 0
Views: 103
Reputation: 942
Giving display:flex
to th will make it lose its table sturcture,Because by default all th are display: table-cell;
so changing that is not recommended
This is what you mean?
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
text-align: left;
padding: 10px;
border: 1px solid #ddd;
}
.d-flex{display:flex;}
.ml-auto{margin-left:auto;}
<table>
<thead>
<tr>
<th>
<div class="d-flex">Column 1
<div class="ml-auto">^</div>
</div>
</th>
<th>
<div class="d-flex">Column 1
<div class="ml-auto">^</div>
</div>
</th>
<th>
<div class="d-flex">Column 1
<div class="ml-auto">^</div>
</div>
</th>
<th>
<div class="d-flex">Column 1
<div class="ml-auto">^</div>
</div>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
<td>Item 4</td>
</tr>
</tbody>
</table>
Upvotes: 1