🙌🏻

Center large content tricks

Issue

Assume we have a modal dialog with a large body content. We want it to be center using justify-content:center, however even if the overflow is auto, we cannot see the full content. To see the full content and scrollbar, the solution is below.

Solution

<div class="container">
  <h1>Vertical flexbox center but overflow</h1>
  <p>
    justify-content:center will hide some items.
    <strong>Use justify-content:start + firstItem:margin-top:auto, lastItem:margin-bottom:auto</strong>
  </p>
  <div class="flex-container">
    <div class="item">First item</div>
    <div class="item">Second item</div>
    <div class="item">Third item</div>
    <div class="item">Fourth item</div>
    <div class="item">Fifth item</div>
    <div class="item">Sixth item</div>
  </div>
</div>
body {
  font-family: 'sans-serif';
}
.container {
  margin: 0 auto;
}

/* Code that matters
 * START:
*/
.flex-container {
  display: flex;
  flex-wrap: nowrap;
  white-space: nowrap;
  overflow-x: auto;
  flex-direction: column;
  align-items: center;
  justify-content: start;
  height: 100vh;
}

.flex-container .item:first-child {
  margin-top: auto;
}

.flex-container .item:last-child {
  margin-bottom: auto;
}
/* Code that matters
 * :END
*/

.item {
  font-size: 1.3rem;
  border: 1px solid #ccc;
  background-color: #eee;
  padding: 0.7rem 1rem;
  margin: 1rem;
  border-radius: 10rem;
  color: #000;
  text-decoration: none;
}
 
💡
If we want to center wide content horizontally, use margin auto instead of justify-content:center;

Reference