Todo Pertin Todo Pertin - 7 months ago 9
HTML Question

How to make child elements equally share an ancestor's(not parent) 100% width?

HTML:

<div class="ancestor1">
<div class="ancestor2">
<div class="ancestor3">
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
<li>....
</ul>
</div>
</div>
</div>


Ancestor 1 is for some reason set to
width: 100%
of it's parent element and it must remain like that. I want the list items to ignore the widths of ancestors 2 & 3 and equally share ancestor 1's width with equal padding between them. The list items must cover the width of ancestor 1 with padding included. You may suggest altering the width of ancestor 2 and 3 in order to achieve the effect but not ancestor 1. Ancestor 1 must have width set to 100%.

Answer

I suppose, that you able to use the flexbox to solve your problem. You can read this guide to find the other nice examples of using this nice approach. But I should notice, that this approach has one disadvantage, it is not complete supported by the old browsers.

The solution is presented below:

HTML:

<div class="ancestor1">
    <div class="ancestor2">
        <div class="ancestor3">
            <ul>
                <li>List Item 1</li>
                <li>List Item 2</li>
                <li>List Item 3</li>
                <li>....
            </ul>
        </div>
    </div>
</div>

CSS:

.ancestor1 {
  width: 100%;
}

.ancestor1 ul {
  display: flex;
  padding: 0;
}

.ancestor1 ul > li {
  flex-grow: 1;
  display: inline-block;
  text-align: center;
  border: solid red 1px;
}

https://jsfiddle.net/y3ob5Ldk/1/

Comments