为什么这种背景会在悬停时延伸到图像之外?

时间:2022-07-03 11:42:54

I'm trying to create a hover effect on a rather complex layout. The hover effect works, but upon hover the background (or overlay) extends beyond the image (I would like it to be just as big as the image).

我正在尝试在相当复杂的布局上创建悬停效果。悬停效果有效,但悬停时背景(或叠加)延伸到图像之外(我希望它与图像一样大)。

Does anyone know why that is and how to fix it?

有谁知道为什么会这样,以及如何解决它?

HTML

<article>
    <div class="img-crop">
        <a href="#" class="title-anchor"><h2>Title</h2></a>
        <a href="#"><img src="http://bit.ly/gUKbAE" /></a>
    </div>
</article>

CSS

* {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
}

article {
    overflow: hidden;
}

.title-anchor {
    display: inline-block;
    position: absolute;
    overflow: hidden;
    z-index: 1;
    width: 100%;
    height: 100%;
}

.img-crop:hover .title-anchor {
    background: rgba(0,0,0,0.5);
}

.img-crop {
    display: inline-block;
    position: relative;
    overflow: hidden;
    max-width: 100%;
    margin: 0;
    padding: 0;
}

h2 {
    color: rgba(0,0,0,0);
    margin: 0;
    padding: 0;
    z-index: 2;
    line-height: 0;
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
    text-align: center;
}

.img-crop:hover h2 {
    color: black;
}

It's here too: http://jsfiddle.net/kmjRu/39/

它也在这里:http://jsfiddle.net/kmjRu/39/

3 个解决方案

#1


2  

You need to add this on the universal css:

你需要在通用css上添加这个:

img { border: 0; vertical-align: top;}

...

http://jsfiddle.net/Riskbreaker/kmjRu/43/

#2


3  

Just add

img {
display: block;
}

http://jsfiddle.net/kmjRu/41/

Images are replaced inline elements by default

默认情况下,图像将替换为内联元素

#3


0  

define the height of .img-crop:hover the same as .img-crop img. E.g.

定义.img-crop的高度:悬停与.img-crop img相同。例如。

.img-crop:hover {
    background: rgba(0,0,0,0.5);
    height: 100px;
}
.img-crop img{height: 100px;}

#1


2  

You need to add this on the universal css:

你需要在通用css上添加这个:

img { border: 0; vertical-align: top;}

...

http://jsfiddle.net/Riskbreaker/kmjRu/43/

#2


3  

Just add

img {
display: block;
}

http://jsfiddle.net/kmjRu/41/

Images are replaced inline elements by default

默认情况下,图像将替换为内联元素

#3


0  

define the height of .img-crop:hover the same as .img-crop img. E.g.

定义.img-crop的高度:悬停与.img-crop img相同。例如。

.img-crop:hover {
    background: rgba(0,0,0,0.5);
    height: 100px;
}
.img-crop img{height: 100px;}