Travis
Travis

Reputation: 53

How do I wrap list items in a container using 'display:flex'?

I'm working with the flexible box module ('display:flex') and cannot get my list items to wrap. I've got some very simple HTML and CSS but for some reason the list items aren't behaving the way I want them to.

Here is what I'm working with on Codepen:

<ul class="flex-container">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
</ul>

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;

  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;

  -webkit-justify-content: space-around;
  justify-content: space-around;
  -webkit-flex-flow: row wrap;
  flex-flow: row wrap;
  -webkit-align-items: stretch;
  align-items: stretch;
}

.flex-item:nth-of-type(1) { flex-grow: 1; }
.flex-item:nth-of-type(2) { flex-grow: 1; }
.flex-item:nth-of-type(3) { flex-grow: 2; }
.flex-item:nth-of-type(4) { flex-grow: 1; }
.flex-item:nth-of-type(5) { flex-grow: 1; }

.flex-item {
  background: tomato;
  border: 3px solid rgba(0,0,0,.2);
  line-height: 100px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
}
<ul class="flex-container">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
</ul>

Specifically, the goal is to have two rows of content. The top level will have items '1', '2', and '3', the bottom will have items '4' and '5'. Any ideas?

Upvotes: 0

Views: 1205

Answers (1)

Oriol
Oriol

Reputation: 288010

You can force a line break inserting a wide enough pseudo-element at the right place:

.flex-container::after {
  content: '';
  width: 100%; /* Force a line break */
}
.flex-item:nth-of-type(n + 3) {
  order: 1;    /* Place them after the ::after */
}

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;

  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;

  -webkit-justify-content: space-around;
  justify-content: space-around;
  -webkit-flex-flow: row wrap;
  flex-flow: row wrap;
  -webkit-align-items: stretch;
  align-items: stretch;
}

.flex-item {
  background: tomato;
  border: 3px solid rgba(0,0,0,.2);
  line-height: 100px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
  flex: 1;
}
.flex-item:nth-of-type(3) {
  flex: 2;
}
.flex-item:nth-of-type(n + 3) {
  order: 1
}
.flex-container::after {
  content: '';
  width: 100%;
}
<ul class="flex-container">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
</ul>

Upvotes: 1

Related Questions