Bancarel Valentin
Bancarel Valentin

Reputation: 531

Adapt all childs width with parent width

I have an html page structure like this:

<div id="list">
    <ul>
        <li style="background-color:orange;">Lorem</li>
        <li style="background-color:red;">Lorem</li>
                .............
        <li style="background-color:black;">Lorem</li>
        <li style="background-color:blue;">Lorem</li>
    </ul>
</div>

On this page, I want all list element to have the same width - I don't care about the content, only the color is really important in this case - and I want all thos elements to fit in their parent div (#list) when the page just loaded, this mean no scroll.

And this list is not final, I can add or delete somme elements in my list after the page load. I would like to know if there is a CSS way to get this result, JavaScript is not really suitable in this case.

Is that possible ?

Upvotes: 0

Views: 71

Answers (4)

Josh Burgess
Josh Burgess

Reputation: 9567

JSFiddle Example

Flexbox is your friend.

div#list {
  height: 800px; /*Whatever you want, really*/
  width: 800px; /*Again, substitute this with whatever size you like*/
} 
div#list ul {
  height: 100%;
  width: 100%;
  display: flex;
  flex-flow: row nowrap;
  align-content: stretch;
  list-style: none;
  padding: 0;
  margin: 0;
}
div#list ul li {
  -webkit-flex: 0 1 100%;
  flex: 0 1 100%;
}

Upvotes: 1

Oriol
Oriol

Reputation: 288120

Yes, you can use flexible boxes:

#list {
  display: flex;    /* Magic begins */
  border: 3px solid;
  padding: 1em;
}
#list > li {
  width: 0;         /* Ignore the width of the content */
  flex-grow: 1;     /* Distribute remaining space equally */
  overflow: hidden; /* Hide possible overflow */
  height: 50px;
  border-style: solid;
}
<ul id="list">
  <li style="background-color:orange;">Lorem</li>
  <li style="background-color:red;">Lorem</li>
  <li style="background-color:black;">Lorem</li>
  <li style="background-color:blue;">Lorem</li>
</ul>

Upvotes: 1

Miguel Jim&#233;nez
Miguel Jim&#233;nez

Reputation: 1303

You can achieve this kind of behavior by using flex:

HTML structure:

<div id="list">
    <ul>
        <li style="background-color:orange;">Lorem</li>
        <li style="background-color:black;">Lorem</li>

        ...

        <li style="background-color:blue;">Lorem</li>
    </ul>
</div>

CSS:

#list {
    border-style: solid;
    border-width: 3px;
    white-space: nowrap;
}

#list ul {
    display: flex;
    flex-direction: row;
    margin: 5px;
    padding: 0;
}

#list ul li {
    border-style: solid;
    height: 50px;
    list-style-type: none;
}

Here is a working demo: http://jsfiddle.net/kmbxawdd/1/

Upvotes: 1

Timofey
Timofey

Reputation: 139

You can try to set display to "table" on list and "table-cell" on li. But it will work as you expect only if all li elements will contain content with same width. And list itself must have explicitly defined width, of course.

Upvotes: 0

Related Questions