【问题标题】:Use image as container for text instead of div使用图像作为文本容器而不是 div
【发布时间】:2018-02-23 10:58:52
【问题描述】:

我试图在图像底部显示一个简短的图像描述,现在它看起来像这样:https://www.bootply.com/render/Gwde8WHtot

但我希望绿色背景与图像对齐(而不是红色边框),这意味着文本的宽度和高度属性应该响应图像,而不是它所在的容器。

这是我当前的代码:

// CSS
.textoverimage {
    position: absolute;
    background: green;
    font-family: 'Roboto', sans-serif;
    font-size: 15px;
    color: white;
    word-wrap: break-word;
    text-align: center;
    width: 100%;
    height: auto;
    bottom: 0;
    left:0;
    padding: 5px;
    z-index: 5;
    border-radius: 0px 0px 3px 3px;
}

// HTML
<div class="container">
  <div class="row">
    <div id="0" class="col-6 col-sm-4 col-md-3 col-lg-2" style="margin-top:7px;margin-bottom:7px;border:1px solid red">
      <a href="#" class="d-block mb-12">
        <img class="rounded  img-fluid" src="http://via.placeholder.com/160x230.jpg">
        <div class="textoverimage">Random</div>
      </a>
    </div>
  </div>
</div>

完整示例:https://www.bootply.com/Gwde8WHtot

有什么方法可以实现吗?如果在调整浏览器大小时调整列/图像大小,则文本也应该是响应式的。任何帮助是极大的赞赏!提前致谢。

【问题讨论】:

  • @AaronMcGuire 是的,它应该看起来像这样,但它应该位于图像底部的顶部,而不是下方

标签: html css image containers


【解决方案1】:

你快到了,你只需要添加:

.d-block {
  position: relative;
}

由于锚点环绕图像,因此您在此处设置了相对边界,这意味着 position: absolute inside 将相对于这些边界。

【讨论】:

  • 谢谢,这成功了!一旦“冷静下来”结束,就会接受作为答案。非常感谢!
  • 只有一件事困扰着我,它与您的解决方案无关,您知道我如何防止这种行为:i.imgur.com/s8hSNWV.png 我在这里用您的示例更新了代码:bootply.com/fJ7RqrD2nX 它仅在达到可能的最小浏览器大小之前发生,但您已经帮了我很多忙,这只是奶油
  • 尝试添加.d-block img { width: 100% }
【解决方案2】:

您可以将 ('.d-block mb-12') div 设置为 position:relative ,然后将文本设置为 position:absolute (希望 div 覆盖整个图像。 完成后,您可以使用:

.textoverimage{
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
margin: 0 auto;
}

那么父 div 将是:

.d-block {
postion:relative;
width:100%;
height:100%;
}

这应该可行,希望 .d-block div 有一个父 div,其宽度/高度在 PX 中设置,如果不降低高度和宽度 attr,那么你应该是完美的。

不要忘记 Margin: 0 auto;

如果它不是绝对居中,那么可以尝试添加

display:block;      or      display:inline-block;

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多