I have the following DIV inside a body tag:
<div id="AlertDiv"><h1>Yes</h1></div>
And these are their CSS classes:
#AlertDiv {
position:absolute;
height: 51px;
left: 365px;
top: 198px;
width: 62px;
background-color:black;
color:white;
}
#AlertDiv h1{
margin:auto;
vertical-align:middle;
}
How can I align vertically and horizontally H1 inside DIV?
AlertDiv
will be bigger than H1.
You can add line-height:51px
to #AlertDiv h1
if you know it's only ever going to be one line. Also add text-align:center
to #AlertDiv
.
#AlertDiv {
top:198px;
left:365px;
width:62px;
height:51px;
color:white;
position:absolute;
text-align:center;
background-color:black;
}
#AlertDiv h1 {
margin:auto;
line-height:51px;
vertical-align:middle;
}
The demo below also uses negative margins to keep the #AlertDiv
centered on both axis, even when the window is resized.
Demo: jsfiddle.net/KaXY5