I'm having trouble making flexbox CSS work for a specific use case scenario. I have written JavaScript that meets my needs, but I want to explore the possibility of achieving this with pure CSS. The challenge lies in ensuring that a container div only takes as much width as needed to contain its items, which are displayed from top to bottom and wrap into new columns when necessary.
Below is some sample HTML code I am testing:
<div class="my-container">
<div class="my-item">Item 1</div>
<div class="my-item">Item 2</div>
...
<div class="my-item">Item 25</div>
</div>
Accompanied by the CSS used for testing:
.my-container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
background-color: rgb(33, 150, 243);
padding: 15px;
height: 600px;
}
.my-item {
width: 250px;
height: 25px;
color: white;
padding: 10px;
flex: 0 0 auto;
}
The issue I am facing is that while the items wrap correctly into new columns, the container expands to fill the viewport. But changing the display attribute to "inline-flex" causes the container to be too narrow to display multiple columns effectively. This dilemma arises due to fixed-sized items needing to flow into columns based on the container's height, with the container's width adjusting accordingly.
I attempted exploring CSS grid as an alternative solution, but it appears that knowing the number of columns beforehand is essential for implementation. Flexbox seems like a promising approach, although not without its limitations.
Are there any other CSS-based techniques that could address this challenge more effectively? While my JavaScript version works, I am keen on discovering a CSS-centric solution if viable.