简体   繁体   中英

background-image hover state

I've got a parent div

#myParentDiv{
   width: 100px;
   height: 200px;
}

Then I've got a child div inside it

#myChildDiv{
   width: 100%;
   height: 100%;
}

inside of the child, I've got a button. The button has a background-image set

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

My question: The cursor changes to cursor:pointer when hovered over any part of #myChildDiv . How do I make the cursor change to pointer only when hovered over #backgroundIndiseChild ?

Based on the clarification provided in comments, I don't think you need the height and width setting on the #myChildDiv at all. You could just use something like in the below snippet. I have used the content property instead of the background-image and set the height and width to 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> 

To vertically center the content , you could use the approach mentioned in the below snippet if your image is always going to be 25% height and 50% width of the parent. It positions the image's container absolutely at 50% from the top and then uses transform: translateY(-50%) to vertically center it. This is the approach I would suggest. ( Note: I have used viewport units vh for the parent to illustrate responsiveness).

 #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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM