I want to add a CSS container query container for my 2nd child in my flexbox where both children are spaced out using space-between but it is not working. My second child goes off-screen and when I inspect the size of the div.container it says 0px width. What am I doing wrong here?
Here is my code:
body {
background: #2b2e36;
color: white;
font-size: 20px;
}
.container {
container-type: inline-size;
background-color: green;
}
.parent {
width: 100%;
display: flex;
justify-content: space-between;
background: #ffff0061;
}
.child {
background-color: #ff000091;
}
<div class="parent">
<div class="child">
<div>First</div>
</div>
<div class="container">
<div>Second</div>
</div>
</div>
Here is a working fiddle: https://jsfiddle.net/kpx6gvn9/

Two important facts about container queries (from Miriam Suzanne, via jerclarke)
No 1. This is the reason I've run into problems with using container-queries inside flex.
For example: This CodePen by OddBird runs fine with the container inside grid:
.spread {
display: grid;
grid-template-columns: minmax(50%, 1fr) minmax(min-content, 20em);
gap: 2rem;
}
But when I fork it and change from grid to flex, it breaks in firefox and chrome: CodePen
.spread {
display: flex;
gap: 2rem;
}
To fix it, I had to add some sizing information to the section, for example with:
.spread section {
flex: 1;
}
I found this solution in Stephanie Eckles article.
In your example, you have the same problem and the same solution will work: add sizing information to the two children of flexbox:
body {
background: #2b2e36;
color: white;
font-size: 20px;
}
.container {
container-type: inline-size;
background-color: green;
flex: 1;
}
.parent {
width: 100%;
display: flex;
justify-content: space-between;
background: #ffff0061;
}
.child {
background-color: #ff000091;
flex: 1;
}
@container (max-width: 600px) {
.container div {
font-size: 10px;
}
}
<div class="parent">
<div class="child">
<div>First</div>
</div>
<div class="container">
<div>Second</div>
</div>
</div>
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