CSS块在图像之上

时间:2016-11-10 17:53:29

标签: html css

我正在尝试创建这样的东西(没有蓝线): enter image description here

灰色是我必须插入的图片,上面必须显示字母。

我试图自己做但我不能

3 个答案:

答案 0 :(得分:2)

<img>标记放入div包装中,将第二个div 放入第一个(img之后),写入文本到该div并使用CSS规则,如

.my_div_wrapper {
  position: relative;
  width: 300px;
}
.my_image {
  width: 100%;
)
.my_text_over_image {
  position: absolute;
  bottom: 20px;
  height: 50px;
  color: white;
  background: rgba(0, 0, 0, 0.5);
}

重要的是绝对的位置。背景设置中的最后一个数字是背景颜色的不透明度。根据需要选择颜色和不透明度(以及其他所有内容)。

答案 1 :(得分:2)

这是一个有着如何解决这个问题的知识库:

http://codepen.io/leofontes/pen/ENPNjq

&#13;
&#13;
.container {
  height: 200px;
  position: relative;
  width: 200px;
}
img {
  height: 100%;
  width: 100%;
}
.sometext {
  background-color: cyan;
  position: absolute;
  top: 100px;
  width: 100%;
  z-index: 999;
}
&#13;
<div class="container">
  <img src="http://cdn.istoe.com.br/wp-content/uploads/sites/14/2016/11/0eea5026741522fcaacbdc814652bfc5dce89aed-768x432.jpg" alt="" />
  <p class="sometext">lorem ipsum</p>
</div>
&#13;
&#13;
&#13;

你必须使用z-index才能拥有一个元素而不是另一个元素。我确定这个问题有很多其他实现,这是我的快速回答,希望它可以帮到你。

我真的推荐这篇博文来更好地理解z-index,以及在这种情况下真正发生的事情:https://philipwalton.com/articles/what-no-one-told-you-about-z-index/

答案 2 :(得分:2)

您可以使用background-img属性在后台使用图片,并使用position: absolute将项目置于其上并制作背景position: relative

请看下面的代码段:

.bg-img {
  width: 300px;
  height: 200px;
  background-image: url('http://lorempixel.com/300/200');
  position: relative;
}

.bg-img:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.6);
}


.link {
  position: absolute;
  top: 70%;
  width: calc(100% - 40px);
  display: flex;
  background: rgba(51, 181, 229, 0.6);
  color: #fff;
  padding: 10px 20px;
  text-decoration: none;
}

.child {
  flex: 1;
}

.arrow {
  text-align: right;
}
<div class="bg-img">
  <a href="#" class="link">
    <span class="child text">Hello World</span>
    <span class="child arrow">-></span>
  </a>
</div>

希望这有帮助!