【问题标题】:Vertically align absolute positioned <p> inside image [closed]垂直对齐绝对定位的<p>内部图像[关闭]
【发布时间】:2016-01-28 17:27:27
【问题描述】:

如何垂直对齐图像内绝对定位的p 元素?

<div>
    <img class="test-img" src="test.jpg">
    <p class="tag">text with multiple lines here</p>
</div>

因为我不知道它的高度。

编辑

我的图片不能是背景,它是在运行时加载的。我想将文本放在图像中。到目前为止我所拥有的就是这张图片,我的文字是top: 0。我现在想将它垂直对齐到图像的中间。

我的 CSS:

.test-img {
    height: 320px;
    width: 240px;
}

.tag {
    position: absolute;
    top: 0;
}

div {
    height: 320px;
    width: 240px;
    display: inline-block;
    position: relative;
}

我不知道我的p 标签的高度,因为它的文本来自数据库。

【问题讨论】:

  • 图像的“内部”是什么意思?
  • Position text over image的可能重复
  • 由于我不知道如何做到这一点,我在谷歌上搜索了很多,但我没有找到任何可以帮助我的东西。这就是我发布这个问题的原因。

标签: html css vertical-alignment absolute


【解决方案1】:

除了使用 display:table; 之外,CSS 确实没有什么可以做到这一点(特别是因为它必须是动态高度),但至少现在是 it has pretty good compatibility

.test-img {
    height: 320px;
    width: 240px;
    display:block;
}

.inner {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: table;
}

.tag {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    font-size: 30px;
    padding: 1em;
}

.outer {
    height: 320px;
    width: 240px;
    position: relative;
}
<div class="outer">
    <img class="test-img" src="//placehold.it/240x320">
    <div class="inner">
        <p class="tag">text with multiple lines here</p>
    </div>
</div>

【讨论】:

  • 完美!非常感谢。
【解决方案2】:

为什么不尝试标签中的样式

<p class="tag" style="position: absolute; right:140px; top:320px;"  >
   text with multiple lines here
</p>

或者添加一个id并在css中设置id的样式

<p class="tag" id="my_id"   >
   text with multiple lines here
</p>

在css中

#my_id {
   position: absolute; right:140px; top:320px;
}

你也可以试试margin-top: 360px;

【讨论】:

  • 我已经这样做了。但是我不能定义一个静态的“top”值,因为我不知道我的“p”会有多少行,所以它不会总是垂直对齐。
  • 尝试相对位置发生了什么?
  • 我的“标签”的相对位置?它不会在图像内部(或上方),这就是我想要的。
  • 你的图片是固定大小还是变化?
  • 绝对顶部是&lt;p&gt; 的顶部位置,如果这是一个问题,请尝试使用margin-top。 (我已经更新了答案)
猜你喜欢
  • 1970-01-01
  • 2010-12-12
  • 1970-01-01
  • 2013-01-12
  • 2013-05-02
  • 1970-01-01
  • 2011-07-22
  • 2018-11-06
  • 1970-01-01
相关资源
最近更新 更多