简体   繁体   中英

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 在此输入图像描述

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

在此输入图像描述

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:

在此输入图像描述

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM