背景图片悬停状态

3
我有一个父级div。
#myParentDiv{
   width: 100px;
   height: 200px;
}

然后我在其中放置了一个子div。
#myChildDiv{
   width: 100%;
   height: 100%;
}

在子元素内部,我有一个按钮。该按钮设置了 background-image

#backgroundIndiseChild{
   background-image: url(/img/img.jpg);
   background-repeat: no-repeat;
   background-size: 50%;
   cursor: pointer;
}

我的问题:当鼠标悬停在#myChildDiv的任何部分时,光标会变成cursor:pointer。我该如何使鼠标仅在悬停在#backgroundIndiseChild上时才更改为指针形状?


1
请展示一个演示,这样就可以了。 - Bhojendra Rauniyar
1
一个演示可能会有帮助,但我怀疑你的问题是因为 background-size: 50%。 图像仅占用50%的空间,但这并不意味着另一个区域不是 #backgroundIndiseChild 元素的一部分。 - Harry
@BhojendraNepal:https://jsfiddle.net/Ln41xeyq/ - Becky
@Harry,你说得完全正确。我该如何纠正这个问题? - Becky
@Becky:我稍微修改了你的问题,使其更加关注光标行为而不是 :hover。如果你认为这没有什么价值,随时可以恢复。 - Harry
显示剩余2条评论
1个回答

2

根据评论中提供的澄清,我认为您根本不需要在#myChildDiv上设置高度和宽度。您可以使用以下代码片段中的内容。我使用了content属性而不是background-image并将heightwidth设置为50%。

#myParentDiv {
  width: 100px;
  height: 200px;
  border: 1px solid #f60;
}
#backgroundIndiseChild {
  content: url(http://lorempixel.com/100/100);
  background-repeat: no-repeat;
  width: 50%;
  height: 50%;
  cursor: pointer;
}
<div id="myParentDiv">
  <div id="myChildDiv">
    <div id="backgroundIndiseChild"></div>
  </div>
</div>

要垂直居中内容,如果您的图像始终是父元素高度的25%和宽度的50%,则可以使用下面片段中提到的方法。它将图像容器的位置绝对定位在距离顶部50%处,然后使用transform: translateY(-50%)来使其垂直居中。这是我建议的方法。(注意:我已经使用视口单位vh来说明响应性)。

#myParentDiv {
  position: relative;
  width: 30vh;
  height: 60vh;
  border: 1px solid #f60;
}
#backgroundIndiseChild {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  content: url(http://lorempixel.com/100/100);
  background-repeat: no-repeat;
  width: 50%;
  height: 25%;
  cursor: pointer;
}
<div id="myParentDiv">
  <div id="myChildDiv">
    <div id="backgroundIndiseChild"></div>
  </div>
</div>


如果没有为#myChildDiv指定大小,#backgroundIndiseChild将不会显示?谢谢。 - Becky
@Becky:是的,你需要设置一些明确的高度和宽度或者添加一些内容到 div 中。否则就没有东西可以显示,因此图像将保持不可见。这就是为什么我在答案中使用了 content 属性而不是 background-image 的原因。 - Harry
我刚刚意识到你编辑了你的答案,看起来可以工作。我之前使用 background-position: 50%; 是为了让它在 #myParentDiv 中居中。那么如何垂直居中呢? - Becky
@Becky:水平和垂直都居中还是只有垂直居中? - Harry
@Becky:这是另一个棘手的部分,因为您需要绝对定位它,然后上面的代码片段就不起作用了 :( - Harry
@Becky:我已经更新了我的答案,并提供了一种可能实现垂直居中的方法。请检查它是否适用于你的情况。 - Harry

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