3

I am confused as to why a flex div takes up 100% width of its parent element. Take the following snippet:

#wrapper {
  width: 100%;
  height: 100px;
  background: green;
}

#flex {
  color: white;
  display: flex;
  flex-direction: row;
  background: blue;
}
<div id="wrapper">
   <div id="flex">
     <div>Item</div>
     <div>Item</div>
     <div>Item</div>
     <div>Item</div>
   </div>
</div>

Why is the flex div expanding to 100% width of the parent? Is there a way to make the flex div only as wide as the contents within it?

Any help appreciated, Thanks

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Joel Hoelting
  • 1,862
  • 2
  • 23
  • 45
  • 1
    "display: flex;" property nature is to cover 100% width just like "display: block;" property. If you don't want to cover whole area then you can use "display: inline-flex" or "display: inline". – Ambuj Khanna Sep 07 '18 at 06:11

1 Answers1

5

Your #flex div has display: flex applied. That's a block-level command (such as display: block) which, by design, occupies the full width of the parent. Use display: inline-flex instead.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701