htmlcssscrollcenterscrollbars

How to make scrollbars appear when DIV doesn't have enough room but keep DIV centered?


I want to create a centered form.

HTML:

<div id="profileContainer”>…</div>

CSS:

#profileContainer {
  border-radius: 25px;
  background: #ffffff;
  padding: 10px;
  width: 100%;
  max-width: 760px;
  display: inline-block;
  position: fixed;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

The problem is when the screen is vertically shorter, part of the form gets hidden, and no scrollbars appear to make it accessible: JSFiddle.

Question:

How do I get scrollbars to appear when vertical space alone is insufficient, but keep my div centered horizontally and vertically when there is enough space?


Solution

  • This can easily be achieved with flexbox by simply removing all of the positioning from #profileContainer and adding the following rules to body:

    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    

    The first three rules will center #profileContainer while the last one makes sure that the body will always be at least the full height of the view.

    JSFiddle doesn't show the last rule correctly and your example is too big to embed it here, so I moved it over to codepen.

    As a side note, you have an extra closing div tag just before you close main.