CSS Centering with Transform

norkuy picture norkuy · Feb 8, 2017 · Viewed 61.3k times · Source

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

Answer

Michael Coker picture Michael Coker · Feb 8, 2017

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>