Search code examples
csscss-positionvertical-alignmentcenteringalignment

Centering content vertically and horizontally, the browser doesn't allow scrolling


I'm using the following css to center my content both vertically and horizontally; the problem is that when you minimize the browser to make it smaller than the content div, it continues to center but without the ability to scroll. The content just cuts off at the top.

#splash-centre-container{
  position: absolute;
  top: 50%;
  left: 50%;
  height: 550px;
  width: 760px;
  min-height: 550px;
  padding: 20px;
  margin: -310px 0 0 -400px;
}

Solution

  • This is because when you position something as absolute you pull it out of the flow of the page, it doesn't "take up space".

    You want to apply min-width and min-height to body (or its container) so that when the screen gets too small, the element that the splash screen is centered within will never get smaller than the splash screen and thus won't go off screen.

    jsFiddle

    enter image description here

    HTML

    <div class="spacer">
        <div id="splash-centre-container">abc</div>
    </div>
    

    CSS

    html, body { 
        min-width:760px;
        height:100%;
        min-height:550px;
        position:relative;
    }
    #splash-centre-container {
        position: absolute;
        top: 50%;
        left: 50%;
        height: 550px;
        width: 760px;
        margin: -275px 0 0 -380px;
        background-color:red;
    }