将列的宽度限制为特定网格项的宽度

Boa*_*and 5 css css-grid

我有一个简单的用例:项目标题和描述。标题应出现在说明上方,我希望标题确定整个列的宽度,也适用于“说明”行。

CSS 网格可以实现这一点吗?如果可以,如何实现?

这是所需的输出:

所需输出的演示

这就是代码,基本上是:

.grid-container {
  display: grid;
  grid-template-columns: 1fr;
}
Run Code Online (Sandbox Code Playgroud)
<div class="grid-container">
  <div class="A">
    DIV A contains the TITLE
  </div>
  <div class="B">
    DIV B has much more text but I want its text to wrap to the width of div.A (no cut of words, just wrapping)
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

Mic*_*l_B 5

不要将列宽设置为1fr,而是使用min-content

使用 时min-content,该列将占据所有换行(文本换行)机会

它基本上会环绕所有文本,直到该列达到最长单词的宽度。

.grid-container {
  display: grid;
  grid-template-columns: min-content; /* formerly 1fr */
}
Run Code Online (Sandbox Code Playgroud)
<div class="grid-container">
  <div class="A">
    DIV A contains the TITLE
  </div>
  <div class="B">
    DIV B has much more text but I want its text to wrap to the width of div.A (no cut of words, just wrapping)
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

然后,抑制标题框中的换行符:

.grid-container {
  display: grid;
  grid-template-columns: min-content;
}

.A {
  white-space: nowrap;
  background-color: lightgreen; /* just for illustration */
}
Run Code Online (Sandbox Code Playgroud)
<div class="grid-container">
  <div class="A">
    DIV A contains the TITLE
  </div>
  <div class="B">
    DIV B has much more text but I want its text to wrap to the width of div.A (no cut of words, just wrapping)
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

参考: