简体   繁体   中英

What's the simplest way to center an image vertically within a line of text?

Presently I use:

<table cellpadding="0" cellspacing="0">
    <tr><td><a href="cv.pdf" target="_blank">
    <img src="graphics/pdf.gif" width="24" height="24" /></a></td>
    <td width="10px"></td> <!--that just spaces the image from the text-->
    <td>
        <a href="cv.pdf" target="_blank"><em>Download CV.</em></a>
    </td></tr>
</table>

Pretty clunky but renders perfectly. Is there any better way to do it?

在图像上设置以下CSS属性:

vertical-align: middle;

Ditch the table, combine the two anchors into one, remove the width and height on the img tag, remove the em tag, then use vertical-align to center the image. You can also use margin to add some space between the text and the image, and font-style for the italic text.

HTML:

<p class="cv">
    <a href="cv.pdf">
        <img src="image/source.png" /> Download CV.
    </a>
</p>

CSS:

.cv {
    font-size: 14px;
    line-height: 1.4em;
    font-family: Arial, sans-serif;
}

.cv a {
    text-decoration: none;
    color: #999;
}

.cv img {
    vertical-align: middle;
    margin-right: 10px;
}

.cv a:hover {
    color: #333;
}

See, much better. Removing width and height makes images display better (because browsers suck at image interpolation. If you need a different size than is available you should do the resizing yourself.), and removing target="_blank" will cause less annoyance for your users.

See it working here: http://jsfiddle.net/kZeCt/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM