Center a H1 tag inside a DIV

后端 未结 7 856
遥遥无期
遥遥无期 2020-12-15 15:39

I have the following DIV inside a body tag:

Yes

And these are their CSS classes

7条回答
  •  一向
    一向 (楼主)
    2020-12-15 16:00

    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

提交回复
热议问题