mana
mana

Reputation: 1239

How the flex box item use the full width of its parent

.container {
  width: 400px;
  border: 2px solid red;
  display: flex;
  flex-flow: row wrap;
}

.item {
  padding: 20px;
  border: 1px solid blue;
  width: 70px;
}
<div class="container">
  <div class=item>Box 1</div>
  <div class=item>Box 2</div>
  <div class=item>Box 3</div>
  <div class=item>Box 4</div>
  <div class=item>Box 5</div>
</div>

My question, how can "Box 1", "Box 2", "Box 3" use the full width of the "container" class? and "Box 4" and "Box 5" will line up from below to the above box "Box 1" and "Box 2".

Upvotes: 2

Views: 6149

Answers (2)

Seimen
Seimen

Reputation: 7250

This was actually kind of a brainteaser until I realized you need CSS grid instead of Flexbox :). There doesn't seem to exist a solution with Flexbox without adding "ghost divs", which isn't really a good option.

.container {
  width: 400px;
  border: 2px solid red;
  display: grid;
  grid-template-columns: 110px 110px 110px;
  justify-content: space-between;
}

.item {
  padding: 20px;
  border: 1px solid blue;
}
<div class="container">
  <div class=item>Box 1</div>
  <div class=item>Box 2</div>
  <div class=item>Box 3</div>
  <div class=item>Box 4</div>
  <div class=item>Box 5</div>
</div>

Upvotes: 1

Cat Perry
Cat Perry

Reputation: 31

You have several ways to go about it; here are two ways:

Use flex-grow. If you add flex-grow: 1 to the item selector then the boxes on each row will take up the full width of the container. Note: With this solution you may want to make sure you have the same number of boxes per row, if you want these boxes to appear as a uniform grid. Otherwise the line with only one or two boxes will be stretched to fill the width of the container. So keep that in mind.

.container {
  width: 400px;
  border: 2px solid red;
  display: flex;
  flex-flow: row wrap;
}

.item {
  padding: 20px;
  border: 1px solid blue;
  width: 70px;
  flex-grow: 1;
}

Second option: Add margin: 0 auto; to the item selector, and they will fill the width by centering.

.container {
  width: 400px;
  border: 2px solid red;
  display: flex;
  flex-flow: row wrap;
}

.item {
  padding: 20px;
  border: 1px solid blue;
  width: 70px;
  margin: 0 auto;
}

Upvotes: 3

Related Questions