Search code examples
htmlcssflexbox

Break elements onto new line with flex-grow and flex-wrap


I have a parent div (.tags) that contains links and a title.

The parent div is set to display: flex; with flex-wrap: wrap;.

I would like the link elements to break onto a new line, clearing the title when the wrap effect takes place.

I have tried using flex-grow: 1 on the title, but this makes it push the links to the right of the screen at all times, which is not what I am after.

I have attached the code I have so far, but here is a link to the Codepen

What I am trying to achieve:

Default - the width of the screen is large enough so nothing wraps and everything is on one line >

Before Wrap

Wrapped - the width of the screen is smaller, the wrap has occurred - the title now has 100% width and the links clear it >

enter image description here

Note that the number of links could vary.

.container {
  background: lightgray;
  width: 100%;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-start;
}
.tags span {
  margin: 1rem;
}
.tags .tag {
  margin: 0.2rem;
  padding: 0.2rem;
  background: dodgerblue;
  color: white;
}
<div class="container">
  <div class="tags">
    <span>Tagged in:</span>
    <a class="tag" href="#">capabilities</a>
    <a class="tag" href="#">sales</a>
  </div>
</div>


Solution

  • Yes, with a change in the structure.

    Wrap the tags in their own div with flex:1. Then it will expand automatically and the tags will drop to the second line when the wrap occurs.

    .container {
      background: lightgray;
      width: 100%;
    }
    .tags {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: flex-start;
    }
    .tags span {
      margin: 0 1rem;
    }
    .tags .tag-wrap {
      display: flex;
      flex: 1;
    }
    .tags .tag {
      margin: 0.2rem;
      padding: 0.2rem;
      background: dodgerblue;
      color: white;
    }
    <div class="container">
      <div class="tags">
        <span>Tagged in:</span>
        <div class="tag-wrap">
          <a class="tag" href="#">capabilities</a>
          <a class="tag" href="#">sales</a>
        </div>
      </div>
    </div>

    Codepen Demo