在 <div> 中居中放置 <h1> 标签

新手上路,请多包涵

我在 --- 标签内有以下 <div> <body> 标签:

 <div id="AlertDiv"><h1>Yes</h1></div>

这些是它们的 CSS 类:

 #AlertDiv {
    position:absolute;
    height: 51px;
    left: 365px;
    top: 198px;
    width: 62px;
    background-color:black;
    color:white;
}

#AlertDiv h1{
    margin:auto;
    vertical-align:middle;
}

我如何垂直和水平对齐 <h1> 内部 <div>

AlertDiv 将大于 <h1>

原文由 VansFannel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 837
2 个回答

您可以将 line-height:51px 添加到 #AlertDiv h1 如果您知道它只会成为一行。还要添加 text-align:center#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;
}

下面的演示还使用负边距来保持 #AlertDiv 在两个轴上居中,即使在调整窗口大小时也是如此。

演示: jsfiddle.net/KaXY5

原文由 Marcel 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 hX 标签上

width: 100px;
margin-left: auto;
margin-right: auto;

原文由 bluehallu 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题