Q:

Distribute and center elements horizontally but limit space between them

I have a situation where I have a variable number of elements 2-5 and I want to evenly distribute them across a variable width div.  That is pretty straightforward, but there is an additional twist.  I want to limit the horizontal space between each element to a max value.  So if the div is really wide and there are only a few elements, I don't want to space them out all the way across the div.  Instead I want to center them in the div.  Something like this:
Narrow div, 5 elements:
[   1  2  3  4  5  ]
Wide div, 3 elements:
[          1  2  3         ]

Here's what I have so far, HTML:
<div id="nav5">
    <ul>
        <li>[1]</li>
        <li>[2]</li>
        <li>[3]</li>
        <li>[4]</li>
        <li>[5]</li>
        <ul>
</div>
<div id="nav3">
    <ul>
        <li>[1]</li>
        <li>[2]</li>
        <li>[3]</li>
        <ul>
</div>
<div id="nav2">
    <ul>
        <li>[1]</li>
        <li>[2]</li>
        <ul>
</div>

CSS:
li {
    float: left;
    font-size: 22px;
    font-weight: bold;
    max-width: 80px;
}
#nav5 li {
    width: 20%;
}
#nav3 li {
    width: 33.333%;
}
#nav2 li {
    width: 50%;
}
ul {
    text-align: center;
    overflow: auto;
    width: 100%;
}
div {
    width: 100%;
    max-width: 320px;
    margin: 0 auto;
    text-align: center;
    background-color: lightgray;
}

Fiddle:  http://jsfiddle.net/jmy690bq/
It is on the right track, but not quite right.  The space between elements is limited properly, but they don't remain centered.  Also, I had to manually specify the width of the various li's to 20%, 33%, and 50%.  It would be great if that was automatic.
I am not adverse to doing JavaScript to help with this, but a CSS-only solution would be ideal.

A:

You can try flexible boxes:
.nav {
  display: flex;           /* Magic begins */
  justify-content: center; /* Center children */
}
.nav > li {
  flex-grow: 1;            /* Let them grow if there is free space... */
  max-width: 80px;         /* ...but with this limit */
  text-align: center;      /* Center content */
}

.nav {
  display: flex;
  justify-content: center;
  max-width: 320px;
  background-color: #D3D3D3;
  list-style: none;
  margin: 0;
  padding: 0;
}
.nav > li {
  flex-grow: 1;
  max-width: 80px;
  text-align: center;
}
<ul class="nav">
  <li>[1]</li>
  <li>[2]</li>
  <li>[3]</li>
  <li>[4]</li>
  <li>[5]</li>
</ul>
<ul class="nav">
  <li>[1]</li>
  <li>[2]</li>
  <li>[3]</li>
</ul>
<ul class="nav">
  <li>[1]</li>
  <li>[2]</li>
</ul>

