开发者

How to best vertically center an image and some text inside a div

开发者 https://www.devze.com 2022-12-17 12:14 出处:网络
I come up against this challenge frequently -- and when trying to solve I always wonder if I\'m doing it wrong.

I come up against this challenge frequently -- and when trying to solve I always wonder if I'm doing it wrong.

In a 'div', I want to position an image to the left -- and some corresponding text to the right -- I'd like them to appear vertically centered. What's the best way to do this?

Currently my xhtml looks like this:

<div class="key">
 <img alt="required" src="/images/forms/asterisk.png?" /> required
</div>

Here's how it currently looks -- http://screencast.com/t/NGMxMjRmMmYt (you'll see that the asterisk image is not vertically aligned with the "required" text. Boooo.

I typically think about positioning 开发者_如何转开发the image absolutely and then adding some left padding to move the text over, then later adjusting the top and bottom padding to get the text vertically centered. In the end, this approach seems like way too much work.


Adding this to your style should do it:

.key * {
   vertical-align: middle;
}

You're basically saying "every element inside the key class element needs to be vertically centered". This is the markup I follow (usually a .button class) and works in IE, Chrome, FF, Safari.


There are a number of options (see Vertical Centering with CSS for the complete rundown). Which one is best depends on a number of factors, the biggest being whether you know the dimensions of your content or not.

If you're just wanting to center the text in relation to the image, setting the text's line-height to the height of the image/container may be the easiest approach...


If the container DIV and Image both have fixed width and height then you could use CSS, but if not, jQuery Center Plugin is by far the best solution.


The following CSS will work:

.key img {
    vertical-align: middle;
}

Hope this helps! :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号