max-content minimum and fixed width for CSS grid columns
P粉245003607
P粉245003607 2023-09-06 11:26:46
0
1
517

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粉245003607
P粉245003607

reply all(1)
P粉642436282

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template