Flex-wrap on flexbox container only affects direct children

this thread related to https://www.sitepoint.com/community/t/grid-and-flexbox-layout-flexbox-header-and-image-grid-front-page/354650/2

To better understand flex parent - child relationship I wrapped div (test) around ul.

In the following media query nav has display: flex; which makes it flexbox container and it also has flex-wrap: wrap; which would affect its children

<nav>
    
    <img src="images/logo.png" alt="logo" width="100" height="100">
  
      <input type="checkbox" id="menu-toggle" />
      <label for="menu-toggle" class="label-toggle"></label>
   
   <div><!--test-->
    
    <ul>
      <li><a href="index.html">work</a></li>
      <li><a href="about.html">about</a></li>
      <li><a href="blog.html">blog</a></li>
      <li><a href="archive.html">archive</a></li>
      <li><a href="contact.html">contact</a></li>
    </ul>
   
   </div>
   
  </nav>    
@media screen and (max-width: 960px) {

.........
.header nav {
  display: flex;
  flex-wrap: wrap;
}
........
.header nav #menu-toggle:checked ~ div > ul {
  height:auto;
  max-height:35rem;
  opacity: 1;
  visibility: visible;
}

After adding that div this is what I get in the browser when it hits 960 screensize and after clicking on ham icon and expanding the menu

Please see above behavior here http://buildandtest.atspace.cc/index.html

Quick Google search revealed: properties applied to flex container only affect its direct children https://www.samanthaming.com/flexbox30/3-immediate-child-only/so if there’s a grandchild which is our nav it wouldn’t be affected. Is that correct?

I also checked flexbox spec but didn’t find anything specific to parent - child - grandchild

The grandchild has nothing to do with the flex layout. It just lives in the space created by the flex item (flex child). You create the space for your elements using the flex item (direct children of a flex box).

It’s a bit like saying that when you put a div in a table-cell it doesn’t behave like a table-cell. :slight_smile:

The grandchildren live in the space created by the flex algorithm of its parent.

There’s noting to stop a flex-item from also being a flexbox itself so its grandchildren can become flex items if required. However in your case all you need to do is set the parent flex-item to 100% wide in your smaller screen media query…

e.g.

.header nav > div{flex:1 0 100%;}

1 Like

Thanks for the tip Paul. Now I have two solutions for the nav - with wrapper div and without. :+1:
I remember that analogy with table cell from your previous explanations.

1 Like