我正在尝试在图像上添加透明文本叠加层.我已经决定使用CSS添加透明div是最简单的,但无法弄清楚为什么我的代码不起作用.我在悬停时更改了图像的不透明度,并将包含文本的div设置为
https://jsfiddle.net/3Lx1pyL9/
这是html:
<div id="chickcontainer"> <img src="http://animal-dream.com/data_images/chicken/chicken7.jpg"><div class="overlay">chicks</div> <img class="chicks" src="https://smittenkitchendotcom.files.wordpress.com/2016/09/piri-piri-chicken.jpg?w=750"> <img class="chicks" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRzRJV4iLzYh0eqyVG9-OidAW1t24Xa_vmVRX4Qy-WoyMIgpCx6"> </div>
和css:
#chickcontainer img{ position:relative; width:30%; height:30%; display:inline-block; margin-left:2%; border-radius:100%; border: solid .5px; } .overlay{ visibility:hidden; position:absolute; width:20%; height:90%; top:12%; left:7%; z-index:0; } #chickcontainer img:hover .overlay{ visibility:visible; z-index:100; }问题是你的选择器:
#chickcontainer img:hover .overlay
这个选择器期望.overlay是img:hover的后代,而图像根本不能有后代.在你的html中,.overlay是一个位于图像旁边的兄弟.
<img src="http://animal-dream.com/data_images/chicken/chicken7.jpg"><div class="overlay">chicks</div>
相反,您应该使用“next sibling”选择器来选择下一个元素并将样式应用于它.
#chickcontainer img:hover + .overlay
这是一个有效的例子
#chickcontainer img{ position:relative; width:30%; height:30%; display:inline-block; margin-left:2%; border-radius:100%; border: solid .5px; } .overlay{ visibility:hidden; position:absolute; width:20%; height:90%; top:12%; left:7%; z-index:0; } #chickcontainer img:hover + .overlay{ visibility:visible; z-index:100; }
<div id="chickcontainer"> <img src="http://animal-dream.com/data_images/chicken/chicken7.jpg"><div class="overlay">chicks</div> <img class="chicks" src="https://smittenkitchendotcom.files.wordpress.com/2016/09/piri-piri-chicken.jpg?w=750"> <img class="chicks" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRzRJV4iLzYh0eqyVG9-OidAW1t24Xa_vmVRX4Qy-WoyMIgpCx6"> </div>