By default a DIV’s width is going to be set to ‘auto’ which is going to cause it to extend to the width of it’s parent container. I ran into a case recently (centering a wordpress gallery) where I wanted to…
- Have the width of the DIV set to the size of it’s contents, the contents are dynamic so the exact size cannot be specified.
- Center that DIV on the page.
It turned out to be pretty simple just setting the display to inline-block caused it to shrink it’s width down to the proper size. So that part’s done, now onto centering it.
My first thought was to use the margin attribute to center it just like I would any other block element, but that’s not going to work here since it’s now an inline element.
margin: 0 auto 0 auto = nope
So what you’ll want to do it’s treat it just like it was some text you’d like to center. On the parent container of the element just add the following attribute
tada, you now have a centered div that will adjust it’s width based on it’s contents.