0

the title pretty much sums it up. I have the following code:

<div class="container">
   <p>Hello world</p>
</div>

And CSS:

.container{
    width: 100%;
    height: 50px;    
    background-color: lightblue;
    vertical-align: middle; /* Why you no work!?!? */
}

But the text is not vertically aligning in the div. I'm clearly missing something here or don't understand a certain concept. Anybody tell me what's happening?

Thanks!

  • possible duplicate of [Vertically Align text in a Div](http://stackoverflow.com/questions/2939914/vertically-align-text-in-a-div) – Madara's Ghost Apr 15 '13 at 12:30
  • It is working, you need to set the line height to see a differance – iConnor Apr 15 '13 at 12:31
  • Do you seriously get some people that as soon as a question is asked goes and checks if someone else already has, and then if so, goes and comments AND posts a link to it and mark the question 'already asked'. LOL WTF –  Apr 16 '13 at 06:46

4 Answers4

2

if you have single line text add this to your css.

.container > p{ line-height:50px; }

Salt Hareket
  • 764
  • 7
  • 18
2

To use vertical-align: middle, you need to use display: inline-block.

Your code will change to this:

.container{
    display: inline-block; /* This is the line you need to introduce */
    width: 100%;
    height: 50px;    
    background-color: lightblue;
    vertical-align: middle;
}

You can take a look at the demo.

Update

Using display: table for .container and display: table-cell for .container p makes it work.

Updated demo

.container{
    display: table;
    width: 100%;
    height: 200px;
    background-color: lightblue;
    vertical-align: middle;
}
.container p {
    display: table-cell;
    vertical-align: middle;
}
Aniket
  • 9,622
  • 5
  • 40
  • 62
  • @Salt That is because `

    ` is not going to move itself due to change in the height. Let me see if this can be done some other way.

    – Aniket Apr 15 '13 at 12:44
1

Vertical alignment in CSS is not as straightforward as horizontal alignment.

Depending on your case and the content you need to apply one technique or another.

You can check this link for different techniques:

http://www.vanseodesign.com/css/vertical-centering/

In short, vertical-align: center; is not going to work in your case

Kenneth
  • 28,294
  • 6
  • 61
  • 84
1

Add to your container the display property as follows:

.container{
    width: 100%;
    height: 50px;    
    background-color: lightblue;
    display:inline-block; 
    vertical-align: middle; 
}
br araujo
  • 1,856
  • 2
  • 13
  • 14