When working with hero images or full screen anything, I typically see text or images with the following bit of css:
.item { top: 50%; left: 50%; transform: translate(-50%, -50%); }
Can someone explain to me what this code is actually doing?
transform-origin changes the point at which the element transforms rather than moving the entire element (as translate would). The default value is transform-origin: 50% 50%; .
An introduction to transform and translate CSS transform is a powerful tranformation property. By using its various functions, you can scale, rotate, skew, or translate HTML elements. One of the most commonly used functions is CSS translate which allows you to move elements.
The transform property applies a 2D or 3D transformation to an element. This property allows you to rotate, scale, move, skew, etc., elements.
The transform CSS property lets you rotate, scale, skew, or translate an element. It modifies the coordinate space of the CSS visual formatting model.
The reason why transform: translate(-50%, -50%)
is required is because you want the center of the element to line up with the center of its parent. In simple terms, it can be boiled down to translateX(-50%) translateY(-50%)
, which means:
This effectively moves the center of the element to its original top left corner. Remember than when you set left: 50%; top 50%
on the element, you are moving its top left corner to the center of its parent (which means it is not visually centered at all). By moving the element back leftwards and upwards by half of its width and height respectively, you sure that its center now aligns with the parent's center, making it visually horizontally + vertically centered.
As a proof-of-concept, see the code snippet below: hover over the parent to cause the child element's "ghost" to reposition itself by means of transform: translate(-50%, -50%)
:
body { margin: 0; padding: p; } .parent { background-color: #ccc; width: 100vw; height: 100vh; position: relative; } .child { background-color: rgba(0,0,255,0.5); width: 50px; height: 50px; position: absolute; top: 50%; left: 50%; } .child::before { background-color: rgba(255, 0, 0, 0.5); position: absolute; top: 0; left: 0; width: 50px; height: 50px; content: ''; transition: all .5s ease-in-out; } body:hover .child::before { transform: translate(-50%, -50%); }
<div class="parent"> <div class="child"></div> </div>
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