1

I am aware there are multiple ways of vertically aligning an image in a div, as pointed out here already: How to vertically align an image inside div

Still, from my own testing, I'm curious as to why the below does not seem to middle align when pasted into a .htm file and opened in Chrome 39 or IE 11, but works just fine in JSFiddle: http://jsfiddle.net/4RPFa/6908/

Is there something entirely obvious which I'm missing?

Thanks.

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <div style="height: 300px; line-height: 300px;background-color:green;"> 
      <img width="70" height="70" style="vertical-align:middle; background-color:blue;" alt="" src="image.png">
    </div>
  </body>
</html> 
Community
  • 1
  • 1
sbgib
  • 5,580
  • 3
  • 19
  • 26

2 Answers2

1

The best way I used to align vertically is

position:absolute;
top:0;
bottom:0;
margin:auto;

It will work in IE (even 8 and 7) and stuff, why not try this ?

If you want absolute center, just use

position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;

..and this will do the trick

PS: Someone asked why this is the best way, didn't get the chance to see who it was, the question was deleted rapidly...my answer is simple, I never encountered any odd behaviour or anomalies with this method, so, FOR ME, this is a simple, easy and basic way of doing it, therefore, the best.

Alin
  • 1,218
  • 5
  • 21
  • 47
  • Thanks very much, I'll look to use this method in future. Provided that the image is always smaller than the container (and you don't want to use the former to expand the size of the latter) then it should prove to be robust. The line-height method I showed above would also break in such a case, and further it might not centre exactly depending on the height of the image as well as the height of the container - this isn't a problem when using your solution :) – sbgib Dec 06 '14 at 19:09
  • 1
    ^^ like I said, the best solution from all i\ve worked with :) i know it will come in handy one day. Cheers – Alin Dec 06 '14 at 20:09
  • Awesome thanks :) I'm always looking to find simpler and more compatible ways of constructing layouts, as we clearly must when working with CSS! – sbgib Dec 07 '14 at 17:50
1

In this specific case, the reason it renders differently outside of fiddle is due to the fact that they are using <!DOCTYPE html>, whereas you are using <html> (quirks mode). Feel free to try it.

You can read more about the oddities of quirks mode here: http://www.cs.tut.fi/~jkorpela/quirks-mode.html

Zack Tanner
  • 2,560
  • 1
  • 29
  • 45