Posts tagged "grid"

Practical use of CSS Grid min-content

There are several use-cases for CSS Grid. In this example, it is used to solve the following requirements:

  • Create a table component with a fixed height
  • A header should always be at the top of the component
  • A footer should always be at the bottom of the component
  • The component should always have the same height, no matter how many rows are displayed
  • Overflow should be scollable

This can be accomplished with auto and min-content:

<div class="grid">
  <div class="header-filter">
    ...
  </div>
  <div class="table">
    ...
  </div>
  <div class="footer-pagination">
    ...
  </div>
</div>
.grid {
  display: grid;
  grid-template-rows: min-content auto min-content;
  height: 250px;
}

.table {
  overflow: auto;
}

Check out this CodePen for a working example.


Infinite rows with CSS Grid

CSS Grids can be used to layout your website in columns and rows. But did you know you don't have to specify the amount of rows?

You can define the height for each row with grid-auto-rows.

#grid {
  background-color: #1a2b3c;
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  grid-auto-rows: 50px;
}

#item1 {
  background-color: #6699ff;
  grid-column: 1 / 4; /* width: 3fr */
  grid-row: 1 / 5; /* height: 200px */
}

#item2 {
  background-color: #66ffff;
  grid-column: 2 / 7; /* width: 5fr */
  grid-row: 2 / 11; /* height: 450px */
}

Check it out on codepen.

You can also use grid-auto-columns for infinite columns.


Set CSS Grid item width

In CSS Grid, you specify the size and position of elements with grid-column and grid-row. Normally you specify the position with {start-position} / {end-position}.

But you can also specify the width with span:

#item {
  /* 3 columns wide, 2 rows high */
  grid-column: 1 / span 3;
  grid-row: 1 / span 2;
}

Check out this codepen example.