0

I'm making an observation more so than stating a problem, if only to help anyone who's also noticed. I'm following a tutorial on flexbox when I accidently comment out display: flex on body{}. The container expands from 120px (flex-direction: column) wide to 100% of the viewport, horizontally. Display: grid also expands to 100% of the horizontal viewport. This observation is enough for me to post the question because I struggle working with flexbox and I end up applying padding and margin manually. I wonder if anyone else has any observations that are not explicitly stated in flexbox documentation.

<div class="flex-container">
    <div class="item">item 1</div>
    <div class="item">item 2</div>
    <div class="item">item 3</div>
  </div> 
.flex-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

 .item {
  background-color: blue;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100px;
  width: 100px;
  margin: 10px;
} 

Why does display: flex shrink the container?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Guiver
  • 1
  • 3

1 Answers1

1

When an element has display: flex applied—making it a flex container—certain default settings come into play. Two of these settings are flex-direction: row on the container and flex-basis: auto on the items.

With display: flex on the body element, the flex item (.flex-container) is automatically set to flex-basis: auto, which is the width of the content. That's why the nested container "shrinks".

When display: flex is removed, the body element reverts back to display: block. Its child (.flex-container) is no longer a flex item and takes the default width: 100% of block elements.

If you want a flex item to expand to 100% width, just give it flex-grow: 1 or flex: 1.

body {
  display: flex;
}

.flex-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid red;
}

.item {
  background-color: blue;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100px;
  width: 100px;
  margin: 10px;
}
<div class="flex-container">
  <div class="item">item 1</div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701