Forum Moderators: not2easy
I want to center an image horizontally in a window using just CSS. The image should automatically re-size if the window is smaller than the width of the image, otherwise the width of the image should be roughly the same as the original graphic.
I am much more concerned with future compatability than backwards for this exercise, so lets just worry about the more recent releases of browsers.
The following works a charm in Netscape and Opera, but has a problem in IE6. Since IE6 doesn't support the max-width attribute, I have to use an expression to achieve the desired results, however... the expression seems to clobber the auto margins left and right which I usually use to center a div, and the image winds up hard against the left margin. I really have to work to pry it off the left margin and when I do get it to move, it (whatever I've had to do to get it off the left margin) screws up how the div/image appears in the other browsers.
If I can figure out how to get it centered in IE6, I suppose I could use some browser specific CSS to avoid causing problems for the others, but just getting it off the left side of the page is a challenge, much less getting it centered.
Any comments or suggestions?
the CSS:
div.normalpic {
margin-right:auto;
margin-left:auto;
}
div.normalpic img {
border: 2px solid #000000;
position: relative;
width: 100%;
height: auto;
}
the xhtml:
<div class="normalpic" style="max-width:446px; width:expression(
document.body.clientWidth > (1.14*446)?
'446px':
'auto');">
<img src="Images/fig2.jpg" alt="Fig. 2" name="Fig2" />
(The math in the expression is to account for a 10% margin on the page plus a bit. This div is nested inside of another one that sets up the general page attributes, including 10% margins. 446px is the width of the image I have been experimenting with.)
Thanks! (and great board -- I just discovered it)
In my version of IE 6 (6.0.288) the image resizes until the window is large enough to hold the whole picture and then stays constant from that point on. Unfortunately, right up against the left margin.
And thanks for the welcome.
But thanks for the suggestion. It was something I hadn't tried before.