3

[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.

  1. The container has a flexible width.
  2. The grid is always centered
  3. 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:

enter image description here

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;
}
Adrien LAMOTTE
  • 548
  • 4
  • 8
  • possible duplicate of [Center grid of inline-block elements in div, but last row is aligned with left edge of grid](http://stackoverflow.com/questions/19527104/center-grid-of-inline-block-elements-in-div-but-last-row-is-aligned-with-left-e) <-- provides CSS and JS solution to your issue. – web-tiki Aug 19 '14 at 17:45
  • Forgot to mention that i'm looking for a No Javascript, No Medias Queries (user can change my container width). But maybe it's just not possible ? – Adrien LAMOTTE Aug 19 '14 at 21:11

1 Answers1

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.

Community
  • 1
  • 1
Brian
  • 4,274
  • 2
  • 27
  • 55