I'm trying to center this element on the screen, also when I hover.
In the example below, the div is not centered, even when I hover it, knowing that I have a 50% transform and the top/left is also transformed, this is what I use to center the element Commonly used methods.
* { box-sizing: border-box; } body { position: relative } .zoom { padding: 50px; background-color: green; transition: transform .2s; width: 200px; height: 200px; margin: 0 auto; transform: scale(.2) translate(-50%, -50%); position: absolute; top: 50%; left: 50%; } .zoom:hover { -ms-transform: scale(1.5); /* IE 9 */ -webkit-transform: scale(1.5); /* Safari 3-8 */ transform: scale(1.5); }
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div class="zoom"></div> </body> </html>
The error is in the
:hover
selector because there is notranslate()
in the transform, you are basically resetting it to 0, which is not what you want. Because it will forget the previous content and overwrite it.Here’s a simple solution:
❌
✅
Here’s a simple explanation:
Modern solution (less code):
Using CSS Grid https://developer.mozilla.org/ en-US/docs/Web/CSS/grid
Use
place-items
It will automatically center without any transform or position... https://developer.mozilla.org/en-US/docs/Web/CSS/place -itemsAlso, you don't have to scale
0.2
at the beginning, just start withscale(1)
and make it larger by hovering for a larger scale, For example4
. (So without any hover it won't produce that error at the beginning of the transition from 200px to 0.2scale)However, if you want the CSS to work in IE and older browsers, it's better to use position, pan, top, left...
But your users are using modern browsers, so for better readability and simplicity it might be a good idea to use Flexbox or Grid.
For more information, use https://caniuse.com (e.g. Grid is 95% supported in any browser starting in 2020, Chrome starting in 2017)
Here is the CSS grid solution
Remember that the order of transformations determines how elements are displayed. You start by moving the element
By putting the translation first, the element willtop: 50%; left: 50%;
, placing it in the lower right quadrant. Then you make it smallertransform:scale(0.2)
thenThenyou move it to the left now smaller sizetranslate(-50%, -50%)# 50% of ##.
be centered before becoming smaller. Remember, when you increase the size, also include translate(-50%, -50%)
as subsequent translations will
overwrite the current translation instead of being added to in.