Forum Moderators: not2easy

Message Too Old, No Replies

Center image vertically and horizontally within DIV

         

terrybarnes

11:58 am on Jun 17, 2009 (gmt 0)

10+ Year Member



I'm using NextGen gallery for Wordpress and what happens is that it generates thumbnails at any given height/width and places them within a DIV container.

I've got access to the CSS so I can tweak the code but what I'd like to be able to do is to position the image inside the div so it is centered.

This would be fairly straight-forward if the image was of a specific size but it can be anything - the only thing is that it's constrained to 320x240. But that can mean that if there's a portrait image that this can be 126x240 for example.

At the moment the images are just aligned left and to the top of their containing div so it all looks a bit messy. I'd like to be able to have borders on the areas that don't fill up the 320x240 box.

Any ideas?

swa66

10:13 am on Jun 18, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you keep the image inline (it is by default), text-align:center should be enough to get it centered horizontally.

To center it vertically, make the image align in the center of the line and make the line the height of the div ...

Warning: might not be pixel perfect.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>untitled</title>
<style type="text/css">
* {
padding:0;
margin:0;
}
div {
border: 1px solid black;
width: 320px;
height: 240px;
text-align:center;
line-height: 240px;
}
div>img {
vertical-align:middle;
}
</style>
</head>
<body>
<div>
<img src="2s.jpg" alt="mandatory" />
</div>
</body>
</html>

Tested in FF, Opera and Safari (latest version), not looked at in IE.

swa66

12:28 pm on Jun 18, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



For completeness: if you set the div to have position:relative (in order to give it "position") and set the img to have position: absolute; bottom:0; top:0; left:0; right:0; margin:auto; it will center despite not being given a height nor a width in FF and safari, but not in Opera (all latest versions), no idea what IE would make of it (IE6 is way out of its league for this).

terrybarnes

5:51 pm on Jun 21, 2009 (gmt 0)

10+ Year Member



Apologies for not getting back sooner about this - got completely sidetracked with another project!

Thanks for this - very much appreciated and works well in Mac Browsers, as you said Ie6 isn't as good though.