在图片上方创建一个响应式按钮并使其保持在同一位置

3
我希望在响应式图片的顶部放置一个按钮,但不在中心位置,并且我希望它保持在图像中另一个按钮的相同位置。这是我的代码 jsfiddle
这是HTML:
<div class="container">

  <div class="img">
      <img src="http://www.playful.ma/wp-content/uploads/2017/02/img.png" class="0">
  </div>

  <div class="overlay">
   <h4>My Button</h4>
</div>

这是 CSS

.container{

  width: 100%;

}

.overlay{
  position:absolute;
  top:70%;
  left:60%;
  padding:10px;
  background:white;
  border-radius:10px;
}


.img{
  position:relative;
  width:100%;
  min-width: 100%;
}

我希望当调整浏览器大小时,.overlay div仍保持在图像中蓝色按钮的上方位置。 谢谢。

https://jsfiddle.net/rvr21jq6/1/ - linktoahref
@linktoahref 谢谢你,但如果图片是响应式的,这种方法不起作用。 - A Trihop
2个回答

3
你可以通过将图像设置为背景图像并使用视口单位字体大小的相对定位来实现相似效果。

.container{
  position: relative;
  padding-top: 31.875%;
  height: 0;
  background: url('http://www.playful.ma/wp-content/uploads/2017/02/img.png') 0 0 no-repeat;
  background-size: cover;
}

h4 {
  position:absolute;
  top:70.5%;
  left:34%;
  color: white;
  margin: 0;
  font-size: 1.4vw;
}
<div class="container">
   <h4>My Button</h4>  
</div>


1
非常感谢 @Michael Coker,这个很好用。我还有一个问题,如果我想使用图像而不是文本,该怎么办?我的意思是当调整浏览器大小时,图像保持在相同的位置。 - A Trihop

0
使用这个CSS可以让你朝着正确的方向前进。
.container{
  width: 100%;
  position: relative
}

.overlay{
  position:absolute;
  top:63%;
  left:50%;
  padding:10px;
  background:white;
  border-radius:10px;
}

注意容器的 position:relative;,覆盖层的 position:absolute;


这段代码没有将覆盖层div放置在图片的同一位置,但谢谢。 - A Trihop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接