0

Can someone please provide an explanation as to how the following styling results in text becoming vertically centered? For example, why are we using position: absolute if we're centering relative to a parent? Why is top: 50% being used? Thanks!


    .vertical-center {
        margin: 0;
        position: absolute;
        top: 50%;
        -ms-transform: translateY(-50%);
        transform: translateY(-50%);
    }

Johannes
  • 64,305
  • 18
  • 73
  • 130

1 Answers1

2

position: absolute takes an element out of the document flow and lets you position it in relation to the next higher ancestor which has position: relative, usually (and intentionally) overlapping other elements (for example text over an image).

top: 50% moves the top of the absolutely positioned element 50% down, i.e. half of the parent's height. That way the top border of the child element will be at the exact center of the parent.

transform: translateY(-50%); moves the absolutely positioned element 50% up, but this time 50% of its own height, above the vertical center of the parent element, resulting in exact vertical centering inside the parent.

All this only works if the parent has position: relative, so it can serve as a position anchor for the absolutely positioned child.

The same goes for horizontal centering, using left: 50% and transform: translateX(-50%);

Combined (i.e. horizontally and vertically) that would be top: 50%; left: 50% and transform: translate(-50%, -50%);

Johannes
  • 64,305
  • 18
  • 73
  • 130