Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does width: 100% shrink this div within a flex parent?

I’m not so much looking for a solution as I am trying to understand what is happening.

In the code below, I have a flex enabled div with two child elements.

  • I explicitly set its width of the first child to 18rem.
  • I set the width of the second child to 100%.
.flex {
  display: flex;
}

.w-72 {
  width: 18rem;
}

.w-full {
  width: 100%;
}

.bg-blue-300 {
  --tw-bg-opacity: 1;
  background-color: rgb(147 197 253 / var(--tw-bg-opacity));
}

.bg-orange-200 {
  --tw-bg-opacity: 1;
  background-color: rgb(254 215 170 / var(--tw-bg-opacity));
}
<div class="flex">
  <nav class="bg-blue-300 w-72">Nav</nav>
  <article class="w-full bg-orange-200">Article</article>
</div>

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I thought this would expand the <article> to fill the remaining horizontal width, but it actually causes the width of the neighboring <nav> to shrink. (Try running this code with and without w-full to see for yourself.)

Why does this happen?

>Solution :

This is because flex always compromises widths when there are conflicts. It cannot both make the right side 100% and the left side 18rem so it cuts the same amount out of both to make them both fit. For example, if you were to have two items in a flex box, and each one is set to width: 60%, the working width of each item will be 50%, because flex will shave 10% off each side to make them both fit. To fix this, you can specify a min-width which is much more powerful than width by itself.

However, the correct way to have an item fill the remaining space in a flexbox is to use flex: 1 instead of using width, as shown below.

.flex {
  display: flex;
}

.w-72 {
  width: 18rem;
}

.w-full {
  flex: 1 0 auto;
}

.bg-blue-300 {
  --tw-bg-opacity: 1;
  background-color: rgb(147 197 253 / var(--tw-bg-opacity));
}

.bg-orange-200 {
  --tw-bg-opacity: 1;
  background-color: rgb(254 215 170 / var(--tw-bg-opacity));
}
<div class="flex">
  <nav class="bg-blue-300 w-72">Nav</nav>
  <article class="w-full bg-orange-200">Article</article>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading