The meaning of auto-fit in CSS grids

Now let's look at the auto-fit value, which is also used when specifying equal-sized columns in combination with the repeat function. It differs from the auto-fill value in that auto-fit adjusts the number of columns to the available width of the container, expanding or contracting them.

Example

Let's look at how the auto-fit value works using an example container with eight elements. Let's apply the minmax function you know from the previous lesson together with the auto-fit value:

html<div id="parent">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
</div>
css#parent {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  border: 2px solid #696989;
  padding: 10px;
  width: 600px;
}
#parent > div {
  padding: 10px;
  border: 1px solid #696989;
}

Результат:

Example

Now let's reduce the width of the grid container to 400px:

html<div id="parent">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
</div>
css#parent {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  border: 2px solid #696989;
  padding: 10px;
  width: 400px;
}
#parent > div {
  padding: 10px;
  border: 1px solid #696989;
}

Результат:

Practical tasks

Задание 1

Let's say you have a table of nine items. Set the column widths and grid container widths using auto-fit so that all the child items fit into three rows.

Задание 2

Now modify the previous problem so that all the elements are arranged in two rows.