将列的宽度限制为特定网格项目的宽度 [英] Limit the width of a column to the width of a particular grid item

查看:92
本文介绍了将列的宽度限制为特定网格项目的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this simple use case: an item title and description. The title should appear above the description and I want the title to determine the width of the entire column, also for the 'description' row.

CSS Grid可以吗?如果可以,怎么办?

Is that possible with CSS Grid, and if so, how?

这是所需的输出:

这就是代码,基本上是:

And that's the code, basically:

.grid-container {
  display: grid;
  grid-template-columns: 1fr;
}

<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>

推荐答案

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

Instead of setting the column width to 1fr, use min-content.

使用min-content,该列将抓住所有换行(换行)的机会.

基本上,它会包装所有文本,直到该列达到最长单词的宽度为止.

It basically wraps all text until the column reaches the width of the longest word.

.grid-container {
  display: grid;
  grid-template-columns: min-content; /* formerly 1fr */
}

<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>

然后,取消标题框中的换行符:

Then, suppress the line breaks in the title box:

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

.A {
  white-space: nowrap;
  background-color: lightgreen; /* just for illustration */
}

<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>

参考文献:

  • https://www.w3.org/TR/css3-grid-layout/#track-sizing
  • https://www.w3.org/TR/css-sizing-3/#min-content
  • Difference between hard wrap and soft wrap?
  • https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

这篇关于将列的宽度限制为特定网格项目的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆