CSS Flexbox: a centered child overflows a parent with position fixed

北城以北 提交于 2019-12-02 05:26:44

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.

‘center’
    The flex item’s margin box is centered in the cross axis within the line. (If the cross size of the     flex line is less than that of the flex item, it will overflow equally in both directions.)

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.

document.getElementById('content').innerHTML = [...Array(100).keys()].join('<br>')
#container {
  position: fixed;
  background: lightblue;
  top: 0; bottom: 0;
  left: 0; right: 0;

  display: flex;
  overflow: auto;
}

#content {
  border: 1px solid green;
  margin: auto;
}
<div id="container">
  <div id="content">
  </div>
</div>

Try this. I have taken one parent div of content id and give height:100vh to content_wrap class.

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 ;*/
}
.content_wrap  {
  height: 100vh;
}
<div id="container">
  <div class="content_wrap">
    <div id="content">
    </div>
  </div>
</div>

Just replace align-items: center; to align-items: left; in your css

because you are using flex and align-items: center; div is showing from center part so just replace it with left.

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;*/
  align-items: left;
  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" class="mx-auto">
  </div>
</div>

you can set the position of the #content as absolute and set top: 0; in the style, here0s a working plunkr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!