Green Files

What's the best way to center an element vertically and horizontally?

Day: 06/02/2022 - Time: 11:04:17

What's the best way to center an element vertically and horizontally? By best we mean with the greatest possible compatibility between browsers and the simplest possible, to position an element in the center of the page, vertically and horizontally and regardless of resolution using only CSS.

The best solution is the one that fits many problems. And this is still relative as the problem may be compatibility or even a fixed height cannot be determined.

The most compatible solution is not necessarily the best, as compatibility is often just a matter of time. The best solution will depend on the project and how compatible it must be, especially when it comes to vertical alignment.

Therefore, I will restrict myself to presenting two great solutions, without determining which is the best.

1. position

As it is compatible with less modern browsers, this might be the most suitable solution in the overview:

position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto;

Requires fixed height

2. translateY

position: relative; top: 50%; transform: translateY(-50%);

Support: IE9+

Does not require fixed height

Reference:

https://pt.stackoverflow.com/questions/2817/qual-a-melhor-forma-de-centralizar-um-elemento-vertical-e-horizontalmente

GO UP
GO TO INDEX