Search code examples
csscss-gridmultiple-columns

How do I prevent a two span div to make a single column wider?


I've got a two column layout in a grid where I want the columns to have the width they need. This works when I have two columns. But when I add a div that spans two columns, the smallest column becomes wider than it needs to be. Causing the wide column to wrap when it's not needed.

The following code:

<div style="display: grid; grid-template-columns: auto auto">
    <div>Small text</div>
    <div>Longer text that needs more space</div>
    <div style="grid-column: span 2">
        A very long text that needs so much space
        I will give it two columns
    <div>   
<div>   

Produces the following:

Result of above html code

As you can see, for some reason the text "space" is placed on a second line. The code without the very long text will show it on one line.

How do I get it on one line, with the very long text in two columns?


Solution

  • You can set grid-template-columns: auto 1fr:

    <div style="display: grid; grid-template-columns: auto 1fr; column-gap:.4em;">
      <div>Small text</div>
      <div>Longer text that needs more space</div>
      <div style="grid-column: span 2">
        A very long text that needs so much space
        I will give it two columns
      <div>   
    <div>