Reputation: 51937
I have a wrapper div element that contains a div that in turns contains divs inside; these divs are added or removed at runtime. The HTML and CSS look like this:
<div id="Wrapper">
<div class="InnerGreen">
<div class="InnerContent"></div>
<div class="InnerContent"></div>
</div>
</div>
#Wrapper{
width:600px;
height:50px;
margin:10px 20px;
background:blue;}
.InnerGreen{
background:green;
margin:10px auto; // this doesn't center
overflow:hidden;
display:inline-block;}
.InnerContent{
background:yellow;
height:30px;
width:40px;
float:left;
margin:3px 5px;}
I'm using inline-block
to wrap the .InnerGreen
inside the Wrapper
; however, the margin:auto
don't seem to horizontally center the div. Of course, this works if I define the width of .InnerGreen
but in reality, the .InnerContent
divs are a collection of divs of all different sizes so I can't set the width of .InnerGreen
at runtime.
How can I make the margin:auto
work? Here the the jsfiddle.
Thanks for your suggestions.
Upvotes: 3
Views: 867
Reputation: 2042
You could just center the div using jquery, something along the lines of...
<script type="text/javascript">
$(function() {
var containerWidth = $(".InnerGreen").width();
$(".InnerGreen).css("width", containerWidth);
});
</script>
Your CSS setting for the margin should then do the rest.
You may also want to add height: auto to your style, as if you are adding internal content at runtime, it will better control the growth of the element.
Upvotes: 0
Reputation: 4977
As far as i know, without being able to determine the width of the element, you cant use the margin:auto method. It isn't exactly elegant, but you can accomplish this with a centered table:
<center>
<table>
<tr><td align="center">
<div>This will be centered.</div>
</td></tr>
</table>
</center>
with your code: http://jsfiddle.net/MaxPRafferty/yA7Nm/
Upvotes: 0
Reputation: 14469
This may not technically be the right way of doing it, but you could put text-align:center
on your wrapper div.
Upvotes: 2
Reputation: 15180
Inline elements have no margins. By telling .InnerGreen
to act as inline-block
, you're essentially telling it to act as inline with regards to positioning. On the other hand, you can still center it using text-align:
#Wrapper {
text-align: center;
}
See updated JSFiddle.
Upvotes: 7