How to Make a Flexbox Width Dependent on That of Its Children

I have a love-hate relationship with HTML and CSS as a front-end developer. I've been one for almost 3 years, but sometimes I still have hard times wrapping my head around those languages.

Actually, today's problem and the solution are so simple that I doubt my ability and knowledge as a frontend, but that's what happens to every developer sometimes, so I'll write about it anyway.

Today's topic is this;

CSS feature: flexbox's width is dependent on that of its parent

Let's say you have this HTML structure;

<div class="wrapper">
  <div class="flexbox">
    <div>aaaa</div>
    <div>bbbb</div>
    <div>aaaa</div>
    <div>bbbb</div>
  </div>
</div>

and this CSS styling;

.wrapper {
  width: 700px;
}

.flexbox {
  display: flex;
  background-color: aqua;
}

.flexbox div {
  width: 100px;
  text-align: center;
  background-color: yellow;
}

This will show you something like this; flexbox whose width depends on its parent

I added background colors to the flexbox and its children so that it's easier to see its width. As you can see, the flexbox's width is dependent on its parent's width, which is 700px in this case. Since it is one of the CSS features, this behavior is expected.

But what if you wish it weren't the case?

I want flexbox's width to be dependent on its children!!

There comes a time when you want to resist the reality presented to you, and for me, it was this time.

I wanted the flexbox's width to be dependent on that of its children.

The image is something like this; flexbox whose width depends on its children

So, how do I do that?

Solution

This problem is simple to solve.

Just use inline-flex instead of flex.

In this case, change .flexbox class into something like this;

.flexbox {
  display: inline-flex;
  ...
}

That's it!! This is ridiculously simple, and I think most developers know the solution, but I'm not ashamed of writing this article anyway...

Conclusion

No matter how much you have learned a specific thing, you sometimes have to doubt your knowledge about it, and for me, it was CSS this time. It actually took a few hours to find out this solution, so I decided to write about this anyway. I hope this article helps someone. Thanks for reading.