'How to stop flex from stretching to 100% width?

I have a section with 2 columns pulled to center in flexbox, but for whatever reason the container doesn't wrap itself around them horizontally and instead fills the whole page.

What can I do to make the section wrap around the text (with expected padding of 1rem)?

body {
  background-color: #444;
  color: white;
}

section {
  border-style: solid;
  border-image: linear-gradient(to top right, goldenrod 0%, transparent 25%, transparent 75%, goldenrod 100%) 2;
  display: flex;
  padding: 1rem;
  justify-content: center;
  align-items: center;
  width: auto;
}

section>div {
  display: flex;
  flex-direction: column;
}

section>div:first-child {
  border-right: 2px solid goldenrod;
  padding-right: 1rem;
  align-items: flex-end;
}

section>div:not(:first-child) {
  padding-left: 1rem;
}
<section>
  <div>
    <p>Line First</p>
    <p>Line Second</p>
  </div>
  <div>
    <p>Line First</p>
    <p>Line Second</p>
  </div>
</section>

JSFiddle: https://jsfiddle.net/mjp1qozs/3/



Solution 1:[1]

The answer was to change display to inline-flex. Thank you, Temani Afif!

Solution 2:[2]

With display: inline-flex, as suggested in the comments above, you achieve the shrink-wrap behavior that you want, but you also lose the horizontal centering. So you solve one problem, but create another one.

Instead, just make the parent a flex container with justify-content: center. That solves both problems with just two lines of code.

body {
  display: flex;           /* new */
  justify-content: center; /* new */
  background-color: #444;
  color: white;
}

section {
  border-style: solid;
  border-image: linear-gradient(to top right, goldenrod 0%, transparent 25%, transparent 75%, goldenrod 100%) 2;
  display: flex;
  padding: 1rem;
  justify-content: center;
  align-items: center;
  width: auto;
}

section>div {
  display: flex;
  flex-direction: column;
}

section>div:first-child {
  border-right: 2px solid goldenrod;
  padding-right: 1rem;
  align-items: flex-end;
}

section>div:not(:first-child) {
  padding-left: 1rem;
}
<section>
  <div>
    <p>Line First</p>
    <p>Line Second</p>
  </div>
  <div>
    <p>Line First</p>
    <p>Line Second</p>
  </div>
</section>

Solution 3:[3]

max-width: fit-content;

works as well as

display: inline-flex;

use first if you don't need another max-with (also fit-content is partially supported)

or use second if inline element is ok for your case

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeaciaz
Solution 2 Michael Benjamin
Solution 3 Lev Lukomsky