htmlcssalignmentvertical-alignment

Vertically align text next to an image?


Why won't vertical-align: middle work? And yet, vertical-align: top does work.

span{
  vertical-align: middle;
}
<div>
  <img src="https://via.placeholder.com/30" alt="small img" />
  <span>Doesn't work.</span>
</div>


Solution

  • Actually, in this case it's quite simple: apply the vertical align to the image. Since it's all in one line, it's really the image you want aligned, not the text.

    <!-- moved "vertical-align:middle" style from span to img -->
    <div>
      <img style="vertical-align:middle" src="https://via.placeholder.com/60x60" alt="A grey image showing text 60 x 60">
      <span style="">Works.</span>
    </div>

    Tested in FF3.

    Now you can use flexbox for this type of layout.

    .box {
       display: flex;
       align-items:center;
    }
    <div class="box">
        <img src="https://via.placeholder.com/60x60">
        <span style="">Works.</span>
    </div>