1

I'm trying to vertically align text in a couple of containers using line-height, but it just won't work. I have never had any problems with it before, but for some reason it just won't line up properly now.

Now, I'm probably just blind from all the coding, but I just can't seem to find where the problem lies...

This is how my HTML looks like:

<div class="formLabel">
    <div class="labelNumber">D</div>
    <div class="labelTitle">
        <h2>New Password</h2>
        <p>Check Help for character and length restrictions</p>
    </div>
</div>

and this is how my CSS looks like:

.formLabel
{
    position: relative;
    width: 400px;
    height: 40px;
    padding: 20px 0px 0px 10px;
    margin: 0;
}

.labelNumber
{
    float: left;
    width: 30px;
    height: 30px;
    line-height: 30px;
    background: #191919;
    font: bold 18px Arial;
    color: #555555;
    text-align: center;
    padding: 0;
    margin: 0;
}

It's the character in the .labelNumber container that I'm trying to vertically align.

Tom
  • 3,290
  • 20
  • 31

2 Answers2

4

The line-height attribute is part of the shorthand font syntax, so put the line-height after it or integrate it into the font attribute.

.labelNumber {
  float: left;
  width: 30px;
  height: 30px;
  background: #191919;
  font: bold 18px/30px Arial; /** Font-size / Line-height */
  color: #fff;
  text-align: center;
  padding: 0;
  margin: 0;
}

Basically the font attribute was overwriting the line-height.

Brandon Wamboldt
  • 15,241
  • 11
  • 49
  • 82
3

The issue with your current code is that the order of your CSS declarations is forcing the browser to forget about the line-height: 30px; declaration, since after it you're using the font short-hand syntax font: bold 18px Arial;.

You can solve your issue with one of two options:

  • Move the line-height: 30px; to after the font: bold 18px Arial;:

    See this working Fiddle Example.

    .labelNumber {
      position: absolute;
      width: 30px;
      height: 30px;
      background: #191919;
      font: bold 18px Arial;
      line-height: 30px;
      color: #555555;
      text-align: center;
      padding: 0;
      margin: 0;
    }
    
  • Loose the line-height: 30px; and update the font short-hand to font: bold 18px/30px Arial;:

    See this working Fiddle Example.

    .labelNumber {
      position: absolute;
      width: 30px;
      height: 30px;
      background: #191919;
      font: bold 18px/30px Arial;
      color: #555555;
      text-align: center;
      padding: 0;
      margin: 0;
    }
    

You can read about the font short-hand syntax here.

As a side note: For the purpose of code reduction, the second option is the preferred one.

Zuul
  • 15,767
  • 6
  • 58
  • 86