Css Centering with Transform
Why Does Centering with Transform Translate and Left 50% Center Perfectly (With Position Relative Parent) but Not Right 50%? Working Example...
why does centering with transform translate and left 50% center perfectly (with position relative parent) but not right 50%?
Working example:
span[class^="icon"] {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Example that doesn't center:
span[class^="icon"] {
position: absolute;
top: 50%;
right: 50%;
transform: translate(-50%, -50%);
}
2 Answers
Because translateX(-50%) moves something back to the left 50% (because of the - negative value), which means it pairs with left: 50%; to center something.
If you want to use right: 50%; then use that with translateX(50%) to center.
* {margin:0;}
span {
position: absolute;
top: 50%; right: 50%;
transform: translate(50%,-50%);
background: black;
color: white;
}
body:after, body:before {
content: '';
position: absolute;
background: red;
}
body:after {
top: 50%;
left: 0; right: 0;
height: 1px;
}
body:before {
left: 50%;
top: 0; bottom: 0;
width: 1px;
}
<span>center me</span>
From what I understand, top: and left: actually mean how far the object's top edge is from the top of its container (container refers to the closest parent element with a relative position) and how far the object's left edge is from the left of its container. Specifically, top: 50% means that the object is shifted by 50% of the container's height and left: 50% means the object is shifted 50% of the container's width.
Once the origin of the element is at the center, you can see that by shifting the element to the left by half of its width and up by half of its height, the center of the object will be at the origin rather than its upper left corner.
If we did right: 50% instead, then the right side of the element would be shifted from the right side of the container by 50% of the container's width, meaning that its upper-right edge is on the origin. Therefore, by shifting it to the right by 50% of its width and up by 50% of its height (transform(50%, -50%)), we will center the object.