I use 2 divs, parent and child. The parent has a width of 100%, and its contents are aligned in the text with the center.
A child div should have a width of zero (or something close to it) and automatically expand its width with its contents, while still centered in the parent div. Example:
+------------ PARENT DIV ------------+ | | | ..some content.. | | | | +--CHILD DIV--+ | | |Inside child | | | +-------------+ | | | +------------------------------------+ +------------ PARENT DIV ------------+ | | | ..some content.. | | | | +------ CHILD DIV ------+ | | |Inside child with more | | | +-----------------------+ | | | +------------------------------------+
If I put a fixed width in a child div, I can set it correctly:
.parent { width: 100%; } .child { width: 100px; margin-left: auto; margin-right: auto; }
But this is not what I need, I need the child div to expand its width according to its contents. So I tried using float and nowrap :
.parent { width: 100%; } .child { float: left; white-space: nowrap; margin-left: auto; margin-right: auto; }
This works for the child himself, but then no longer centers as the contents of the parent.
I can solve this using Javascript, but I really prefer not to.
I searched for similar questions in SO, but I did not find the one that exactly answers this situation.
Can someone please throw me a light?
Thanks in advance for any comments.
Francisco
source share