Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a responsive layout which consists 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

What I am trying to achieve is making the header (yellow box) take the same width as the child divs (green boxes). And it works well when the layout is rendered at first, here is a screenshot from the JSFiddle enter image description here

But when the screen size becomes more narrow the header doesn't shrink correctly, here is a screenshot for a smaller area:

enter image description here

I spent a few hours trying to figure it out, but I could not. Part of the challenge is that I don't know in advance what the number of green boxes is going to be as they are rendered dynamically by .NET

Update 1

The fact that the green boxes wrap is desired, what I'm trying to achieve is for the yellow box to have the same width as the combined width of the green boxes. Desired result:

enter image description here

like image 317
Vlad Spreys Avatar asked Aug 30 '16 21:08

Vlad Spreys


1 Answers

I don't think it's possible to do what you want with pure CSS. The dangling space is there because that's how much space is left. The box just goes below because there's no space above, you cannot shrink the yellow header because it does not "know" anything about the fact that green boxes do not fit. I tried a few hacks but couldn't get it to work. The safest bet is to go with JS.

However, here are some alternatives which you might find worth checking if you're flexible to change your design a bit.

1. Don't specify the size at all

You can let flex-box do its thing. JSFiddle. Works with every number of elements, but they get too big or too small depending on the parent size and number of children.

2. Allow for space inbetween

flex-box to the rescue again, you can use justify-content: space-between to keep the header from the most-left box to most-right box correctly, but introduce space between. JSFiddle.

like image 148
Lazar Ljubenović Avatar answered Nov 14 '22 08:11

Lazar Ljubenović