Reputation: 151
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/
Upvotes: 10
Views: 17696
Reputation: 6667
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
Upvotes: 14
Reputation: 371231
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>
Upvotes: 3
Reputation: 151
The answer was to change display
to inline-flex
. Thank you, Temani Afif!
Upvotes: 4