问题
[EDIT]
I'm looking for a solution without javascript, and without medias queries (user can change the container size).
[/EDIT]
I need to create a grid of items.
- The container has a flexible width.
- The grid is always centered
- Items inside the grid need to be left aligned
Pretty simple, but I can't find the solution !!
Here is an image that present what I need:
And here is a jsfiddle : http://jsfiddle.net/5e4bcc9L/1/
HTML :
<div class="container">
<div class="grid">
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
</div>
</div>
CSS :
.container {
width: 100%;
background-color:#CCC;
text-align: center;
}
.grid {
background-color:#999;
display: inline-block;
text-align: left;
}
a {
display:inline-block;
height: 100px;
width: 100px;
background-color:#000;
margin: 5px;
}
回答1:
Given that you don't want to use JavaScript or media queries, this is tough to achieve exactly the way you want. The problem lies in the fact that you're setting exact heights and widths of your blocks within the grid. I'll explain more:
Centered grid with left alignment
CSS (keeping HTML the same)
.container{
width: 100%;
height:100%;
background-color:#CCC;
text-align:center;
}
.grid{
background-color:#999;
display: inline-block;
position:relative;
width: 80%;
border:1px solid black;
}
.grid a{
display:inline-block;
height: 100px;
width: 100px;
background-color:#000;
margin: 5px;
float:left;
}
.ghost{clear: both;}
If you look at the fiddle, it works the way you described...until you resize the window. That's because the blocks in the grid can't float until there's enough space for them to do so, which leaves you with an "incorrectly" (to you) sized block.
If the left alignment standard can be dropped, you get a much more pleasant experience as far as centered content is concerned as demonstrated here. Simply comment out the float in the CSS above to see what I mean.
Otherwise, the link web-tiki gave above is probably the best option.
来源:https://stackoverflow.com/questions/25389534/centered-grid-inner-grid-align-left-no-javascript-no-medias-queries