Skip to content

Instantly share code, notes, and snippets.

@schmich
Last active March 21, 2018 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schmich/f253b268a449098f2f8e43279497e490 to your computer and use it in GitHub Desktop.
Save schmich/f253b268a449098f2f8e43279497e490 to your computer and use it in GitHub Desktop.
Flexbox vertical centering with top overflow limit

Layout

  • Vertically-centered flexbox layout
  • Absolutely-positioned fullscreen container (top/left/right/bottom: 0)
  • On content overflow, content is contained at the top and scrolls to the bottom
  • The crux of the layout:
    • .container { justify-content: space-between; } and .container .content { margin: auto 0; }
    • This allows the content to be centered in the flexbox container while not otherwise overflowing the top
  • The content is positioned just above center with .container .content { padding-bottom: 100px; }
<!DOCTYPE html>
<html>
<head>
<style>
/* Demo controls */
* {
font-size: 50px;
margin: 0;
padding: 0;
}
.controls {
position: fixed;
top: 0;
left: 0;
z-index: 1;
}
.controls button {
font-size: 40px;
display: block;
width: 220px;
}
.centerline {
position: fixed;
top: 50vh;
left: 0;
right: 0;
height: 0;
border: 1px dashed #777;
z-index: 1;
}
/* Important styles */
html, body {
height: 100%;
background: #ffc;
}
.container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #ccf;
overflow: visible;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
}
.container .content {
margin: auto 0;
padding-bottom: 100px;
}
p {
background: #cfc;
}
</style>
<script type="text/javascript">
let counter = 0;
function addItems() {
let content = document.querySelector('.container .content');
for (let i = 0; i < 3; ++i) {
let p = document.createElement('p');
p.innerText = `Item ${++counter}`;
content.appendChild(p);
}
}
function removeItems() {
counter = Math.max(counter - 3, 0);
let content = document.querySelector('.container .content');
for (let i = 0; i < 3; ++i) {
if (content.hasChildNodes()) {
content.removeChild(content.lastChild);
}
}
}
</script>
</head>
<body>
<!-- Demo elements -->
<div class="controls">
<button onclick="addItems()">Add</button>
<button onclick="removeItems()">Remove</button>
</div>
<div class="centerline"></div>
<!-- Important elements -->
<div class="container">
<div class="content"></div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment