I recently had the challenge of centering a div with a set of image thumbnails in it. The problem was that the number of thumbnails varied depending on the project that was being viewed;  i.e. - the width of the div was unknown, or more precisely, the width would change.  Typical CSS centering techniques required that the width of the div to be centered was known and set  by either pixel or percentage as so:

.center {
width: 70%;
margin-left:auto;
margin-right:auto;
}

In my case, since the width changed, the above solution would not work.  After a couple hours of searching through  CSS documentation, I found the following solution using the display parameter.

.variable-width-center{
    display:table;
    margin-left:auto;
    margin-right:auto;
}


What this effectively does is treats my div with class .variable-width-center as a table element - which can be centered within another div using margin-left:auto and margin-right:auto;
I found this technique was compatible in IE8, Safari 4.0, and Firefox 3.0.  I did not check older/alternative browsers, so you may want to perform additional QA if supporting those browsers is a priority of yours.

If you found this useful to you, or would like to suggest alternatives, please comment below.  I love comments :)

 

Add your comment

Your name:
Your email:
Your website:
Comment:
  The word for verification. Lowercase letters only with no spaces.
Word verification: