如何将未知大小的图片垂直对齐到div的中心? [英] How to vertically align an image in unknown size to the center of a div?
问题描述
我有一个简单的HTML按钮,其中包含文字和图片:
I have a simple HTML button which contains text and an image:
HTML http://jsfiddle.net/EFwgN\">http://jsfiddle.net/EFwgN )
HTML: (Already on http://jsfiddle.net/EFwgN)
<span class="Button">
<img src="http://www.connectedtext.com/Image/ok.gif" />
Small Icon
</span>
CSS:
span.Button {display:inline-block; margin:2px 4px;padding:3px 6px;
background-color:#ddd; height:24px; line-height:24px;
vertical-align:middle;}
span.Button img {vertical-align:middle;}
b $ b
我无法想出符合这些要求的组合:
I can't come up with a combination that would fit these requirements:
- 图片和文字需要垂直在div的中间,文本在图像的中间。 - 图片可能处于任何宽度,按钮应该会逐渐显示。/ li>
- 垂直 - 图片可能处于小于或大于的任何高度。当图片较大时,我不介意是否显示或裁剪多余的像素,只要它居中。
- 按钮在固定高度。目前我使用
line-height
将文本居中。 - 按钮应该与其他按钮和文本一致。 li>
- 该解决方案需要在所有最新版本的主要浏览器和Internet Explorer 8上运行。
- The image and text need to be vertically at the middle of the div, with the text in the middle of the image. It should be neat.
- Horizontally - the image may be in any width, and the button should grow to show it.
- Vertically - the image may be in any height, smaller or larger than the button. When the image is larger, I don't mind if the extra pixels are displayed or cropped, as long as it is centered.
- The button is in a fixed height. Currently I use
line-height
to center the text. - The button should sit nicely in line with other buttons and text.
- The solution needs to work on all latest versions of major browsers, and Internet Explorer 8.
这里是一个jsfiddle与我目前的代码: http://jsfiddle.net/EFwgN
(注意小图标稍微低于按钮中心)
Here's a jsfiddle with my current code: http://jsfiddle.net/EFwgN
(note the small icon is slightly below the center of the button)
推荐答案
一个简单的解决方案,如果你需要不少于IE8(在标准模式下): http://jsfiddle.net/kizu/EFwgN/31/
A simple solution, if you need no less than IE8 (in Standards mode): http://jsfiddle.net/kizu/EFwgN/31/
只需将 margin:-100px 0
添加到 img
,所以负边距会吃任何大的高度:
Just add margin: -100px 0
to img
, so the negative margin would eat any large height:
span.Button img {vertical-align:middle; margin:-100px 0;
position:relative; top:-2px;}
我添加了
I've added position: relative; top:-2px;
just to look it better :)
但是如果你需要支持兼容模式或IE lt 8(for一些原因),带边缘的东西将不工作。因此,您需要一个额外的标记: http://jsfiddle.net/kizu/EFwgN/28/ ,但它有点黑客,只有固定按钮的高度(如在你的例子)。
But if you'll need support for compatibility mode or IE lt 8 (for some reason), the thing with margin won't work. So you'll need an extra markup: http://jsfiddle.net/kizu/EFwgN/28/, but it's somewhat hacky and works only with the fixed button's height (like in your example).
这篇关于如何将未知大小的图片垂直对齐到div的中心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!