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.
Is that possible with CSS Grid, and if so, how?
This is the desired output:
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>
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>
来源:https://stackoverflow.com/questions/47452362/limit-the-width-of-a-column-to-the-width-of-a-particular-grid-item
