Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

html - How to vertically align both image and text in a DIV using CSS?

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      #
#                                  #
####################################

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

Obs. The parent div of the div I'm referring to have position:relative so there's another problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

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

EDIT: 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.

EDIT: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...