Search code examples
htmlcssdivider

Cannot vertically center multiple divs within a div, and vertically center their elements within them


I'm quite new to HTML/CSS and trying to understand a lot of the concepts involved. I'm trying to vertically center 2 divs within a larger div, and also center the elements within those divs.

HTML:

<html>
<head>
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
    <div id="MainDiv">

      <div id="SubDiv">
        <form method="POST">
            <input type="text" name="example1" class="Text">
            <input type="text" name="example2" class="Text">
            <input type="submit" value="Go"> <br>
        </form> <br/>
      </div>

      <div id="SubDiv">
          <input type="button" value="Button 1"/>
          <input type="button" value="Button 2"/>
      </div>

  </div>
</body>

CSS:

#MainDiv 
{
    width: 60%;
    height: 30%;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
    text-align: center;
    border:  1px solid black;
}

#SubDiv
{
    width: 90%;
    height: 45;
    margin: auto;
    border:  1px solid black;

}

.Text
{
    width: 40%;
}

You can see the result here: the main div completely centered, but I'm unable to control the vertical centering of anything else.

Naturally, I've done a lot of searching trying to fix this, but any fixes seem to either do nothing or mess things up even more. Any assistance would be greatly appreciated.


Solution

  • You may want to consider flexbox for this, which has vertical centering built in

    Great intro to flexbox here: http://flexboxin5.com/