20

I want to create image box(with image).
It's ugly when text is in the top of box.

How can I align text to middle?
I tried to use vertical-align, but it seems, that it don't works

Demo of my code

EDIT:
Your solution works fine with short messages.
But if they will be multi-lined, it is ugly again.
Is it possible to not increase size of line If we don't need it?

enter image description here

RiaD
  • 42,649
  • 10
  • 67
  • 110

3 Answers3

8

If you want to middle align a block with multiple lines, you can use display:inline-block around that block. So if you have:

<div class="messageInfo">
   <div class="messageInner">You are logged out<br>You are crazy<br> gogo</div>
</div>

with

.messageInfo{
    background: lightskyblue;
    background-image: url(http://i.stack.imgur.com/Z6lkS.png) ;
    background-repeat: no-repeat;
    min-height: 32px;
    vertical-align: middle;
    padding-left:32px;
    line-height:32px;
}

add

.messageInner {
    display:inline-block;
    line-height:1.2em;
    vertical-align:middle;
}

See http://jsfiddle.net/yNpRE/1/ and http://jsfiddle.net/yNpRE/

Be warned though, that while this works in modern browsers, it doesn't work with IE7 or earlier.

Alohci
  • 70,004
  • 12
  • 103
  • 143
6

What usually works fine is line-height:

line-height: 32px;

http://jsfiddle.net/DhHnZ/2/

Niko
  • 25,682
  • 7
  • 85
  • 108
  • 1
    Works fine with 1-line messages. But is it possible to not increase its size if it will multilined? Example: jsfiddle.net/mRbgq – RiaD Sep 24 '11 at 22:51
  • If you expect multiple lines, I would recommend using `padding-top: 8px; padding-bottom: 8px;` instead of the line-height thing. (font-size: 16px + 8px above + 8px below = 32px total height) – Niko Sep 24 '11 at 23:01
  • See http://jsfiddle.net/mRbgq/2/ – Niko Sep 24 '11 at 23:13
2

Set the line-height to the height of the div.

So

.messageInfo{
    background: lightskyblue;
    background-image: url(http://i.stack.imgur.com/Z6lkS.png) ;
    background-repeat: no-repeat;
    min-height: 32px;
    vertical-align: middle;
    padding-left:32px;
    line-height:32px; //ADD THIS
}

Working example: http://jsfiddle.net/jasongennaro/DhHnZ/1/

Jason Gennaro
  • 32,917
  • 6
  • 59
  • 84
  • 1
    Works fine with 1-line messages. But is it possible to not increase its size if it will multilined? Example: http://jsfiddle.net/mRbgq/ – RiaD Sep 24 '11 at 22:50