I'm building a navigation based on two lists on same line. All of the items in the two lists should have spacing between each other, but 25px at most.
The problem with flex-grow: If I use flex-grow, the elements get bigger than their own width + 25px because there's enough space available.
The problem with margin-right: If the container is smaller, the margin-right of 25px is not reduced, then the items will break lines instead of shrinking their margins.
Possible solution:
Using a div between each element, giving it flex-grow:1 and max-width:25px.
Is there another way without additional html?
Here's a codepen showing the problem:
ul,
li {
list-style: none;
margin: 0;
padding: 0;
}
ul,
.container,
.container2 {
display: flex;
justify-content: space-between;
}
.container,
.container2 {
border: 1px solid red;
width: 500px;
margin-bottom: 20px;
}
h2 {
margin-bottom: 5px;
}
p {
margin: 0 0 5px 0;
}
.container ul.first {
flex-grow: 1;
/* this works, but each element should only grow by 25px */
}
.container ul.first,
.container2 ul.first {
margin-right: 30px;
}
.container2 ul.first li {
margin-right: 25px;
/* this works, but should be reduced if not enough space */
}
<h2>Example 1: flex-grow on li</h2>
<p>Problem: the items get too big, should be max 25px spacing</p>
<div class=container>
<ul class=first>
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
<li>fifth</li>
<li>sixth</li>
</ul>
<ul class=second>
<li>first</li>
<li>second</li>
</ul>
</div>
<h2>Example 2: margin-right on li</h2>
<p>Problem: the spacing is not reduced on smaller containers</p>
<div class=container2>
<ul class=first>
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
<li>fifth</li>
<li>sixth</li>
</ul>
<ul class=second>
<li>first</li>
<li>second</li>
</ul>
</div>