htmlcssalignmentvertical-alignment

Center an <h1> tag inside a <div>


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 vertically and horizontally align an <h1> inside of a <div>?

AlertDiv will be bigger than <h1>.


Solution

  • 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