Alex Marshall
Alex Marshall

Reputation: 449

How to auto expand flex item to prevent item horizontal overflow?

I have a flex container that contains some flex items. I would like the items to expand by default to contain all of their content without horizontally overflowing the flex container. As you can see from the attached image, "Content 7" is overflowing.

How the flex-container looks currently:

How flexbox currently looks

HTML:

<div class="flexContainer">
  <div class="flexItem">Content 4</div>
  <div class="flexItem">Content 5</div>
  <div class="flexItem">Content 6</div>
  <div class="flexItem">Content 7 - Lorem ipsum dolor sit amet consectetur adipisicing elit. Labore vero deleniti veritatis iste at odit, quae placeat. Voluptas, dolorem dolore.</div>
  <div class="flexItem">Content 8</div>
</div>

CSS:

.flexContainer {
  display: flex;
  width: 800px;
  background-color: lightgray;
  height: 150px;
  border: 4px solid black;
  gap: 10px;
  align-items: center;
}

.flexItem {
  background-color: darkcyan;
  flex-basis: 0px;
  flex: 1;
}

Upvotes: 0

Views: 989

Answers (1)

Typical
Typical

Reputation: 155

Changing height: 150px in .flexContainer to height: fit-content will do the job. Now the height of .flexContainer will expand until everything fits inside.

Change to the following code:

.flexContainer {
  display: flex;
  width: 800px;
  height: fit-content;
  background-color: lightgray;
  border: 4px solid black;
  gap: 10px;
  align-items: center;
}

Upvotes: 1

Related Questions