Transform: translate(-50%, -50%)

Viewed 106352

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?

2 Answers

TL;DR version

let's say, there is a .container and an .item inside

this code below is positioning .item relatively to .container; meaning .item top left corner is in the center of it's container

.item {
  top: 50%;
  left: 50%;
}

while below is positioning .item relatively to it's own width and height; meaning minus 50% of it's width and height

.item {
  transform: translate(-50%, -50%);
}

if two code below combined, then the expected center will show up

Related