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;
...
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%;
...
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%);
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)