By using flex: 1
on flex items, the Flexbox feature will automatically adjust the sizes of your items, even if you include margins (gaps) or not. All items will maintain the same width. However, a scenario may arise where a flex item has the same width as in a different flexbox, but this item is nested within another flexbox with fewer children. In this case, simply using flex: 1
may not work. You will need to specify a max-width
or flex-basis
to match the width of an item in the flexbox where all items use flex: 1
.
The closest solution I found is by using flex: 0 1 <width>%
or max-width: <width>%
(which yield the same result).
It seems that the issue arises when margins are added, as without them, there is no problem. However, knowing the size of the margin and how many will be used can help in replicating the width of the other flexbox's items.
Take a look at this example:
ul {
display: flex;
}
ul li {
flex: 1;
margin-right: 25px;
}
ul li:last-child {
margin-right: 0;
}
ul li.fourth {
flex: 0 1 25%;
}
/* The irrelavent part starts here */
ul {
list-style:none;
margin: 0;
padding: 0;
font-size: 0;
line-height: 0;
}
ul li {
height: 100px;
}
ul:nth-child(odd) li:nth-child(even),
ul:nth-child(even) li:nth-child(odd) {
background-color: red;
}
ul:nth-child(odd) li:nth-child(odd),
ul:nth-child(even) li:nth-child(even) {
background-color: blue;
}
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<ul>
<li></li>
<li class="fourth"></li>
</ul>