【问题标题】:position: absolute bottom: 0 not working when centering text on image位置:绝对底部:0 在图像上居中文本时不起作用
【发布时间】:2014-09-03 15:44:37
【问题描述】:

我正在尝试在页面上的图像中间放置文本。我也想在页面上具有不同高度和宽度的其他图像上使用它。我有相对定位的图像和绝对定位的文本,但底部: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;
}

还有一个指向小提琴的链接:http://jsfiddle.net/yg4Ar/

【问题讨论】:

  • bottom:0 在你的例子中工作得很好——给.text 一个背景颜色,然后你会看到它,元素从其容器元素的顶部到底部拉伸。 (我可能无法实现你想要的,但这完全是另一回事——而且在那个问题上得到了广泛讨论,以 CSS 为中心是一个几乎与网络一样古老的话题......)
  • 您对 CSS 中的定位有一些误解,其中之一是该位置不是应用于它所设置的元素内的子元素,而是应用于相对于它的元素 父母.

标签: html css image absolute


【解决方案1】:

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

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

【讨论】:

  • 是的,我认为百分比是要走的路。当我有不同尺寸的图像时,我只需要覆盖顶部。
【解决方案2】:

你有:

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;
} 

Example:http://jsfiddle.net/9zyx2/

【讨论】:

  • Removing 'top:0' "fixes 'bottom: 0'; 但是,文本然后锚定到图像的底部。OP的问题实际上是“试图将文本放在中间一张图片”。
  • 将此选项添加到我的答案中。
【解决方案3】:

试试这个:

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

【讨论】:

  • 在这里查看它,您会看到它居中 jsfiddle.net/yg4Ar/15 110 可能是一个更好的数字,但是您可以通过更改顶部值看到它会将文本向下移动
  • 是的,但图像高度可能会有所不同.. 阅读“我想在页面上具有不同高度和宽度的其他图像上使用它”那么当图像高度为 100 像素时会发生什么? ?我告诉你:文本 div 消失了..
  • 这就是为什么在我的解决方案中,我建议在顶部使用 %。
猜你喜欢
  • 1970-01-01
  • 2017-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多