Css: prevent the width of the div from expanding to the available width

How can I prevent a div extension? I want a div with elements to not take up 100% of the free space and have the width that it has. I need this to center the parent div horizontally. The trick is that child elements should share float: left or diplay: inline block and fluid width, so there may be several rows of child elements.

I cannot wrap each line in my own div, as it breaks responsive design.

+11
html css css-float css-position
source share
4 answers

You should use display: table; It will be reduced to the size of its contents, and can also be centered and positioned without assigning a specified width.

DEMO http://jsfiddle.net/kevinPHPkevin/9VRzM/

+11
source share

Have you tried using display: inline-block ? DIV will occupy 100% of the width, because they are block elements.

0
source share

If you really want the parent div collapse around its children (for whatever reason, based on what you are trying to execute), and then you want to center this div , then the @Vector answer will be spot, use display: table with margin: 0 auto .

If it is normal for a div to remain expanded to the full width of the container in which you are trying to center your children, then you have at least a few more options, again depending on your specific situation.

You can use text-align: center .

 .content { text-align: center; border-style: solid; border-width: thin; } .content span { display: inline; border-style: solid; border-width: thin; } 
 <div class="content"> <div>Test</div> <div>Test</div> </div> 

You can also use the new display: flex with justify-content: center , depending on the compatibility level of the browser you support, of course.

 .content { display: flex; justify-content: center; border-style: solid; border-width: thin; } .content div { border-style: solid; border-width: thin; } 
 <div class="content"> <div>Test</div> <div>Test</div> </div> 
0
source share

You can set the width property of child elements to fit-content . This will cause these elements to occupy as much horizontal space as they need, and be available inside the parent element.

You can also set the width to max-content , but this will ignore the width of the parent element, and the content will expand as much as any descendants will need, and possibly overflow the parent element.

An example :

Setting up the problem:

 .parent { width: 15rem; height: 5rem; border: 1px solid blue; } .child { border: 1px solid red; } 
 <div class="parent"> <div class="child"> Content for child </div> </div> 

Decision:

 .parent { width: 15rem; height: 5rem; border: 1px solid blue; } .child { width: fit-content; border: 1px solid red; } 
 <div class="parent"> <div class="child"> Content for child </div> </div> 

The fit-content support is pretty good ( caniuse ?). At the time of this writing, at least there is some fit-content support in all browsers except IE, Edge, and Opera.

0
source share

All Articles