Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Container queries not working with flexbox space-between

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/

enter image description here

like image 923
Martin Zeltin Avatar asked Nov 16 '25 03:11

Martin Zeltin


1 Answers

Two important facts about container queries (from Miriam Suzanne, via jerclarke)

  1. Containers can't be sized by their contents,
  2. inline elements can't be containers.

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>
like image 59
bjelli Avatar answered Nov 17 '25 20:11

bjelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!