使用对象适合将div放在图像顶部的正确位置

时间:2016-09-14 10:18:39

标签: html css image

我想在这个图像上放一个div(一个蛋糕)。 enter image description here

例如,我想把我的div放在红樱桃之上,就像这样enter image description here

因为我的图片具有动态宽度和高度,我在我的CSS中使用object-fit: cover;, 所以当我的图像调整大小时,div位置必须相应移动。

如果我的图片具有固定尺寸,则使用position: absolute;即可完成工作。但是,在我的图片中使用object-fit: cover;时,我的图片就会随着用户调整大小而移动。调整大小时如何使我的div出现在确切的位置?

感谢。如果我的问题很乱,你无法理解,请告诉我,因为我不是母语为英语的人。

2 个答案:

答案 0 :(得分:1)

你回答了自己的问题。您需要做的是:使用百分比值进行定位,例如:

.my_cover_div {
    position: absolute;
    left: 60%;
    top: 5%;
}

如果准确定位,this article可能会有用。

答案 1 :(得分:0)

试试这个,以获得div的准确顶部和中心位置,您可以使用CSS calc() function



#box{
  width:auto;
  height:auto;
  position:relative;
  overflow:hidden;
}
img{
  width:100%;
  min-height:100%;
  object-fit:cover;
}
#box > .bx{
  position:absolute;
  width:60px;
  height:60px;
  background:#111;
  top:5%;
  left:calc(100% - 60%);
  color:#fff;
}

<div id="box">
<div class="bx">Text</div>
<img src="http://i.stack.imgur.com/7Mj25.jpg">
</div>
&#13;
&#13;
&#13;