问题
I know similar questions have been asked before but I haven't seen one where the parent div has an unknown width with a definitive answer.
So here's the situation.
<style>
.parent {
width: 100%;
}
.child {
width: 300px;
float: left;
}
</style>
<div class="parent>
<div class="child></div>
<div class="child></div>
<div class="child></div>
<div class="child></div>
<div class="child></div>
<div class="child></div>
...
<div class="child></div>
<div>
Basically, I want to fit as many child divs in the parent container as the user's screen resolution can support.
I don't want to use css3 media queries because I want to support IE7.
I tried using javascript to specify a width to the parent but it's not ideal as the content jumps to the center after it loads. Any ideas?
回答1:
This is the nearest solution without the use of javascript.
It is display:inline-block;
that makes divs side bar side and being in center at the same time. I've try turning .parent into display:table-cell;
but didn't work. So need to use the actual <table>
for the powerful centering behavior.
http://jsfiddle.net/Dgdhr/
Edited: http://jsfiddle.net/Dgdhr/1 (without table: thanks to MartinodF)
<table width="100%">
<tr>
<td align="center">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
<div class="child">5</div>
<div class="child">6</div>
</td>
</tr>
</table>
.child {
width: 100px;
height:100px;
margin:10px;
display:inline-block;
background:#e0e0e0;
}
回答2:
Just use display:inline-block;
instead of float: left;
and for .parent use text-align: center
.
回答3:
Using Roman answer I ended with this. All div inside my parent div will center, so you dont need to set child class.
.parent{
text-align: center;
}
.parent div{
display: inline-block;
}
来源:https://stackoverflow.com/questions/8131119/how-do-you-center-align-floating-divs-where-the-parent-container-doesnt-have-a