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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With