How to make parent div wrap (and squeeze) its floating children?

I have a responsive layout consisting of a bunch of elements. Here is a very simplified version of the code:

HTML:

<div class="parent"> <div class="header"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div> 

CSS

 .parent { background: red; display:inline-block; } .child { background: green; width:100px; height:100px; float:left; } .header { background: yellow; width:100%; height:30px; } 

Jsfiddle

I am trying to ensure that the title (yellow box) is the same width as the child divs (green fields). And it works well when the layout is displayed first, here is a screenshot from JSFiddle enter image description here

But when the screen size becomes narrower, the title does not compress correctly, here is a screenshot for a smaller area:

enter image description here

I spent several hours trying to figure it out, but I could not. Part of the problem is that I don’t know in advance how many green boxes there will be, since they are dynamically displayed by .NET.

Update 1

The fact that packing green boxes is desirable, I am trying to ensure that the yellow box is the same width as the combined width of the green boxes. Desired Result:

enter image description here

+5
source share
1 answer

I don’t think you can do what you want with pure CSS. The space going on is there because so much space is left. The box just goes lower because there is no space above, you cannot squeeze the yellow heading because it knows nothing about the fact that green boxes are not suitable. I tried several hacks, but could not get it to work. The safest bet is to go with JS.

However, here are a few alternatives you might find worth checking out if you can change your design a bit.

1. Do not indicate size at all

You can let flex-box do its job. JSFiddle . It works with every number of elements, but they become too large or too small depending on the size of the parent and the number of children.

2. Allow a space between

flex-box to save again, you can use justify-content: space-between to save the title from the leftmost field to the most correct field correctly, but enter a space between them. JSFiddle .

+1
source

All Articles