CSS Grid:使 grid-cell 只与 max-content 一样宽,但不能超过 1fr。或者 display: flex 能够解决这个问题吗?

con*_*exo 5 css css-grid

如何使网格中的单元格仅与其 一样宽max-content,但永远不会溢出父网格容器?

检查这个例子:

.grid {
  border: 1px dotted blue;
  display: grid;
  gap: 5px;
  grid-template-columns: min-content max-content;
  width: 120px;
}

label {
  background-color: yellow;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
Run Code Online (Sandbox Code Playgroud)
<div class="grid">
  <input type="checkbox" id="foo" /><label for="foo">foo label, must not overflow parent grid!</label>
</div>

<div class="grid">
  <input type="checkbox" id="bar" /><label for="bar">bar label</label>
</div>
Run Code Online (Sandbox Code Playgroud)

代码示例还展示了我的真实用例。我需要它,所以标签仅限于父元素,同时也不能比必要的更宽,因为我不希望标签右侧的空白成为可点击区域的一部分。

如果我将其设置为1fr而不是max-content,则标签会覆盖容器的整个其余部分,这是不需要的,因为现在您可以单击标签右侧的空白来切换复选框。

.grid {
  border: 1px dotted blue;
  display: grid;
  gap: 5px;
  grid-template-columns: min-content 1fr;
  width: 120px;
}

label {
  background-color: yellow;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
Run Code Online (Sandbox Code Playgroud)
<div class="grid">
  <input type="checkbox" id="foo" /><label for="foo">foo label, must not overflow parent grid!</label>
</div>

<div class="grid">
  <input type="checkbox" id="bar" /><label for="bar">bar label</label>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS 会在这里提供一个解决方案

min(max-content, 1fr)
Run Code Online (Sandbox Code Playgroud)

但不幸的max-content是不能在min()-function 中使用。

Tem*_*fif 2

您可以使用fit-content(100%) 参考

.grid {
  border: 1px dotted blue;
  display: grid;
  gap: 5px;
  grid-template-columns: min-content fit-content(100%);
  width: 120px;
}

label {
  background-color: yellow;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
Run Code Online (Sandbox Code Playgroud)
<div class="grid">
  <input type="checkbox" id="foo" /><label for="foo">foo label, must not overflow parent grid!</label>
</div>

<div class="grid">
  <input type="checkbox" id="bar" /><label for="bar">bar label</label>
</div>
Run Code Online (Sandbox Code Playgroud)

使用 Flexbox 这是一项微不足道的任务,因为您所需要做的就是使元素成为 Flexbox 容器:

.grid {
  border: 1px dotted blue;
  display: flex;
  gap: 5px;
  width: 120px;
}

label {
  background-color: yellow;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
Run Code Online (Sandbox Code Playgroud)
<div class="grid">
  <input type="checkbox" id="foo" /><label for="foo">foo label, must not overflow parent grid!</label>
</div>

<div class="grid">
  <input type="checkbox" id="bar" /><label for="bar">bar label</label>
</div>
Run Code Online (Sandbox Code Playgroud)