I want to ensure my loading spinner is always centered when used, in a table, a button, …
.th-loader {
.progress {
top: calc(50% - (var(--loading-indicator-border)/2));
left: calc(50% - (var(--loading-indicator-border)/2));
width: var(--loading-indicator-border);
aspect-ratio: 1;
background: #006edb;
border-radius: 50%;
transform: rotate(0deg) translateY(calc((var(--loading-indicator-size) * -0.5) + (var(--loading-indicator-border) * 0.5)));
animation: spin 1s infinite linear;
&.mini{
--loading-indicator-size: 24px;
--loading-indicator-border: 4px;
}
}
@keyframes spin {
to{transform: rotate(360deg) translateY(calc((var(--loading-indicator-size) * -0.5) + (var(--loading-indicator-border) * 0.5)))}
}
.progress:after {
position: absolute;
content: '';
width: var(--loading-indicator-size);
aspect-ratio: 1;
top: 0%;
left: 50%;
translate: -50% 0;
background: conic-gradient(transparent 10%, #006edb);
border-radius: 50%;
mask: radial-gradient(transparent calc(((var(--loading-indicator-size) * 0.5) - var(--loading-indicator-border)) - 1px), #006edb calc((var(--loading-indicator-size) * 0.5) - var(--loading-indicator-border)));
}
}
<div>
<button>Click Me</button>
<div class="th-loader">
<div class="progress mini"></div>
</div>
</div>
but the spinner doesn’t stay in the middle relative to other siblings. Any idea if it’s possible to ensure that an element is always centered?
2
Answers
This is the tried-and-tried method for keeping an element in the centre of its parent:
There are many ways to add loader but this works best for me. Its also responsive for all screen sizes.
I have used
position: absolute
withwidth: 100%
andheight: 100vh
which covers entire screen then used flexbox to center the spinner vertically and horizontally both. Finally usedz-index: 100
so that it is above any other UI element.Below is working example.