user2039981
user2039981

Reputation:

Vertical and horizontal align all content and elements inside a div

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>

Upvotes: 3

Views: 6530

Answers (2)

Stano
Stano

Reputation: 8949

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

Upvotes: 0

reggaemahn
reggaemahn

Reputation: 6658

Change your html to this:

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

And your CSS to

.middle
{
padding: 0;
}

#mydiv
{
display: table;
margin: 0 auto;
}

#mydiv *
{
display: block;
}

input[type='button']
{
margin: 0;
}

Working fiddle: http://jsfiddle.net/n6522/1/

PS. The border and width is just to give you an idea. You don't need to add the first block.

Upvotes: 1

Related Questions