I want a three column layout, completely dynamic (no fixed widths) where the left and right columns are equal in width, and between the two of them, expand to fill all available space after the middle column has been made as wide as it needs to be to accommodate its contents. In other words, I want the middle column to be dynamic and driving the width, and I want it to be centered on the page and have minimal width for its contents, and I want the two side columns equal in width and maximal, given the width of the middle column.
In practice, the middle column's width is going to be small, imagine a small word like "and" or "or", between two boxes that have equal size independently of their contents.
Ideally I would like this to be able to be coded with three consecutive elements:
<div class="left"></div>
<div class="middle"></div>
<div class="right"></div>
so that I can easily collapse the layout on narrow layouts, like mobile, to be vertically-oriented with one div below the other.
Any ideas? I've been surprised at how difficult this has seemed and I'm wondering if the answer is so simple that I'm just having a random blank and failing to see it, or if this is genuinely tricky.
CodePudding user response:
If you put the three divs in one container with 'display:flex' you can achieve what I think you're after.
Simply give 'left' and 'right' a 'width: 100%' so they stretch as far as they can with the same proportion and the middle one gets only as big as needed. (If you want another ratio at a different time - maybe the right one should be twice as big as the left - simply put 100% and 200% width - the width might be bigger than 100% and like that it's really easy to calculate the ratio)
Notice that if you have more than one word, the lines would break. To prevent this I put 'flex-shrink: 0' on the middle one (alternative would be 'white-space: nowrap'). If it's just one word or the line break is what you want, you can even leave these.
#wrapper {
display: flex;
}
#wrapper>* {
border: 1px solid teal;
}
.left,
.right {
width: 100%;
}
#middle {
flex-shrink: 0;
/* white-space: nowrap; */
}
<div id="wrapper">
<div class="left"></div>
<div id="middle">two words</div>
<div class="right"></div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>