When cod­ing web pages, a com­mon prob­lem is align­ing (link) text ver­ti­cally, often in rela­tion to an icon. This is eas­ily accom­plished by set­ting height and line-height equal and by adding padding for the icon which is set as the background-image cen­tered vertically.

<style>
a {
  background:url('16x16icon.png') no-repeat left center;
  display:block;
  height:16px;
  line-height:16px;
  padding-left:20px;
}
</style>
<a href="#">Link Text</a>

But what if the link text needs to span more than one line for the given width? What if the icon is taller than the text height?


This is where display:inline-block comes in.

<style>
.container {
  width:192px;
}

.container img {
  border:0;
  vertical-align:middle
}

.container span {
  display:inline-block;
  width:128px;
  vertical-align:middle;
}
</style>

<div class="container">
  <a href="#"><img src="64x64icon.png" alt="an icon" /><span>Link text that is really, really long that it takes up more than one line.</span></a>
</div>

Because the span is a block, text will wrap if longer than the width, but since the span is also inline, vertical-align:middle will align the img and the span. The only bug I’ve noticed so far is that text-decoration:underline doesn’t ren­der prop­erly dur­ing the hover state.

Comments are closed.