1

I am trying to centre a DIV which contains a form. I have managed to grey out the back ground and would like to centre the form within the window. Below is what I have done so far, but I do not know how to progress it further to get the result that I need.

I am able to 'auto margin' horizontally, but I am not able to do this vertically (please see image). If you stretch the browser window further vertically, the form stretches to occupy all of the vertically space.

enter image description here

 #idOfForm{
 margin: auto;
 z-index: 10000;
 position: absolute;
 background-color: white;
 top: 0;
 bottom: 0;
 left: 0;
 right: 0;
 padding: 10px;
 width: 500px;
 min-height: 250px;
 border: 1px solid #ccc;
 border-radius: 10px;
 box-shadow: 3px 3px 3px #b8b8b8;
 font-family: sans-serif;
 color: #484848;
 }
dave
  • 475
  • 6
  • 17

4 Answers4

2

This is how you can center elements easily:

Suppose you have the following:

<div class="aaa">
    fsdfsd
</div>

Use the following css:

.aaa {
    transform: translate3d(-50%, -50%, 0);
    position: absolute;
    top: 50%;
    left: 50%;
 }

Here is jsfiddle: https://jsfiddle.net/ffnvjz4q/
This is the code you need:

#idOfForm{
    transform: translate3d(-50%, -50%, 0);
    z-index: 10000;
    position: absolute;
    background-color: white;
    top: 50%;
    bottom: 0;
    left: 50%;
    right: 0;
    padding: 10px;
    width: 500px;
    min-height: 250px;
    border: 1px solid #ccc;
    border-radius: 10px;
    box-shadow: 3px 3px 3px #b8b8b8;
    font-family: sans-serif;
    color: #484848;
 }
Naor
  • 23,465
  • 48
  • 152
  • 268
1

What browsers does your 'app' must support ? The easiest way to achieve this is using CSS flexbox but it is not fully support yet

http://caniuse.com/#search=flexbox

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

.parent {
  display: flex;
  height: 300px; /* Or whatever */
}

.child {
  width: 100px;  /* Or whatever */
  height: 100px; /* Or whatever */
  margin: auto;  /* Magic! */
}
1
<div class="modal">
 <div class="modal-body">
  <!-----put your form code here --->
 </div>
</div>


.modal {
 position: fixed;
 top: 0;
 bottom: 0;
 left: 0;
 width: 100%;
 height: 100%;
 background-color: rgba(0,0,0,0.4);
 z-index: 2;
}

.modal-body {
 position: relative;
 max-width: 500px;
 width: 100%;
 margin: 50px auto 20px;
 background-color: #fff;
 min-height: 50px;
}
Srikanth Reddy
  • 345
  • 2
  • 4
0

You could try

.element {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

Source: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

Dave
  • 66
  • 3