DEV Community 👩‍💻👨‍💻

Ali Bahaari
Ali Bahaari

Posted on

How to make an object center that doesn't have `static` position in CSS?

Sometimes you may have asked yourself the question above. It's so simple which I want to explain.

Consider you have a div tag along with these CSS properties:

width: 50px;
height: 50px;
background-color: #000;
...
Enter fullscreen mode Exit fullscreen mode

The code above is simple and I'm sure if you've experienced CSS, you can understand it.

I add more to the code above:

position: absolute;
top: 50%;
left: 50%;
...
Enter fullscreen mode Exit fullscreen mode

The article is suitable for non-static position. It may consist of relative, absolute and fixed positions. Thus, you must specify the position property with the values above to be correctly worked.

top: 50% and left: 50% properties work simply and they make the object center vertically and horizontally... . But!
The aligning coordinates are start against properties you have used.

Until now, If you've checked the code above, you may have noticed the object is slightly to the right of its parent and if you use right: 50% instead of left: 50%, you may notice the object is slightly to the left of the parent and not exactly center. Even for top and bottom this phenomenon occurs.

So there should be miracle here to fix the code! Use the code below and check it again:

transform: translate(-50%, -50%);
Enter fullscreen mode Exit fullscreen mode

Boom! It works nicely and correctly. Why!?
The value of the transform property works based on objects' width and height and the slight movement talked before will be covered and makes the object center exactly.

Use and enjoy!

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.