如何垂直对齐图像和文本在DIV使用CSS? [英] How to vertically align both image and text in a DIV using CSS?

查看:122
本文介绍了如何垂直对齐图像和文本在DIV使用CSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图像和一些文本在一个div,我想把图像和文本在div的垂直中心使用CSS。问题是,我不知道有多少行文本,但文本和图像必须总是在中间。例如,当只有一行文本时,div应如下所示:

I have an image and some text inside a div and I'd like to put the image and the text in the vertical center of the div using CSS. The problem is that I don't know how many lines of text I will have but the text and the image must be ALWAYS in the middle. For example, when there's only one line of text the div should look like this:

####################################
#  _______                         #
# |       |                        #
# |       |                        #
# | IMAGE |    text text text      #
# |       |                        #
# |_______|                        #
#                                  #
####################################

如果最终我有更多的行或文本的高度大于图像的高度,对齐,如下所示:

If eventually I have more lines or the height of text is larger than the height of the image then the image should be aligned, just like this:

####################################
#                                  #
#              text text text      #
#  _______     text text text      #
# |       |    text text text      #
# |       |    text text text      #
# | IMAGE |    text text text      #
# |       |    text text text      #
# |_______|    text text text      #
#              text text text      #
#              text text text      #
#                                  #
####################################

在麻烦获得这个效果,有没有使用javascript这样做吗?

I'm in trouble to get this effect, is there any way without using javascript to do this?

Obs。

推荐答案

提供图片和文本a vertical-align:middle - 文本需要包含在也是display:inline的元素中。所以标记如下:

Give both the image and the text a vertical-align: middle - the text needs to be contained in an element that is also display: inline. So markup like this:

<div>
  <span><img src="blah.jpg" /></span>
  <span>text text text</span>
</div>

div {
  display: table;
}

img {
  vertical-align: middle;
  display: table-cell;
}
span {
  vertical-align: middle;
  display: table-cell;
}

这是一个 jsfiddle 演示(编辑小提示,以显示一切都在一个容器内垂直对齐。)

should work. Here's a jsfiddle to demonstrate (edited fiddle to show everything is vertically aligned within a container as well.)

编辑:为了获得所需的行为,我建议使用额外的显示属性 - 容器的table和包含的元素的table-cell。

to get the behavior you want, I recommend using additional display properties - table for the container and table-cell for the contained elements. Fiddle link has been updated with the changes.

编辑:我唯一能想到的工作方式是将图像包装在另一个内联容器中,在这个情况跨度。我更新了小提琴来演示。

the only way I could think of to get it to work was to wrap the image in another inline container, in this case a span. I've updated the fiddle to demonstrate.

这篇关于如何垂直对齐图像和文本在DIV使用CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆