Background image hover state
I have a parent div
#myParentDiv{
width: 100px;
height: 200px;
}
Then I have a child div inside
#myChildDiv{
width: 100%;
height: 100%;
}
inside the child, I have 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 it hovers over any part #myChildDiv
. How to change cursor
to pointer only on hover over #backgroundIndiseChild
?
source to share
Based on the clarifications provided in the comments, I don't think you need to set the height and width to at #myChildDiv
all. You could just use something like the snippet below. I used property content
instead background-image
and set 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 content
you can use the approach mentioned in the snippet below if your image will always be 25% of the height and 50% of the width of the parent. It positions the image container at absolutely 50% of the level top
and then uses it transform: translateY(-50%)
to center it vertically. I would suggest this approach. ( Note: I used vh
parent view units to show 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>
source to share