Vertically Align Arbitrary Length String Relative To Image
Posted December 7th, 2010 in ProgrammingTags: CSS
When coding web pages, a common problem is aligning (link) text vertically, often in relation to an icon. This is easily accomplished by setting height
and line-height
equal and by adding padding for the icon which is set as the background-image
centered 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 render properly during the hover state.