Search code examples
htmlcsscss-positionvertical-alignment

When to use position absolute vs position relative when vertically aligning with css


Originally I followed this article which used position: relative on the child element: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

http://codepen.io/anon/pen/KpWKWg

But I couldn't get it to work on my code for the life of me:

http://jsfiddle.net/ge77ma0e/


Then I found these instructions which use position: absolute on the child element: https://css-tricks.com/centering-css-complete-guide/#vertical-block-unknown

http://codepen.io/chriscoyier/pen/lpema

And when I tried it on my code it finally worked:

http://jsfiddle.net/y2ajtmks/

Any good explanations?


Solution

  • You miss display: block; on .valign. The transform element as it seems should be applied to a block element, not inline. Here is the documentation:

    CSS Transforms Module Level 1 - Terminology - Transformable Element

    A transformable element is an element in one of these categories:

    • an element whose layout is governed by the CSS box model which is either a block-level or atomic inline-level element, or whose display property computes to table-row, table-row-group, table-header-group, table-footer-group, table-cell, or table-caption
    • an element in the SVG namespace and not governed by the CSS box model which has the attributes transform, ‘patternTransform‘ or gradientTransform.

    Also if you need to center only verticaly (and not horizontaly), change you transforms to:

    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);