【问题标题】:Limit the width of a column to the width of a particular grid item将列的宽度限制为特定网格项的宽度
【发布时间】:2018-05-07 05:37:34
【问题描述】:

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

CSS Grid 是否可以实现,如果可以,如何实现?

这是所需的输出:

这就是代码,基本上:

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

【问题讨论】:

    标签: css css-grid


    【解决方案1】:

    我认为这对于网格(或任何其他没有明确设置宽度的 CSS 显示类型)是不可能的。如果你有兴趣,CSS-tricks 有一个关于网格的综合指南:

    https://css-tricks.com/snippets/css/complete-guide-grid/

    我知道您要求提供 CSS 解决方案,但以防万一您在这里找不到 jQuery 解决方案:

    $( document ).ready(function() {
    	$('.B').outerWidth($('.A').outerWidth()).show();
    });
    .A{
      display: table;
    }
    .B{
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <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>

    【讨论】:

      【解决方案2】:

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

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

      它基本上将所有文本换行,直到列达到最长单词的宽度。

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

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

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

      参考资料:

      【讨论】:

      • 超级!它工作得很好!我是 CSS Grid 的新手,几乎不是纯旧 CSS 方面的专家。对其他人的一条评论:我正在 Angular 5 + Material 2 上执行此操作,截至目前,它将默认为任何 mat-nav-list 提供空白:nowrap。在这种情况下,除非您手动将第二段的空白“重置”为正常,否则上述内容将不起作用。我仍然缺少一件事 - 当“标题”网格项目(第一个)中的文本太长时,我没有得到“省略号”。如果网格容器的容器限制了整个网格的空间,这可能实现吗?再次感谢!
      • 不客气。这是省略号问题的尝试:jsfiddle.net/uutmsLoh
      • 实际上,我的用例更复杂,因此这个(省略号)对我不起作用,但我想我可以从这里开始。感谢您的迅速帮助!
      • 这很好。我根本不知道这是可能的。 (我自己是网格新手)
      猜你喜欢
      • 1970-01-01
      • 2017-12-05
      • 2020-11-09
      • 1970-01-01
      • 2012-08-07
      • 2012-07-16
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      相关资源
      最近更新 更多