Currently, I am in the process of designing a CSS layout for items with some specific requirements:
- The layout should accommodate at least two items per row, and more if the items are narrow enough to fit on one line.
- If an item's content is too lengthy to fit within the available space, it should be truncated with an ellipsis without wrapping onto multiple lines.
- The goal is to utilize space efficiently by fitting as many items as possible on each row while minimizing truncation and maintaining a minimum of two items per row.
The primary objectives include maximizing the number of items per row (at least two) while minimizing truncation (utilize space effectively).
--
To achieve these goals, I have attempted to use flexbox for the layout. However, I am facing challenges in ensuring that there are at least two items per row (setting max-width to 50%), while allowing items to expand to fill the space and avoid text truncation.
Here is an example illustrating this issue:
https://i.sstatic.net/m0oPk.png
In the example, there is excess space after "Item Two..." in the top row. Ideally, this item should extend to occupy the empty space and reduce truncation.
On the second row, "Item Three..." could stretch further to display more content, possibly moving "Item Five" to the next row. However, "Item Four" must remain on the current row to meet the requirement of having two items per row.
I aim to have at least two items per row (or more without excessive truncation), showing as much content as possible for each item. The objective is to minimize whitespace without compromising truncation.
Any suggestions on potential changes or improvements here would be greatly appreciated. One possibility is eliminating the max-width constraint to prevent unnecessary truncation. Yet, removing this constraint might result in longer items occupying the entire line, potentially reducing to only one item per row, which is not desired.
.box {
display: flex;
flex-wrap:wrap;
}
.box > * {
flex: 0 1 max-content;
max-width:calc(50% - 4px);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Just for visual styling purposes */
.box {
border: 2px dotted rgb(96, 139, 168);
width: 300px;
}
.box > * {
border: 2px solid rgb(96, 139, 168);
border-radius: 5px;
background-color: rgba(96, 139, 168, 0.2);
}
<div class="box">
<div>Item One</div>
<div>Item Two two two two two two two two two two two two two two two</div>
<div>Item Three has more content and so has a larger size</div>
<div>Item Four</div>
<div>Item Five</div>
<div>Six</div>
<div>Seven</div>
</div>