Make centered div inside wide div expand with content width

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

+6
source share
4 answers

You can use display: inline-block; (not supported in <IE7), but you must wrap all other content in another block level element (e.g. <p> or another <div> )

 .parent { width: 100%; text-align: center; border: 1px solid #000; } .child { display: inline-block; border: 1px solid #f00; } 

http://jsfiddle.net/4kpsK/

(Click the red div frame to add more content and see the solution in action.)

+3
source

You must make your child inline :

 .parent { width: 100%; text-align: center; } .child { display: inline; } 

See here Fiddle: http://jsfiddle.net/4wXTd/1/

0
source

I think you can use max-width and display:inline instead of width . But this has drawbacks: max-width will not be interpreted correctly in IE (at least, as it seems to me, 9), but you should be safe in Webkit / Moz / Opera browsers.

0
source
 .child{display:block; margin: auto;} 

Must work.

0
source

Source: https://habr.com/ru/post/943601/


All Articles