图像上居中文本时,使用绝对定位的底部0位置不起作用。

5
我正试图将文本放置在页面上一张图片的中间。我想在页面上其他不同高度和宽度的图片上也使用这个方法。我已经将图片相对定位,文本绝对定位,但是 bottom:0 似乎不起作用。
<div class="image">
<img src="http://lorempixel.com/300/300/">
    <header class="text">
        <h1>header</h1>
        <a href="#">button</a>
    </header>
</div>

这是CSS代码:
.image {
  display: inline-block;
  position: relative;
}

.text {
  position: absolute;
  top: 0;
  left: 0;
  color: white;
  text-align: center;
  bottom: 0;
  right: 0;
}

.text h1 {
  text-transform: uppercase;
  font-family: Helvetica, Arial;
  font-size: 16px;
  letter-spacing: .5px;
}

.text a {
  font-size: 14px;
  border: 1px solid white;
  padding: 5px 30px;
  color: white;
  text-decoration: none;
}

这是一段英文,意思是:“这里有一个指向 jsfiddle 的链接:http://jsfiddle.net/yg4Ar/”。

"bottom:0" 在你的示例中运行得非常好 - 给 .text 设置一个背景颜色,然后你就会看到它了,该元素从顶部拉伸到其容器元素的底部。(我可能无法实现你想要的,但这是完全不同的问题 - 这也是一个广泛讨论的话题,使用CSS居中内容几乎和Web一样古老...) - CBroe
1
你对CSS中的定位有一些误解,其中之一是位置不应该应用于设置它的元素内部的子元素,而是相对于其父元素的元素。 - marekful
3个回答

5

您拥有:

position: absolute;
top: 0; // This keeps text top.
left: 0;
color: white;
text-align: center;
bottom: 0;
right: 0;

所以这会使你的文本高度达到100%.. 因为有了 top:0.. 所以只需删除那个 top:0 即可。

如果你想要垂直居中你的文本,你需要指定/计算一些文本的高度,并将其减半作为负边距添加到你的CSS中,并将顶部值设置为50%,例如:

.text {
    position: absolute;
    top: 50%;
    left: 0;
    margin-top: -30px; // This should be half of your text div:s height
    color: white;
    text-align: center;
    bottom: 0;
    right: 0;
} 

例子:http://jsfiddle.net/9zyx2/


移除'top:0'可以解决'bottom: 0'的问题,但是文本会被固定在图像底部。原帖作者的实际问题是“试图将文本放置在图像中央”。 - Jim
将此选项添加到我的答案中。 - Hardy

5

尝试将顶部设置为百分比:

.text {
    position: absolute;
    top: 25%;
    left: 0;
    color: white;
    text-align: center;
    bottom: 0;
    right: 0;
}

是的,我想百分比是正确的选择。当我有不同尺寸的图像时,我只需要覆盖顶部即可。 - hannah

1

试试这个:

.text {
    position:absolute;
    top: 100px;
    left: 0;
    color: white;
    text-align: center;
    bottom: 0;
    right: 0;
}

1
在这里查看,您会发现它是居中的:http://jsfiddle.net/yg4Ar/15/ 110可能是一个更好的数字,但是通过改变顶部值,您可以看到它会将文本向下移动。 - freeWind
1
是的,但图像高度可能会有所不同。阅读“我还想在页面上使用其他高度和宽度不同的图像”,那么当图像高度为100px时会发生什么?我告诉你:文本div消失了。 - Hardy
1
这就是为什么在我的解决方案中,我建议在顶部使用百分号的原因。 - Jim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接