如何将文本块放在固定背景上的图像上?

时间:2018-02-21 17:03:27

标签: html css

我想把新闻标题放在图像背景上:

enter image description here

我想出的是:

 <div class="image-container">
     <a href="/path"><img src="/path/to/img" class="img-thumbnail"></a> 
     <div class="text-block">
         <div class="bottom-right">My News Title</div>
     </div>
 </div> 

CSS:

.text-block {
    position: absolute;
    bottom: 0px;
    right: 0px;
    background-color: #fff;
     opacity: .8; 
    color: black;
    width: 100%;
}

.bottom-right {
  color: black;
    position: absolute;
    bottom: 8px;
    right: 16px;
    background-color: #fff;
}

结果如下:

enter image description here

我的问题是如何修改我的代码,使标题出现在半透明的背景上,覆盖了底部的1/3,就像上面的咖啡图片一样?

3 个答案:

答案 0 :(得分:1)

您可以稍微清理标记并使用带标题的简单容器元素(例如div和标题)。

正如@ zero298所述,如果图像没有传达任何信息,则应将其定义为容器的背景

  

Codepen demo

<强>标记

<div style="background-image: url(https://.../coffee-serum-300x240.jpg)">
  <h2>
       The title of this article  
       may span across several lines. 
       but it's always anchored on the bottom
   </h2>
</div>

<强> CSS

div {
  width: 300px;
  height: 240px;
  background-size: cover;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

div h2 {
  background: rgba(255, 255, 255, .6);
  margin: 0;
  padding: 1em 1em 3em 1em;
}

最终结果

enter image description here

答案 1 :(得分:1)

由于图像是装饰性的,请使用.card { width: 100px; height: 200px; color: white; background-color: blue; background-image: url(https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg); background-size: contain; background-position: center; background-repeat: no-repeat; display: flex; flex-direction: column; justify-content: flex-end; } .text{ background-color: rgba(1,1,1,0.5); }

&#13;
&#13;
<div class="card">
<div class="text">
  <h2>Hello World</h2>
  <p>Foo bar</p>
  </div>
</div>
&#13;
{
    _id: value
    colorValues: [
        {
            color: purple  (string)
            stateField: Open  (string)
        }
        {
            color: green  (string)
            stateField: Closed  (string)
        }
    ]
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以执行以下操作:

.bottom-right {
color: black;
position: absolute;
bottom: 50%;
right: 50%;
background-color: #fff; }

.image-container {
position: relative;
text-align: center;
color: white; }

.text-block {
position: absolute;
top: 95%;
left: 50%;
height: 40%;
transform: translate(-50%, -50%); }

另外,我认为这对w3schools非常有帮助。  https://www.w3schools.com/howto/howto_css_image_text.asp

相关问题