I'd like to create a grid of items that places as many items on each row as can fit. It should:
- Automatically size columns to fit their elements
- Automatically add/remove columns to fit the container
Effectively, I'm looking for a table with auto-sized columns and an auto number of columns. Flexbox with flex-wrap
doesn't work for me, since the columns wouldn't be aligned.
I've tried using grid
with auto-fill
, but I can't figure out how to ensure each column grows to fit its content. In this example, it only works if I specify a fixed minimum width, e.g.:
grid-template-columns: repeat(auto-fill, minmax(50px, 1fr));
I tried replacing the minmax
function with auto
, but that results in each column taking up 100% width. Is there another way to achieve what I'm trying to do (without JavaScript)?
div {
width: 300px;
border: 1px solid red;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(50px, 1fr));
}
<div>
<span>word</span>
<span>word</span>
<span>longword</span>
<span>word</span>
<span>longword</span>
<span>word</span>
<span>word</span>
<span>word</span>
<span>word</span>
<span>word</span>
<span>word</span>
<span>word</span>
<span>word</span>
<span>word</span>
</div>
My desired layout would look just like the above, except that any columns containing a "longword" cell would be wide enough to fit that cell (and the number of columns would shrink, if necessary). The end result would be several auto-sized columns, each of which is only as wide as necessary to fit their cells' contents. Basically, an HTML table with an indeterminate number of columns.