When it comes to centering elements, the traditional method of using
.center { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); }
can sometimes result in the centered element not utilizing the full width it should. This approach leaves empty space around the element, causing it to appear smaller than intended.
@proseosoc's solution addresses this issue by extending the centered element to the edges of the viewport, ensuring that it takes up the entire available space. However, this method includes the scrollbar in its centering calculation. If you need to center elements within the viewport excluding the scrollbar, you can use the modified solution provided here. This alternative method aligns elements in the viewport without accounting for the scrollbar, similar to the traditional approach.
Horizontal Centering
.horizontal-center {
position: fixed;
left: calc((50vw - 50%) * -1); /* adjust with a negative value equivalent to half of the scrollbar width, if applicable */
transform: translate(calc(50vw - 50%));
}
Vertical Centering
.vertical-center {
position: fixed;
top: calc((50vh - 50%) * -1);
transform: translate(0, calc(50vh - 50%));
}
Horizontal and Vertical Centering
.center {
position: fixed;
left: calc((50vw - 50%) * -1);
top: calc((50vh - 50%) * -1);
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
}