Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

justify-content: space-between vs. flex-grow to align content

Tags:

html

css

flexbox

I have a top horizontal navigation which I'm using the css flexbox rule to control spacing.

enter image description here

I would like the the first item in the menu to be aligned to the left, the last item to be aligned to the right and for the spacing in between the rest of the items to be equal.

Is this possible? I thought justify-content: space-between; would have achieved this but I can't get it to work.

I put an example of what I'm trying to do on jsfiddle. I also put this code below too.

The only other way I can think of doing it is to give a text-align: center to each of the li elements but for the first and last, which I could give a text-align: left and text-align: right but this would give too much spacing between the second and second last elements.

.container{
  background-color: yellow;
  width: 1100px;
}
.container ul#nav {
  padding: 0;
  display: block;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content: space-between;
}
.container ul#nav li {
  list-style: none;
  -webkit-flex: 2 1 auto;
  -ms-flex: 2 1 auto;
  flex: 2 1 auto;
  justify-content: space-between;
}
.container ul#nav li {
  justify-content: space-between;
}
<div class="container">
  <ul id="nav">
    <li><a href="#">Apples</a></li>
    <li><a href="#">Oranges</a></li>
    <li><a href="#">Pears</a></li>
    <li><a href="#">Kiwis</a></li>
  </ul>
</div>
like image 359
Holly Avatar asked Sep 18 '25 12:09

Holly


2 Answers

The problem is that if even one element has a flex-grow > 0, automatically any value of justify-content ceases to have effect, and the positive extra space will be distributed among the items with flex-grow.

In conclution: "All flex-items must have flex-grow: 0; in order justify-content to work:.

In your specific case the problem is the line: flex: 2 1 auto; which automatically set flex-grow: 2;

In order to fix it just change the flex-grow to 0 with the code line flex: 0 1 auto;

like image 64
Juanma Menendez Avatar answered Sep 21 '25 03:09

Juanma Menendez


You could achieve this by removing the flex: 2 1 auto; from .container ul#nav li like this:

.container{
  background-color: yellow;
  width: 1100px;
}
.container ul#nav {
  padding: 0;
  display: block;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content: space-between;
}
.container ul#nav li {
  list-style: none;
  -webkit-flex: 2 1 auto;
  -ms-flex: 2 1 auto;
  justify-content: space-between;
}
.container ul#nav li {
  justify-content: space-between;
}
<div class="container">
  <ul id="nav">
    <li><a href="#">Apples</a></li>
    <li><a href="#">Oranges</a></li>
    <li><a href="#">Pears</a></li>
    <li><a href="#">Kiwis</a></li>
  </ul>
</div>
like image 27
Anonymous Avatar answered Sep 21 '25 03:09

Anonymous