• Advertisement
Sign in to follow this  

[web] Vertically center text and image inside cell

This topic is 4232 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want to vertically center text and an image inside a table cell. This is what I want it to look like:
+----------------------------------------------+
|+---+                                         |
||img|           This is my text               |
|+---+                                         |
+----------------------------------------------+
To get this, I tried the following code, among several other failed attempts:
<table border="2">
	<tr>
		<td style="text-align: center; vertical-align:middle;">
		<img border="0" src="myfile.jpg" style="float:left; width: 100px; height:100px;">
		Email This</td>
	</tr>
</table>
The text is not vertically aligned in the center. I'm getting pretty frustrated. I tried wrapping the text in a div with height=100% and vertical-align=middle, but that didn't work. Any ideas?

Share this post


Link to post
Share on other sites
Advertisement
The CSS vertical-align is not what you might think it is:


// does not do what you expect (unless it is a TD/display:table-cell)
<div style="vertical-align: middle; height: 100px;">Hello World</div>



It doesn't work like that. Instead, the vertical-align is for inline elements like:

<div>
<img style="vertical-align: middle;" />
<span style="vertical-align: middle;">Hello World</span>
</div>


It positions them relative to each other's middle... It doesn't position them in the middle of the parent.

But that is not 100% relevant here, because table cells are the exception to the rule. :) You can use vertical-align in TDs. Your problem is that the floated image + text are considered the same. If you unfloat the image, and add style="vertical-align: middle;" to both the image and [span]text[/span], it will be completely centered.

Share this post


Link to post
Share on other sites
Quote:
You can use vertical-align in TDs.


Now where's the fun in hardcoding style attributes like that? :)
You're right, but the correct attribute is "valign"

Take the high road. Use CSS! X-D

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement