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

时间:2017-11-23 09:50:18

标签: css css3 css-grid

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

CSS Grid可以实现,如果可以,怎么做?

这是所需的输出:

demo of desired output

这就是代码,基本上是:

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

2 个答案:

答案 0 :(得分:3)

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

参考文献:

答案 1 :(得分:1)

我不认为这可以用网格(或任何其他CSS显示类型而不明确设置宽度)。如果您对它感兴趣,CSS-tricks有一个全面的网格指南:

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

我知道你要求一个CSS解决方案,但万一你不能在这里找到它是一个jQuery解决方案:

&#13;
&#13;
$( document ).ready(function() {
	$('.B').outerWidth($('.A').outerWidth()).show();
});
&#13;
.A{
  display: table;
}
.B{
  display: none;
}
&#13;
<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>
&#13;
&#13;
&#13;