vertically center content that exceeds window height

人盡茶涼 提交于 2019-12-24 16:49:20

问题


I'm trying to vertically center a box by using display: flex;, while it's working when the box is small enough, but when the box exceeds the window height, part of the content will be cut off.

Working example: http://codepen.io/woutr_be/pen/bVQXLe

Example with large height: http://codepen.io/woutr_be/pen/KdrOZm

It seems to be related to the body: { height: 100%; }, but when I remove that, the box isn't centered anymore: http://codepen.io/woutr_be/pen/MazNrE

I can't figure out how to make it work when the box has a large height.


回答1:


This is generally what I tend to use when I need to align an element vertically. Try changing the height and width and you will notice how it automatically calculates to center the element.

div.container{
    width: 300px;
    height: 300px;
    position: relative;
  
    background: salmon;
}

div.container > div.wrapper{
    position: absolute;
  
    top: 50%;
    left: 50%;
  
  
    -webkit-transform: translate(-50%, -50%);
       -moz-transform: translate(-50%, -50%);
            transform: translate(-50%, -50%);
  
    background: red;
}
<div class='container'>
    <div class='wrapper'>
      <label>Some text</label>
      <label>Some more text</label>
    </div>
</div>



回答2:


You could simply add max-height: 90% to .modal-box. The 90% is a bit arbitrary, but will give you some padding around the modal.



来源:https://stackoverflow.com/questions/33664202/vertically-center-content-that-exceeds-window-height

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