Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 925
Dave Avatar asked Oct 02 '16 16:10

Dave


1 Answers

I would change the CSS rule for #profileContainer like this:

#profileContainer {
    border-radius: 25px;
    background: #ffffff;
    padding: 10px;
    width: 90%;
    max-width: 760px;
    display: block;
    position: relative;
    margin: 30px auto 0;
}

position: relative instead of fixed, less width, since 100% plus the padding exceeds the container width. margin: 0 auto to center horizontally instead of left: 50% and transformX(-50%). Fixed margin top instead of vertical centering to avoid the effect you describe.

Fiddle: http://jsfiddle.net/qacv17gq/1/

Addition: Except with javascript/jQuery you won't be able to center a container vertically and not have parts of it hidden with no scrollbar when the window/screen height is less than the container's height.

like image 158
Johannes Avatar answered Oct 03 '22 20:10

Johannes