I have a css grid and I want its column width to be the width of the largest item in the column or 100px, whichever is smaller. I thought minmax(max-content, 100px)
might work, but it doesn't. In the example below, the narrow column should be max-content (but 100px) and the wide column should be 100px (but max-content). Is it possible to do this using css grid?
.table { display: grid; gap: 4px; grid-template-columns: repeat(4, minmax(max-content, 100px)); } .element { background-color: lightblue; word-break: break-all; white-space: nowrap; }
<div class="table"> <div class="element">a</div> <div class="element">wiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiide</div> <div class="element">narrow</div> <div class="element">d</div> <div class="element">narrow</div> <div class="element">b</div> <div class="element">c</div> <div class="element">wiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiide</div> </div>
P粉6424362822023-09-07 00:02:09
Use max-width
on items and keep columns auto-width
.table { display: grid; gap: 4px; grid-template-columns: repeat(4, auto); justify-content: start; /* you need this to avoid the gap between column */ } .element { background-color: lightblue; word-break: break-all; white-space: nowrap; max-width: 100px; /* hiding the overflow */ overflow: hidden; text-overflow: ellipsis; }
<div class="table"> <div class="element">a</div> <div class="element">wiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiide</div> <div class="element">narrow</div> <div class="element">d</div> <div class="element">narrow</div> <div class="element">b</div> <div class="element">c</div> <div class="element">wiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiide</div> </div>