0

I am trying center text vertically and I use trick with translate.

HTML

<div class="first">
    <div class="second">
        <span>TESTING</span>
    </div>
</div>

CSS

div.first > div.second {
   border: 1px solid red;
   height: 2em;
}

div.first > div.second > span{
   position: relative;
   top: 50%;
   transform: translateY(-50%);
}

Why the text isn't vertical center?Fiddler

I notice when I change height css property to line-height text started center.

Can someone explain me why this working like that?

user1297783
  • 193
  • 1
  • 1
  • 9

2 Answers2

0

A span is not a block element. Note that if you add display:block to your CSS, it will vertically align.

div.first > div.second > span{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  display: block;
}

Or you could change your span to a div.

terrywb
  • 3,740
  • 3
  • 25
  • 50
  • This article has a nice summary of block vs inline: http://stackoverflow.com/questions/9189810/css-display-inline-vs-inline-block – terrywb Aug 28 '14 at 22:40
0

The correct way to have an element vertically center is to,

Set the effective div's position to absolute width a top value of 50% and set the parent's position to relative.

Example:

div.first > div.second {
    position: relative;
}
div.first > div.second > span {
    position: absolute;
    top: 50%;
}

DEMO

height vs line-height

  • height is the vertical measurement of a container.
  • line-height is the distance from top of the first line to the top of the second line.

Since you have only one line of text here you are seeing it middle of the container. Try adding another line of text and you will understand clearly.

Community
  • 1
  • 1
aniskhan001
  • 7,981
  • 8
  • 36
  • 57