Reputation:
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
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;
}
Alternatively you can put all your html code into some container div
and stylize it instead of the body
tag:
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;
}
Upvotes: 0
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