Felipe Araujo
Felipe Araujo

Reputation: 13

Making flexbox shrink to size before wrapping

I'm trying to make a responsive page that has the following behavior:

I need two <a> tags, one next to the other. These tags have an icon in a <i> tag and a <span> tag with some text in it.

As the viewport reduces in width, I want the icon to keep the same size but I want the text to wrap as much as possible before pushing the second <a> to the next line. This image shows in sequence what I want to happen:

Image

This CodePen is as close as I got. The functionality I want is there, but I had to set flex-basis: 100px and flex-grow: 1 in .outer-item to make it work, which has the undesirable effect of making both items the same width and spreading them in the available space.

.outer-wrapper {
  display: flex;
  flex-wrap: wrap;
}

.outer-item {
  flex: 1 0 100px;
}

.inner-container {
  display: flex;
  flex: 0 1 auto;
  padding-top: 5px;
}

.inner-img {
  flex: 0 0 40px;
  height: 40px;
  line-height: 40px;
  background-color: red;
}

.inner-label {
  flex: 0 1 auto;
}
<div class="outer-wrapper">
  <a class="outer-item">
    <div class="inner-container">
      <i class="inner-img">img</i>
      <span class="inner-label">label label label label</span>
    </div>
  </a>
  <a class="outer-item">
    <div class="inner-container">
      <i class="inner-img">img</i>
      <span class="inner-label">label label label label label label label </span>
    </div>
  </a>
</div>

Is there a way to make it work? Is flexbox even the way to go or should I use something else?

Upvotes: 1

Views: 1527

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 372194

The functionality I want is there, but I had to set flex-basis: 100px and flex-grow: 1 in .outer-item to make it work, which has the undesirable effect of making both items the same width and spreading them in the available space.

You have outer-wrapper set to display: flex, which acts like a block-level container (i.e., it will occupy all available space on the line).

Instead, use display: inline-flex, which will consume only enough width to accommodate the content.

revised codepen

Upvotes: 1

Related Questions