I have come across some methods of centering a div within a div, but those usually requires the element to be centered to have a fixed width and height. Is there a way to do it if the inner div to be centered will be of variable width and height (example: centering an image inside a frame of a fixed size, and the image could be of variable width/height)
views:
73answers:
3
A:
The only ways to center variable width in all browsers (that I know of) is with
<table align="center" cellpadding="0" cellspacing="0"><tr><td><div>This div is variable width and is centered.</div></td></tr></table>
or JavaScript
As for center horizontal that would force you to use JavaScript (I think)
cjavapro
2010-10-27 13:53:17
A:
Centering the width is easy...you probably already know this, but just set the left and right margin to auto. For height, unfortunately, I've only seen weird positioning work-arounds. You'd think that they'd make a similar margin for top/bottom, but alas, no. I'll try to find a link on the work-arounds.
<div style='width:400px;height:200px;background-color:#CCCCCC;'>
<div style='margin:0px auto;width:30px;height:30px;background-color:#0000CC;'> </div>
</div>
EDIT: Found link that might help on the vertical part:
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
Kevin Nelson
2010-10-27 13:58:16
Honestly, as much as I like doing css positioning and avoiding tables, when I need something to be vertically aligned in the middle, I still use tables even for non-tabular data rather than the CSS positioning fixes like the link I posted.
Kevin Nelson
2010-10-27 14:07:18
Based on my experience, this doesn't work for IE. IE ignores margin auto setting, and put element at left side. Any comment?
Sheen
2010-10-27 14:08:25
What's your DOCTYPE? The above example works fine with XHTML transitional: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Kevin Nelson
2010-10-27 20:46:23
Also works in IE for XHTML strict, HTML 4.0 transitional, and HTML 5. I can only get it to go to the left by removing the DOCTYPE completely...are you using a DOCTYPE at all? IE is picky about that.
Kevin Nelson
2010-10-27 20:50:11
A:
horizontal centering can be done with CSS:
#containerDiv {
text-align:center;
}
#innerDiv {
margin: 0 auto;
text-align: left;
}
For vertical centering I use Javascript if the containerDiv doesn't have a fixed height.
Steve Claridge
2010-10-27 14:03:53