Skip to content

Instantly share code, notes, and snippets.

@martynchamberlin
Last active January 29, 2018 16:30
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 martynchamberlin/8077219248bfd0ddfb529aa83c123896 to your computer and use it in GitHub Desktop.
Save martynchamberlin/8077219248bfd0ddfb529aa83c123896 to your computer and use it in GitHub Desktop.
How Flexbox Handles Uneven Amounts of Space in justify-content: center
<html>
<head></head>
<body>
<h2>The Question</h2>
<p>In flexbox, if <code>align-items: center</code> is declared, and a child has a width that cannot be perfectly centered, where does the extra pixel go? <em>Note: on a retina device, the browser can split the "pixels" so this is a non-issue there</em>.</p>
<h2>The Answer</h2>
<h3>In Horizontal spacing</h3>
<p>The left gets the extra pixel.</p>
<div class="flex horizontal outer">
<div class="inner"></div>
</div>
<h3>In Horizontal spacing done with a different implementation</h3>
<p>The left gets the extra pixel.</p>
<div class="flex horizontal-alt outer">
<div class="inner"></div>
</div>
<h3>In Vertical spacing</h3>
<p>The top gets the extra pixel.</p>
<div class="flex vertical outer">
<div class="inner"></div>
</div>
<h3>Non-flexbox</h3>
<p>What about a simple <code>margin: 0 auto</code> situation? In that case, the left gets the extra pixel as well.</p>
<div class="horizontal outer zero-auto">
<div class="inner">
</div>
<style>
* {
font-size: 17px;
}
h3, p {
margin: 0 0 10px;
}
.outer {
height: 10px;
width: 10px;
background: red;
margin-bottom: 10px;
}
.flex {
display: flex;
justify-content: center;
}
.inner {
background: white;
}
.horizontal-alt {
flex-direction: column;
align-items: center;
}
.horizontal {
flex-direction: row;
}
.horizontal .inner, .horizontal-alt .inner {
width: 3px;
height: 100%;
}
.vertical {
flex-direction: column;
}
.vertical .inner {
width: 100%;
height: 3px;
}
.inner.second {
background: green;
}
.vertical .second {
height: 2px;
}
.horizontal .second {
width: 2px;
}
.zero-auto .inner {
margin: 0 auto;
}
</style>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment