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

时间:2013-04-09 15:39:56

标签: html css image header hover

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

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

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;
}

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

3 个答案:

答案 0 :(得分:3)

添加

img {
display: block;
}

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

默认情况下,图片为replaced inline elements

答案 1 :(得分:2)

你需要在通用css上添加它:

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

...

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

答案 2 :(得分:0)

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

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