为什么我的文本对齐和垂直对齐不适用于图像?

Why does my text-align & vertical-align not work with an image?

我是新来的,也是 HTML 的新手 :D

刚刚遇到一个问题,发现 Whosebug 有很多很棒的开发人员,所以我把我的问题扔在这里,等待你的帮助!

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Cafe</title>
    <style>
    #container {
        width:550px;
        height:733px;
        position:relative;
    }

    img#containerImage {
        position:absolute;
        left: 0;
        top: 0;
    }

    h1#header {
        z-index: 100;
        position: absolute;
        color: white;
        font-size:24px;
        font-weight:bold;
        border:1px solid red;
        margin: 0px;
        vertical-align: middle;
        text-align: center;
    }
</style>
</head>

<body>
    <div id="container">
        <img id="containerImage" src="olgagonggam.jpg"/>
        <h1 id="header">Cafe</h1>
    </div>
</body>
</html>

这是我编写的代码。我想知道为什么没有设置文本 middle/center,如何解决这个问题?文本显示在页面的左上角,但我想将其设置在图像的中心。任何人都请帮助我! :D

如果图像的大小已知(问题并未完全清楚)并且 h1 的大小也已知,您可以简单地以像素为单位指定位置。在这种情况下,将左侧定位在图像宽度 (275px) 减去 h1 宽度的一半 (30px) 的一半,顶部定位在图像高度 (367px) 的一半减去 h1 高度的一半 (15px)。

#container {
  width: 550px;
  height: 733px;
  position: relative;
}
img#containerImage {
  position: absolute;
  left: 0;
  top: 0;
}
h1#header {
  z-index: 1;
  position: absolute;
  left: 245px;
  top: 352px;
  width: 60px;
  line-height: 30px;
  color: white;
  font-size: 24px;
  font-weight: bold;
  border: 1px solid red;
  margin: 0;
}
<div id="container">
  <img id="containerImage" src="http://lorempixel.com/550/733" />
  <h1 id="header">Cafe</h1>
</div>

如果您不想以像素为单位对大小进行硬编码,那就更棘手了。我想出了这个解决方案,但它没有围绕 h1 的边框。

#container {
  width: 550px;
  height: 733px;
  position: relative;
}
img#containerImage {
  position: absolute;
  left: 0;
  top: 0;
}
h1#header {
  z-index: 1;
  position: absolute;
  top:50%; left:0; width:100%;
  color: white;
  font-size: 24px; line-height:0;
  font-weight: bold;
  text-align:center;
}
<div id="container">
  <img id="containerImage" src="http://lorempixel.com/550/733" />
  <h1 id="header">Cafe</h1>
</div>