Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center fluid grid of elements without setting hard width on parent

Tags:

html

css

I'd like to center a 'grid' of elements that—when resized—adjusts to center itself.

Like this:

 ___________________
|                   |
|    [] [] [] []    |
|    [] [] [] []    |
|    [] [] []       |
 -------------------
 ________________
|                |
|    [] [] []    |
|    [] [] []    |
|    [] [] []    |
|    [] []       |
 ----------------
 _____________
|             |
|    [] []    |
|    [] []    |
|    [] []    |
|    [] []    |
|    [] []    |
|    []       |
 -------------

I've tried setting a max-width, but that leads to this problem when resized:

 ________________
|                |
|    [] [] []    |
|    [] [] []    |
|    [] [] []    |
|    [] []       |
 ----------------
 _____________
|             |
| [] []       |
| [] []       |
| [] []       |
| [] []       |
| [] []       |
| []          |
 -------------

I do not consider using media queries and setting hard widths (or even max-widths) for every configuration a real solution.

I am open to CSS3 as long as it degrades gracefully, and would like to avoid javascript.

Edit: Adding non-semantic elements is also a deal breaker, a container div or something would be passable but not ideal.

The markup should be as follows:

 <ul>
      <li>...</li>
      <li>...</li>
      <li>...</li>
 </ul>

Here is a demo to get you started.

Thank you.

like image 872
bookcasey Avatar asked Nov 30 '11 18:11

bookcasey


1 Answers

It's still a little vague as to what your exact requirements are for centering (as in, all your illustrations above show an even number of elements, so I don't know what you expect for odd number. In your fiddle, I just added a text-align: center to the ul and achieved a centering effect ( http://jsfiddle.net/nR9Mk/1/ ), but I don't know if it is behaving as you desire.

Update: If you are only dealing with even numbers and you want them to remain grouped by two's, then this would work: http://jsfiddle.net/nR9Mk/8/.

ROUND 2: Based on your revealed "odd number" requirements, I have come up with a solution that works. Note: 1) it does require some extra HTML markup, 2) you have to set some type of practical limit to how wide you want to go and still get the effect. Here is the code with the "buffer" elements revealed by an outline and here is it with the outline removed.

ROUND 3: I know you already accepted my answer, but I was already working on this, so I figured I would offer it anyway. Based on your deal breaker comment, here is a modified plan that may be useful for you (or someone else). It is a hybrid -- "sometimes" it pushes the elements left (usually when it would be most awkward to not) and sometimes lets them stay "off column" but centered. To keep it from ever looking plain "weird" it is given a max-width of six columns wide.

like image 103
ScottS Avatar answered Oct 27 '22 10:10

ScottS