views:

79

answers:

3

I have the following code:

<html>
<head>
<style type="text/css">
#test img {vertical-align: middle;}


div#test {
border: 1px solid green;
height: 150px;
line-height: 150px;
text-align: center;
color: white
}
</style>
</head>

<body>

<div id="test">t<img class="bottom" src="http://www.w3schools.com/css/w3schools_logo.gif" alt="W3Schools" width="270" height="50" /></div>
</body>
</html>

If I remove the t after the the image, then it doesn't align vertically in the center (I test it in firefox). As it is now it aligns, so I could change the color of the text to be the same as the background or the other way was to put an inline style and set it as a background.

Is there any other way to align vertically an image with CSS? I found these ways to be a bit of a hack. How would that worked in CSS3?

+1  A: 

instead of t character use &nbsp; it is an space.

but i dont know why this happen. any suggestion guys?

rahim asgari
+1  A: 

I think your problem is applying the vertical-align property on a wrong element - it should be applied to the surrounding element of the img, that is div#test in your case:

div#test {
border: 1px solid green;
height: 150px;
line-height: 150px;
text-align: center;
color: white
vertical-align: middle;
}

I don't know why it works with the t symbol added, perhaps a browser quirk?

dark_charlie
Furthermore this doesnt apply to aligning an image within the div. it applies to aligning it within the actual line its on within the given `line-height`... the same as its going to align the actual text of the div and other applicable inline elements. If this is the only thing in the div, then there is only a single line so you may get the result youre looking for... but if you set the height of the div to something taller than a single line you will to get the result you want.
prodigitalson
I tried every possible combination with vertical-align but it doesn't work when I remove the t. I am wondering how is the right way to do it in CSS3 this one.
JohnDel
+6  A: 

The reason that the t makes a diffence, is because images are treated differently if they are the only element, or if they are part of a text.

How images are treated as single elements depend on the rendering mode of the page. In the beginning images as single elements were treated as block elements, and that behaviour is retained in certain sitations to be backwards compatible. You should put a proper doctype on the page, so that it's not rendered in quirks mode, if it doesn't solve your problem, at least it will make it behave more consistently.

Guffa
Indeed with html transitional it doesn't work, but with doctype strict is working without the letter t. Thank you, even though this means that I can't use doctype transitional to align vertical an image with css...
JohnDel