Keep a Clean Horizontal Scroll Layout with flex-shrink: 0;

Post in English

When arranging content horizontally along the X-axis in web design, it is common to use Flexbox. Among the various properties available, the flex-shrink property plays a crucial role in adjusting the size of child elements.

 

In the example below, the child elements do not reflect the specified width as intended:

 

1
2
3
4
5
<div id="parent">
        <div class="items"></div>
        <div class="items"></div>
        <div class="items"></div>
    </div>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#parent {
  display: flex;
  align-items: center;
  overflow-x: scroll;
  width: 100%;
  background: #000;
 height: 400px;
}
.items {
  height: 300px;
  width: 300px;
  background: #fff;
  color: #000;
  margin: 0 1rem;
}

 

 

 

 

In this example, the child elements (.items) are displayed in a way that perfectly fits within the parent container (#parent), and the specified width: 500px is not respected.

 

To prevent this behavior, you can use flex-shrink: 0;.

 

1
2
3
4
5
<div id="parent">
        <div class="items"></div>
        <div class="items"></div>
        <div class="items"></div>
    </div>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#parent {
  display: flex;
  align-items: center;
  overflow-x: scroll;
  width: 100%;
  background: #000;
 height: 400px;
}
.items1 {
  height: 300px;
  width: 300px;
  background: #fff;
  color: #000;
  margin: 0 1rem;
  flex-shrink: 0; /*追加*/
}

 

 

 

 

By specifying flex-shrink: 0;, you can prevent the child elements from shrinking, ensuring that the intended layout is preserved. This helps maintain alignment between adjacent elements in a horizontal layout. It is especially useful when arranging elements along the X-axis and allowing users to scroll horizontally.