Search code examples
csspaddingspacing

Center text in div?


I have a div 30px high and 500px wide. This div can contain two lines of text one under the other, and is styled (padded) accordingly. But sometimes it only contains one line, and I want it to be centered. Is this possible?


Solution

  • You may try to use in your CSS the property vertical-align in order to center it verticaly

    div {  
        vertical-align:middle;  
    }
    

    if it's a size problem, please notice that 2 text lines and a padding style have great chance to have a height superior to 30px.

    For example, if your font size is 12 px and your div padding is 5 px, a one text line div height will be 5px (padding-top) + 12px + 5 px (padding-bottom) = 22px < 30px so no problem,

    With a 2 text lines div, it will be 5px +12px *2 (2 lines) + 5px = 34px > 30px and your div height will be automatically changed.

    Try either to increase your div height (maybe 40px) or to reduce your padding.

    Hope it will help