I have a table with a loading spinner that is displayed when the data is being fetched. The loading spinner is placed inside the tbody tag, but it is only centered in the first column of the table instead of being centered in the whole row. How can I center the loading spinner in the middle of the table row?
.table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 8px;
text-align: left;
border: 1px solid #ccc;
}
th {
background-color: #f2f2f2;
font-weight: bold;
cursor: pointer;
}
.loading .spinner {
border: 4px solid #f3f3f3;
/* Light grey */
border-top: 4px solid #3498db;
/* Blue */
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
<table class="table">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<!--<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
<tr>
<td>Data 4</td>
<td>Data 5</td>
<td>Data 6</td>
</tr>-->
<tr>
<td colspan="3" class="loading">
<div class="spinner"></div>
</td>
</tr>
</tbody>
</table>
I've tried:
.loading {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
But always center it in first column!
Simply use margin: auto
:
.loading .spinner {
margin: 0 auto;
}
For the flex
– center
– center
incantation to work, it needs to be applied to the flex container, which is td.loading
. However, since <td>
elements are displayed as table-cell
by default, overriding that would not be a choice.
Try it:
.table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 8px;
text-align: left;
border: 1px solid #ccc;
}
th {
background-color: #f2f2f2;
font-weight: bold;
cursor: pointer;
}
.loading .spinner {
margin: auto;
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
<table class="table">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3" class="loading">
<div class="spinner"></div>
</td>
</tr>
</tbody>
</table>