Link to home
Start Free TrialLog in
Avatar of joomla
joomlaFlag for Australia

asked on

horizontally and vertically center image within a div

I want to centre an image within a div (height = 200px, width = 200px)
The image is 175px wide, height is dynamic
Horizontally aligning is not an issue, but vertical alignment is not working.

I don't want to use a background-image

The solution must work in IE7&8   (so not a CSS3 solution)

There are lots of samples in EE but I can't get any to work in IE7 with images that have dynamic heights, without setting the background-image
Avatar of Scott Fell
Scott Fell
Flag of United States of America image

Try using a position relative div with an absolute div inside.  http://jsbin.com/gogum/1/edit?html,css,output  

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
 
  <div class="outer">
    <div class="inner">
      <img src="" width="200" height="200">  
    </div>
</div>
   
</body>
</html>

Open in new window

.outer{position:relative;width:400px;height:400px;background-color:green;}

.inner{position:absolute;bottom:100px;}

img{background-color:red;}

Open in new window

Avatar of joomla

ASKER

Hi Scott
not sure I understand

my div is a set dimension (200*200)
my image has a set width of 175
I dont know the height of my image

how do I apply your solution?
I was thinking of from the bottom...been a long night...

http://jsbin.com/gogum/2/edit

This uses jquery 1.1 and will work with ie.  You can type any height in the with to simulate what will happen.  Just click the "Run with js" after you change the hight (if you test in jsbin).  

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
 
  <div class="outer">
      <img src="" width="175" height="300">  

</div>
   
</body>
</html>

Open in new window

.outer{width:400px;height:400px;background-color:green;text-align:center;}



img{background-color:red;}

Open in new window

$(function() {
  var h = $('.outer img').height();
  var m = (400-h)/2;
  
  $('.outer img').css('margin-top',m);
});

Open in new window

This of course assumes that the image will not be taller then your 200px outer div.
ASKER CERTIFIED SOLUTION
Avatar of Scott Fell
Scott Fell
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of joomla

ASKER

Thanks Scott,
the function is just what i needed
really appreciate you sticking in there
M
Glad it worked out.  I'm sorry you have to worry about ie 7 and 8.