Claudiu Creanga
Claudiu Creanga

Reputation: 8366

Make a list of an unknown number of items stretch to full width of container, responsive

I have a list of an unknown number of items. The container has a border top that shows the width.

No matter the browser size (responsive) the list items should occupy all the width of the container. Currently, as you can see, there is a space to the right of the container. The last li item of a row should be in line with the end of the border.

How can it be done without a lot of media queries? End result as the image bellow. Basically the thing that should change on resize is the space between list items..

enter image description here

Thanks!

.Container{
  width:40px;
  height:40px;
  background-color:red;
  display:inline-block;
}
#list{
  padding:20px 0 0 0;
  border-top: 4px solid black;
  width:50%;
  list-style-type:none;
}
<ul id="list">

    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
    <li class="Container"></li>
  
</ul

Upvotes: 0

Views: 607

Answers (1)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

Here's a flex solution:

#list{
  display: flex;
  flex-flow: wrap;
  justify-content: space-between;
  padding:20px 0 0 0;
  border-top: 4px solid black;
  width:30%;
  list-style-type:none;
}

.Container{
  width:40px;
  height:40px;
  background-color:red;
  margin: 1px;
}

This works for all rows except the last one:

enter image description here

A fix is to add additional elements, with visibility hidden:

.hidden {
  visibility: hidden;
}

<li class="Container hidden"></li>
<li class="Container hidden"></li>
...

Since elements with visibility: hidden still take up screen space, the flex box will take them into account during layout:

enter image description here

In this fiddle, the elements stay evenly spaced as you grow and shrink the viewport.

Upvotes: 3

Related Questions