JamieITGirl
JamieITGirl

Reputation: 191

CSS flexbox behaviour with nested elements

Can anyone tell me how exactly CSS flexbox behaves with nested elements? For example, I have this code:

    <div id="layout">
    <nav id="menus">
        <div><a href="#m1">Menu 1</a></div>
        <div><a href="#m2">Menu 2</a></div>
        <div><a href="#m3">Menu 3</a></div>
        <div><a href="#m4">Menu 4</a></div>
    </nav>
    <div id="sidebar">
        <p>Sidebar</p>
    </div>
</div>

And this:

#layout {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}

I supposed that the nav menu elements would have been displayed as inline-elements but they haven't; if I want to achieve this result I need to add this code:

nav {
width: 100%;
display: flex;}

So...why the nav elements doesn't inherit the display: flex property even if they are children of the layout div? Thanks.

Upvotes: 1

Views: 1622

Answers (2)

Yupma
Yupma

Reputation: 2544

As div is a block level element so to have effect on it like inline then its parent should have property of flex and direction: row . Also flex property is applied on direct child only , not on there child Childs .

#layout {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

nav {
  width: 100%;
  display: flex;
}
<div id="layout">
  <nav id="menus">
    <div><a href="#m1">Menu 1</a></div>
    <div>
      <a href="#m2">Menu 2.1</a>
      <a href="#m2">Menu 2.2</a>
      <a href="#m2">Menu 2.3</a>
      <a href="#m2">Menu 2.4</a>
    </div>
    <div>
      <div><a href="#m3">Menu 3.1</a></div>
      <div><a href="#m3">Menu 3.2</a></div>
      <div><a href="#m3">Menu 3.3</a></div>
      <div><a href="#m3">Menu 3.4</a></div>
    </div>
    <span>
    <div><a href="#m4">Menu 4.1</a></div>
    <div><a href="#m4">Menu 4.2</a></div>
    <div><a href="#m4">Menu 4.3</a></div>
    <div><a href="#m4">Menu 4.4</a></div>
    </span>
  </nav>
  <div id="sidebar">
    <p>Sidebar</p>
  </div>
</div>

You can see in the above snippet , once I have taken inline level <a> tag and once block level div tag to demonstrate what is happening , also inline level span tag is used with div tags

Upvotes: 1

Quentin
Quentin

Reputation: 944564

why the nav elements doesn't inherit the display: flex property even if they are children of the layout div?

<nav> elements are, by default, display: block and not display: inherit.

I can't think of any element which is display: inherit by default.

Upvotes: 2

Related Questions