Limit the width of a column to the width of a particular grid item

扶醉桌前 提交于 2019-11-28 02:07:15

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

With min-content, the column will take all line break (text wrapping) opportunities.

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>

References:

I do not think this is possible with grid (or any other CSS display type without explicitly setting the width). CSS-tricks has a comprehensive guide on grid if you are interested in it:

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

I know you asked for a CSS solution, but just in case you don't find it here is a jQuery solution:

$( 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>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!