Location: CSS

Image vertical align with CSS, avoid absmiddle

Image vertical align with CSS, avoid absmiddle
Ever got stuck with the annoying problem of aligning an image next to some text? We all did. There were times when align="absmiddle" would solve this immediately, but how would you accomplish this with CSS?

Ever got stuck with the annoying problem of aligning an image next to some text? We all did. There were times when align="absmiddle" would solve this immediately, but how would you accomplish this with CSS? The truth of the matter is that absmiddle is a proprietary attribute that is not supported in any HTML version. The simple solution for this problem is using the 'vertical-align' css property:

Test 1:
<style type="text/css">
    div img { vertical-align: middle }
</style>

Furthermore, if you notice careful at the results of vertical-align (or even the proprietary absmiddle), often the alignment is not perfectly in the middle, but slightly closer to the top. You can add a small bottom margin to make it perfectly centered to the middle:

Test 2:
<style type="text/css">
    div img { vertical-align: middle; margin-bottom: .25em }
</style>

Notice that in all tests, behaviour will depend on the containing block style, for example, if the containing div is float to left, or display block.
Here are the results for the three tests I wrote, notice how the vertical-align and absmiddle are identical, while not perfectly in the middle. The second test, uses the margin-bottom: .25em to nudge the text straight to the middle.



Here is the HTML for the tests:
<!DOCTYPE html>
<html>
<head>
    <title>HTML tests<title>
    <style type="text/css">
       
        body { font-size: 9px; font-family: Verdana, sans-serif; color: #333; background: #FFF }
        h1 { clear: left; font-size: 1.2em; padding: 7px 0 3px; margin: 0 }
        div { float: left; width: 120px; border: 1px solid green }
        br { clear: left }
       
        div#test1 img,
        div#test2 img
            { vertical-align: middle }
       
        /* vertical-align:middle puts the center of an image at 1/4 em above the text baseline, not at the center of the line height */
        div#test2 img
            { margin-bottom: .25em }


    </style>
</head>
<body>

    <h1>&lt;div&gt; + vertical-align</h1>
    <div id="test1">
        <img src="icon.gif" /> Some words here
    </div>
   
    <h1>&lt;div&gt; + vertical-align + margin</h1>
    <div id="test2">
        <img src="icon.gif" /> Some words here
    </div>
   
    <h1>&lt;div&gt; + absmiddle</h1>
    <div id="test3">
        <img src="icon.gif" align="absmiddle" /> Some words here
    </div>

    <br />
   
</body>
</html>


Rate:  

Add To Facebook Share on Twitter Add To Google Bookmarks Add To Linkedin Add To Del.icio.us Add To digg Add To Stumble Upon Add To Yahoo My Web Add To Technorati