为什么我的文字对齐& vertical-align不能与图像一起使用?

时间:2015-07-06 08:29:36

标签: html css alignment

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

刚遇到问题,发现Stackoverflow有很多令人惊讶的开发人员,所以我在这里抛出我的问题,等待你的帮助!

<!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>

这就是我编码的内容。我想知道为什么文本没有设置在中间/中心,以及如何解决这个问题?文本显示在页面的左上方,但我想将其设置在图像的中心。有人请帮帮我! :d

1 个答案:

答案 0 :(得分:0)

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

&#13;
&#13;
#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;
}
&#13;
<div id="container">
  <img id="containerImage" src="http://lorempixel.com/550/733" />
  <h1 id="header">Cafe</h1>
</div>
&#13;
&#13;
&#13;

如果您不想以像素为单位对硬件进行硬编码,则会变得更加棘手。我提出了这个解决方案,但它并没有围绕h1的边界。

&#13;
&#13;
#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;
}
&#13;
<div id="container">
  <img id="containerImage" src="http://lorempixel.com/550/733" />
  <h1 id="header">Cafe</h1>
</div>
&#13;
&#13;
&#13;

相关问题