I have some elements that display a key/value list. I'm using css grid to ensure the "key" span "column" is the same width, so the list looks nice. min-content
is a good way do this.
However, if the width of the parent DIV is too small to display everything, I need the key column to shrink to give more space to the "value" column. Something like grid-column-template: 1fr 2fr
can do this acceptably.
The problem is that I can't use both settings at the same time. min-content
doesn't do what I need when the panel is small, and nothing else seems to do what I need when large.
To clarify, I need to do the following:
- At all times, the "key" spans must be the same length. Usually the length of the longest "cell".
- When the div is wide, the "key" span must be
min-content
: as wide as the longest "cell". - When the div is narrower, the "key" span must collapse so that the "value" doesn't overflow.
.panel {
display: grid;
gap: 0 20px;
grid-auto-rows: 1fr;
grid-template-columns: 1fr 2fr;
margin-bottom: 20px;
}
.text-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
<div >
<span >key:</span>
<span >value</span>
<span >some really long key that should be truncated:</span>
<span >some really long value that should be truncated</span>
</div>
CodePudding user response:
You could use minmax()
css function to restrict the length of each column:
grid-template-columns: minmax(50px, min-content) minmax(max-content, 1fr);
.panel {
display: grid;
gap: 0 20px;
grid-auto-rows: 1fr;
grid-template-columns: minmax(50px, min-content) minmax(max-content, 1fr);
margin-bottom: 20px;
resize: horizontal;
overflow: hidden;
}
.text-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
<div >
<span >key:</span>
<span >value</span>
<span >some really long key that should be truncated:</span>
<span >some really long value that should be truncated</span>
</div>
<h3 style="text-align: right;">Resize it by dragging this ↑</h3>