How can I properly center the #content
without overflowing the #container
? margin: auto
kinda works, but looks like a hack to me, I would like not to use any margins with CSS Flexbox.
Keep in mind that the #container
has position: fixed
.
Here's the code demonstrates the issue: [View in JSFiddle ↗]
document.getElementById('content').innerHTML = [...Array(100).keys()].join('<br>')
#container {
position: fixed;
background: lightblue;
top: 0; bottom: 0;
left: 0; right: 0;
display: flex;
align-items: center;
justify-content: center;
overflow: auto;
}
#content {
border: 1px solid green;
/* uncomment the hack below to get desired behavior */
/* margin: auto */
}
<div id="container">
<div id="content">
</div>
</div>
Desired behavior you can check with uncommenting margin: auto
, question is how to achieve the same result with only flex-
properties and without margin: auto
.
you can set the
position
of the#content
asabsolute
and settop: 0;
in the style, here0s a working plunkrTry this. I have taken one parent div of
content
id and giveheight:100vh
tocontent_wrap
class.Just replace
align-items: center;
toalign-items: left;
in your cssbecause you are using flex and
align-items: center;
div is showing from center part so just replace it with left.Without a markup change you can't, as when using
align-items: center
, it by design overflow in both directions if the content exceed the flex container.Also note that
auto
margins has a special meaning in Flexbox, and it is not a hack, quite the opposite, so in this case, they are the flex based solution to accomplish exactly that.