33

I am trying to vertically align to the middle both an image and some text within a list element but having no luck.

eg:

<ul>
 <li><img src="somepath" /> sometext
  </li>
<li><img src="somepath2" /> sometext2
  </li>
</ul>

how can i do it? thanks

raklos
  • 28,027
  • 60
  • 183
  • 301

5 Answers5

85

Assuming your list items have a fixed height, you can use line-height combined with vertical-align: middle to do this.

Example:

ul li {
    display: block;
    height: 100px;
    line-height: 100px;
}

ul li img {
    vertical-align: middle;
}

Working example here.

Aron Rotteveel
  • 81,193
  • 17
  • 104
  • 128
  • 4
    It's worth noting for anyone else that stumbles across this question like me, that using line-height only works if you have one line of text. If your text wraps onto multiple lines then this solution is not the one for you. – Quiver Sep 10 '15 at 19:20
  • 1
    if li is auto height? – lyhong Jun 08 '16 at 08:51
8

You should be able to use the CSS property "vertical-align" for the img tag. Example:

<style type="text/css">
  img { vertical-align: middle; }
</style>
<ul>
  <li><img src="test.jpg" />test</li>
</ul>
Ben Jakuben
  • 3,147
  • 11
  • 62
  • 104
0

You should wrap text within "li"

<li><div><span>My text</span></div></li>

li div{
    display: table;
    height: 100%;
    width: 100%;
}
li span{
    display: table-cell;
    vertical-align: middle;
}
Sergey Onishchenko
  • 6,943
  • 4
  • 44
  • 51
0

Following on from the above answers that suggest the line-height method for vertical centering. If you apply a font that has glyphs that aren't vertically centered in the font file then the result will be that your element won't be vertically centered either, but be positioned higher or lower than it should be.

I had this issue and was tricky to work out. If your element doesn't vertically align correctly and you can't work out why, try applying a standard font such as 'Arial'.

See here for more information.

0

If you know the height of the image (assuming it is an icon), you can set the line height to the height of the image. Then it should work by setting vertical-align:middle. See a live example at w3schools: http://www.w3schools.com/Css/tryit.asp?filename=trycss_vertical-align

naivists
  • 32,681
  • 5
  • 61
  • 85