我停止使用背景图片时屏蔽位置不正确

时间:2017-05-27 09:32:15

标签: html css

http://jsfiddle.net/4UNuB/5/为例,图片已设为背景

.box1 {
    border: #999 2px solid;
    width: 180px;
    height: 250px;
    background-image:  url(http://smilesoftware.com/assets/images/uploads/products/icon_pdfpenipad_140x140.png);
    background-position: center;
    background-repeat: no-repeat;
}

但是,如果我不能使用背景图片,而是在div中拥有img src,就像这样

<div class="box1"> 
    <a href="https://placehold.it"><img src="http://placehold.it/180x250"></a>
</div>

面具不再覆盖图像,而是位于图像下方。

请参阅此小提琴http://jsfiddle.net/4UNuB/6/

但是面具仍然和以前一样被应用到同一个地方,为什么它会移动,以及如何阻止它移动?

2 个答案:

答案 0 :(得分:1)

您可以将两者放在同一个锚中并使用定位+ z-index:

.box1 {
  border: #999 2px solid;
  width: 180px;
  height: 250px;
  /*background-image: url(http://smilesoftware.com/assets/images/uploads/products/icon_pdfpenipad_140x140.png);
  background-position: center;
  background-repeat: no-repeat;*/
}

img {
  position: absolute;
  z-index: 0;
}

.black-box {
  position: relative;
  z-index: 1;
  text-align: center;
  font-size: 16px;
  color: #fff;
  background-color: rgba(00,00,00,0.8);
  width: 100%;
  height: 100%;
  opacity: 1.0;
  transition: all 0.5s ease-in-out;
}

.black-box:hover {
  opacity: 0.0;
  transition: all 0.5s ease-in-out;
}

h2 {
  padding-top: 110px;
  margin: 0px;
}
<div class="box1"> 
  <a href="http://placehold.it">
    <img src="http://placehold.it/180x250">
    <div class="black-box">
      <h2>View Details</h2>
    </div>
  </a>
</div>

另外,我必须删除h2的保证金。

答案 1 :(得分:1)

为方框添加位置绝对和相对css。

检查Fiddle此处

  .box1 {
      border: #999 2px solid;
      width: 180px;
      height: 250px;
      /*background-image: url(http://smilesoftware.com/assets/images/uploads/products/icon_pdfpenipad_140x140.png);*/
      background-position: center;
      background-repeat: no-repeat;
      position: relative;
  }


 .black-box {
    text-align: center;
    font-size: 16px;
    color: #fff;
    background-color: rgba(00,00,00,0.8);
    width: 100%;
    height: 100%;
    opacity: 1.0;
    transition: all 0.5s ease-in-out;
    position: absolute;
    top: 0;
}