line-height as a percentage not working

line-height: 100% means 100% of the font size for that element, not 100% of its height. In fact, the line height is always relative to the font size, not the height, unless its value uses a unit of absolute length (px, pt, etc).


I know this question is old, but I found what for me is the perfect workaround.

I add this css to the div that I want to center:

div:before {
  content: "";
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

This works every time and it is clean.

Edit: Just for completion's sake, I use scss and I have a handy mixin that I include on every parent who's direct children I want to have vertically centered:

@mixin vertical-align($align: middle) {
  &:before {
    content: "";
    display: inline-block;
    height: 100%;
    vertical-align: $align;
    // you can add font-size 0 here and restore in the children to prevent
    // the inline-block white-space to mess the width of your elements
    font-size: 0;
  }
  & > * {
    vertical-align: $align;
    // although you need to know the font-size, because "inherit" is 0
    font-size: 14px;
  }
}

Full explanation: div:before will add an element inside the div, but before any of its children. When using :before or :after we must use a content: declaration otherwise nothing will happen, but for our purpose, the content can be empty. Then we tell the element to be as tall as its parent, as long as its parent's height is defined and this element is at least inline-block. vertical-align defines the vertical position of self related to parent, as opposed to text-align that works differently.

The @mixin declaration is for sass users and it would be used like this:

div {
    @include vertical-align(middle)
}

Tags:

Css