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%);
}
If you want to center something horizontally in CSS you can do it just by, using the text-align: center; (when working with inline elements) or margin: 0 auto; (when working with block element).
Use transform: translate(-50%, -50%) to negate its position, so that it is vertically and horizontally centered.
Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.
The -50% transform basically means, in simple words, "move this element left and upwards by 50% of the computed dimension along the axis". -50% along the x-axis means "move me leftwards by half my computed width", likewise for that in the y-axis.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With