Set column width to content length in CSS Grid

To make all columns “shrink-to-fit”, use an inline-level grid container:

article {
  display: inline-grid;
  grid-template-columns: auto auto;
}

/* non-essential demo styles */
article { background-color: black; border: 1px solid black; }
section { background-color: white; border: 1px solid black; }
<article>
  <section>content</section>
  <section>content</section>
  <section>cell3</section>
  <section>cell4</section>
</article>

To make one column “shrink-to-fit”, use min-content:

article {
  display: grid;
  grid-template-columns: min-content auto;
}

/* non-essential demo styles */
article { background-color: black; border: 1px solid black; }
section { background-color: white; border: 1px solid black; }
<article>
  <section>content</section>
  <section>content</section>
  <section>cell3</section>
  <section>cell4</section>
</article>

But auto with 1fr would also work because the fr would consume all free space on the line, collapsing the other column as much as possible:

article {
  display: grid;
  grid-template-columns: auto 1fr;
}

/* non-essential demo styles */
article { background-color: black; border: 1px solid black; }
section { background-color: white; border: 1px solid black; }
<article>
  <section>content</section>
  <section>content</section>
  <section>cell3</section>
  <section>cell4</section>
</article>

More info in the spec:

  • 7.2. Explicit Track Sizing: the grid-template-rows and grid-template-columns properties

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)