当我将鼠标悬停在图像上时,我试图在图像上创建一个叠加层。 我用来创建叠加层的颜色不会覆盖图像。它围绕着图像,我希望它位于图像的顶部。 我不确定我哪里错了。 当你将鼠标悬停在它上面时,它也会做这种奇怪的跳跃 Action 。
HTML
<div class="overlay">
<div class="overlay2"></div>
<figure class="box-img">
<img src="http://i.imgur.com/PHKC3T9.jpg" alt="" />
</figure>
</div>
CSS
.overlay:hover{
background: red;
position: absolute;
opacity: 0.7;
}
.box-img img{
position: relative;
}
这是一个jsfiddle:JSFIDDLE
最佳答案
大的“边框”是因为 figure
元素的默认边距和填充,根据 W3,这些是常见规范:
figure {
display: block;
margin-top: 1em;
margin-bottom: 1em;
margin-left: 40px;
margin-right: 40px;
}
我总是喜欢在样式表开始时自己进行完全重置:
*, *:before, *:after {
margin: 0;
padding: 0;
}
在代码的当前形式中,覆盖层不会显示在顶部,因为颜色将位于背景中。伪元素可能会执行您想要的操作(使用直接方法更新了此处的代码):
<figure class="box-img">
<img src="http://i.imgur.com/PHKC3T9.jpg" alt="" />
</figure>
.box-img {
display: inline-block;
position: relative;
line-height: 0;
}
.box-img:hover:after {
content: '';
width: 100%;
height: 100%;
background: red;
position: absolute;
top: 0;
left: 0;
opacity: 0.7;
}
初稿的完整性,更接近原始标记:
关于html - 获取图像顶部的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29722892/