In my current scenario, I am working with a flexible number of elements ranging from 2 to 5. My goal is to evenly distribute these elements within a div that also has variable width. This task might seem straightforward, but there's a unique twist involved. I want to limit the horizontal spacing between each element to a maximum value. This means that even if the div is wide and only a few elements are present, I do not want them spread out across the entire width. Instead, I prefer to center them in the div. Here's an example of what I aim to achieve:
Narrow div, 5 elements:
[ 1 2 3 4 5 ]
Wide div, 3 elements:
[ 1 2 3 ]
Below is my initial attempt at solving this issue, starting with the HTML structure:
<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>
Now, let's move on to the CSS styling:
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;
}
If you'd like to see a live demonstration, check out this Fiddle link: http://jsfiddle.net/jmy690bq/
While the current implementation is close to what I envisioned, it falls short in keeping the elements centered. Additionally, manually specifying the widths of li items is not ideal. An automatic solution would be more efficient. Although using JavaScript is an option, I prefer finding a CSS-only approach.