Vertical and horizontal align all content and elements inside a div

advertisements

I have a div with some content, in this case 2 buttons and a paragraph. I want to vertically and horizontally align all the elements and content inside that div by changing its CSS. How can I do this?

<style>
  .middle {
    What to type in here?
  }
</style>

<div class="middle">
  <p>Hello</p>
  <br />
  <input type="button" value="Button 1">
  <br />
  <input type="button" value="Button 2">
</div>


Check this style:

/* stretch them to window's height */
html, body {
    height:100%;
}

/* normalize them from default 8px to zero */
html, body, div, p {
    margin:0;
    padding:0;
}

/* vertical align */
 body {
    display:table;
    width:100%;
    overflow:auto;
}
.middle {
    display:table-cell;
    vertical-align:middle;
}

/* horizontal align */
.middle {
    text-align:center;
}

jsfiddle #1

Alternatively you can put all your html code into some container div and stylize it instead of the body tag:

jsfiddle #2

For completeness' sake, the simplest style where the content of the .middle division is centered and the height of the .middle also depends on its inner content can be made with the equal top and bottom paddings as follows:

.middle {
    padding:5em 0;
    text-align:center;
}

jsfiddle #3