Comparison of Scrollable Layouts with Flexbox and Grid

Kenji Tomita - Aug 2 - - Dev Community

This blog introduces implementations using Flexbox and Grid to create a scrollable view with items arranged horizontally. We'll explore how to achieve a design where items can be scrolled horizontally, showing three and a half items at a time.

Scrollable Layout with Flexbox

Below is an example using Flexbox for horizontal scrolling, designed to display three and a half items.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .container {
      display: flex;
      overflow-x: scroll;
      padding: 10px;
      flex-wrap: nowrap;
    }
    .item {
      flex: 0 0 calc(33.33% - 10px);
      margin-right: 10px;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    <div class="item">Item 3</div>
    <div class="item">Item 4</div>
    <div class="item">Item 5</div>
  </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Image description

The flex property is used to set the size of each item in Flexbox. Specifically, the flex-basis part of flex: 0 0 calc(33.33% - 10px) determines the base size of each item.

Scrollable Layout with Grid

Next is an example using Grid, also designed to display three and a half items.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .container {
      display: grid;
      grid-auto-flow: column;
      grid-auto-columns: calc(33.33% - 10px);
      gap: 10px;
      padding: 10px;
      overflow-x: auto;
    }
    .item {
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    <div class="item">Item 3</div>
    <div class="item">Item 4</div>
    <div class="item">Item 5</div>
  </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Image description

In Grid, grid-auto-columns is used to set the size of each item, and grid-auto-flow: column arranges the items horizontally.

Summary

Both Flexbox and Grid make it easy to implement scrollable layouts with items arranged horizontally. Use the approach that best fits your project's design and layout needs.

. . . . . . . . . .
Terabox Video Player