Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a flex container take the space of its elements? [duplicate]

Tags:

html

css

flexbox

I would like to have a box with two rows, using flexbox. The problem I cannot resolve is that the container is taking the full width of the page instead of tightly adapting to the elements:

.container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  border-style: solid;
}

.header {
  background-color: black;
  color: white;
}

.body {
  background-color: blue;
  color: white;
}
<div class="container">
  <div class="header">
    the header
  </div>
  <div class="body">
    the body
  </div>
</div>

What should be set so that the container is just the width of the elements? I know that I could force its width but I would like it to be rather driven by the content of the elements.

like image 310
WoJ Avatar asked Nov 24 '25 07:11

WoJ


1 Answers

You're looking for inline-flex

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes

.container {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  border-style: solid;
}

.header {
  background-color: black;
  color: white;
}

.body {
  background-color: blue;
  color: white;
}
<div class="container">
  <div class="header">
    the header
  </div>
  <div class="body">
    the body
  </div>
</div>
like image 176
Michael Coker Avatar answered Nov 26 '25 21:11

Michael Coker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!